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/rosmsg/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.3)
project(rosmsg)
find_package(catkin)
catkin_package()
catkin_python_setup()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/package.xml | <package>
<name>rosmsg</name>
<version>1.11.21</version>
<description>
rosmsg contains two command-line tools: <tt>rosmsg</tt> and
<tt>rossrv</tt>. <tt>rosmsg</tt> is a command-line tool for
displaying information about <a
href="http://www.ros.org/wiki/msg">ROS Message
types</a>. <tt>rossrv</tt> is a command-line tool for displaying
information about <a href="http://www.ros.org/wiki/srv">ROS
Service types</a>.
</description>
<maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer>
<license>BSD</license>
<url>http://ros.org/wiki/rosmsg</url>
<author>Ken Conley</author>
<author>Tully Foote</author>
<buildtool_depend>catkin</buildtool_depend>
<run_depend version_gte="0.6.4">catkin</run_depend>
<run_depend>genmsg</run_depend>
<run_depend>python-rospkg</run_depend>
<run_depend>rosbag</run_depend>
<run_depend>roslib</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/rosmsg/rosdoc.yaml | - builder: epydoc
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/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=['rosmsg'],
package_dir={'': 'src'},
scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'],
requires=['genmsg', 'rosbag', 'roslib', 'rospkg']
)
setup(**d)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/.tar | {!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/rosmsg/1.11.21-0.tar.gz',
!!python/unicode 'version': ros_comm-release-release-indigo-rosmsg-1.11.21-0}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/CHANGELOG.rst | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package rosmsg
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
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)
--------------------
* improve rosmsg show to print error message and return non-zero rc when message is not found (`#691 <https://github.com/ros/ros_comm/issues/691>`_)
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 (`#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)
-------------------
* fix rosmsg to find messages existing only in devel space (e.g. messages generated for actions) (`#385 <https://github.com/ros/ros_comm/issues/385>`_)
* 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)
-------------------
* allow reusing rospack instance in rosmsg api
1.9.48 (2013-08-21)
-------------------
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)
-------------------
* fix output of 'rossrv --help' (`#3979 <https://code.ros.org/trac/ros/ticket/3979>`_)
1.9.39 (2012-12-29)
-------------------
* first public release for Groovy
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/test/test_rosmsgproto.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2011, 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: Thibault Kruse
from __future__ import with_statement
NAME = 'test_rosmsgproto'
import os
import sys
import unittest
import time
import std_msgs
import rostest
import rosmsg
from rosmsg import *
from nose.plugins.skip import SkipTest
_NO_DICT=True
if "OrderedDict" in collections.__dict__:
_NO_DICT=False
class RosMsgProtoTest(unittest.TestCase):
def test_get_array_type_instance(self):
self.assertEqual(0, get_array_type_instance("int16[]"))
self.assertEqual(0, get_array_type_instance("char[]"))
self.assertEqual(0, get_array_type_instance("uint16[]"))
self.assertEqual(0, get_array_type_instance("int32[]"))
self.assertEqual(0, get_array_type_instance("uint16[]"))
self.assertEqual(False,get_array_type_instance("bool[]"))
self.assertEqual(0, get_array_type_instance("float32[]"))
self.assertEqual(0, get_array_type_instance("float64[]"))
self.assertEqual("", get_array_type_instance("string[]"))
self.assertFalse(None == get_array_type_instance("time[]"))
self.assertFalse(None == get_array_type_instance("duration[]"))
self.assertTrue(None == get_array_type_instance("colorRGBA[]"))
self.assertTrue(None == get_array_type_instance("empty[]"))
# TODO check for complex types
def test_create_names_filter(self):
class foo:
def __init__(self):
self.__slots__= ["bar","foo","bar","baz","bar"]
self.assertEqual(["foo", "baz"], create_names_filter("bar")(foo()))
def test_rosmsg_cmd_prototype_std_msgs_Int16(self):
if _NO_DICT: raise SkipTest("Test skipped because Python version too low")
self.assertEqual('"data: 0"', rosmsg_cmd_prototype(["msg", "std_msgs/Int16"]))
self.assertEqual('data: 0', rosmsg_cmd_prototype(["msg", "std_msgs/Int16", "-H"]))
self.assertEqual('" data: 0"', rosmsg_cmd_prototype(["msg", "std_msgs/Int16", "-p", " "]))
self.assertEqual(' data: 0', rosmsg_cmd_prototype(["msg", "std_msgs/Int16", "-p", " ", "-H"]))
self.assertEqual('"{}"', rosmsg_cmd_prototype(["msg", "std_msgs/Int16","-x", "data"]))
def test_rosmsg_cmd_prototype_std_msgs_String(self):
if _NO_DICT: raise SkipTest("Test skipped because Python version too low")
self.assertEqual('"data: \'\'"', rosmsg_cmd_prototype(["msg", "std_msgs/String"]))
self.assertEqual('data: \'\'', rosmsg_cmd_prototype(["msg", "std_msgs/String", "-H"]))
self.assertEqual(' data: \'\'', rosmsg_cmd_prototype(["msg", "std_msgs/String", "-p", " ", "-H"]))
def test_rosmsg_cmd_prototype_std_msgs_Header(self):
if _NO_DICT: raise SkipTest("Test skipped because Python version too low")
self.assertEqual('"seq: 0\nstamp:\n secs: 0\n nsecs: 0\nframe_id: \'\'"', rosmsg_cmd_prototype(["msg", "std_msgs/Header"]))
self.assertEqual('"{seq: 0, stamp: {secs: 0, nsecs: 0}, frame_id: \'\'}"', rosmsg_cmd_prototype(["msg", "std_msgs/Header", "-f1"]))
def test_rosmsg_cmd_prototype_std_msgs_Bool(self):
if _NO_DICT: raise SkipTest("Test skipped because Python version too low")
self.assertEqual('"data: false"', rosmsg_cmd_prototype(["msg", "std_msgs/Bool"]))
def test_rosmsg_cmd_prototype_std_msgs_Time(self):
if _NO_DICT: raise SkipTest("Test skipped because Python version too low")
self.assertEqual('"data:\n secs: 0\n nsecs: 0"', rosmsg_cmd_prototype(["msg", "std_msgs/Time"]))
self.assertEqual('"{data: {secs: 0, nsecs: 0}}"', rosmsg_cmd_prototype(["msg", "std_msgs/Time", "-f1"]))
def test_rosmsg_cmd_prototype_std_msgs_Duration(self):
if _NO_DICT: raise SkipTest("Test skipped because Python version too low")
self.assertEqual('"data:\n secs: 0\n nsecs: 0"', rosmsg_cmd_prototype(["msg", "std_msgs/Duration"]))
self.assertEqual('"{data: {secs: 0, nsecs: 0}}"', rosmsg_cmd_prototype(["msg", "std_msgs/Duration", "-f1"]))
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/test/test_rosmsgproto_command_line.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2011, 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: Thibault Kruse
from __future__ import with_statement
NAME = 'test_rosmsgproto'
import os
import sys
import unittest
import time
import copy
import rostest
import subprocess
from subprocess import Popen, PIPE, call
import collections
import rosmsg
from nose.plugins.skip import SkipTest
ROSMSGPROTO_FN = [os.path.join(os.getcwd(), '../scripts/rosmsg-proto')]
_NO_DICT = True
if "OrderedDict" in collections.__dict__:
_NO_DICT = False
class RosMsgProtoCommandlineTestMsg(unittest.TestCase):
def setUp(self):
# proto depends on python 2.7 having OrderedDict
if _NO_DICT: raise SkipTest("Test skipped because Python version too low")
self.new_environ = os.environ
self.new_environ["PYTHONPATH"] = os.path.join(os.getcwd(), "src")+':'+os.environ['PYTHONPATH']
def testFail(self):
cmd = copy.copy(ROSMSGPROTO_FN)
cmd.extend(["msg", "foo123barxyz"])
call = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE, env = self.new_environ)
(output, erroutput) = call.communicate()
self.assertEqual('', output)
self.assertTrue('Unknown message name foo123barxyz' in erroutput)
def testSilentFail(self):
cmd = copy.copy(ROSMSGPROTO_FN)
cmd.extend(["msg", "-s", "foo123barxyz"])
call = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE, env = self.new_environ)
(output, erroutput) = call.communicate()
self.assertEqual('', output)
self.assertEqual('', erroutput)
def testSilentFailCpp(self):
cmd = copy.copy(ROSMSGPROTO_FN)
cmd.extend(["msg", "-s", "foo123barxyz::bar"])
call = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE, env = self.new_environ)
(output, erroutput) = call.communicate()
self.assertEqual('', output)
self.assertEqual('', erroutput)
def testSilentFailDot(self):
cmd = copy.copy(ROSMSGPROTO_FN)
cmd.extend(["msg", "-s", "foo123barxyz.bar"])
call = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE, env = self.new_environ)
(output, erroutput) = call.communicate()
self.assertEqual('', output)
self.assertEqual('', erroutput)
def testSilentFailMode(self):
cmd = copy.copy(ROSMSGPROTO_FN)
cmd.extend(["msgfoobar", "-s", "foo123barxyz.bar"])
call = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE, env = self.new_environ)
(output, erroutput) = call.communicate()
self.assertEqual('', output)
self.assertEqual('', erroutput)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/test/test_rosmsg.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.
import os
import sys
import unittest
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
import time
import rosmsg
from subprocess import Popen, PIPE, check_call, call
#TODO: currently have an extra copy of msg and srv files in local dir
# for historical/porting reasons. Ideally there would only be one copy
# in test_ros instead.
def get_test_path():
return os.path.abspath(os.path.dirname(__file__))
class TestRosmsg(unittest.TestCase):
def setUp(self):
pass
def test_fullusage(self):
from rosmsg import MODE_MSG
text = rosmsg.fullusage(MODE_MSG)
self.assert_("Commands" in text)
cmds = ['show', 'md5', 'package', 'packages']
for c in cmds:
self.assert_(c in text)
def test_get_msg_text(self):
d = get_test_path()
msg_d = os.path.join(d, 'msg')
for t in ['RosmsgA', 'RosmsgB']:
with open(os.path.join(msg_d, '%s.msg'%t), 'r') as f:
text = f.read()
type_ = 'test_ros/'+t
self.assertEquals(text, rosmsg.get_msg_text(type_, raw=False))
self.assertEquals(text, rosmsg.get_msg_text(type_, raw=True))
# test recursive types
t = 'RosmsgC'
with open(os.path.join(msg_d, '%s.msg'%t), 'r') as f:
text = f.read()
type_ = 'test_ros/'+t
self.assertEquals(text, rosmsg.get_msg_text(type_, raw=True))
self.assertEquals("""std_msgs/String s1
string data
std_msgs/String s2
string data""", rosmsg.get_msg_text(type_, raw=False).strip())
def test_iterate_packages(self):
from rosmsg import iterate_packages, MODE_MSG, MODE_SRV
import rospkg
rospack = rospkg.RosPack()
found = {}
for p, path in iterate_packages(rospack, MODE_MSG):
found[p] = path
assert os.path.basename(path) == 'msg', path
# make sure it's a package
assert rospack.get_path(p)
assert found
for p, path in iterate_packages(rospack, MODE_SRV):
found[p] = path
assert os.path.basename(path) == 'srv', path
# make sure it's a package
assert rospack.get_path(p)
assert found
def test_list_types(self):
try:
l = rosmsg.list_types('rosmsg', '.foo')
self.fail("should have failed on invalid mode")
except ValueError: pass
# test msgs
l = rosmsg.list_types('rospy', mode='.msg')
self.assertEquals([], l)
l = rosmsg.list_types('test_ros', mode='.msg')
for t in ['test_ros/RosmsgA', 'test_ros/RosmsgB', 'test_ros/RosmsgC']:
assert t in l
l = rosmsg.list_types('rospy', mode='.srv')
self.assertEquals([], l)
l = rosmsg.list_types('test_ros', mode='.srv')
for t in ['test_ros/RossrvA', 'test_ros/RossrvB']:
assert t in l
def test_get_srv_text(self):
d = get_test_path()
srv_d = os.path.join(d, 'srv')
with open(os.path.join(srv_d, 'RossrvA.srv'), 'r') as f:
text = f.read()
self.assertEquals(text, rosmsg.get_srv_text('test_ros/RossrvA', raw=False))
self.assertEquals(text, rosmsg.get_srv_text('test_ros/RossrvA', raw=True))
# std_msgs/empty / std_msgs/empty
with open(os.path.join(srv_d, 'RossrvB.srv'), 'r') as f:
text = f.read()
self.assertEquals(text, rosmsg.get_srv_text('test_ros/RossrvB', raw=False))
self.assertEquals(text, rosmsg.get_srv_text('test_ros/RossrvB', raw=True))
def test_rosmsg_cmd_packages(self):
from rosmsg import rosmsg_cmd_packages, MODE_MSG, MODE_SRV
with fakestdout() as b:
rosmsg_cmd_packages(MODE_MSG, 'foo', ['packages'])
val = b.getvalue().strip()
packages1 = val.split('\n')
assert 'std_msgs' in packages1
with fakestdout() as b:
rosmsg_cmd_packages(MODE_MSG, 'foo', ['packages', '-s'])
val = b.getvalue().strip()
packages2 = val.split(' ')
assert 'std_msgs' in packages2
assert set(packages1) == set(packages2), "%s vs. %s"%(packages1, packages2)
def test_rosmsg_cmd_list(self):
from rosmsg import rosmsg_cmd_list, MODE_MSG, MODE_SRV
with fakestdout() as b:
rosmsg_cmd_list(MODE_MSG, 'messages', ['list'])
val = b.getvalue().strip()
packages1 = val.split('\n')
assert 'std_msgs/String' in packages1
from contextlib import contextmanager
@contextmanager
def fakestdout():
realstdout = sys.stdout
fakestdout = StringIO()
sys.stdout = fakestdout
yield fakestdout
sys.stdout = realstdout
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/test/test_rosmsg_command_line.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.
import os
import sys
import unittest
import time
import rospkg
from subprocess import Popen, PIPE, check_call, call
_SCRIPT_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'scripts'))
class TestRosmsg(unittest.TestCase):
def setUp(self):
self.new_environ = os.environ
self.new_environ["PYTHONPATH"] = os.path.join(os.getcwd(), "src")+':'+os.environ['PYTHONPATH']
## test that the rosmsg command works
def test_cmd_help(self):
sub = ['show', 'md5', 'package', 'packages', 'list']
for cmd in ['rosmsg', 'rossrv']:
glob_cmd=[os.path.join(_SCRIPT_FOLDER, cmd)]
output = Popen(glob_cmd, stdout=PIPE, env=self.new_environ).communicate()[0]
self.assert_('Commands' in output)
output = Popen(glob_cmd+['-h'], stdout=PIPE, env=self.new_environ).communicate()[0]
self.assert_('Commands' in output)
self.assert_('Traceback' not in output)
for c in sub:
self.assert_("%s %s"%(cmd, c) in output, "%s %s"%(cmd, c) + " not in "+ output + " of " + str(glob_cmd))
for c in sub:
output = Popen(glob_cmd + [c, '-h'], stdout=PIPE, env=self.new_environ).communicate()[0]
self.assert_('Usage' in output)
self.assert_("%s %s"%(cmd, c) in output, output)
def test_cmd_packages(self):
# - single line
output1 = Popen(['rosmsg', 'packages', '-s'], stdout=PIPE).communicate()[0]
# - multi-line
output2 = Popen(['rosmsg', 'packages'], stdout=PIPE).communicate()[0]
l1 = [x for x in output1.split() if x]
l2 = [x.strip() for x in output2.split('\n') if x.strip()]
self.assertEquals(l1, l2)
for p in ['std_msgs', 'test_ros']:
self.assert_(p in l1)
for p in ['std_srvs', 'rosmsg']:
self.assert_(p not in l1)
output1 = Popen(['rossrv', 'packages', '-s'], stdout=PIPE).communicate()[0]
output2 = Popen(['rossrv', 'packages'], stdout=PIPE).communicate()[0]
l1 = [x for x in output1.split() if x]
l2 = [x.strip() for x in output2.split('\n') if x.strip()]
self.assertEquals(l1, l2)
for p in ['std_srvs', 'test_ros']:
self.assert_(p in l1)
for p in ['std_msgs', 'rospy']:
self.assert_(p not in l1)
def test_cmd_list(self):
# - multi-line
output1 = Popen([os.path.join(_SCRIPT_FOLDER,'rosmsg'), 'list'], stdout=PIPE).communicate()[0]
l1 = [x.strip() for x in output1.split('\n') if x.strip()]
for p in ['std_msgs/String', 'test_ros/Floats']:
self.assert_(p in l1)
for p in ['std_srvs/Empty', 'roscpp/Empty']:
self.assert_(p not in l1)
output1 = Popen([os.path.join(_SCRIPT_FOLDER,'rossrv'), 'list'], stdout=PIPE).communicate()[0]
l1 = [x.strip() for x in output1.split('\n') if x.strip()]
for p in ['std_srvs/Empty', 'roscpp/Empty']:
self.assert_(p in l1)
for p in ['std_msgs/String', 'test_ros/Floats']:
self.assert_(p not in l1)
def test_cmd_package(self):
# this test is obviously very brittle, but should stabilize as the tests stabilize
# - single line output
output1 = Popen(['rosmsg', 'package', '-s', 'test_ros'], stdout=PIPE).communicate()[0]
# - multi-line output
output2 = Popen(['rosmsg', 'package', 'test_ros'], stdout=PIPE).communicate()[0]
l = set([x for x in output1.split() if x])
l2 = set([x.strip() for x in output2.split('\n') if x.strip()])
self.assertEquals(l, l2)
for m in ['test_ros/RosmsgA',
'test_ros/RosmsgB',
'test_ros/RosmsgC']:
self.assertTrue(m in l, l)
output = Popen(['rossrv', 'package', '-s', 'test_ros'], stdout=PIPE).communicate()[0]
output2 = Popen(['rossrv', 'package','test_ros'], stdout=PIPE).communicate()[0]
l = set([x for x in output.split() if x])
l2 = set([x.strip() for x in output2.split('\n') if x.strip()])
self.assertEquals(l, l2)
for m in ['test_ros/RossrvA', 'test_ros/RossrvB']:
self.assertTrue(m in l, l)
## test that the rosmsg/rossrv show command works
def test_cmd_show(self):
output = Popen(['rosmsg', 'show', 'std_msgs/String'], stdout=PIPE).communicate()[0]
self.assertEquals('string data', output.strip())
output = Popen(['rossrv', 'show', 'std_srvs/Empty'], stdout=PIPE).communicate()[0]
self.assertEquals('---', output.strip())
output = Popen(['rossrv', 'show', 'std_srvs/Empty'], stdout=PIPE).communicate()[0]
self.assertEquals('---', output.strip())
output = Popen(['rossrv', 'show', 'test_ros/AddTwoInts'], stdout=PIPE).communicate()[0]
self.assertEquals('int64 a\nint64 b\n---\nint64 sum', output.strip())
# test against test_rosmsg package
rospack = rospkg.RosPack()
d = rospack.get_path('test_ros')
msg_d = os.path.join(d, 'msg')
# - test with non-recursive types, which should have identical raw/non-raw
for t in ['RosmsgA', 'RosmsgB']:
with open(os.path.join(msg_d, '%s.msg'%t), 'r') as f:
text = f.read()
text = text+'\n' # running command adds one new line
type_ ='test_ros/'+t
output = Popen(['rosmsg', 'show', type_], stdout=PIPE).communicate()[0]
self.assertEquals(text, output)
output = Popen(['rosmsg', 'show', '-r',type_], stdout=PIPE, stderr=PIPE).communicate()
self.assertEquals(text, output[0], "Failed: %s"%(str(output)))
output = Popen(['rosmsg', 'show', '--raw', type_], stdout=PIPE).communicate()[0]
self.assertEquals(text, output)
# test as search
type_ = t
text = "[test_ros/%s]:\n%s"%(t, text)
output = Popen(['rosmsg', 'show', type_], stdout=PIPE).communicate()[0]
self.assertEquals(text, output)
output = Popen(['rosmsg', 'show', '-r',type_], stdout=PIPE, stderr=PIPE).communicate()
self.assertEquals(text, output[0], "Failed: %s"%(str(output)))
output = Popen(['rosmsg', 'show', '--raw', type_], stdout=PIPE).communicate()[0]
self.assertEquals(text, output)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/test/test_rosmsgproto_geometry.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2011, 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: Thibault Kruse
from __future__ import with_statement
NAME = 'test_rosmsgproto'
import os
import sys
import unittest
import time
import std_msgs
import rostest
import roslib.packages
import rosmsg
from rosmsg import *
from nose.plugins.skip import SkipTest
_NO_DICT=True
if "OrderedDict" in collections.__dict__:
_NO_DICT=False
class RosMsgProtoTest(unittest.TestCase):
def setUp(self):
# proto depends on python 2.7 having OrderedDict
if _NO_DICT: raise SkipTest("Test skipped because Python version too low")
def test_rosmsg_cmd_prototype_geom_msgs_Pose(self):
self.assertEqual('"position:\n x: 0.0\n y: 0.0\n z: 0.0\norientation:\n x: 0.0\n y: 0.0\n z: 0.0\n w: 0.0"', rosmsg_cmd_prototype(["msg", "geometry_msgs/Pose", "-f0"]))
def test_rosmsg_cmd_prototype_geom_msgs_PoseArray(self):
self.assertEqual('"header:\n seq: 0\n stamp:\n secs: 0\n nsecs: 0\n frame_id: \'\'\nposes:\n- position:\n x: 0.0\n y: 0.0\n z: 0.0\n orientation:\n x: 0.0\n y: 0.0\n z: 0.0\n w: 0.0"', rosmsg_cmd_prototype(["msg", "geometry_msgs/PoseArray"]))
self.assertEqual('"header:\n seq: 0\n stamp:\n secs: 0\n nsecs: 0\n frame_id: \'\'\nposes: []"', rosmsg_cmd_prototype(["msg", "geometry_msgs/PoseArray", "-e"]))
def test_rosmsg_cmd_prototype_geom_msgs_PoseStamped(self):
self.assertEqual('"header:\n seq: 0\n stamp:\n secs: 0\n nsecs: 0\n frame_id: \'\'\npose:\n position:\n x: 0.0\n y: 0.0\n z: 0.0\n orientation:\n x: 0.0\n y: 0.0\n z: 0.0\n w: 0.0"', rosmsg_cmd_prototype(["msg", "geometry_msgs/PoseStamped"]))
self.assertEqual('"header:\n frame_id: \'\'\npose:\n position:\n x: 0.0\n y: 0.0\n z: 0.0\n orientation:\n x: 0.0\n y: 0.0\n z: 0.0\n w: 0.0"', rosmsg_cmd_prototype(["msg", "geometry_msgs/PoseStamped", "-x", "stamp,seq"]))
def test_rosmsg_cmd_prototype_geom_msgs_Transform(self):
self.assertEqual('"translation:\n x: 0.0\n y: 0.0\n z: 0.0\nrotation:\n x: 0.0\n y: 0.0\n z: 0.0\n w: 0.0"', rosmsg_cmd_prototype(["msg", "geometry_msgs/Transform"]))
def test_rosmsg_cmd_prototype_geom_msgs_TransformStamped(self):
self.assertEqual('"header:\n seq: 0\n stamp:\n secs: 0\n nsecs: 0\n frame_id: \'\'\nchild_frame_id: \'\'\ntransform:\n translation:\n x: 0.0\n y: 0.0\n z: 0.0\n rotation:\n x: 0.0\n y: 0.0\n z: 0.0\n w: 0.0"', rosmsg_cmd_prototype(["msg", "geometry_msgs/TransformStamped"]))
self.assertEqual('"header:\n seq: 0\n stamp:\n secs: 0\n nsecs: 0\n frame_id: \'\'\nchild_frame_id: \'\'\ntransform:\n translation:\n x: 0.0\n y: 0.0\n z: 0.0\n rotation:\n x: 0.0\n y: 0.0\n z: 0.0\n w: 0.0"', rosmsg_cmd_prototype(["msg", "geometry_msgs/TransformStamped", "-f0"]))
self.assertEqual('"{header: {seq: 0, stamp: {secs: 0, nsecs: 0}, frame_id: \'\'}, child_frame_id: \'\', transform: {\n translation: {x: 0.0, y: 0.0, z: 0.0}, rotation: {x: 0.0, y: 0.0, z: 0.0, w: 0.0}}}"', rosmsg_cmd_prototype(["msg", "geometry_msgs/TransformStamped", "-f1"]))
def test_rosmsg_cmd_prototype_geom_msgs_TwistWithCovariance(self):
self.assertEqual('"twist:\n linear:\n x: 0.0\n y: 0.0\n z: 0.0\n angular:\n x: 0.0\n y: 0.0\n z: 0.0\ncovariance:\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0"', rosmsg_cmd_prototype(["msg", "geometry_msgs/TwistWithCovariance", "-f0"]))
self.assertEqual('"twist:\n linear:\n x: 0.0\n y: 0.0\n z: 0.0\n angular:\n x: 0.0\n y: 0.0\n z: 0.0\ncovariance:\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0\n- 0.0"', rosmsg_cmd_prototype(["msg", "geometry_msgs/TwistWithCovariance", "-e", "-f0"]))
self.assertEqual('"{twist: {linear: {x: 0.0, y: 0.0, z: 0.0}, angular: {x: 0.0, y: 0.0, z: 0.0}}, covariance: [\n 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0, 0.0]}"', rosmsg_cmd_prototype(["msg", "geometry_msgs/TwistWithCovariance", "-f1"]))
self.assertEqual('"twist:\n linear: {x: 0.0, y: 0.0, z: 0.0}\n angular: {x: 0.0, y: 0.0, z: 0.0}\ncovariance: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]"', rosmsg_cmd_prototype(["msg", "geometry_msgs/TwistWithCovariance"]))
def test_rosmsg_cmd_prototype_geom_msgs_Polygon(self):
self.assertEqual('"points:\n- x: 0.0\n y: 0.0\n z: 0.0"', rosmsg_cmd_prototype(["msg", "geometry_msgs/Polygon"]))
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/test | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/test/msg/RosmsgB.msg | std_msgs/Empty empty
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/test | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/test/msg/RosmsgC.msg | std_msgs/String s1
std_msgs/String s2
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/test | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/test/msg/RosmsgA.msg | int32 a
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/test | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/test/srv/RossrvA.srv | int32 areq
---
int32 aresp
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/test | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/test/srv/RossrvB.srv | std_msgs/Empty empty
---
std_msgs/Empty empty
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/scripts/rossrv | #!/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 rosmsg
from rosmsg import MODE_SRV
rosmsg.rosmsgmain(rosmsg.MODE_SRV)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/scripts/rosmsg-proto | #!/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.
from __future__ import print_function
# check for yaml early
import sys
try:
import yaml
import collections
if "OrderedDict" not in collections.__dict__:
# don't want to fail
sys.exit(0)
except:
# don't want to fail
sys.exit(0)
import rosmsg
if __name__ == "__main__":
result = rosmsg.rosmsg_cmd_prototype(sys.argv[1:])
if result != None:
print(result)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/scripts/rosmsg | #!/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 rosmsg
rosmsg.rosmsgmain()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosmsg/src/rosmsg/__init__.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.
"""
Implements rosmsg/rossrv command-line tools.
The code API of the rosmsg module is unstable.
"""
from __future__ import print_function
import collections
import inspect
import os
import sys
import yaml
from catkin.find_in_workspaces import find_in_workspaces
import rospkg
import genmsg
import roslib.message
import rosbag
from optparse import OptionParser
MODE_MSG = '.msg'
MODE_SRV = '.srv'
class ROSMsgException(Exception): pass
class RosMsgProtoException(Exception): pass
class RosMsgProtoArgsException(Exception): pass
# If flowtype chosen is default, instead use flow-style
# False except if meeting objects or arrays with more than
# this size of sub-elements
MAX_DEFAULT_NON_FLOW_ITEMS = 4
## copied from the web, recipe for ordered yaml output ######
def construct_ordered_mapping(self, node, deep=False):
if not isinstance(node, yaml.MappingNode):
raise yaml.constructor.ConstructorError(None, None,
"expected a mapping node, but found %s" % node.id,
node.start_mark)
mapping = collections.OrderedDict()
for key_node, value_node in node.value:
key = self.construct_object(key_node, deep=deep)
if not isinstance(key, collections.Hashable):
raise yaml.constructor.ConstructorError("while constructing a mapping", node.start_mark,
"found unhashable key", key_node.start_mark)
value = self.construct_object(value_node, deep=deep)
mapping[key] = value
return mapping
def construct_yaml_map_with_ordered_dict(self, node):
data = collections.OrderedDict()
yield data
value = self.construct_mapping(node)
data.update(value)
def represent_ordered_mapping(self, tag, mapping, flow_style=None):
value = []
node = yaml.MappingNode(tag, value, flow_style=flow_style)
if self.alias_key is not None:
self.represented_objects[self.alias_key] = node
best_style = True
if hasattr(mapping, 'items'):
mapping = list(mapping.items())
for item_key, item_value in mapping:
node_key = self.represent_data(item_key)
node_value = self.represent_data(item_value)
if not (isinstance(node_key, yaml.ScalarNode) and not node_key.style):
best_style = False
if not (isinstance(node_value, yaml.ScalarNode) and not node_value.style):
best_style = False
value.append((node_key, node_value))
if flow_style is None:
if self.default_flow_style is not None:
node.flow_style = self.default_flow_style
else:
node.flow_style = best_style
return node
## end recipe for ordered yaml output ######
def get_array_type_instance(field_type, default_package = None):
"""
returns a single instance of field_type, where field_type can be a
message or ros primitive or an flexible size array.
"""
field_type = field_type.strip().rstrip("[]")
if field_type == "empty":
return None
if not "/" in field_type:
# is either built-in, Header, or in same package
# it seems built-in types get a priority
if field_type in ['byte', 'int8', 'int16', 'int32', 'int64',\
'char', 'uint8', 'uint16', 'uint32', 'uint64']:
return 0
elif field_type in ['float32', 'float64']:
return 0
elif field_type in ['string']:
return ""
elif field_type == 'bool':
return False
elif field_type == 'time':
field_type = "std_msgs/Time"
elif field_type == 'duration':
field_type = "std_msgs/Duration"
elif field_type == 'Header':
field_type = "std_msgs/Header"
else:
if default_package is None:
return None
field_type = default_package + "/" + field_type
msg_class = roslib.message.get_message_class(field_type)
if (msg_class == None):
# not important enough to raise exception?
return None
instance = msg_class()
return instance
def get_yaml_for_msg(msg, prefix='', time_offset=None, current_time=None, field_filter=None, flow_style_ = None, fill_arrays_ = False):
"""
Builds a YAML string of message.
@param msg: A object, dict or array
@param flow_style_: if True, produces one line with brackets, if false uses multiple lines with indentation, if None uses both using heuristics
@param prefix: prefixes all lines with this string
@param fill_arrays_: if True, for all flexible size arrays an element will be generated
@param current_time: currently not used. Only provided for API compatibility. current_time passes in the current time with respect to the message.
@type current_time: Time
@param field_filter: filter the fields that are strified for Messages.
@type field_filter: fn(Message)->iter(str)
@type flow_style_: bool
@return: a string
"""
def object_representer(dumper, obj):
ndict = collections.OrderedDict()
index = 0
# allow caller to select which fields of message are strified
if field_filter != None:
fields = list(field_filter(obj))
else:
fields = obj.__slots__
for key in fields:
if not key.startswith('_'):
val = getattr(obj, key)
if type(val) == list and len(val) > MAX_DEFAULT_NON_FLOW_ITEMS:
dumper.default_flow_style = flow_style_
if time_offset is not None and isinstance(val, Time):
ndict[key] = val-time_offset
# create initial array element (e.g. for code completion)
elif fill_arrays_ == True and val == []:
message_type = obj._slot_types[index]
if (obj._type != None) and "/" in obj._type:
def_pack = obj._type.split("/")[0]
instance = get_array_type_instance(message_type, default_package = def_pack)
if instance == None:
# not important enough to raise exception?
ndict[key] = val
else:
ndict[key] = [instance]
elif not inspect.ismethod(val) and not inspect.isfunction(val):
ndict[key] = val
index += 1
# as a hack, we improve the heuristics of pyyaml and say with less than 5 objects, no need for brackets
if len(ndict) > MAX_DEFAULT_NON_FLOW_ITEMS:
dumper.default_flow_style = flow_style_
return dumper.represent_dict(ndict)
yaml.representer.SafeRepresenter.add_representer(None, object_representer)
# we force False over None here and set the style in dumper, to
# avoid unecessary outer brackets pyyaml chooses e.g. to
# represent msg Int32 as "{data: 0}"
initial_flow_style = False
if flow_style_ == True:
initial_flow_style = True
# need to set default flow style True for bash prototype
# means will generate one line with [] and {} brackets
# bash needs bracket notation for rostopic pub
txt = yaml.safe_dump(msg,
# None, True, False (None chooses a compromise)
default_flow_style = initial_flow_style,
# Can be None, '', '\'', '"', '|', '>'.
default_style = '',
#indent=2, #>=2, indentation depth
#line_break=?,
#allow_unicode=?,
#if true writes plenty of tags
#canonical = False,
#version={}?,
#width=40,
#encoding=?,
#tags={}?,
# when True, produces --- at start
#explicit_start=False,
# when True, produces ... at end
#explicit_end=False
)
if prefix != None and prefix != '':
result = prefix + ("\n"+prefix).join(txt.splitlines())
else:
result = txt.rstrip('\n')
return result
def create_names_filter(names):
"""
returns a function to use as filter that returns all objects slots except those with names in list.
"""
return lambda obj : filter(lambda slotname : not slotname in names, obj.__slots__)
def init_rosmsg_proto():
if "OrderedDict" in collections.__dict__:
yaml.constructor.BaseConstructor.construct_mapping = construct_ordered_mapping
yaml.constructor.Constructor.add_constructor(
'tag:yaml.org,2002:map',
construct_yaml_map_with_ordered_dict)
yaml.representer.BaseRepresenter.represent_mapping = represent_ordered_mapping
yaml.representer.Representer.add_representer(collections.OrderedDict,
yaml.representer.SafeRepresenter.represent_dict)
def rosmsg_cmd_prototype(args):
init_rosmsg_proto()
parser = OptionParser(usage="usage: rosmsgproto msg/srv [options]",
description="Produces output or a msg or service request, intended for tab completion support.")
parser.add_option("-f","--flow_style",
dest="flow_style", type="int", default=None, action="store",
help="if 1 always use brackets, if 0 never use brackets. Default is a heuristic mix.")
parser.add_option("-e","--empty-arrays",
dest="empty_arrays", default=False, action="store_true",
help="if true flexible size arrays are not filled with default instance")
parser.add_option("-s","--silent",
dest="silent", default=False, action="store_true",
help="if true supresses all error messages")
parser.add_option("-p", "--prefix", metavar="prefix", default="",
help="prefix to print before each line, can be used for indent")
parser.add_option("-H","--no-hyphens",
dest="no_hyphens", default="", action="store_true",
help="if true output has no outer hyphens")
parser.add_option("-x", "--exclude-slots", metavar="exclude_slots", default="",
help="comma separated list of slot names not to print")
options, args = parser.parse_args(args)
try:
if len(args) < 2:
raise RosMsgProtoArgsException("Insufficient arguments")
mode = ".%s"%args[0]
message_type=args[1]
field_filter = None
if options.exclude_slots != None and options.exclude_slots.strip() != "":
field_filter = create_names_filter(options.exclude_slots.split(','))
# possible extentions: options for
# - target language
# - initial values for standard types
# - get partial message (subtree)
# try to catch the user specifying code-style types and error
if '::' in message_type:
if not options.silent:
parser.error("rosmsgproto does not understand C++-style namespaces (i.e. '::').\nPlease refer to msg/srv types as 'package_name/Type'.")
elif '.' in message_type:
if not options.silent:
parser.error("invalid message type '%s'.\nPlease refer to msg/srv types as 'package_name/Type'." % message_type)
if not '/' in message_type:
# if only one such msg or srv exists, use it
results = []
for found in rosmsg_search(rospkg.RosPack(), mode, message_type):
results.append(found)
if len(results) > 1:
raise RosMsgProtoException("Ambiguous message name %s"%message_type)
elif len(results) < 1:
raise RosMsgProtoException("Unknown message name %s"%message_type)
else:
message_type=results[0]
if mode == MODE_SRV:
msg_class = roslib.message.get_service_class(message_type)
if (msg_class == None):
raise RosMsgProtoException("Unknown service class: %s"%message_type)
instance = msg_class()._request_class()
elif mode == MODE_MSG:
msg_class = roslib.message.get_message_class(message_type)
if (msg_class == None):
raise RosMsgProtoException("Unknown message class: %s"%message_type)
instance = msg_class()
else:
raise RosMsgProtoException("Invalid mode: %s"%mode)
txt = get_yaml_for_msg(instance,
prefix = options.prefix,
flow_style_ = options.flow_style,
fill_arrays_ = not options.empty_arrays,
field_filter = field_filter)
if options.no_hyphens == True:
return txt
else:
return '"' + txt + '"'
except KeyError as e:
if not options.silent:
sys.stderr.write("Unknown message type: %s"%e, file=sys.stderr)
sys.exit(getattr(os, 'EX_USAGE', 1))
# except rospkg.InvalidROSPkgException as e:
# if not options.silent:
# print(file=sys.stderr, "Invalid package: '%s'"%e)
# sys.exit(getattr(os, 'EX_USAGE', 1))
except ValueError as e:
if not options.silent:
sys.stderr.write("Invalid type: '%s'"%e)
sys.exit(getattr(os, 'EX_USAGE', 1))
except RosMsgProtoException as e:
if not options.silent:
sys.stderr.write(str(e))
sys.exit(1)
except RosMsgProtoArgsException as e:
if not options.silent:
sys.stderr.write("%s"%e)
sys.exit(getattr(os, 'EX_USAGE', 1))
except KeyboardInterrupt:
pass
#### Start of rosmsg ####
try:
from cStringIO import StringIO # Python 2.x
except ImportError:
from io import StringIO # Python 3.x
def spec_to_str(msg_context, spec, buff=None, indent=''):
"""
Convert spec into a string representation. Helper routine for MsgSpec.
:param indent: internal use only, ``str``
:param buff: internal use only, ``StringIO``
:returns: string representation of spec, ``str``
"""
if buff is None:
buff = StringIO()
for c in spec.constants:
buff.write("%s%s %s=%s\n"%(indent, c.type, c.name, c.val_text))
for type_, name in zip(spec.types, spec.names):
buff.write("%s%s %s\n"%(indent, type_, name))
base_type = genmsg.msgs.bare_msg_type(type_)
if not base_type in genmsg.msgs.BUILTIN_TYPES:
subspec = msg_context.get_registered(base_type)
spec_to_str(msg_context, subspec, buff, indent + ' ')
return buff.getvalue()
def get_srv_text(type_, raw=False, rospack=None):
"""
Get .srv file for type_ as text
:param type_: service type, ``str``
:param raw: if True, include comments and whitespace (default False), ``bool``
:returns: text of .srv file, ``str``
@raise ROSMsgException: if type_ is unknown
"""
if rospack is None:
rospack = rospkg.RosPack()
srv_search_path = {}
msg_search_path = {}
for p in rospack.list():
package_paths = _get_package_paths(p, rospack)
msg_search_path[p] = [os.path.join(d, 'msg') for d in package_paths]
srv_search_path[p] = [os.path.join(d, 'srv') for d in package_paths]
#TODO: cache context somewhere
context = genmsg.MsgContext.create_default()
try:
spec = genmsg.load_srv_by_type(context, type_, srv_search_path)
genmsg.load_depends(context, spec, msg_search_path)
except Exception as e:
raise ROSMsgException("Unknown srv type [%s]: %s"%(type_, e))
if raw:
return spec.text
else:
return spec_to_str(context, spec.request)+'---\n'+spec_to_str(context, spec.response)
def get_msg_text(type_, raw=False, rospack=None):
"""
Get .msg file for type_ as text
:param type_: message type, ``str``
:param raw: if True, include comments and whitespace (default False), ``bool``
:returns: text of .msg file, ``str``
:raises :exc:`ROSMsgException` If type_ is unknown
"""
if rospack is None:
rospack = rospkg.RosPack()
search_path = {}
for p in rospack.list():
package_paths = _get_package_paths(p, rospack)
search_path[p] = [os.path.join(d, 'msg') for d in package_paths]
context = genmsg.MsgContext.create_default()
try:
spec = genmsg.load_msg_by_type(context, type_, search_path)
genmsg.load_depends(context, spec, search_path)
except Exception as e:
raise ROSMsgException("Unable to load msg [%s]: %s"%(type_, e))
if raw:
return spec.text
else:
return spec_to_str(context, spec)
def rosmsg_debug(rospack, mode, type_, raw=False):
"""
Prints contents of msg/srv file
:param mode: MODE_MSG or MODE_SRV, ``str``
"""
if mode == MODE_SRV:
print(get_srv_text(type_, raw=raw, rospack=rospack))
elif mode == MODE_MSG:
print(get_msg_text(type_, raw=raw, rospack=rospack))
else:
raise ROSMsgException("Invalid mode for debug: %s"%mode)
def list_srvs(package, rospack=None):
"""
List srvs contained in package
:param package: package name, ``str``
:param rospack: an optional rospack instance to be reused, ``rospkg.RosPack``
:returns: list of srvs in package, ``[str]``
"""
return list_types(package, mode=MODE_SRV, rospack=rospack)
def list_msgs(package, rospack=None):
"""
List msgs contained in package
:param package: package name, ``str``
:param rospack: an optional rospack instance to be reused, ``rospkg.RosPack``
:returns: list of msgs in package, ``[str]``
"""
return list_types(package, rospack=rospack)
def list_types(package, mode=MODE_MSG, rospack=None):
"""
Lists msg/srvs contained in package
:param package: package name, ``str``
:param mode: MODE_MSG or MODE_SRV. Defaults to msgs, ``str``
:param rospack: an optional rospack instance to be reused, ``rospkg.RosPack``
:returns: list of msgs/srv in package, ``[str]``
"""
if rospack is None:
rospack = rospkg.RosPack()
if mode == MODE_MSG:
subdir = 'msg'
elif mode == MODE_SRV:
subdir = 'srv'
else:
raise ValueError('Unknown mode for list_types: %s'%mode)
path = os.path.join(rospack.get_path(package), subdir)
return [genmsg.resource_name(package, t) for t in _list_types(path, subdir, mode)]
def _msg_filter(ext):
def mfilter(f):
"""
Predicate for filtering directory list. matches message files
:param f: filename, ``str``
"""
return os.path.isfile(f) and f.endswith(ext)
return mfilter
def _list_types(path, subdir, ext):
"""
List all messages in the specified package
:param package str: name of package to search
:param include_depends bool: if True, will also list messages in package dependencies
:returns [str]: message type names
"""
types = _list_resources(path, _msg_filter(ext))
result = [x[:-len(ext)] for x in types]
result.sort()
return result
def _list_resources(path, rfilter=os.path.isfile):
"""
List resources in a package directory within a particular
subdirectory. This is useful for listing messages, services, etc...
:param rfilter: resource filter function that returns true if filename is the desired resource type, ``fn(filename)->bool``
"""
resources = []
if os.path.isdir(path):
resources = [f for f in os.listdir(path) if rfilter(os.path.join(path, f))]
else:
resources = []
return resources
def iterate_packages(rospack, mode):
"""
Iterator for packages that contain messages/services
:param mode: .msg or .srv, ``str``
"""
if mode == MODE_MSG:
subdir = 'msg'
elif mode == MODE_SRV:
subdir = 'srv'
else:
raise ValueError('Unknown mode for iterate_packages: %s'%mode)
pkgs = rospack.list()
for p in pkgs:
package_paths = _get_package_paths(p, rospack)
for package_path in package_paths:
d = os.path.join(package_path, subdir)
if os.path.isdir(d):
yield p, d
_catkin_workspace_to_source_spaces = {}
_catkin_source_path_to_packages = {}
def _get_package_paths(pkgname, rospack):
paths = []
path = rospack.get_path(pkgname)
paths.append(path)
results = find_in_workspaces(search_dirs=['share'], project=pkgname, first_match_only=True, workspace_to_source_spaces=_catkin_workspace_to_source_spaces, source_path_to_packages=_catkin_source_path_to_packages)
if results and results[0] != path:
paths.append(results[0])
return paths
def rosmsg_search(rospack, mode, base_type):
"""
Iterator for all packages that contain a message matching base_type
:param base_type: message base type to match, e.g. 'String' would match std_msgs/String, ``str``
"""
for p, path in iterate_packages(rospack, mode):
if os.path.isfile(os.path.join(path, "%s%s"%(base_type, mode))):
yield genmsg.resource_name(p, base_type)
def _stdin_arg(parser, full):
options, args = parser.parse_args(sys.argv[2:])
# read in args from stdin pipe if not present
if not args:
arg = None
while not arg:
arg = sys.stdin.readline().strip()
return options, arg
else:
if len(args) > 1:
parser.error("you may only specify one %s"%full)
return options, args[0]
def rosmsg_cmd_show(mode, full):
cmd = "ros%s"%(mode[1:])
parser = OptionParser(usage="usage: %s show [options] <%s>"%(cmd, full))
parser.add_option("-r", "--raw",
dest="raw", default=False,action="store_true",
help="show raw message text, including comments")
parser.add_option("-b", "--bag",
dest="bag", default=None,
help="show message from .bag file", metavar="BAGFILE")
options, arg = _stdin_arg(parser, full)
if arg.endswith(mode):
arg = arg[:-(len(mode))]
# try to catch the user specifying code-style types and error
if '::' in arg:
parser.error(cmd+" does not understand C++-style namespaces (i.e. '::').\nPlease refer to msg/srv types as 'package_name/Type'.")
elif '.' in arg:
parser.error("invalid message type '%s'.\nPlease refer to msg/srv types as 'package_name/Type'." % arg)
if arg.find('pb_msgs/') >= 0:
print("Protobuf message not support sub-commond 'show' yet")
exit()
if options.bag:
bag_file = options.bag
if not os.path.exists(bag_file):
raise ROSMsgException("ERROR: bag file [%s] does not exist"%bag_file)
for topic, msg, t in rosbag.Bag(bag_file).read_messages(raw=True):
datatype, _, _, _, pytype = msg
if datatype == arg:
print(get_msg_text(datatype, options.raw, pytype._full_text))
break
else:
rospack = rospkg.RosPack()
if '/' in arg: #package specified
rosmsg_debug(rospack, mode, arg, options.raw)
else:
found_msgs = list(rosmsg_search(rospack, mode, arg))
if not found_msgs:
print("Could not find msg '%s'" % arg, file=sys.stderr)
return 1
for found in found_msgs:
print("[%s]:"%found)
rosmsg_debug(rospack, mode, found, options.raw)
def rosmsg_md5(mode, type_):
try:
if mode == MODE_MSG:
msg_class = roslib.message.get_message_class(type_)
else:
msg_class = roslib.message.get_service_class(type_)
except ImportError:
raise IOError("cannot load [%s]"%(type_))
if msg_class is not None:
return msg_class._md5sum
else:
raise IOError("cannot load [%s]"%(type_))
def rosmsg_cmd_md5(mode, full):
parser = OptionParser(usage="usage: ros%s md5 <%s>"%(mode[1:], full))
options, arg = _stdin_arg(parser, full)
if '/' in arg: #package specified
try:
md5 = rosmsg_md5(mode, arg)
print(md5)
except IOError:
print("Cannot locate [%s]"%arg, file=sys.stderr)
else:
rospack = rospkg.RosPack()
matches = [m for m in rosmsg_search(rospack, mode, arg)]
for found in matches:
try:
md5 = rosmsg_md5(mode, found)
print("[%s]: %s"%(found, md5))
except IOError:
print("Cannot locate [%s]"%found, file=sys.stderr)
if not matches:
print("No messages matching the name [%s]"%arg, file=sys.stderr)
def rosmsg_cmd_package(mode, full):
parser = OptionParser(usage="usage: ros%s package <package>"%mode[1:])
parser.add_option("-s",
dest="single_line", default=False,action="store_true",
help="list all msgs on a single line")
options, arg = _stdin_arg(parser, full)
joinstring='\n'
if options.single_line:
joinstring=' '
print(joinstring.join(list_types(arg, mode=mode)))
def rosmsg_cmd_packages(mode, full, argv=None):
if argv is None:
argv = sys.argv[1:]
parser = OptionParser(usage="usage: ros%s packages"%mode[1:])
parser.add_option("-s",
dest="single_line", default=False,action="store_true",
help="list all packages on a single line")
options, args = parser.parse_args(argv[1:])
rospack = rospkg.RosPack()
joinstring='\n'
if options.single_line:
joinstring=' '
p1 = [p for p, _ in iterate_packages(rospack, mode)]
p1.sort()
print(joinstring.join(p1))
def rosmsg_cmd_list(mode, full, argv=None):
if argv is None:
argv = sys.argv[1:]
parser = OptionParser(usage="usage: ros%s list"%mode[1:])
options, args = parser.parse_args(argv[1:])
if mode == MODE_MSG:
subdir = 'msg'
elif mode == MODE_SRV:
subdir = 'srv'
else:
raise ValueError('Unknown mode for iterate_packages: %s'%mode)
rospack = rospkg.RosPack()
packs = sorted([x for x in iterate_packages(rospack, mode)])
for (p, direc) in packs:
for file in _list_types(direc, subdir, mode):
print( "%s/%s"%(p, file))
def fullusage(mode):
"""
:param cmd: command name, ``str``
:returns: usage text for cmd, ``str``
"""
cmd = 'ros' + mode[1:]
if mode == MODE_MSG:
type_ = 'Message'
else:
type_ = 'Service'
type_lower = type_.lower()
return """%(cmd)s is a command-line tool for displaying information about ROS %(type_)s types.
Commands:
\t%(cmd)s show\tShow %(type_lower)s description
\t%(cmd)s list\tList all %(type_lower)ss
\t%(cmd)s md5\tDisplay %(type_lower)s md5sum
\t%(cmd)s package\tList %(type_lower)ss in a package
\t%(cmd)s packages\tList packages that contain %(type_lower)ss
Type %(cmd)s <command> -h for more detailed usage
"""%locals()
def rosmsgmain(mode=MODE_MSG):
"""
Main entry point for command-line tools (rosmsg/rossrv).
rosmsg can interact with either ros messages or ros services. The mode
param indicates which
:param mode: MODE_MSG or MODE_SRV, ``str``
"""
try:
if mode == MODE_MSG:
ext, full = mode, "message type"
elif mode == MODE_SRV:
ext, full = mode, "service type"
else:
raise ROSMsgException("Invalid mode: %s"%mode)
if len(sys.argv) == 1:
print(fullusage(mode))
sys.exit(0)
command = sys.argv[1]
if command == 'show':
sys.exit(rosmsg_cmd_show(ext, full))
elif command == 'package':
rosmsg_cmd_package(ext, full)
elif command == 'packages':
rosmsg_cmd_packages(ext, full)
elif command == 'list':
rosmsg_cmd_list(ext, full)
elif command == 'md5':
rosmsg_cmd_md5(ext, full)
elif command == '--help':
print(fullusage(mode))
sys.exit(0)
else:
print(fullusage(mode))
sys.exit(getattr(os, 'EX_USAGE', 1))
except KeyError as e:
print("Unknown message type: %s"%e, file=sys.stderr)
sys.exit(getattr(os, 'EX_USAGE', 1))
except rospkg.ResourceNotFound as e:
print("Invalid package: %s"%e, file=sys.stderr)
sys.exit(getattr(os, 'EX_USAGE', 1))
except ValueError as e:
print("Invalid type: '%s'"%e, file=sys.stderr)
sys.exit(getattr(os, 'EX_USAGE', 1))
except ROSMsgException as e:
print(str(e), file=sys.stderr)
sys.exit(1)
except KeyboardInterrupt:
pass
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rospbconvertor/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.3)
project(rospbconvertor)
find_package(catkin REQUIRED)
catkin_package()
catkin_python_setup()
catkin_install_python(PROGRAMS scripts/rospbconvertor
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rospbconvertor/package.xml | <package>
<name>rospbconvertor</name>
<version>1.0.0</version>
<description>
rospbconvertor used to transform Std::String to pb mseesage.
</description>
<license>Licensed under the Apache License, Version 2.0</license>
<maintainer email="info@apollo.auto">Apollo Authors</maintainer>
<author>Apollo Authors</author>
<buildtool_depend version_gte="0.5.78">catkin</buildtool_depend>
<run_depend version_gte="0.5.4">genpy</run_depend>
<run_depend>rospy</run_depend>
</package>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rospbconvertor/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=['rospbconvertor'],
package_dir={'': 'src'},
scripts=['scripts/rospbconvertor'],
requires=['genmsg', 'genpy', 'roslib', 'rospkg']
)
setup(**d)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rospbconvertor/.tar | {!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/rostopic/1.11.21-0.tar.gz',
!!python/unicode 'version': ros_comm-release-release-indigo-rostopic-1.11.21-0}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rospbconvertor | apollo_public_repos/apollo-platform/ros/ros_comm/rospbconvertor/scripts/rospbconvertor | #!/usr/bin/python
from rospbconvertor import rospbconvertor
rospbconvertor.rospbconvert_main()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rospbconvertor/src | apollo_public_repos/apollo-platform/ros/ros_comm/rospbconvertor/src/rospbconvertor/batch_include.py | from modules.canbus.proto import chassis_detail_pb2
from modules.canbus.proto import chassis_pb2
from modules.common.monitor.proto import monitor_pb2
from modules.common.configs.proto import config_extrinsics_pb2
from modules.common.configs.proto import vehicle_config_pb2
from modules.common.proto import geometry_pb2
from modules.common.proto import header_pb2
from modules.control.proto import control_cmd_pb2
from modules.control.proto import pad_msg_pb2
from modules.decision.proto import decision_pb2
from modules.localization.proto import localization_pb2
from modules.perception.proto import perception_obstacle_pb2
from modules.perception.proto import traffic_light_detection_pb2
from modules.planning.proto import planning_internal_pb2
from modules.planning.proto import planning_pb2
from modules.prediction.proto import prediction_obstacle_pb2
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rospbconvertor/src | apollo_public_repos/apollo-platform/ros/ros_comm/rospbconvertor/src/rospbconvertor/Message.py | #!/usr/bin/env python
######################################################
#
# Message Handle
#
######################################################
"""
Message Handle
"""
import curses
import rospy
import batch_include
class Message(object):
"""
Message Class
"""
def __init__(self, name, proto_name, topic, topic_out):
self.name = name
self.topic = topic
self.proto_name = 'batch_include.' + proto_name[:-2]
self.proto = eval('batch_include.' + proto_name)
self.topic_out = topic_out
self.publisher = rospy.Publisher(topic_out, eval(self.proto_name), queue_size=16)
def callback(self, data):
"""
callback function
"""
self.proto.ParseFromString(data.data)
self.publisher.publish(self.proto)
#print("recv %s, pub %s " %(self.topic, self.topic_out))
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rospbconvertor/src | apollo_public_repos/apollo-platform/ros/ros_comm/rospbconvertor/src/rospbconvertor/rospbconvertor.py | #!/usr/bin/env python
import os
import random
import rospy
import threading
import traceback
from std_msgs.msg import String
from Message import Message
primitive = (int, str, bool, unicode)
class Convertor(object):
"""
Plotter Class
"""
def __init__(self):
# topic
self.META_DATA_FILE = os.path.join(os.path.dirname(__file__), 'meta.data')
self.messages = []
try:
with open(self.META_DATA_FILE) as f:
for line in f:
module_name, proto_name, topic, topic_out = line.strip().split(' ')
if module_name == 'MODULE' or proto_name == '#' or\
topic == '#' or topic_out == '#':
pass
else:
cur_message = Message(module_name, proto_name,
topic, topic_out)
self.messages.append(cur_message)
except Exception as e:
print '{0} open failed! with error: {1}'.format(self.META_DATA_FILE, e.message)
exit(1)
def main():
"""
Main function
"""
rospy.init_node('pb_convertor', anonymous=True)
cov = Convertor()
sublist = []
for msg in cov.messages:
sublist.append(rospy.Subscriber(msg.topic, String, msg.callback, queue_size=16))
rospy.spin()
def rospbconvert_main():
try:
main()
except Exception as e:
tb = traceback.format_exc()
print tb
if __name__ == '__main__':
try:
main()
except Exception as e:
tb = traceback.format_exc()
print tb
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rospbconvertor/src | apollo_public_repos/apollo-platform/ros/ros_comm/rospbconvertor/src/rospbconvertor/meta.data | MODULE class topic topic_out
CHASSIS chassis_pb2.Chassis() /planning/proxy/DuDriveChassis /apollo/canbus/chassis
CONTROL control_cmd_pb2.ControlCommand() /pnc/control /apollo/control
LOCALIZATION localization_pb2.LocalizationEstimate() /localization/100hz/localization_pose /apollo/localization/pose
PLANNING planning_pb2.ADCTrajectory() /pnc/planning /apollo/planning
Pad pad_msg_pb2.PadMessage() /pnc/control/PadMessage /apollo/control/pad
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.3)
project(rosgraph)
find_package(catkin REQUIRED)
catkin_package()
catkin_python_setup()
# logging config file goes in both etc and package layout (for now).
# want to get rid of package layout copy, but need to be able to
# locate etc first.
install(FILES conf/python_logging.conf
DESTINATION ${CATKIN_GLOBAL_ETC_DESTINATION}/ros)
install(FILES conf/python_logging.conf
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/conf)
catkin_install_python(PROGRAMS scripts/rosgraph
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
if(CATKIN_ENABLE_TESTING)
catkin_add_nosetests(test)
endif()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/package.xml | <package>
<name>rosgraph</name>
<version>1.11.21</version>
<description>
rosgraph contains the rosgraph command-line tool, which prints
information about the ROS Computation Graph. It also provides an
internal library that can be used by graphical tools.
</description>
<maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer>
<license>BSD</license>
<url>http://ros.org/wiki/rosgraph</url>
<author>Ken Conley</author>
<buildtool_depend version_gte="0.5.78">catkin</buildtool_depend>
<run_depend>python-netifaces</run_depend>
<run_depend>python-rospkg</run_depend>
<test_depend>python-mock</test_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/rosgraph/rosdoc.yaml | - builder: epydoc
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/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=['rosgraph', 'rosgraph.impl'],
package_dir={'': 'src'},
scripts=['scripts/rosgraph'],
requires=['rospkg']
)
setup(**d)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/.tar | {!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/rosgraph/1.11.21-0.tar.gz',
!!python/unicode 'version': ros_comm-release-release-indigo-rosgraph-1.11.21-0}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/CHANGELOG.rst | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package rosgraph
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1.11.21 (2017-03-06)
--------------------
* increase request_queue_size for xmlrpc server (`#849 <https://github.com/ros/ros_comm/issues/849>`_)
1.11.20 (2016-06-27)
--------------------
* fix symlink of the log dir itself as latest (`#795 <https://github.com/ros/ros_comm/pull/795>`_)
1.11.19 (2016-04-18)
--------------------
* fix str conversion in encode_ros_handshake_header (`#792 <https://github.com/ros/ros_comm/pull/792>`_)
1.11.18 (2016-03-17)
--------------------
1.11.17 (2016-03-11)
--------------------
* fix raising classes not derived from `Exception` which caused a TypeError (`#761 <https://github.com/ros/ros_comm/pull/761>`_)
* fix handshake header with Python 3 (`#759 <https://github.com/ros/ros_comm/issues/759>`_)
* fix encoding of header fields (`#704 <https://github.com/ros/ros_comm/issues/704>`_)
1.11.16 (2015-11-09)
--------------------
1.11.15 (2015-10-13)
--------------------
1.11.14 (2015-09-19)
--------------------
* create a symlink to the latest log directory (`#659 <https://github.com/ros/ros_comm/pull/659>`_)
1.11.13 (2015-04-28)
--------------------
1.11.12 (2015-04-27)
--------------------
1.11.11 (2015-04-16)
--------------------
1.11.10 (2014-12-22)
--------------------
* rosconsole format for rospy (`#517 <https://github.com/ros/ros_comm/issues/517>`_)
* fix exception at roscore startup if python has IPv6 disabled (`#515 <https://github.com/ros/ros_comm/issues/515>`_)
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 (`#426 <https://github.com/ros/ros_comm/issues/426>`_, `#427 <https://github.com/ros/ros_comm/issues/427>`_, `#429 <https://github.com/ros/ros_comm/issues/429>`_)
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)
-------------------
1.9.54 (2014-01-27)
-------------------
1.9.53 (2014-01-14)
-------------------
1.9.52 (2014-01-08)
-------------------
1.9.51 (2014-01-07)
-------------------
* allow different 127. addresses than 127.0.0.1 (`#315 <https://github.com/ros/ros_comm/issues/315>`_)
* work around for nose 1.3.0 bug (`#323 <https://github.com/ros/ros_comm/issues/323>`_)
1.9.50 (2013-10-04)
-------------------
1.9.49 (2013-09-16)
-------------------
1.9.48 (2013-08-21)
-------------------
1.9.47 (2013-07-03)
-------------------
* check for CATKIN_ENABLE_TESTING to enable configure without tests
1.9.46 (2013-06-18)
-------------------
1.9.45 (2013-06-06)
-------------------
* add warnings for obviously wrong environment variables ROS_HOSTNAME and ROS_IP (`#134 <https://github.com/ros/ros_comm/issues/134>`_)
* fix exception on netifaces.ifaddresses() (`#211 <https://github.com/ros/ros_comm/issues/211>`_, `#213 <https://github.com/ros/ros_comm/issues/213>`_) (regression from 1.9.42)
1.9.44 (2013-03-21)
-------------------
1.9.43 (2013-03-13)
-------------------
1.9.42 (2013-03-08)
-------------------
* replace custom code with Python module netifaces (`#130 <https://github.com/ros/ros_comm/issues/130>`_)
* 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>`_)
1.9.39 (2012-12-29)
-------------------
* first public release for Groovy
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/test/test_names.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.
import os
import sys
def test_get_ros_namespace():
if 'ROS_NAMESPACE' in os.environ:
rosns = os.environ['ROS_NAMESPACE']
del os.environ['ROS_NAMESPACE']
else:
rosns = None
sysargv = sys.argv
from rosgraph.names import get_ros_namespace
try:
sys.argv = []
assert '/' == get_ros_namespace()
assert '/' == get_ros_namespace(argv=[])
assert '/' == get_ros_namespace(env={})
assert '/' == get_ros_namespace(env={}, argv=[])
os.environ['ROS_NAMESPACE'] = 'unresolved'
assert '/unresolved/' == get_ros_namespace()
assert '/unresolved/' == get_ros_namespace(env={'ROS_NAMESPACE': 'unresolved'})
sys.argv = ['foo', '__ns:=unresolved_override']
assert '/unresolved_override/' == get_ros_namespace(env={'ROS_NAMESPACE': 'unresolved'})
assert '/override2/' == get_ros_namespace(env={'ROS_NAMESPACE': 'unresolved'}, argv=['foo', '__ns:=override2'])
sys.argv = []
os.environ['ROS_NAMESPACE'] = '/resolved/'
assert '/resolved/' == get_ros_namespace()
assert '/resolved/' == get_ros_namespace(env={'ROS_NAMESPACE': '/resolved'})
del os.environ['ROS_NAMESPACE']
sys.argv = ['foo', '__ns:=unresolved_ns']
assert '/unresolved_ns/' == get_ros_namespace()
assert '/unresolved_ns2/' == get_ros_namespace(argv=['foo', '__ns:=unresolved_ns2'])
sys.argv = ['foo', '__ns:=/resolved_ns/']
assert '/resolved_ns/' == get_ros_namespace()
assert '/resolved_ns2/' == get_ros_namespace(argv=['foo', '__ns:=resolved_ns2'])
finally:
sys.argv = sysargv
# restore
if rosns:
os.environ['ROS_NAMESPACE'] = rosns
def test_make_global_ns():
from rosgraph.names import make_global_ns
for n in ['~foo']:
try:
make_global_ns(n)
assert False, "make_global_ns should fail on %s"%n
except ValueError: pass
assert '/foo/' == make_global_ns('foo')
assert '/' == make_global_ns('')
assert '/foo/' == make_global_ns('/foo')
assert '/foo/' == make_global_ns('/foo/')
assert '/foo/bar/' == make_global_ns('/foo/bar')
assert '/foo/bar/' == make_global_ns('/foo/bar/')
def test_make_caller_id():
from rosgraph.names import make_caller_id
if 'ROS_NAMESPACE' is os.environ:
rosns = os.environ['ROS_NAMESPACE']
del os.environ['ROS_NAMESPACE']
else:
rosns = None
for n in ['~name']:
try:
make_caller_id('~name') # illegal
assert False, "make_caller_id should fail on %s"%n
except ValueError:
pass
assert '/node/' == make_caller_id('node')
assert '/bar/node/' == make_caller_id('bar/node')
assert '/bar/node/' == make_caller_id('/bar/node')
os.environ['ROS_NAMESPACE'] = '/test/'
assert '/test/node/' == make_caller_id('node')
assert '/test/bar/node/' == make_caller_id('bar/node')
assert '/bar/node/' == make_caller_id('/bar/node')
# restore
if rosns:
os.environ['ROS_NAMESPACE'] = rosns
def test_is_global():
from rosgraph.names import is_global
try:
is_global(None)
assert False, "is_global should raise exception on invalid param"
except: pass
tests = ['/', '/global', '/global2']
for t in tests:
assert is_global(t)
fails = ['', 'not_global', 'not/global']
for t in fails:
assert not is_global(t)
def test_is_private():
from rosgraph.names import is_private
try:
is_private(None)
assert False, "is_private should raise exception on invalid param"
except: pass
tests = ['~name', '~name/sub']
for t in tests:
assert is_private(t)
fails = ['', 'not_private', 'not/private', 'not/~private', '/not/~private']
for t in fails:
assert not is_private(t)
def test_namespace():
from rosgraph.names import namespace
try:
namespace(1)
assert False, "1"
except TypeError: pass
try:
namespace(None)
assert False, "None"
except ValueError: pass
assert '/'== namespace('')
assert '/'== namespace('/')
assert '/'== namespace('/foo')
assert '/'== namespace('/foo/')
assert '/foo/'== namespace('/foo/bar')
assert '/foo/'== namespace('/foo/bar/')
assert '/foo/bar/'== namespace('/foo/bar/baz')
assert '/foo/bar/'== namespace('/foo/bar/baz/')
# unicode tests
assert u'/'== namespace(u'')
assert u'/'== namespace(u'/')
assert u'/foo/bar/'== namespace(u'/foo/bar/baz/')
def test_nsjoin():
from rosgraph.names import ns_join
# private and global names cannot be joined
assert '~name' == ns_join('/foo', '~name')
assert '/name' == ns_join('/foo', '/name')
assert '~name' == ns_join('~', '~name')
assert '/name' == ns_join('/', '/name')
# ns can be '~' or '/'
assert '~name' == ns_join('~', 'name')
assert '/name' == ns_join('/', 'name')
assert '/ns/name' == ns_join('/ns', 'name')
assert '/ns/name' == ns_join('/ns/', 'name')
assert '/ns/ns2/name' == ns_join('/ns', 'ns2/name')
assert '/ns/ns2/name' == ns_join('/ns/', 'ns2/name')
# allow ns to be empty
assert 'name' == ns_join('', 'name')
def test_load_mappings():
from rosgraph.names import load_mappings
assert {} == load_mappings([])
assert {} == load_mappings(['foo'])
assert {} == load_mappings([':='])
assert {} == load_mappings([':=:='])
assert {} == load_mappings(['f:='])
assert {} == load_mappings([':=b'])
assert {} == load_mappings(['foo:=bar:=baz'])
# should ignore node param assignments
assert {} == load_mappings(['_foo:=bar'])
assert {'foo': 'bar'} == load_mappings(['foo:=bar'])
# should allow double-underscore names
assert {'__foo': 'bar'} == load_mappings(['__foo:=bar'])
assert {'foo': 'bar'} == load_mappings(['./f', '-x', '--blah', 'foo:=bar'])
assert {'a': '1', 'b': '2', 'c': '3'} == load_mappings(['c:=3', 'c:=', ':=3', 'a:=1', 'b:=2'])
def test_is_legal_name():
from rosgraph.names import is_legal_name
failures = [None,
'foo++', 'foo-bar', '#foo',
'hello\n', '\t', ' name', 'name ',
'f//b',
'1name', 'foo\\']
for f in failures:
assert not is_legal_name(f), f
tests = ['',
'f', 'f1', 'f_', 'f/', 'foo', 'foo_bar', 'foo/bar', 'foo/bar/baz',
'~f', '~a/b/c',
'~/f',
'/a/b/c/d', '/']
for t in tests:
assert is_legal_name(t), "[%s]"%t
def test_is_legal_base_name():
from rosgraph.names import is_legal_base_name
failures = [None, '', 'hello\n', '\t', 'foo++', 'foo-bar', '#foo',
'f/', 'foo/bar', '/', '/a',
'f//b',
'~f', '~a/b/c',
' name', 'name ',
'1name', 'foo\\']
for f in failures:
assert not is_legal_base_name(f), f
tests = ['f', 'f1', 'f_', 'foo', 'foo_bar']
for t in tests:
assert is_legal_base_name(t), "[%s]"%t
def test_resolve_name():
from rosgraph.names import resolve_name
# TODO: test with remappings
tests = [
('', '/', '/'),
('', '/node', '/'),
('', '/ns1/node', '/ns1/'),
('foo', '', '/foo'),
('foo/', '', '/foo'),
('/foo', '', '/foo'),
('/foo/', '', '/foo'),
('/foo', '/', '/foo'),
('/foo/', '/', '/foo'),
('/foo', '/bar', '/foo'),
('/foo/', '/bar', '/foo'),
('foo', '/ns1/ns2', '/ns1/foo'),
('foo', '/ns1/ns2/', '/ns1/foo'),
('foo', '/ns1/ns2/ns3/', '/ns1/ns2/foo'),
('foo/', '/ns1/ns2', '/ns1/foo'),
('/foo', '/ns1/ns2', '/foo'),
('foo/bar', '/ns1/ns2', '/ns1/foo/bar'),
('foo//bar', '/ns1/ns2', '/ns1/foo/bar'),
('foo/bar', '/ns1/ns2/ns3', '/ns1/ns2/foo/bar'),
('foo//bar//', '/ns1/ns2/ns3', '/ns1/ns2/foo/bar'),
('~foo', '/', '/foo'),
('~foo', '/node', '/node/foo'),
('~foo', '/ns1/ns2', '/ns1/ns2/foo'),
('~foo/', '/ns1/ns2', '/ns1/ns2/foo'),
('~foo/bar', '/ns1/ns2', '/ns1/ns2/foo/bar'),
# #3044
('~/foo', '/', '/foo'),
('~/foo', '/node', '/node/foo'),
('~/foo', '/ns1/ns2', '/ns1/ns2/foo'),
('~/foo/', '/ns1/ns2', '/ns1/ns2/foo'),
('~/foo/bar', '/ns1/ns2', '/ns1/ns2/foo/bar'),
]
for name, node_name, v in tests:
assert v == resolve_name(name, node_name)
def test_anonymous_name():
from rosgraph.names import anonymous_name, is_legal_name
val = anonymous_name('foo')
assert 'foo' in val
assert 'foo' != val
assert val != anonymous_name('foo')
assert not '/' in val
assert is_legal_name(val)
def test_script_resolve_name():
from rosgraph.names import script_resolve_name, get_ros_namespace, ns_join
assert '/global' == script_resolve_name('/myscript', '/global')
val = script_resolve_name('/myscript', '')
assert get_ros_namespace() == val, val
val = script_resolve_name('/myscript', 'foo')
assert ns_join(get_ros_namespace(), 'foo') == val, val
assert '/myscript/private' == script_resolve_name('/myscript', '~private')
def test_canonicalize_name():
from rosgraph.names import canonicalize_name
tests = [
('', ''),
('/', '/'),
('foo', 'foo'),
('/foo', '/foo'),
('/foo/', '/foo'),
('/foo/bar', '/foo/bar'),
('/foo/bar/', '/foo/bar'),
('/foo/bar//', '/foo/bar'),
('/foo//bar', '/foo/bar'),
('//foo/bar', '/foo/bar'),
('foo/bar', 'foo/bar'),
('foo//bar', 'foo/bar'),
('foo/bar/', 'foo/bar'),
('/foo/bar', '/foo/bar'),
]
for t, v in tests:
assert v == canonicalize_name(t)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/test/test_rosenv.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2011, 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 test_vars():
import rosgraph.rosenv
assert 'ROS_MASTER_URI' == rosgraph.rosenv.ROS_MASTER_URI
assert rosgraph.rosenv.ROS_IP == 'ROS_IP'
assert rosgraph.rosenv.ROS_HOSTNAME == 'ROS_HOSTNAME'
assert rosgraph.rosenv.ROS_NAMESPACE == 'ROS_NAMESPACE'
def test_get_master_uri():
from rosgraph.rosenv import get_master_uri
val = get_master_uri()
if 'ROS_MASTER_URI' in os.environ:
assert val == os.environ['ROS_MASTER_URI']
# environment override
val = get_master_uri(env=dict(ROS_MASTER_URI='foo'))
assert val == 'foo'
# argv override precedence, first arg wins
val = get_master_uri(env=dict(ROS_MASTER_URI='foo'), argv=['__master:=bar', '__master:=bar2'])
assert val == 'bar'
# empty env
assert None == get_master_uri(env={})
# invalid argv
try:
val = get_master_uri(argv=['__master:='])
assert False, "should have failed"
except ValueError:
pass
# invalid argv
try:
val = get_master_uri(argv=['__master:=foo:=bar'])
assert False, "should have failed"
except ValueError:
pass
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/test/test_rosgraph_masterapi_offline.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.
import os
import sys
import unittest
import rosgraph.masterapi
_ID = '/caller_id'
_MASTER_URI = 'http://localhost:12345'
class MasterMock(object):
"""
Mock for testing Master without using actual master
"""
def __init__(self):
self.call = None
self.return_val = None
def getMasterUri(self, caller_id):
self.call = ('getMasterUri', caller_id)
return self.return_val
def getPid(self, caller_id):
self.call = ('getPid', caller_id)
return self.return_val
def getUri(self, caller_id):
self.call = ('getUri', caller_id)
return self.return_val
def registerService(self, caller_id, service, service_api, caller_api):
self.call = ('registerService', caller_id, service, service_api, caller_api)
return self.return_val
def lookupService(self, caller_id, service):
self.call = ('lookupService', caller_id, service)
return self.return_val
def unregisterService(self, caller_id, service, service_api):
self.call = ('unregisterService', caller_id, service, service_api)
return self.return_val
def registerSubscriber(self, caller_id, topic, topic_type, caller_api):
self.call = ('registerSubscriber', caller_id, topic, topic_type, caller_api)
return self.return_val
def unregisterSubscriber(self, caller_id, topic, caller_api):
self.call = ('unregisterSubscriber', caller_id, topic, caller_api)
return self.return_val
def registerPublisher(self, caller_id, topic, topic_type, caller_api):
self.call = ('registerPublisher', caller_id, topic, topic_type, caller_api)
return self.return_val
def unregisterPublisher(self, caller_id, topic, caller_api):
self.call = ('unregisterPublisher', caller_id, topic, caller_api)
return self.return_val
def lookupNode(self, caller_id, node_name):
self.call = ('lookupNode', caller_id, node_name)
return self.return_val
def getPublishedTopics(self, caller_id, subgraph):
self.call = ('getPublishedTopics', caller_id, subgraph)
return self.return_val
def getTopicTypes(self, caller_id):
self.call = ('getTopicTypes', caller_id)
return self.return_val
def getSystemState(self, caller_id):
self.call = ('getSystemState', caller_id)
return self.return_val
def getParam(self, caller_id, p):
self.call = ('getParam', caller_id, p)
return self.return_val
def hasParam(self, caller_id, p):
self.call = ('hasParam', caller_id, p)
return self.return_val
def deleteParam(self, caller_id, p):
self.call = ('deleteParam', caller_id, p)
return self.return_val
def searchParam(self, caller_id, p):
self.call = ('searchParam', caller_id, p)
return self.return_val
def setParam(self, caller_id, p, v):
self.call = ('setParam', caller_id, p, v)
return self.return_val
def subscribeParam(self, caller_id, api, p):
self.call = ('subscribeParam', caller_id, api, p)
return self.return_val
def unsubscribeParam(self, caller_id, api, p):
self.call = ('unsubscribeParam', caller_id, api, p)
return self.return_val
def getParamNames(self, caller_id):
self.call = ('getParamNames', caller_id)
return self.return_val
class MasterApiOfflineTest(unittest.TestCase):
def setUp(self):
self.m = rosgraph.masterapi.Master(_ID, master_uri = _MASTER_URI)
# replace xmlrpclib server proxy with mock
self.m.handle = MasterMock()
def throw_failure(self, attr, args, ret_val):
self.m.handle.return_val = ret_val
f = getattr(self.m, attr)
try:
f(*args)
self.fail("[%s] should have thrown Failure with args [%s], ret_val [%s]"%(attr, str(args), str(ret_val)))
except rosgraph.masterapi.Failure:
pass
def throw_error(self, attr, args, ret_val):
self.m.handle.return_val = ret_val
f = getattr(self.m, attr)
try:
f(*args)
self.fail("[%s] should have thrown Error with args [%s], ret_val [%s]"%(attr, str(args), str(ret_val)))
except rosgraph.masterapi.Error:
pass
def test_Master(self):
# test constructor args
m = rosgraph.masterapi.Master(_ID, master_uri = 'http://localhost:12345')
self.assertEquals(_ID, m.caller_id)
self.assertEquals(_MASTER_URI, m.master_uri)
reset_uri = False
if 'ROS_MASTER_URI' not in os.environ:
os.environ['ROS_MASTER_URI'] = 'http://localhost:21311'
try:
m = rosgraph.masterapi.Master(_ID)
self.assertEquals(os.environ['ROS_MASTER_URI'], m.master_uri)
id = '/some/other/id'
m = rosgraph.masterapi.Master(id)
self.assertEquals(id, m.caller_id)
finally:
if reset_uri:
del os.environ['ROS_MASTER_URI']
def test_getPid(self):
h = self.m.handle
r = 1235
h.return_val = (1, '', r)
self.assertEquals(r, self.m.getPid())
self.assertEquals(('getPid',_ID), h.call)
self.throw_failure('getPid', (), (0, '', r))
self.throw_error('getPid', (), (-1, '', r))
def test_getPid(self):
h = self.m.handle
r = 'http://foo:1234'
h.return_val = (1, '', r)
self.assertEquals(r, self.m.getUri())
self.assertEquals(('getUri',_ID), h.call)
self.throw_failure('getUri', (), (0, '', r))
self.throw_error('getUri', (), (-1, '', r))
def test_lookupService(self):
h = self.m.handle
r = 'rosrpc://localhost:12345'
h.return_val = (1, '', r)
self.assertEquals(r, self.m.lookupService('/bar/service'))
self.assertEquals(('lookupService',_ID, '/bar/service'), h.call)
self.throw_failure('lookupService', ('/bar/service',), (0, '', r))
self.throw_error('lookupService', ('/bar/service',), (-1, '', r))
def test_registerService(self):
h = self.m.handle
r = 11
h.return_val = (1, '', r)
self.assertEquals(r, self.m.registerService('/bar/service', 'rosrpc://localhost:9812', 'http://localhost:893'))
self.assertEquals(('registerService',_ID, '/bar/service', 'rosrpc://localhost:9812', 'http://localhost:893'), h.call)
args = ('/bar/service', 'rosrpc://localhost:9812', 'http://localhost:893')
self.throw_failure('registerService', args, (0, '', r))
self.throw_error('registerService', args, (-1, '', r))
def test_unregisterService(self):
h = self.m.handle
r = 1
h.return_val = (1, '', r)
self.assertEquals(r, self.m.unregisterService('/bar/service', 'rosrpc://localhost:9812'))
self.assertEquals(('unregisterService',_ID, '/bar/service', 'rosrpc://localhost:9812'), h.call)
args = ('/bar/service', 'rosrpc://localhost:9812')
self.throw_failure('unregisterService', args, (0, '', r))
self.throw_error('unregisterService', args, (-1, '', r))
def test_registerSubscriber(self):
h = self.m.handle
r = ['http://localhost:1234', 'http://localhost:98127']
h.return_val = (1, '', r)
self.assertEquals(r, self.m.registerSubscriber('/foo/node', 'std_msgs/String', 'http://localhost:9812'))
self.assertEquals(('registerSubscriber',_ID, '/foo/node', 'std_msgs/String', 'http://localhost:9812'), h.call)
args = ('/foo/node', 'std_msgs/String', 'http://localhost:9812')
self.throw_failure('registerSubscriber', args, (0, '', r))
self.throw_error('registerSubscriber', args, (-1, '', r))
def test_unregisterSubscriber(self):
h = self.m.handle
r = 1
h.return_val = (1, '', r)
self.assertEquals(r, self.m.unregisterSubscriber('/foo/node', 'http://localhost:9812'))
self.assertEquals(('unregisterSubscriber',_ID, '/foo/node', 'http://localhost:9812'), h.call)
args = ('/foo/node', 'http://localhost:9812')
self.throw_failure('unregisterSubscriber', args, (0, '', r))
self.throw_error('unregisterSubscriber', args, (-1, '', r))
def test_registerPublisher(self):
h = self.m.handle
r = 5
h.return_val = (1, '', r)
self.assertEquals(r, self.m.registerPublisher('/foo/node', 'std_msgs/String', 'http://localhost:9812'))
self.assertEquals(('registerPublisher',_ID, '/foo/node', 'std_msgs/String', 'http://localhost:9812'), h.call)
args = ('/foo/node', 'std_msgs/String', 'http://localhost:9812')
self.throw_failure('registerPublisher', args, (0, '', r))
self.throw_error('registerPublisher', args, (-1, '', r))
def test_unregisterPublisher(self):
h = self.m.handle
r = 10
h.return_val = (1, '', r)
self.assertEquals(r, self.m.unregisterPublisher('/foo/node', 'http://localhost:9812'))
self.assertEquals(('unregisterPublisher',_ID, '/foo/node', 'http://localhost:9812'), h.call)
args = ('/foo/node', 'http://localhost:9812')
self.throw_failure('unregisterPublisher', args, (0, '', r))
self.throw_error('unregisterPublisher', args, (-1, '', r))
def test_lookupNode(self):
h = self.m.handle
r = 'http://localhost:123'
h.return_val = (1, '', r)
self.assertEquals(r, self.m.lookupNode('/foo/node'))
self.assertEquals(('lookupNode',_ID, '/foo/node'), h.call)
args = ('/foo/node',)
self.throw_failure('lookupNode', args, (0, '', r))
self.throw_error('lookupNode', args, (-1, '', r))
def test_getPublishedTopics(self):
h = self.m.handle
r = [ ['foo', 'bar'], ['baz', 'blah'] ]
h.return_val = (1, '', r)
self.assertEquals(r, self.m.getPublishedTopics('/foo'))
self.assertEquals(('getPublishedTopics',_ID, '/foo'), h.call)
args = ('/baz',)
self.throw_failure('getPublishedTopics', args, (0, '', r))
self.throw_error('getPublishedTopics', args, (-1, '', r))
def test_getTopicTypes(self):
h = self.m.handle
r = [ ['/foo', 'std_msgs/String'], ['/baz', 'std_msgs/Int32'] ]
h.return_val = (1, '', r)
self.assertEquals(r, self.m.getTopicTypes())
self.assertEquals(('getTopicTypes',_ID), h.call)
self.throw_failure('getTopicTypes', (), (0, '', r))
self.throw_error('getTopicTypes', (), (-1, '', r))
def test_getSystemState(self):
h = self.m.handle
r = [ [], [], [] ]
h.return_val = (1, '', r)
self.assertEquals(r, self.m.getSystemState())
self.assertEquals(('getSystemState', _ID), h.call)
self.throw_failure('getSystemState', (), (0, '', r))
self.throw_error('getSystemState', (), (-1, '', r))
################################################################################
# PARAM SERVER API TESTS
def test_getParam(self):
h = self.m.handle
r = 1
h.return_val = (1, '', r)
p = '/test_param'
self.assertEquals(r, self.m.getParam(p))
self.assertEquals(('getParam', _ID, p), h.call)
args = (p,)
self.throw_failure('getParam', args, (0, '', r))
self.throw_error('getParam', args, (-1, '', r))
def test_getParamNames(self):
h = self.m.handle
r = [ '/foo' ]
h.return_val = (1, '', r)
self.assertEquals(r, self.m.getParamNames())
self.assertEquals(('getParamNames', _ID), h.call)
self.throw_failure('getParamNames', (), (0, '', r))
self.throw_error('getParamNames', (), (-1, '', r))
def test_hasParam(self):
h = self.m.handle
r = True
h.return_val = (1, '', r)
p = '/test_param'
self.assertEquals(r, self.m.hasParam(p))
self.assertEquals(('hasParam', _ID, p), h.call)
self.throw_failure('hasParam', (p,), (0, '', r))
self.throw_error('hasParam', (p,), (-1, '', r))
def test_searchParam(self):
h = self.m.handle
r = '/foo'
h.return_val = (1, '', r)
p = '/test_param'
self.assertEquals(r, self.m.searchParam(p))
self.assertEquals(('searchParam', _ID, p), h.call)
self.throw_failure('searchParam', (p,), (0, '', r))
self.throw_error('searchParam', (p,), (-1, '', r))
def test_deleteParam(self):
h = self.m.handle
r = '/foo'
h.return_val = (1, '', r)
p = '/test_param'
self.assertEquals(r, self.m.deleteParam(p))
self.assertEquals(('deleteParam', _ID, p), h.call)
self.throw_failure('deleteParam', (p,), (0, '', r))
self.throw_error('deleteParam', (p,), (-1, '', r))
def test_is_online(self):
self.failIf(rosgraph.masterapi.is_online(master_uri="http://fake:12345"))
self.m.handle.return_val = (1, '', 1235)
self.assert_(self.m.is_online())
def test_subscribeParam(self):
h = self.m.handle
r = 1
h.return_val = (1, '', r)
args = ('http://bar:12345', '/test_param')
self.assertEquals(r, self.m.subscribeParam(*args))
self.assertEquals(('subscribeParam', _ID, args[0], args[1]), h.call)
self.throw_failure('subscribeParam', args, (0, '', r))
self.throw_error('subscribeParam', args, (-1, '', r))
def test_unsubscribeParam(self):
h = self.m.handle
r = 1
h.return_val = (1, '', r)
args = ('http://bar:12345', '/test_param')
self.assertEquals(r, self.m.unsubscribeParam(*args))
self.assertEquals(('unsubscribeParam', _ID, args[0], args[1]), h.call)
self.throw_failure('unsubscribeParam', args, (0, '', r))
self.throw_error('unsubscribeParam', args, (-1, '', r))
def test_setParam(self):
h = self.m.handle
r = 1
h.return_val = (1, '', r)
args = ('/test_set_param', 'foo')
self.assertEquals(r, self.m.setParam(*args))
self.assertEquals(('setParam', _ID, args[0], args[1]), h.call)
self.throw_failure('setParam', args, (0, '', r))
self.throw_error('setParam', args, (-1, '', r))
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/test/test_network.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.
import os
import struct
import sys
import unittest
class MockSock(object):
def __init__(self, data=''):
self.data = data
def recv(self):
d = self.data
self.data = ''
return d
def sendall(self, d):
self.data = self.data + d
def send(self, d):
self.data = self.data + d
return len(d)
class NetworkTest(unittest.TestCase):
def test_encode_ros_handshake_header(self):
from rosgraph.network import encode_ros_handshake_header
d = {}
assert struct.pack('<I', 0) == encode_ros_handshake_header(d)
s = b"a=b"
d['a'] = 'b'
encoded = struct.pack('<I', len(s))+s
assert struct.pack('<I', len(encoded))+encoded == \
encode_ros_handshake_header({'a': 'b'})
d['c'] = 'd'
s = b"c=d"
encoded = encoded+struct.pack('<I', len(s))+s
assert struct.pack('<I', len(encoded))+encoded == \
encode_ros_handshake_header(d)
d['rawtype'] = '#line 1\nline 2\nline 3\nline\t4\r\r\n'
s = b"rawtype=#line 1\nline 2\nline 3\nline\t4\r\r\n"
encoded = encoded+struct.pack('<I', len(s))+s
assert struct.pack('<I', len(encoded))+encoded == \
encode_ros_handshake_header(d)
if sys.version_info > (3, 0):
assert \
encode_ros_handshake_header(
{'a': 'b', 'c': 'd', 'e': 'f'}) == \
encode_ros_handshake_header(
{b'a': 'b', 'c': b'd', b'e': b'f'})
else:
assert \
encode_ros_handshake_header(
{'a': 'b', 'c': 'd', 'e': 'f'}) == \
encode_ros_handshake_header(
{u'a': 'b', 'c': u'd', u'e': u'f'})
def test_decode_ros_handshake_header(self):
from rosgraph.network import decode_ros_handshake_header, ROSHandshakeException
invalids = [b"field1",b"",]
# prepend field length
invalids = [(struct.pack('<I', len(s)) + s) for s in invalids]
# prepend message length
invalids = [(struct.pack('<I', len(s)) + s) for s in invalids]
# invalid message length prefix
valid = b"a=b"
valid = struct.pack('<I', len(valid)) + valid
invalids.append(struct.pack('<I', 123)+valid)
# invalid field length prefix
invalid = struct.pack('<I', 123) + b'a=b'
invalids.append(struct.pack("<I", len(invalid)) + invalid)
for i in invalids:
try:
decode_ros_handshake_header(i)
assert False, "should have failed: %s"%i
except ROSHandshakeException: pass
assert {} == decode_ros_handshake_header(struct.pack('<I', 0))
# single-field tests
tests = [
(b"a=b", {'a': 'b'}),
# whitespace in keys is ignored
(b" a =b", {'a': 'b'}),
(b'newlines=\n\n\n\n', {'newlines': '\n\n\n\n'}),
(b'equals=foo=bar=car', {'equals': 'foo=bar=car'}),
(b"spaces=one two three four",{'spaces': 'one two three four'}),
]
for s, d in tests:
# add in length fields
s = struct.pack('<I', len(s)+4) + struct.pack('<I', len(s)) + s
assert d == decode_ros_handshake_header(s)
# multi-field tests
tests = [ {'a': 'b', 'c': 'd'},
{'spaces': ' ', 'tabs': '\t\t\t\t', 'equals': '====='},
]
for t in tests:
s = b''
for k, v in t.items():
f = "%s=%s"%(k, v)
f = f.encode()
s += struct.pack('<I', len(f)) + f
s = struct.pack('<I', len(s)) + s
assert t == decode_ros_handshake_header(s)
# make sure that decode ignores extra past header len
assert t == decode_ros_handshake_header(s+s)
def test_parse_http_host_and_port(self):
from rosgraph.network import parse_http_host_and_port
invalid = ['', 'http://', 'http://localhost:bar', None]
for t in invalid:
try:
parse_http_host_and_port(t)
assert False, "should have failed: %s"%t
except ValueError:
pass
assert ('localhost', 80) == parse_http_host_and_port('http://localhost')
assert ('localhost', 1234) == parse_http_host_and_port('http://localhost:1234')
assert ('localhost', 1) == parse_http_host_and_port('http://localhost:1')
assert ('willowgarage.com', 1) == parse_http_host_and_port('http://willowgarage.com:1')
def test_get_local_address(self):
# mostly a tripwire test
from rosgraph.network import get_local_address
a = get_local_address()
assert a
# now test address override
os.environ['ROS_IP'] = 'bar'
assert 'bar' == get_local_address()
os.environ['ROS_HOSTNAME'] = 'foo'
assert 'foo' == get_local_address()
try:
real_argv = sys.argv[:]
sys.argv = real_argv[:] + ['__ip:=1.2.3.4']
assert '1.2.3.4' == get_local_address()
sys.argv = real_argv[:] + ['__hostname:=bar']
assert 'bar' == get_local_address()
finally:
sys.argv = real_argv
def test_get_local_addresses(self):
# mostly a tripwire test
from rosgraph.network import get_local_addresses
addrs = get_local_addresses()
assert type(addrs) == list
assert len(addrs)
# should be unaffected
os.environ['ROS_IP'] = 'bar'
assert addrs == get_local_addresses()
os.environ['ROS_HOSTNAME'] = 'foo'
assert addrs == get_local_addresses()
def test_get_bind_address(self):
from rosgraph.network import get_bind_address
assert '0.0.0.0' == get_bind_address('foo')
assert '127.0.0.1' == get_bind_address('localhost')
assert '127.0.1.1' == get_bind_address('127.0.1.1')
# now test address override
os.environ['ROS_IP'] = 'bar'
assert '0.0.0.0' == get_bind_address()
assert '0.0.0.0' == get_bind_address('foo')
os.environ['ROS_IP'] = 'localhost'
assert '127.0.0.1' == get_bind_address()
assert '0.0.0.0' == get_bind_address('foo')
os.environ['ROS_HOSTNAME'] = 'bar'
assert '0.0.0.0' == get_bind_address()
assert '0.0.0.0' == get_bind_address('foo')
os.environ['ROS_HOSTNAME'] = 'localhost'
assert '127.0.0.1' == get_bind_address()
assert '0.0.0.0' == get_bind_address('foo')
def test_get_host_name(self):
from rosgraph.network import get_host_name
os.environ['ROS_IP'] = 'foo'
assert 'foo' == get_host_name()
os.environ['ROS_HOSTNAME'] = 'bar'
assert 'bar' == get_host_name()
try:
real_argv = sys.argv[:]
sys.argv = real_argv[:] + ['__ip:=1.2.3.4']
assert '1.2.3.4' == get_host_name()
sys.argv = real_argv[:] + ['__hostname:=baz']
assert 'baz' == get_host_name()
finally:
sys.argv = real_argv
def test_create_local_xmlrpc_uri(self):
from rosgraph.network import parse_http_host_and_port, create_local_xmlrpc_uri
os.environ['ROS_HOSTNAME'] = 'localhost'
assert ('localhost', 1234) == parse_http_host_and_port(create_local_xmlrpc_uri(1234))
def setUp(self):
self._ros_hostname = self._ros_ip = None
if 'ROS_HOSTNAME' in os.environ:
self._ros_hostname = os.environ['ROS_HOSTNAME']
del os.environ['ROS_HOSTNAME']
if 'ROS_IP' in os.environ:
self._ros_ip = os.environ['ROS_IP']
del os.environ['ROS_IP']
def tearDown(self):
if 'ROS_HOSTNAME' in os.environ:
del os.environ['ROS_HOSTNAME']
if 'ROS_IP' in os.environ:
del os.environ['ROS_IP']
if self._ros_hostname:
os.environ['ROS_HOSTNAME'] = self._ros_hostname
if self._ros_ip:
os.environ['ROS_IP'] = self._ros_ip
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/test/test_rosgraph_command_offline.py | #!/usr/bin/env python
# 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.
import os
import sys
import unittest
import time
from subprocess import Popen, PIPE, check_call, call
class TestRosgraphOffline(unittest.TestCase):
def setUp(self):
pass
## test that the rosmsg command works
def test_cmd_help(self):
cmd = 'rosgraph'
output = Popen([cmd, '-h'], stdout=PIPE).communicate()[0]
self.assert_('Usage' in output.decode())
def test_offline(self):
cmd = 'rosgraph'
# point at a different 'master'
env = os.environ.copy()
env['ROS_MASTER_URI'] = 'http://localhost:11312'
kwds = { 'env': env, 'stdout': PIPE, 'stderr': PIPE}
msg = "ERROR: Unable to communicate with master!\n"
output = Popen([cmd], **kwds).communicate()
self.assertEquals(msg, output[1].decode())
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/test/test_xmlrpc.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.
import os
import sys
import time
import mock
def test_XmlRpcHandler():
from rosgraph.xmlrpc import XmlRpcHandler
# tripwire
h = XmlRpcHandler()
# noop
h._ready('http://localhost:1234')
def test_XmlRpcNode():
from rosgraph.xmlrpc import XmlRpcNode, XmlRpcHandler
# not a very comprehensive test (yet)
#port, handler
tests = [
(None, None, None),
(8080, None, 8080),
('8080', None, 8080),
(u'8080', None, 8080),
]
for port, handler,true_port in tests:
n = XmlRpcNode(port, handler)
assert true_port == n.port
assert handler == n.handler
assert None == n.uri
assert None == n.server
n.set_uri('http://fake:1234')
assert 'http://fake:1234' == n.uri
n.start()
start = time.time()
while not n.uri and time.time() - start < 5.:
time.sleep(0.00001) #poll for XMLRPC init
assert n.uri
n.shutdown('test case')
# get coverage on run init
n = XmlRpcNode(0, XmlRpcHandler())
n._run_init()
n.shutdown('test case')
# mock in server in order to play with _run()
n.server = mock.Mock()
n.is_shutdown = False
n._run_init = mock.Mock()
n.server.serve_forever.side_effect = IOError(1, 'boom')
n._run()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/test/test_myargv.py | # Software License Agreement (BSD License)
#
# Copyright (c) 2011, 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 sys
def test_myargv():
orig_argv = sys.argv
try:
from rosgraph import myargv
args = myargv()
assert args == sys.argv
assert ['foo', 'bar', 'baz'] == myargv(['foo','bar', 'baz'])
assert ['-foo', 'bar', '-baz'] == myargv(['-foo','bar', '-baz'])
assert ['foo'] == myargv(['foo','bar:=baz'])
assert ['foo'] == myargv(['foo','-bar:=baz'])
finally:
sys.argv = orig_argv
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/scripts/rosgraph | #!/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.
#
# Revision $Id: rosgraph 3804 2009-02-11 02:16:00Z rob_wheeler $
import rosgraph.rosgraph_main
rosgraph.rosgraph_main.rosgraph_main()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/conf/python_logging.conf | [loggers]
keys=root, rosout
[handlers]
keys=fileHandler,streamHandler
[formatters]
keys=defaultFormatter
[logger_root]
level=INFO
handlers=fileHandler
[logger_rosout]
level=INFO
handlers=streamHandler
propagate=1
qualname=rosout
[handler_fileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=defaultFormatter
# log filename, mode, maxBytes, backupCount
args=(os.environ['ROS_LOG_FILENAME'],'a', 50000000, 4)
[handler_streamHandler]
class=rosgraph.roslogging.RosStreamHandler
level=DEBUG
formatter=defaultFormatter
# colorize output flag
args=(True,)
[formatter_defaultFormatter]
format=[%(name)s][%(levelname)s] %(asctime)s: %(message)s
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src/rosgraph/rosgraph_main.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.
from __future__ import print_function
import sys
import time
from . import roslogging
from . import masterapi
from .impl import graph
def fullusage():
print("""rosgraph is a command-line tool for debugging the ROS Computation Graph.
Usage:
\trosgraph
""")
def rosgraph_main():
if len(sys.argv) == 1:
pass
elif len(sys.argv) == 2 and (sys.argv[1] == '-h' or sys.argv[1] == '--help'):
fullusage()
return
else:
fullusage()
sys.exit(-1)
roslogging.configure_logging('rosgraph')
# make sure master is available
master = masterapi.Master('rosgraph')
try:
master.getPid()
except:
print("ERROR: Unable to communicate with master!", file=sys.stderr)
return
g = graph.Graph()
try:
while 1:
g.update()
if not g.nn_nodes and not g.srvs:
print("empty")
else:
print('\n')
if g.nn_nodes:
print('Nodes:')
for n in g.nn_nodes:
prefix = n + '|'
print(' ' + n + ' :')
print(' Inbound:')
for k in g.nn_edges.edges_by_end.keys():
if k.startswith(prefix):
for c in g.nn_edges.edges_by_end[k]:
print(' ' + c.start)
print(' Outbound:')
for k in g.nn_edges.edges_by_start.keys():
if k.startswith(prefix):
for c in g.nn_edges.edges_by_start[k]:
print(' ' + c.end)
if g.srvs:
print('Services:')
for s in g.srvs:
print(' ' + s)
time.sleep(1.0)
except KeyboardInterrupt:
pass
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src/rosgraph/xmlrpc.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: xmlrpc.py 15336 2011-11-07 20:43:00Z kwc $
from __future__ import print_function
"""
Common XML-RPC for higher-level libraries running XML-RPC libraries in
ROS. In particular, this library provides common handling for URI
calculation based on ROS environment variables.
The common entry point for most libraries is the L{XmlRpcNode} class.
"""
import logging
import select
import socket
try:
import _thread
except ImportError:
import thread as _thread
import traceback
try:
from xmlrpc.server import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler #Python 3.x
except ImportError:
from SimpleXMLRPCServer import SimpleXMLRPCServer #Python 2.x
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler #Python 2.x
try:
import socketserver
except ImportError:
import SocketServer as socketserver
import rosgraph.network
def isstring(s):
"""Small helper version to check an object is a string in a way that works
for both Python 2 and 3
"""
try:
return isinstance(s, basestring)
except NameError:
return isinstance(s, str)
class SilenceableXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
def log_message(self, format, *args):
if 0:
SimpleXMLRPCRequestHandler.log_message(self, format, *args)
class ThreadingXMLRPCServer(socketserver.ThreadingMixIn, SimpleXMLRPCServer):
"""
Adds ThreadingMixin to SimpleXMLRPCServer to support multiple concurrent
requests via threading. Also makes logging toggleable.
"""
def __init__(self, addr, log_requests=1):
"""
Overrides SimpleXMLRPCServer to set option to allow_reuse_address.
"""
# allow_reuse_address defaults to False in Python 2.4. We set it
# to True to allow quick restart on the same port. This is equivalent
# to calling setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
self.allow_reuse_address = True
# Increase request_queue_size to handle issues with many simultaneous
# connections in OSX 10.11
self.request_queue_size = min(socket.SOMAXCONN, 128)
if rosgraph.network.use_ipv6():
logger = logging.getLogger('xmlrpc')
# The XMLRPC library does not support IPv6 out of the box
# We have to monipulate private members and duplicate
# code from the constructor.
# TODO IPV6: Get this into SimpleXMLRPCServer
SimpleXMLRPCServer.__init__(self, addr, SilenceableXMLRPCRequestHandler, log_requests, bind_and_activate=False)
self.address_family = socket.AF_INET6
self.socket = socket.socket(self.address_family, self.socket_type)
logger.info('binding ipv6 xmlrpc socket to' + str(addr))
# TODO: set IPV6_V6ONLY to 0:
# self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
self.server_bind()
self.server_activate()
logger.info('bound to ' + str(self.socket.getsockname()[0:2]))
else:
SimpleXMLRPCServer.__init__(self, addr, SilenceableXMLRPCRequestHandler, log_requests)
def handle_error(self, request, client_address):
"""
override ThreadingMixin, which sends errors to stderr
"""
if logging and traceback:
logger = logging.getLogger('xmlrpc')
if logger:
logger.error(traceback.format_exc())
class ForkingXMLRPCServer(socketserver.ForkingMixIn, SimpleXMLRPCServer):
"""
Adds ThreadingMixin to SimpleXMLRPCServer to support multiple concurrent
requests via forking. Also makes logging toggleable.
"""
def __init__(self, addr, request_handler=SilenceableXMLRPCRequestHandler, log_requests=1):
SimpleXMLRPCServer.__init__(self, addr, request_handler, log_requests)
class XmlRpcHandler(object):
"""
Base handler API for handlers used with XmlRpcNode. Public methods will be
exported as XML RPC methods.
"""
def _ready(self, uri):
"""
callback into handler to inform it of XML-RPC URI
"""
pass
def _shutdown(self, reason):
"""
callback into handler to inform it of shutdown
"""
pass
class XmlRpcNode(object):
"""
Generic XML-RPC node. Handles the additional complexity of binding
an XML-RPC server to an arbitrary port.
XmlRpcNode is initialized when the uri field has a value.
"""
def __init__(self, port=0, rpc_handler=None, on_run_error=None):
"""
XML RPC Node constructor
:param port: port to use for starting XML-RPC API. Set to 0 or omit to bind to any available port, ``int``
:param rpc_handler: XML-RPC API handler for node, `XmlRpcHandler`
:param on_run_error: function to invoke if server.run() throws
Exception. Server always terminates if run() throws, but this
enables cleanup routines to be invoked if server goes down, as
well as include additional debugging. ``fn(Exception)``
"""
super(XmlRpcNode, self).__init__()
self.handler = rpc_handler
self.uri = None # initialize the property now so it can be tested against, will be filled in later
self.server = None
if port and isstring(port):
port = int(port)
self.port = port
self.is_shutdown = False
self.on_run_error = on_run_error
def shutdown(self, reason):
"""
Terminate i/o connections for this server.
:param reason: human-readable debug string, ``str``
"""
self.is_shutdown = True
if self.server:
server = self.server
handler = self.handler
self.handler = self.server = self.port = self.uri = None
if handler:
handler._shutdown(reason)
if server:
server.socket.close()
server.server_close()
def start(self):
"""
Initiate a thread to run the XML RPC server. Uses thread.start_new_thread.
"""
_thread.start_new_thread(self.run, ())
def set_uri(self, uri):
"""
Sets the XML-RPC URI. Defined as a separate method as a hood
for subclasses to bootstrap initialization. Should not be called externally.
:param uri: XMLRPC URI, ``str``
"""
self.uri = uri
def run(self):
try:
self._run()
except Exception as e:
if self.is_shutdown:
pass
elif self.on_run_error is not None:
self.on_run_error(e)
else:
raise
# separated out for easier testing
def _run_init(self):
logger = logging.getLogger('xmlrpc')
try:
log_requests = 0
port = self.port or 0 #0 = any
bind_address = rosgraph.network.get_bind_address()
logger.info("XML-RPC server binding to %s:%d" % (bind_address, port))
self.server = ThreadingXMLRPCServer((bind_address, port), log_requests)
self.port = self.server.server_address[1] #set the port to whatever server bound to
if not self.port:
self.port = self.server.socket.getsockname()[1] #Python 2.4
assert self.port, "Unable to retrieve local address binding"
# #528: semi-complicated logic for determining XML-RPC URI
# - if ROS_IP/ROS_HOSTNAME is set, use that address
# - if the hostname returns a non-localhost value, use that
# - use whatever rosgraph.network.get_local_address() returns
uri = None
override = rosgraph.network.get_address_override()
if override:
uri = 'http://%s:%s/'%(override, self.port)
else:
try:
hostname = socket.gethostname()
if hostname and not hostname == 'localhost' and not hostname.startswith('127.') and hostname != '::':
uri = 'http://%s:%s/'%(hostname, self.port)
except:
pass
if not uri:
uri = 'http://%s:%s/'%(rosgraph.network.get_local_address(), self.port)
self.set_uri(uri)
logger.info("Started XML-RPC server [%s]", self.uri)
self.server.register_multicall_functions()
self.server.register_instance(self.handler)
except socket.error as e:
if e.errno == 98:
msg = "ERROR: Unable to start XML-RPC server, port %s is already in use"%self.port
else:
msg = "ERROR: Unable to start XML-RPC server: %s" % e.strerror
logger.error(msg)
print(msg)
raise #let higher level catch this
if self.handler is not None:
self.handler._ready(self.uri)
logger.info("xml rpc node: starting XML-RPC server")
def _run(self):
"""
Main processing thread body.
:raises: :exc:`socket.error` If server cannot bind
"""
self._run_init()
while not self.is_shutdown:
try:
self.server.serve_forever()
except (IOError, select.error) as e:
# check for interrupted call, which can occur if we're
# embedded in a program using signals. All other
# exceptions break _run.
if self.is_shutdown:
pass
elif e.errno != 4:
self.is_shutdown = True
logging.getLogger('xmlrpc').error("serve forever IOError: %s, %s"%(e.errno, e.strerror))
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src/rosgraph/masterapi.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: masterapi.py 9672 2010-05-11 21:57:40Z kwc $
"""
Python adapter for calling ROS Master API. While it is trivial to call the
Master directly using XML-RPC, this API provides a safer abstraction in the event
the Master API is changed.
"""
try:
from xmlrpc.client import ServerProxy # Python 3.x
except ImportError:
from xmlrpclib import ServerProxy # Python 2.x
from . names import make_caller_id
from . rosenv import get_master_uri
from . network import parse_http_host_and_port
from rospy.impl.broadcast_manager import BroadcastManager
class MasterException(Exception):
"""
Base class of ROS-master related errors.
"""
pass
class MasterFailure(MasterException):
"""
Call to Master failed. This generally indicates an internal error
in the Master and that the Master may be in an inconsistent state.
"""
pass
class MasterError(MasterException):
"""
Master returned an error code, which indicates an error in the
arguments passed to the Master.
"""
pass
# backwards compat
ROSMasterException = MasterException
Error = MasterError
Failure = MasterFailure
def is_online(master_uri=None):
"""
@param master_uri: (optional) override environment's ROS_MASTER_URI
@type master_uri: str
@return: True if Master is available
"""
return Master('rosgraph', master_uri=master_uri).is_online()
class Master(object):
"""
API for interacting with the ROS master. Although the Master is
relatively simple to interact with using the XMLRPC API, this
abstraction layer provides protection against future updates. It
also provides a streamlined API with builtin return code checking
and caller_id passing.
"""
def __init__(self, caller_id, master_uri=None):
"""
:param caller_id: name of node to use in calls to master, ``str``
:param master_uri: (optional) override default ROS master URI, ``str``
:raises: :exc:`ValueError` If ROS master uri not set properly
"""
if master_uri is None:
master_uri = get_master_uri()
self._reinit(master_uri)
self.caller_id = make_caller_id(caller_id) #resolve
if self.caller_id[-1] == '/':
self.caller_id = self.caller_id[:-1]
self.bm = BroadcastManager(name=self.caller_id)
def _reinit(self, master_uri):
"""
Internal API for reinitializing this handle to be a new master
:raises: :exc:`ValueError` If ROS master uri not set
"""
if master_uri is None:
raise ValueError("ROS master URI is not set")
# #1730 validate URL for better error messages
try:
parse_http_host_and_port(master_uri)
except ValueError:
raise ValueError("invalid master URI: %s"%(master_uri))
self.master_uri = master_uri
self.handle = ServerProxy(self.master_uri)
def is_online(self):
"""
Check if Master is online.
NOTE: this is not part of the actual Master API. This is a convenience function.
@param master_uri: (optional) override environment's ROS_MASTER_URI
@type master_uri: str
@return: True if Master is available
"""
try:
self.getPid()
return True
except:
return False
def _succeed(self, args):
"""
Check master return code and return the value field.
@param args: master return value
@type args: (int, str, XMLRPCLegalValue)
@return: value field of args (master return value)
@rtype: XMLRPCLegalValue
@raise rosgraph.masterapi.Error: if Master returns ERROR.
@raise rosgraph.masterapi.Failure: if Master returns FAILURE.
"""
code, msg, val = args
if code == 1:
return val
elif code == -1:
raise Error(msg)
else:
raise Failure(msg)
################################################################################
# PARAM SERVER
def deleteParam(self, key):
"""
Parameter Server: delete parameter
@param key: parameter name
@type key: str
@return: 0
@rtype: int
"""
return self._succeed(self.handle.deleteParam(self.caller_id, key))
def setParam(self, key, value):
"""
Parameter Server: set parameter. NOTE: if value is a
dictionary it will be treated as a parameter tree, where key
is the parameter namespace. For example:::
{'x':1,'y':2,'sub':{'z':3}}
will set key/x=1, key/y=2, and key/sub/z=3. Furthermore, it
will replace all existing parameters in the key parameter
namespace with the parameters in value. You must set
parameters individually if you wish to perform a union update.
@param key: parameter name
@type key: str
@param value: parameter value.
@type value: XMLRPCLegalValue
@return: 0
@rtype: int
"""
return self._succeed(self.handle.setParam(self.caller_id, key, value))
def getParam(self, key):
"""
Retrieve parameter value from server.
@param key: parameter to lookup. If key is a namespace,
getParam() will return a parameter tree.
@type key: str
getParam() will return a parameter tree.
@return: parameterValue. If key is a namespace,
the return value will be a dictionary, where each key is a
parameter in that namespace. Sub-namespaces are also
represented as dictionaries.
@rtype: XMLRPCLegalValue
"""
return self._succeed(self.handle.getParam(self.caller_id, key))
def searchParam(self, key):
"""
Search for parameter key on parameter server. Search starts in caller's namespace and proceeds
upwards through parent namespaces until Parameter Server finds a matching key.
searchParam's behavior is to search for the first partial match.
For example, imagine that there are two 'robot_description' parameters::
/robot_description
/robot_description/arm
/robot_description/base
/pr2/robot_description
/pr2/robot_description/base
If I start in the namespace /pr2/foo and search for
'robot_description', searchParam will match
/pr2/robot_description. If I search for 'robot_description/arm'
it will return /pr2/robot_description/arm, even though that
parameter does not exist (yet).
@param key: parameter key to search for.
@type key: str
@return: foundKey
@rtype: str
"""
return self._succeed(self.handle.searchParam(self.caller_id, key))
def subscribeParam(self, caller_api, key):
"""
Retrieve parameter value from server and subscribe to updates to that param. See
paramUpdate() in the Node API.
@param key: parameter to lookup.
@type key: str
@param caller_api: API URI for paramUpdate callbacks.
@type caller_api: str
@return: parameterValue. parameterValue is an empty dictionary if the parameter has not been set yet.
@rtype: XMLRPCLegalValue
"""
return self._succeed(self.handle.subscribeParam(self.caller_id, caller_api, key))
def unsubscribeParam(self, caller_api, key):
"""
Retrieve parameter value from server and subscribe to updates to that param. See
paramUpdate() in the Node API.
@param key: parameter to lookup.
@type key: str
@param caller_api: API URI for paramUpdate callbacks.
@type caller_api: str
@return: numUnsubscribed. If numUnsubscribed is zero it means that the caller was not subscribed to the parameter.
@rtype: int
"""
return self._succeed(self.handle.unsubscribeParam(self.caller_id, caller_api, key))
def hasParam(self, key):
"""
Check if parameter is stored on server.
@param key: parameter to check
@type key: str
@return: [code, statusMessage, hasParam]
@rtype: [int, str, bool]
"""
return self._succeed(self.handle.hasParam(self.caller_id, key))
def getParamNames(self):
"""
Get list of all parameter names stored on this server.
This does not adjust parameter names for caller's scope.
@return: [code, statusMessage, parameterNameList]
@rtype: [int, str, [str]]
"""
return self._succeed(self.handle.getParamNames(self.caller_id))
################################################################################
def getPid(self):
"""
Get the PID of this server
@return: serverProcessPID
@rtype: int
@raise rosgraph.masterapi.Error: if Master returns ERROR.
@raise rosgraph.masterapi.Failure: if Master returns FAILURE.
"""
return self._succeed(self.handle.getPid(self.caller_id))
def getUri(self):
"""
Get the URI of this Master
@return: masterUri
@rtype: str
@raise rosgraph.masterapi.Error: if Master returns ERROR.
@raise rosgraph.masterapi.Failure: if Master returns FAILURE.
"""
return self._succeed(self.handle.getUri(self.caller_id))
def registerService(self, service, service_api, caller_api):
"""
Register the caller as a provider of the specified service.
@param service str: Fully-qualified name of service
@param service_api str: Service URI
@param caller_api str: XML-RPC URI of caller node
@return: ignore
@rtype: int
@raise rosgraph.masterapi.Error: if Master returns ERROR.
@raise rosgraph.masterapi.Failure: if Master returns FAILURE.
"""
return self._succeed(self.bm.registerService(self.caller_id, service, service_api, caller_api))
def lookupService(self, service):
"""
Lookup all provider of a particular service.
@param service: fully-qualified name of service to lookup.
@type: service: str
@return (int, str, str): (code, message, serviceUrl). service URL is provides
and address and port of the service. Fails if there is no provider.
@raise rosgraph.masterapi.Error: if Master returns ERROR.
@raise rosgraph.masterapi.Failure: if Master returns FAILURE.
"""
return self._succeed(self.bm.lookupService(self.caller_id, service))
def lookupServiceCache(self, service):
"""
Lookup all provider of a particular service.
@param service: fully-qualified name of service to lookup.
@type: service: str
@return (int, str, str): (code, message, serviceUrl). service URL is provides
and address and port of the service. Fails if there is no provider.
@raise rosgraph.masterapi.Error: if Master returns ERROR.
@raise rosgraph.masterapi.Failure: if Master returns FAILURE.
"""
return self._succeed(self.handle.lookupService(self.caller_id, service))
def unregisterService(self, service, service_api):
"""
Unregister the caller as a provider of the specified service.
@param service: Fully-qualified name of service
@type service: str
@param service_api: API URI of service to unregister. Unregistration will only occur if current
registration matches.
@type service_api: str
@return: (code, message, numUnregistered). Number of unregistrations (either 0 or 1).
If this is zero it means that the caller was not registered as a service provider.
The call still succeeds as the intended final state is reached.
@rtype: (int, str, int)
@raise rosgraph.masterapi.Error: if Master returns ERROR.
@raise rosgraph.masterapi.Failure: if Master returns FAILURE.
"""
return self._succeed(self.bm.unregisterService(self.caller_id, service, service_api))
def registerSubscriber(self, topic, topic_type, caller_api):
"""
Subscribe the caller to the specified topic. In addition to receiving
a list of current publishers, the subscriber will also receive notifications
of new publishers via the publisherUpdate API.
@param topic str: Fully-qualified name of topic to subscribe to.
@param topic_type: Datatype for topic. Must be a package-resource name, i.e. the .msg name.
@type topic_type: str
@param caller_api: XML-RPC URI of caller node for new publisher notifications
@type caller_api: str
@return: (code, message, publishers). Publishers is a list of XMLRPC API URIs
for nodes currently publishing the specified topic.
@rtype: (int, str, list(str))
@raise rosgraph.masterapi.Error: if Master returns ERROR.
@raise rosgraph.masterapi.Failure: if Master returns FAILURE.
"""
return self._succeed(self.bm.registerSubscriber(self.caller_id, topic, topic_type, caller_api))
def unregisterSubscriber(self, topic, caller_api):
"""
Unregister the caller as a publisher of the topic.
@param topic: Fully-qualified name of topic to unregister.
@type topic: str
@param caller_api: API URI of service to unregister. Unregistration will only occur if current
@type caller_api: str
registration matches.
@return: (code, statusMessage, numUnsubscribed).
If numUnsubscribed is zero it means that the caller was not registered as a subscriber.
The call still succeeds as the intended final state is reached.
@rtype: (int, str, int)
@raise rosgraph.masterapi.Error: if Master returns ERROR.
@raise rosgraph.masterapi.Failure: if Master returns FAILURE.
"""
return self._succeed(self.bm.unregisterSubscriber(self.caller_id, topic, caller_api))
def registerPublisher(self, topic, topic_type, caller_api):
"""
Register the caller as a publisher the topic.
@param topic: Fully-qualified name of topic to register.
@type topic: str
@param topic_type: Datatype for topic. Must be a
package-resource name, i.e. the .msg name.
@type topic_type: str
@param caller_api str: ROS caller XML-RPC API URI
@type caller_api: str
@return: subscriberApis.
List of current subscribers of topic in the form of XMLRPC URIs.
@rtype: [str]
@raise rosgraph.masterapi.Error: if Master returns ERROR.
@raise rosgraph.masterapi.Failure: if Master returns FAILURE.
"""
return self._succeed(self.bm.registerPublisher(self.caller_id, topic, topic_type, caller_api))
def unregisterPublisher(self, topic, caller_api):
"""
Unregister the caller as a publisher of the topic.
@param topic: Fully-qualified name of topic to unregister.
@type topic: str
@param caller_api str: API URI of service to
unregister. Unregistration will only occur if current
registration matches.
@type caller_api: str
@return: numUnregistered.
If numUnregistered is zero it means that the caller was not registered as a publisher.
The call still succeeds as the intended final state is reached.
@rtype: int
@raise rosgraph.masterapi.Error: if Master returns ERROR.
@raise rosgraph.masterapi.Failure: if Master returns FAILURE.
"""
return self._succeed(self.bm.unregisterPublisher(self.caller_id, topic, caller_api))
def lookupNode(self, node_name):
"""
Get the XML-RPC URI of the node with the associated
name/caller_id. This API is for looking information about
publishers and subscribers. Use lookupService instead to lookup
ROS-RPC URIs.
@param node: name of node to lookup
@type node: str
@return: URI
@rtype: str
@raise rosgraph.masterapi.Error: if Master returns ERROR.
@raise rosgraph.masterapi.Failure: if Master returns FAILURE.
"""
return self._succeed(self.handle.lookupNode(self.caller_id, node_name))
def getPublishedTopics(self, subgraph):
"""
Get list of topics that can be subscribed to. This does not return topics that have no publishers.
See L{getSystemState()} to get more comprehensive list.
@param subgraph: Restrict topic names to match within the specified subgraph. Subgraph namespace
is resolved relative to the caller's namespace. Use '' to specify all names.
@type subgraph: str
@return: [[topic1, type1]...[topicN, typeN]]
@rtype: [[str, str],]
@raise rosgraph.masterapi.Error: if Master returns ERROR.
@raise rosgraph.masterapi.Failure: if Master returns FAILURE.
"""
return self._succeed(self.handle.getPublishedTopics(self.caller_id, subgraph))
def getTopicTypes(self):
"""
Retrieve list topic names and their types.
New in ROS 1.2.
@rtype: (int, str, [[str,str]] )
@return: (code, statusMessage, topicTypes). topicTypes is a list of [topicName, topicType] pairs.
"""
return self._succeed(self.handle.getTopicTypes(self.caller_id))
def getSystemState(self):
"""
Retrieve list representation of system state (i.e. publishers, subscribers, and services).
@rtype: [[str,[str]], [str,[str]], [str,[str]]]
@return: systemState
System state is in list representation::
[publishers, subscribers, services].
publishers is of the form::
[ [topic1, [topic1Publisher1...topic1PublisherN]] ... ]
subscribers is of the form::
[ [topic1, [topic1Subscriber1...topic1SubscriberN]] ... ]
services is of the form::
[ [service1, [service1Provider1...service1ProviderN]] ... ]
@raise rosgraph.masterapi.Error: if Master returns ERROR.
@raise rosgraph.masterapi.Failure: if Master returns FAILURE.
"""
return self._succeed(self.handle.getSystemState(self.caller_id))
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src/rosgraph/__init__.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.
import sys
from . rosenv import get_master_uri, ROS_MASTER_URI, ROS_NAMESPACE, ROS_HOSTNAME, ROS_IP, ROS_IPV6
from . masterapi import Master, MasterFailure, MasterError, MasterException
from . masterapi import is_online as is_master_online
# bring in names submodule
from . import names
def myargv(argv=None):
"""
Remove ROS remapping arguments from sys.argv arguments.
:returns: copy of sys.argv with ROS remapping arguments removed, ``[str]``
"""
if argv is None:
argv = sys.argv
return [a for a in argv if not names.REMAP in a]
__all__ = ['myargv',
'get_master_uri', 'ROS_MASTER_URI', 'ROS_NAMESPACE', 'ROS_HOSTNAME', 'ROS_IP', 'ROS_IPV6',
'Master', 'MasterFailure', 'MasterError', 'MasterException',
'is_master_online']
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src/rosgraph/roslogging.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.
"""
Library for configuring python logging to standard ROS locations (e.g. ROS_LOG_DIR).
"""
import os
import sys
import time
import logging
import logging.config
import rospkg
from rospkg.environment import ROS_LOG_DIR
class LoggingException(Exception): pass
def renew_latest_logdir(logfile_dir):
log_dir = os.path.dirname(logfile_dir)
latest_dir = os.path.join(log_dir, 'latest')
if os.path.lexists(latest_dir):
if not os.path.islink(latest_dir):
return False
os.remove(latest_dir)
os.symlink(logfile_dir, latest_dir)
return True
def configure_logging(logname, level=logging.INFO, filename=None, env=None):
"""
Configure Python logging package to send log files to ROS-specific log directory
:param logname str: name of logger, ``str``
:param filename: filename to log to. If not set, a log filename
will be generated using logname, ``str``
:param env: override os.environ dictionary, ``dict``
:returns: log file name, ``str``
:raises: :exc:`LoggingException` If logging cannot be configured as specified
"""
if env is None:
env = os.environ
logname = logname or 'unknown'
log_dir = rospkg.get_log_dir(env=env)
# if filename is not explicitly provided, generate one using logname
if not filename:
log_filename = os.path.join(log_dir, '%s-%s.log'%(logname, os.getpid()))
else:
log_filename = os.path.join(log_dir, filename)
logfile_dir = os.path.dirname(log_filename)
if not os.path.exists(logfile_dir):
try:
makedirs_with_parent_perms(logfile_dir)
except OSError:
# cannot print to screen because command-line tools with output use this
sys.stderr.write("WARNING: cannot create log directory [%s]. Please set %s to a writable location.\n"%(logfile_dir, ROS_LOG_DIR))
return None
elif os.path.isfile(logfile_dir):
raise LoggingException("Cannot save log files: file [%s] is in the way"%logfile_dir)
# the log dir itself should not be symlinked as latest
if logfile_dir != log_dir:
if sys.platform not in ['win32']:
try:
success = renew_latest_logdir(logfile_dir)
if not success:
sys.stderr.write("INFO: cannot create a symlink to latest log directory\n")
except OSError as e:
sys.stderr.write("INFO: cannot create a symlink to latest log directory: %s\n" % e)
if 'ROS_PYTHON_LOG_CONFIG_FILE' in os.environ:
config_file = os.environ['ROS_PYTHON_LOG_CONFIG_FILE']
else:
# search for logging config file in /etc/. If it's not there,
# look for it package-relative.
fname = 'python_logging.conf'
rosgraph_d = rospkg.RosPack().get_path('rosgraph')
for f in [os.path.join(rospkg.get_ros_home(), 'config', fname),
'/etc/ros/%s'%(fname),
os.path.join(rosgraph_d, 'conf', fname)]:
if os.path.isfile(f):
config_file = f
break
else:
config_file = None
if config_file is None or not os.path.isfile(config_file):
# logging is considered soft-fail
sys.stderr.write("WARNING: cannot load logging configuration file, logging is disabled\n")
logging.getLogger(logname).setLevel(logging.CRITICAL)
return log_filename
# pass in log_filename as argument to pylogging.conf
os.environ['ROS_LOG_FILENAME'] = log_filename
# #3625: disabling_existing_loggers=False
logging.config.fileConfig(config_file, disable_existing_loggers=False)
return log_filename
def makedirs_with_parent_perms(p):
"""
Create the directory using the permissions of the nearest
(existing) parent directory. This is useful for logging, where a
root process sometimes has to log in the user's space.
:param p: directory to create, ``str``
"""
p = os.path.abspath(p)
parent = os.path.dirname(p)
# recurse upwards, checking to make sure we haven't reached the
# top
if not os.path.exists(p) and p and parent != p:
makedirs_with_parent_perms(parent)
s = os.stat(parent)
os.mkdir(p)
# if perms of new dir don't match, set anew
s2 = os.stat(p)
if s.st_uid != s2.st_uid or s.st_gid != s2.st_gid:
os.chown(p, s.st_uid, s.st_gid)
if s.st_mode != s2.st_mode:
os.chmod(p, s.st_mode)
_logging_to_rospy_names = {
'DEBUG': ('DEBUG', '\033[32m'),
'INFO': ('INFO', None),
'WARNING': ('WARN', '\033[33m'),
'ERROR': ('ERROR', '\033[31m'),
'CRITICAL': ('FATAL', '\033[31m')
}
_color_reset = '\033[0m'
class RosStreamHandler(logging.Handler):
def __init__(self, colorize=True):
super(RosStreamHandler, self).__init__()
self._colorize = colorize
try:
from rospy.rostime import get_time, is_wallclock
self._get_time = get_time
self._is_wallclock = is_wallclock
except ImportError:
self._get_time = None
self._is_wallclock = None
def emit(self, record):
level, color = _logging_to_rospy_names[record.levelname]
if 'ROSCONSOLE_FORMAT' in os.environ.keys():
msg = os.environ['ROSCONSOLE_FORMAT']
msg = msg.replace('${severity}', level)
msg = msg.replace('${message}', str(record.getMessage()))
msg = msg.replace('${walltime}', '%f' % time.time())
msg = msg.replace('${thread}', str(record.thread))
msg = msg.replace('${logger}', str(record.name))
msg = msg.replace('${file}', str(record.pathname))
msg = msg.replace('${line}', str(record.lineno))
msg = msg.replace('${function}', str(record.funcName))
try:
from rospy import get_name
node_name = get_name()
except ImportError:
node_name = '<unknown_node_name>'
msg = msg.replace('${node}', node_name)
if self._get_time is not None and not self._is_wallclock():
t = self._get_time()
else:
t = time.time()
msg = msg.replace('${time}', '%f' % t)
msg += '\n'
else:
msg = '[%s] [WallTime: %f]' % (level, time.time())
if self._get_time is not None and not self._is_wallclock():
msg += ' [%f]' % self._get_time()
msg += ' %s\n' % record.getMessage()
if record.levelno < logging.WARNING:
self._write(sys.stdout, msg, color)
else:
self._write(sys.stderr, msg, color)
def _write(self, fd, msg, color):
if self._colorize and color and hasattr(fd, 'isatty') and fd.isatty():
msg = color + msg + _color_reset
fd.write(msg)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src/rosgraph/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: names.py 14589 2011-08-07 18:30:21Z kwc $
"""
Library for manipulating ROS Names. See U{http://ros.org/wiki/Names}.
"""
import os
import sys
from .rosenv import ROS_NAMESPACE
#TODO: why are these here?
MSG_EXT = '.msg'
SRV_EXT = '.srv'
SEP = '/'
GLOBALNS = '/'
PRIV_NAME = '~'
REMAP = ":="
ANYTYPE = '*'
if sys.hexversion > 0x03000000: #Python3
def isstring(s):
return isinstance(s, str) #Python 3.x
else:
def isstring(s):
"""
Small helper version to check an object is a string in a way that works
for both Python 2 and 3
"""
return isinstance(s, basestring) #Python 2.x
def get_ros_namespace(env=None, argv=None):
"""
@param env: environment dictionary (defaults to os.environ)
@type env: dict
@param argv: command-line arguments (defaults to sys.argv)
@type argv: [str]
@return: ROS namespace of current program
@rtype: str
"""
#we force command-line-specified namespaces to be globally scoped
if argv is None:
argv = sys.argv
for a in argv:
if a.startswith('__ns:='):
return make_global_ns(a[len('__ns:='):])
if env is None:
env = os.environ
return make_global_ns(env.get(ROS_NAMESPACE, GLOBALNS))
def make_caller_id(name):
"""
Resolve a local name to the caller ID based on ROS environment settings (i.e. ROS_NAMESPACE)
@param name: local name to calculate caller ID from, e.g. 'camera', 'node'
@type name: str
@return: caller ID based on supplied local name
@rtype: str
"""
return make_global_ns(ns_join(get_ros_namespace(), name))
def make_global_ns(name):
"""
Convert name to a global name with a trailing namespace separator.
@param name: ROS resource name. Cannot be a ~name.
@type name: str
@return str: name as a global name, e.g. 'foo' -> '/foo/'.
This does NOT resolve a name.
@rtype: str
@raise ValueError: if name is a ~name
"""
if is_private(name):
raise ValueError("cannot turn [%s] into a global name"%name)
if not is_global(name):
name = SEP + name
if name[-1] != SEP:
name = name + SEP
return name
def is_global(name):
"""
Test if name is a global graph resource name.
@param name: must be a legal name in canonical form
@type name: str
@return: True if name is a globally referenced name (i.e. /ns/name)
@rtype: bool
"""
return name and name[0] == SEP
def is_private(name):
"""
Test if name is a private graph resource name.
@param name: must be a legal name in canonical form
@type name: str
@return bool: True if name is a privately referenced name (i.e. ~name)
"""
return name and name[0] == PRIV_NAME
def namespace(name):
"""
Get the namespace of name. The namespace is returned with a
trailing slash in order to favor easy concatenation and easier use
within the global context.
@param name: name to return the namespace of. Must be a legal
name. NOTE: an empty name will return the global namespace.
@type name: str
@return str: Namespace of name. For example, '/wg/node1' returns '/wg/'. The
global namespace is '/'.
@rtype: str
@raise ValueError: if name is invalid
"""
"map name to its namespace"
if name is None:
raise ValueError('name')
if not isstring(name):
raise TypeError('name')
if not name:
return SEP
elif name[-1] == SEP:
name = name[:-1]
return name[:name.rfind(SEP)+1] or SEP
def ns_join(ns, name):
"""
Join a namespace and name. If name is unjoinable (i.e. ~private or
/global) it will be returned without joining
@param ns: namespace ('/' and '~' are both legal). If ns is the empty string, name will be returned.
@type ns: str
@param name str: a legal name
@return str: name concatenated to ns, or name if it is
unjoinable.
@rtype: str
"""
if is_private(name) or is_global(name):
return name
if ns == PRIV_NAME:
return PRIV_NAME + name
if not ns:
return name
if ns[-1] == SEP:
return ns + name
return ns + SEP + name
def load_mappings(argv):
"""
Load name mappings encoded in command-line arguments. This will filter
out any parameter assignment mappings.
@param argv: command-line arguments
@type argv: [str]
@return: name->name remappings.
@rtype: dict {str: str}
"""
mappings = {}
for arg in argv:
if REMAP in arg:
try:
src, dst = [x.strip() for x in arg.split(REMAP)]
if src and dst:
if len(src) > 1 and src[0] == '_' and src[1] != '_':
#ignore parameter assignment mappings
pass
else:
mappings[src] = dst
except:
#TODO: remove
sys.stderr.write("ERROR: Invalid remapping argument '%s'\n"%arg)
return mappings
################################################################################
# NAME VALIDATORS
import re
#~,/, or ascii char followed by (alphanumeric, _, /)
NAME_LEGAL_CHARS_P = re.compile('^[\~\/A-Za-z][\w\/]*$')
def is_legal_name(name):
"""
Check if name is a legal ROS name for graph resources
(alphabetical character followed by alphanumeric, underscore, or
forward slashes). This constraint is currently not being enforced,
but may start getting enforced in later versions of ROS.
@param name: Name
@type name: str
"""
# should we enforce unicode checks?
if name is None:
return False
# empty string is a legal name as it resolves to namespace
if name == '':
return True
m = NAME_LEGAL_CHARS_P.match(name)
return m is not None and m.group(0) == name and not '//' in name
BASE_NAME_LEGAL_CHARS_P = re.compile('^[A-Za-z][\w]*$') #ascii char followed by (alphanumeric, _)
def is_legal_base_name(name):
"""
Validates that name is a legal base name for a graph resource. A base name has
no namespace context, e.g. "node_name".
"""
if name is None:
return False
m = BASE_NAME_LEGAL_CHARS_P.match(name)
return m is not None and m.group(0) == name
def canonicalize_name(name):
"""
Put name in canonical form. Extra 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])
def resolve_name(name, namespace_, remappings=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 namespace_: node name to resolve relative to.
@type namespace_: str
@param remappings: Map of resolved remappings. Use None to indicate no remapping.
@return: Resolved name. If name is empty/None, resolve_name
returns parent namespace_. If namespace_ is empty/None,
@rtype: str
"""
if not name: #empty string resolves to parent of the namespace_
return namespace(namespace_)
name = canonicalize_name(name)
if name[0] == SEP: #global name
resolved_name = name
elif is_private(name): #~name
# #3044: be careful not to accidentally make rest of name global
resolved_name = canonicalize_name(namespace_ + SEP + name[1:])
else: #relative
resolved_name = namespace(namespace_) + 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 remappings and resolved_name in remappings:
return remappings[resolved_name]
else:
return resolved_name
def script_resolve_name(script_name, name):
"""
Name resolver for scripts. Supports :envvar:`ROS_NAMESPACE`. Does not
support remapping arguments.
:param name: name to resolve, ``str``
:param script_name: name of script. script_name must not
contain a namespace., ``str``
:returns: resolved name, ``str``
"""
if not name: #empty string resolves to namespace
return get_ros_namespace()
#Check for global name: /foo/name resolves to /foo/name
if is_global(name):
return name
#Check for private name: ~name resolves to /caller_id/name
elif is_private(name):
return ns_join(make_caller_id(script_name), name[1:])
return get_ros_namespace() + name
def anonymous_name(id):
"""
Generate a ROS-legal 'anonymous' name
@param id: prefix for anonymous name
@type id: str
"""
import socket, random
name = "%s_%s_%s_%s"%(id, socket.gethostname(), os.getpid(), random.randint(0, sys.maxsize))
# RFC 952 allows hyphens, IP addrs can have '.'s, both
# of which are illegal for ROS names. For good
# measure, screen ipv6 ':'.
name = name.replace('.', '_')
name = name.replace('-', '_')
return name.replace(':', '_')
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src/rosgraph/network.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: network.py 15125 2011-10-06 02:51:15Z kwc $
"""
Network APIs for ROS-based systems, including IP address and ROS
TCP header libraries. Because ROS-based runtimes must respect the
ROS_IP and ROS_HOSTNAME environment variables, ROS-specific APIs
are necessary for correctly retrieving local IP address
information.
"""
import logging
import os
import socket
import struct
import sys
import platform
try:
from cStringIO import StringIO #Python 2.x
python3 = 0
except ImportError:
from io import BytesIO #Python 3.x
python3 = 1
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
from .rosenv import ROS_IP, ROS_HOSTNAME, ROS_IPV6
SIOCGIFCONF = 0x8912
SIOCGIFADDR = 0x8915
if platform.system() == 'FreeBSD':
SIOCGIFADDR = 0xc0206921
if platform.architecture()[0] == '64bit':
SIOCGIFCONF = 0xc0106924
else:
SIOCGIFCONF = 0xc0086924
logger = logging.getLogger('rosgraph.network')
def parse_http_host_and_port(url):
"""
Convenience routine to handle parsing and validation of HTTP URL
port due to the fact that Python only provides easy accessors in
Python 2.5 and later. Validation checks that the protocol and host
are set.
:param url: URL to parse, ``str``
:returns: hostname and port number in URL or 80 (default), ``(str, int)``
:raises: :exc:`ValueError` If the url does not validate
"""
# can't use p.port because that's only available in Python 2.5
if not url:
raise ValueError('not a valid URL')
p = urlparse.urlparse(url)
if not p[0] or not p[1]: #protocol and host
raise ValueError('not a valid URL')
if ':' in p[1]:
hostname, port = p[1].split(':')
port = int(port)
else:
hostname, port = p[1], 80
return hostname, port
def _is_unix_like_platform():
"""
:returns: true if the platform conforms to UNIX/POSIX-style APIs
@rtype: bool
"""
#return platform.system() in ['Linux', 'Mac OS X', 'Darwin']
return platform.system() in ['Linux', 'FreeBSD']
def get_address_override():
"""
:returns: ROS_IP/ROS_HOSTNAME override or None, ``str``
:raises: :exc:`ValueError` If ROS_IP/ROS_HOSTNAME/__ip/__hostname are invalidly specified
"""
# #998: check for command-line remappings first
# TODO IPV6: check for compatibility
for arg in sys.argv:
if arg.startswith('__hostname:=') or arg.startswith('__ip:='):
try:
_, val = arg.split(':=')
return val
except: #split didn't unpack properly
raise ValueError("invalid ROS command-line remapping argument '%s'"%arg)
# check ROS_HOSTNAME and ROS_IP environment variables, which are
# aliases for each other
if ROS_HOSTNAME in os.environ:
hostname = os.environ[ROS_HOSTNAME]
if hostname == '':
msg = 'invalid ROS_HOSTNAME (an empty string)'
sys.stderr.write(msg + '\n')
logger.warn(msg)
else:
parts = urlparse.urlparse(hostname)
if parts.scheme:
msg = 'invalid ROS_HOSTNAME (protocol ' + ('and port ' if parts.port else '') + 'should not be included)'
sys.stderr.write(msg + '\n')
logger.warn(msg)
elif hostname.find(':') != -1:
# this can not be checked with urlparse()
# since it does not extract the port for a hostname like "foo:1234"
msg = 'invalid ROS_HOSTNAME (port should not be included)'
sys.stderr.write(msg + '\n')
logger.warn(msg)
return hostname
elif ROS_IP in os.environ:
ip = os.environ[ROS_IP]
if ip == '':
msg = 'invalid ROS_IP (an empty string)'
sys.stderr.write(msg + '\n')
logger.warn(msg)
elif ip.find('://') != -1:
msg = 'invalid ROS_IP (protocol should not be included)'
sys.stderr.write(msg + '\n')
logger.warn(msg)
elif ip.find('.') != -1 and ip.rfind(':') > ip.rfind('.'):
msg = 'invalid ROS_IP (port should not be included)'
sys.stderr.write(msg + '\n')
logger.warn(msg)
elif ip.find('.') == -1 and ip.find(':') == -1:
msg = 'invalid ROS_IP (must be a valid IPv4 or IPv6 address)'
sys.stderr.write(msg + '\n')
logger.warn(msg)
return ip
return None
def is_local_address(hostname):
"""
:param hostname: host name/address, ``str``
:returns True: if hostname maps to a local address, False otherwise. False conditions include invalid hostnames.
"""
try:
if use_ipv6():
reverse_ips = [host[4][0] for host in socket.getaddrinfo(hostname, 0, 0, 0, socket.SOL_TCP)]
else:
reverse_ips = [host[4][0] for host in socket.getaddrinfo(hostname, 0, socket.AF_INET, 0, socket.SOL_TCP)]
except socket.error:
return False
local_addresses = ['localhost'] + get_local_addresses()
# 127. check is due to #1260
if ([ip for ip in reverse_ips if (ip.startswith('127.') or ip == '::1')] != []) or (set(reverse_ips) & set(local_addresses) != set()):
return True
return False
def get_local_address():
"""
:returns: default local IP address (e.g. eth0). May be overriden by ROS_IP/ROS_HOSTNAME/__ip/__hostname, ``str``
"""
override = get_address_override()
if override:
return override
addrs = get_local_addresses()
if len(addrs) == 1:
return addrs[0]
for addr in addrs:
# pick first non 127/8 address
if not addr.startswith('127.') and not addr == '::1':
return addr
else: # loopback
if use_ipv6():
return '::1'
else:
return '127.0.0.1'
# cache for performance reasons
_local_addrs = None
def get_local_addresses():
"""
:returns: known local addresses. Not affected by ROS_IP/ROS_HOSTNAME, ``[str]``
"""
# cache address data as it can be slow to calculate
global _local_addrs
if _local_addrs is not None:
return _local_addrs
local_addrs = None
if _is_unix_like_platform():
# unix-only branch
v4addrs = []
v6addrs = []
import netifaces
for iface in netifaces.interfaces():
try:
ifaddrs = netifaces.ifaddresses(iface)
except ValueError:
# even if interfaces() returns an interface name
# ifaddresses() might raise a ValueError
# https://bugs.launchpad.net/ubuntu/+source/netifaces/+bug/753009
continue
if socket.AF_INET in ifaddrs:
v4addrs.extend([addr['addr'] for addr in ifaddrs[socket.AF_INET]])
if socket.AF_INET6 in ifaddrs:
v6addrs.extend([addr['addr'] for addr in ifaddrs[socket.AF_INET6]])
if use_ipv6():
local_addrs = v6addrs + v4addrs
else:
local_addrs = v4addrs
else:
# cross-platform branch, can only resolve one address
if use_ipv6():
local_addrs = [host[4][0] for host in socket.getaddrinfo(socket.gethostname(), 0, 0, 0, socket.SOL_TCP)]
else:
local_addrs = [host[4][0] for host in socket.getaddrinfo(socket.gethostname(), 0, socket.AF_INET, 0, socket.SOL_TCP)]
_local_addrs = local_addrs
return local_addrs
def use_ipv6():
return ROS_IPV6 in os.environ and os.environ[ROS_IPV6] == 'on'
def get_bind_address(address=None):
"""
:param address: (optional) address to compare against, ``str``
:returns: address TCP/IP sockets should use for binding. This is
generally 0.0.0.0, but if \a address or ROS_IP/ROS_HOSTNAME is set
to localhost it will return 127.0.0.1, ``str``
"""
if address is None:
address = get_address_override()
if address and (address == 'localhost' or address.startswith('127.') or address == '::1' ):
#localhost or 127/8
if use_ipv6():
return '::1'
elif address.startswith('127.'):
return address
else:
return '127.0.0.1' #loopback
else:
if use_ipv6():
return '::'
else:
return '0.0.0.0'
# #528: semi-complicated logic for determining XML-RPC URI
def get_host_name():
"""
Determine host-name for use in host-name-based addressing (e.g. XML-RPC URIs):
- if ROS_IP/ROS_HOSTNAME is set, use that address
- if the hostname returns a non-localhost value, use that
- use whatever L{get_local_address()} returns
"""
hostname = get_address_override()
if not hostname:
try:
hostname = socket.gethostname()
except:
pass
if not hostname or hostname == 'localhost' or hostname.startswith('127.'):
hostname = get_local_address()
return hostname
def create_local_xmlrpc_uri(port):
"""
Determine the XMLRPC URI for local servers. This handles the search
logic of checking ROS environment variables, the known hostname,
and local interface IP addresses to determine the best possible
URI.
:param port: port that server is running on, ``int``
:returns: XMLRPC URI, ``str``
"""
#TODO: merge logic in rosgraph.xmlrpc with this routine
# in the future we may not want to be locked to http protocol nor root path
return 'http://%s:%s/'%(get_host_name(), port)
## handshake utils ###########################################
class ROSHandshakeException(Exception):
"""
Exception to represent errors decoding handshake
"""
pass
def decode_ros_handshake_header(header_str):
"""
Decode serialized ROS handshake header into a Python dictionary
header is a list of string key=value pairs, each prefixed by a
4-byte length field. It is preceeded by a 4-byte length field for
the entire header.
:param header_str: encoded header string. May contain extra data at the end, ``str``
:returns: key value pairs encoded in \a header_str, ``{str: str}``
"""
(size, ) = struct.unpack('<I', header_str[0:4])
size += 4 # add in 4 to include size of size field
header_len = len(header_str)
if size > header_len:
raise ROSHandshakeException("Incomplete header. Expected %s bytes but only have %s"%((size+4), header_len))
d = {}
start = 4
while start < size:
(field_size, ) = struct.unpack('<I', header_str[start:start+4])
if field_size == 0:
raise ROSHandshakeException("Invalid 0-length handshake header field")
start += field_size + 4
if start > size:
raise ROSHandshakeException("Invalid line length in handshake header: %s"%size)
line = header_str[start-field_size:start]
#python3 compatibility
if python3 == 1:
line = line.decode()
idx = line.find("=")
if idx < 0:
raise ROSHandshakeException("Invalid line in handshake header: [%s]"%line)
key = line[:idx]
value = line[idx+1:]
d[key.strip()] = value
return d
def read_ros_handshake_header(sock, b, buff_size):
"""
Read in tcpros header off the socket \a sock using buffer \a b.
:param sock: socket must be in blocking mode, ``socket``
:param b: buffer to use, ``StringIO`` for Python2, ``BytesIO`` for Python 3
:param buff_size: incoming buffer size to use, ``int``
:returns: key value pairs encoded in handshake, ``{str: str}``
:raises: :exc:`ROSHandshakeException` If header format does not match expected
"""
header_str = None
while not header_str:
d = sock.recv(buff_size)
if not d:
raise ROSHandshakeException("connection from sender terminated before handshake header received. %s bytes were received. Please check sender for additional details."%b.tell())
b.write(d)
btell = b.tell()
if btell > 4:
# most likely we will get the full header in the first recv, so
# not worth tiny optimizations possible here
bval = b.getvalue()
(size,) = struct.unpack('<I', bval[0:4])
if btell - 4 >= size:
header_str = bval
# memmove the remnants of the buffer back to the start
leftovers = bval[size+4:]
b.truncate(len(leftovers))
b.seek(0)
b.write(leftovers)
header_recvd = True
# process the header
return decode_ros_handshake_header(bval)
def encode_ros_handshake_header(header):
"""
Encode ROS handshake header as a byte string. Each header
field is a string key value pair. The encoded header is
prefixed by a length field, as is each field key/value pair.
key/value pairs a separated by a '=' equals sign.
FORMAT: (4-byte length + [4-byte field length + field=value ]*)
:param header: header field keys/values, ``dict``
:returns: header encoded as byte string, ``bytes``
"""
str_cls = str if python3 else unicode
# encode all unicode keys in the header. Ideally, the type of these would be specified by the api
encoded_header = {}
for k, v in header.items():
if isinstance(k, str_cls):
k = k.encode('utf-8')
if isinstance(v, str_cls):
v = v.encode('utf-8')
encoded_header[k] = v
fields = [k + b"=" + v for k, v in sorted(encoded_header.items())]
s = b''.join([struct.pack('<I', len(f)) + f for f in fields])
return struct.pack('<I', len(s)) + s
def write_ros_handshake_header(sock, header):
"""
Write ROS handshake header header to socket sock
:param sock: socket to write to (must be in blocking mode), ``socket.socket``
:param header: header field keys/values, ``{str : str}``
:returns: Number of bytes sent (for statistics), ``int``
"""
s = encode_ros_handshake_header(header)
sock.sendall(s)
return len(s) #STATS
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src/rosgraph/rosenv.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.
import os
import sys
ROS_MASTER_URI = "ROS_MASTER_URI"
ROS_IP ="ROS_IP"
ROS_IPV6 ="ROS_IPV6"
ROS_HOSTNAME ="ROS_HOSTNAME"
ROS_NAMESPACE ="ROS_NAMESPACE"
def get_master_uri(env=None, argv=None):
"""
Get the :envvar:`ROS_MASTER_URI` setting from the command-line args or
environment, command-line args takes precedence.
:param env: override environment dictionary, ``dict``
:param argv: override ``sys.argv``, ``[str]``
:raises: :exc:`ValueError` If :envvar:`ROS_MASTER_URI` value is invalidly
specified
"""
if env is None:
env = os.environ
if argv is None:
argv = sys.argv
try:
for arg in argv:
if arg.startswith('__master:='):
val = None
try:
_, val = arg.split(':=')
except:
pass
# we ignore required here because there really is no
# correct return value as the configuration is bad
# rather than unspecified
if not val:
raise ValueError("__master remapping argument '%s' improperly specified"%arg)
return val
return env[ROS_MASTER_URI]
except KeyError as e:
return None
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src/rosgraph | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src/rosgraph/impl/graph.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
"""
Data structures and library for representing ROS Computation Graph state.
"""
import sys
import time
import itertools
import random
import logging
import traceback
try:
from xmlrpc.client import ServerProxy
except ImportError:
from xmlrpclib import ServerProxy
import socket
import rosgraph.masterapi
logger = logging.getLogger('rosgraph.graph')
_ROS_NAME = '/rosviz'
def topic_node(topic):
"""
In order to prevent topic/node name aliasing, we have to remap
topic node names. Currently we just prepend a space, which is
an illegal ROS name and thus not aliased.
@return str: topic mapped to a graph node name.
"""
return ' ' + topic
def node_topic(node):
"""
Inverse of topic_node
@return str: undo topic_node() operation
"""
return node[1:]
class BadNode(object):
"""
Data structure for storing info about a 'bad' node
"""
## no connectivity
DEAD = 0
## intermittent connectivity
WONKY = 1
def __init__(self, name, type, reason):
"""
@param type: DEAD | WONKY
@type type: int
"""
self.name =name
self.reason = reason
self.type = type
class EdgeList(object):
"""
Data structure for storing Edge instances
"""
__slots__ = ['edges_by_start', 'edges_by_end']
def __init__(self):
# in order to make it easy to purge edges, we double-index them
self.edges_by_start = {}
self.edges_by_end = {}
def __iter__(self):
return itertools.chain(*[v for v in self.edges_by_start.values()])
def has(self, edge):
"""
@return: True if edge is in edge list
@rtype: bool
"""
key = edge.key
return key in self.edges_by_start and \
edge in self.edges_by_start[key]
def add(self, edge):
"""
Add an edge to our internal representation. not multi-thread safe
@param edge: edge to add
@type edge: Edge
"""
# see note in __init__
def update_map(map, key, edge):
if key in map:
l = map[key]
if not edge in l:
l.append(edge)
return True
else:
return False
else:
map[key] = [edge]
return True
updated = update_map(self.edges_by_start, edge.key, edge)
updated = update_map(self.edges_by_end, edge.rkey, edge) or updated
return updated
def add_edges(self, start, dest, direction, label=''):
"""
Create Edge instances for args and add resulting edges to edge
list. Convenience method to avoid repetitve logging, etc...
@param edge_list: data structure to add edge to
@type edge_list: EdgeList
@param start: name of start node. If None, warning will be logged and add fails
@type start: str
@param dest: name of start node. If None, warning will be logged and add fails
@type dest: str
@param direction: direction string (i/o/b)
@type direction: str
@return: True if update occured
@rtype: bool
"""
# the warnings should generally be temporary, occuring of the
# master/node information becomes stale while we are still
# doing an update
updated = False
if not start:
logger.warn("cannot add edge: cannot map start [%s] to a node name", start)
elif not dest:
logger.warn("cannot add edge: cannot map dest [%s] to a node name", dest)
else:
for args in edge_args(start, dest, direction, label):
updated = self.add(Edge(*args)) or updated
return updated
def delete_all(self, node):
"""
Delete all edges that start or end at node
@param node: name of node
@type node: str
"""
def matching(map, pref):
return [map[k] for k in map.keys() if k.startswith(pref)]
pref = node+"|"
edge_lists = matching(self.edges_by_start, pref) + matching(self.edges_by_end, pref)
for el in edge_lists:
for e in el:
self.delete(e)
def delete(self, edge):
# see note in __init__
def update_map(map, key, edge):
if key in map:
edges = map[key]
if edge in edges:
edges.remove(edge)
return True
update_map(self.edges_by_start, edge.key, edge)
update_map(self.edges_by_end, edge.rkey, edge)
class Edge(object):
"""
Data structure for representing ROS node graph edge
"""
__slots__ = ['start', 'end', 'label', 'key', 'rkey']
def __init__(self, start, end, label=''):
self.start = start
self.end = end
self.label = label
self.key = "%s|%s"%(self.start, self.label)
# reverse key, indexed from end
self.rkey = "%s|%s"%(self.end, self.label)
def __ne__(self, other):
return self.start != other.start or self.end != other.end
def __str__(self):
return "%s->%s"%(self.start, self.end)
def __eq__(self, other):
return self.start == other.start and self.end == other.end
def edge_args(start, dest, direction, label):
"""
compute argument ordering for Edge constructor based on direction flag
@param direction str: 'i', 'o', or 'b' (in/out/bidir) relative to \a start
@param start str: name of starting node
@param start dest: name of destination node
"""
edge_args = []
if direction in ['o', 'b']:
edge_args.append((start, dest, label))
if direction in ['i', 'b']:
edge_args.append((dest, start, label))
return edge_args
class Graph(object):
"""
Utility class for polling ROS statistics from running ROS graph.
Not multi-thread-safe
"""
def __init__(self, node_ns='/', topic_ns='/'):
self.master = rosgraph.masterapi.Master(_ROS_NAME)
self.node_ns = node_ns or '/'
self.topic_ns = topic_ns or '/'
# ROS nodes
self.nn_nodes = set([])
# ROS topic nodes
self.nt_nodes = set([])
# ROS nodes that aren't responding quickly
self.bad_nodes = {}
import threading
self.bad_nodes_lock = threading.Lock()
# ROS services
self.srvs = set([])
# ROS node->node transport connections
self.nn_edges = EdgeList()
# ROS node->topic connections
self.nt_edges = EdgeList()
# ROS all node->topic connections, including empty
self.nt_all_edges = EdgeList()
# node names to URI map
self.node_uri_map = {} # { node_name_str : uri_str }
# reverse map URIs to node names
self.uri_node_map = {} # { uri_str : node_name_str }
# time we last contacted master
self.last_master_refresh = 0
self.last_node_refresh = {}
# time we last communicated with master
# seconds until master data is considered stale
self.master_stale = 5.0
# time we last communicated with node
# seconds until node data is considered stale
self.node_stale = 5.0 #seconds
def set_master_stale(self, stale_secs):
"""
@param stale_secs: seconds that data is considered fresh
@type stale_secs: double
"""
self.master_stale = stale_secs
def set_node_stale(self, stale_secs):
"""
@param stale_secs: seconds that data is considered fresh
@type stale_secs: double
"""
self.node_stale = stale_secs
def _master_refresh(self):
"""
@return: True if nodes information was updated
@rtype: bool
"""
logger.debug("master refresh: starting")
updated = False
try:
val = self.master.getSystemState()
except rosgraph.masterapi.MasterException as e:
print("Unable to contact master", str(e), file=sys.stderr)
logger.error("unable to contact master: %s", str(e))
return False
pubs, subs, srvs = val
nodes = []
nt_all_edges = self.nt_all_edges
nt_nodes = self.nt_nodes
for state, direction in ((pubs, 'o'), (subs, 'i')):
for topic, l in state:
if topic.startswith(self.topic_ns):
nodes.extend([n for n in l if n.startswith(self.node_ns)])
nt_nodes.add(topic_node(topic))
for node in l:
updated = nt_all_edges.add_edges(
node, topic_node(topic), direction) or updated
nodes = set(nodes)
srvs = set([s for s, _ in srvs])
purge = None
if nodes ^ self.nn_nodes:
purge = self.nn_nodes - nodes
self.nn_nodes = nodes
updated = True
if srvs ^ self.srvs:
self.srvs = srvs
updated = True
if purge:
logger.debug("following nodes and related edges will be purged: %s", ','.join(purge))
for p in purge:
logger.debug('purging edges for node %s', p)
self.nn_edges.delete_all(p)
self.nt_edges.delete_all(p)
self.nt_all_edges.delete_all(p)
logger.debug("master refresh: done, updated[%s]", updated)
return updated
def _mark_bad_node(self, node, reason):
try:
# bad nodes are updated in a separate thread, so lock
self.bad_nodes_lock.acquire()
if node in self.bad_nodes:
self.bad_nodes[node].type = BadNode.DEAD
else:
self.bad_nodes[node] = (BadNode(node, BadNode.DEAD, reason))
finally:
self.bad_nodes_lock.release()
def _unmark_bad_node(self, node, reason):
"""
Promotes bad node to 'wonky' status.
"""
try:
# bad nodes are updated in a separate thread, so lock
self.bad_nodes_lock.acquire()
bad = self.bad_nodes[node]
bad.type = BadNode.WONKY
finally:
self.bad_nodes_lock.release()
def _node_refresh_businfo(self, node, api, bad_node=False):
"""
Retrieve bus info from the node and update nodes and edges as appropriate
@param node: node name
@type node: str
@param api: XML-RPC proxy
@type api: ServerProxy
@param bad_node: If True, node has connectivity issues and
should be treated differently
@type bad_node: bool
"""
try:
logger.debug("businfo: contacting node [%s] for bus info", node)
# unmark bad node, though it stays on the bad list
if bad_node:
self._unmark_bad_node(node)
# Lower the socket timeout as we cannot abide by slow HTTP timeouts.
# If a node cannot meet this timeout, it goes on the bad list
# TODO: override transport instead.
old_timeout = socket.getdefaulttimeout()
if bad_node:
#even stricter timeout for bad_nodes right now
socket.setdefaulttimeout(0.2)
else:
socket.setdefaulttimeout(1.0)
code, msg, bus_info = api.getBusInfo(_ROS_NAME)
socket.setdefaulttimeout(old_timeout)
except Exception as e:
# node is (still) bad
self._mark_bad_node(node, str(e))
code = -1
msg = traceback.format_exc()
updated = False
if code != 1:
logger.error("cannot get stats info from node [%s]: %s", node, msg)
else:
# [[connectionId1, destinationId1, direction1, transport1, ...]... ]
for info in bus_info:
# #3579 bad node, ignore
if len(info) < 5:
continue
connection_id = info[0]
dest_id = info[1]
direction = info[2]
transport = info[3]
topic = info[4]
if len(info) > 5:
connected = info[5]
else:
connected = True #backwards compatibility
if connected and topic.startswith(self.topic_ns):
# blindly add as we will be able to catch state change via edges.
# this currently means we don't cleanup topics
self.nt_nodes.add(topic_node(topic))
# update node->topic->node graph edges
updated = self.nt_edges.add_edges(node, topic_node(topic), direction) or updated
# update node->node graph edges
if dest_id.startswith('http://'):
#print("FOUND URI", dest_id)
dest_name = self.uri_node_map.get(dest_id, None)
updated = self.nn_edges.add_edges(node, dest_name, direction, topic) or updated
else:
#TODO: anyting to do here?
pass
return updated
def _node_refresh(self, node, bad_node=False):
"""
Contact node for stats/connectivity information
@param node: name of node to contact
@type node: str
@param bad_node: if True, node has connectivity issues
@type bad_node: bool
@return: True if node was successfully contacted
@rtype bool
"""
# TODO: I'd like for master to provide this information in
# getSystemState() instead to prevent the extra connection per node
updated = False
uri = self._node_uri_refresh(node)
try:
if uri:
api = ServerProxy(uri)
updated = self._node_refresh_businfo(node, api, bad_node)
except KeyError as e:
logger.warn('cannot contact node [%s] as it is not in the lookup table'%node)
return updated
def _node_uri_refresh(self, node):
try:
uri = self.master.lookupNode(node)
except:
msg = traceback.format_exc()
logger.warn("master reported error in node lookup: %s"%msg)
return None
# update maps
self.node_uri_map[node] = uri
self.uri_node_map[uri] = node
return uri
def _node_uri_refresh_all(self):
"""
Build self.node_uri_map and self.uri_node_map using master as a
lookup service. This will make N requests to the master for N
nodes, so this should only be used sparingly
"""
for node in self.nn_nodes:
self._node_uri_refresh(node)
def bad_update(self):
"""
Update loop for nodes with bad connectivity. We box them separately
so that we can maintain the good performance of the normal update loop.
Once a node is on the bad list it stays there.
"""
last_node_refresh = self.last_node_refresh
# nodes left to check
try:
self.bad_nodes_lock.acquire()
# make copy due to multithreading
update_queue = self.bad_nodes.values()[:]
finally:
self.bad_nodes_lock.release()
# return value. True if new data differs from old
updated = False
# number of nodes we checked
num_nodes = 0
start_time = time.time()
while update_queue:
# figure out the next node to contact
next = update_queue.pop()
# rate limit talking to any particular node
if time.time() > (last_node_refresh.get(next, 0.0) + self.node_stale):
updated = self._node_refresh(next.name, True) or updated
# include in random offset (max 1/5th normal update interval)
# to help spread out updates
last_node_refresh[next] = time.time() + (random.random() * self.node_stale / 5.0)
num_nodes += 1
# small yield to keep from torquing the processor
time.sleep(0.01)
end_time = time.time()
#print("Update (bad nodes) took %ss for %s nodes"%((end_time-start_time), num_nodes))
logger.debug("ROS stats (bad nodes) update took %ss"%(end_time-start_time))
return updated
def update(self):
"""
Update all the stats. This method may take awhile to complete as it will
communicate with all nodes + master.
"""
last_node_refresh = self.last_node_refresh
# nodes left to check
update_queue = None
# True if there are still more stats to fetch this cycle
work_to_do = True
# return value. True if new data differs from old
updated = False
# number of nodes we checked
num_nodes = 0
start_time = time.time()
while work_to_do:
# each time through the loop try to talk to either the master
# or a node. stop when we have talked to everybody.
# get a new node list from the master
if time.time() > (self.last_master_refresh + self.master_stale):
updated = self._master_refresh()
if self.last_master_refresh == 0:
# first time we contact the master, also refresh our full lookup tables
self._node_uri_refresh_all()
self.last_master_refresh = time.time()
# contact the nodes for stats
else:
# initialize update_queue based on most current nodes list
if update_queue is None:
update_queue = list(self.nn_nodes)
# no nodes left to contact
elif not update_queue:
work_to_do = False
# contact next node
else:
# figure out the next node to contact
next = update_queue.pop()
# rate limit talking to any particular node
if time.time() > (last_node_refresh.get(next, 0.0) + self.node_stale):
updated = self._node_refresh(next) or updated
# include in random offset (max 1/5th normal update interval)
# to help spread out updates
last_node_refresh[next] = time.time() + (random.random() * self.node_stale / 5.0)
num_nodes += 1
# small yield to keep from torquing the processor
time.sleep(0.01)
end_time = time.time()
#print("Update took %ss for %s nodes"%((end_time-start_time), num_nodes))
logger.debug("ROS stats update took %ss"%(end_time-start_time))
return updated
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src/rosgraph | apollo_public_repos/apollo-platform/ros/ros_comm/rosgraph/src/rosgraph/impl/__init__.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: __init__.py 5735 2009-08-20 21:31:27Z sfkwc $
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.3)
project(rosbag_storage)
if(NOT WIN32)
set_directory_properties(PROPERTIES COMPILE_OPTIONS "-Wall;-Wextra")
endif()
find_package(console_bridge REQUIRED)
find_package(catkin REQUIRED COMPONENTS cpp_common roscpp_serialization roscpp_traits rostime roslz4)
find_package(Boost REQUIRED COMPONENTS date_time filesystem program_options regex)
find_package(BZip2 REQUIRED)
catkin_package(
INCLUDE_DIRS include
LIBRARIES rosbag_storage
CATKIN_DEPENDS roslz4
DEPENDS console_bridge Boost
)
# Support large bags (>2GB) on 32-bit systems
add_definitions(-D_FILE_OFFSET_BITS=64)
include_directories(include ${catkin_INCLUDE_DIRS} ${console_bridge_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${BZIP2_INCLUDE_DIR})
add_definitions(${BZIP2_DEFINITIONS})
add_library(rosbag_storage
src/bag.cpp
src/bag_player.cpp
src/buffer.cpp
src/bz2_stream.cpp
src/lz4_stream.cpp
src/chunked_file.cpp
src/message_instance.cpp
src/query.cpp
src/stream.cpp
src/view.cpp
src/uncompressed_stream.cpp
)
target_link_libraries(rosbag_storage ${catkin_LIBRARIES} ${Boost_LIBRARIES} ${BZIP2_LIBRARIES} ${console_bridge_LIBRARIES})
install(TARGETS rosbag_storage
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
install(DIRECTORY include/
DESTINATION ${CATKIN_GLOBAL_INCLUDE_DESTINATION}
FILES_MATCHING PATTERN "*.h"
)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/package.xml | <package>
<name>rosbag_storage</name>
<version>1.11.21</version>
<description>
This is a set of tools for recording from and playing back ROS
message without relying on the ROS client library.
</description>
<maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer>
<license>BSD</license>
<buildtool_depend>catkin</buildtool_depend>
<build_depend>boost</build_depend>
<build_depend>bzip2</build_depend>
<build_depend version_gte="0.3.17">cpp_common</build_depend>
<build_depend>libconsole-bridge-dev</build_depend>
<build_depend>roscpp_serialization</build_depend>
<build_depend version_gte="0.3.17">roscpp_traits</build_depend>
<build_depend>rostime</build_depend>
<build_depend>roslz4</build_depend>
<run_depend>boost</run_depend>
<run_depend>bzip2</run_depend>
<run_depend version_gte="0.3.17">cpp_common</run_depend>
<run_depend>libconsole-bridge-dev</run_depend>
<run_depend>roscpp_serialization</run_depend>
<run_depend version_gte="0.3.17">roscpp_traits</run_depend>
<run_depend>rostime</run_depend>
<run_depend>roslz4</run_depend>
<export>
<rosdoc config="${prefix}/rosdoc.yaml"/>
</export>
</package>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/mainpage.dox | /**
\mainpage
\htmlinclude manifest.html
\b rosbag_storage is a set of tools and API's for recording/writing messages to bag files and playing/reading them back without relying on the ROS client library.
The code is still in the rosbag namespace since it was extracted from the <a href="../../../rosbag/html/c++/">rosbag</a> package without renaming any API.
\section codeapi Code API
The C++ and Python API's are provided for serializing bag files. The C++ API consists of the following classes:
- rosbag::Bag - Serializes to/from a bag file on disk.
- rosbag::View - Specifies a view into a bag file to allow for querying for messages on specific connections withn a time range.
Here's a simple example of writing to a bag file:
\verbatim
#include "rosbag/bag.h"
...
rosbag::Bag bag("test.bag", rosbag::bagmode::Write);
std_msgs::Int32 i;
i.data = 42;
bag.write("numbers", ros::Time::now(), i);
bag.close();
\endverbatim
Likewise, to read from that bag file:
\verbatim
#include "rosbag/bag.h"
...
rosbag::Bag bag("test.bag");
rosbag::View view(bag, rosbag::TopicQuery("numbers"));
BOOST_FOREACH(rosbag::MessageInstance const m, view)
{
std_msgs::Int32::ConstPtr i = m.instantiate<std_msgs::Int32>();
if (i != NULL)
std::cout << i->data << std::endl;
}
bag.close();
\endverbatim
The Python API is similar. Writing to a bag file:
\verbatim
import rosbag
from std_msgs.msg import Int32, String
bag = rosbag.Bag('test.bag', 'w')
i = Int32()
i.data = 42
bag.write('numbers', i);
bag.close();
\endverbatim
Example usage for read:
\verbatim
import rosbag
bag = rosbag.Bag('test.bag')
for topic, msg, t in bag.read_messages('numbers'):
print msg.data
bag.close();
\endverbatim
*/
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/rosdoc.yaml | - builder: epydoc
output_dir: python
- builder: doxygen
name: C++ API
output_dir: c++
file_patterns: '*.c *.cpp *.h *.cc *.hh *.dox'
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/.tar | {!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/rosbag_storage/1.11.21-0.tar.gz',
!!python/unicode 'version': ros_comm-release-release-indigo-rosbag_storage-1.11.21-0}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/CHANGELOG.rst | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package rosbag_storage
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
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)
--------------------
* 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)
--------------------
1.11.13 (2015-04-28)
--------------------
1.11.12 (2015-04-27)
--------------------
1.11.11 (2015-04-16)
--------------------
* support large bagfiles (>2GB) on 32-bit systems (`#464 <https://github.com/ros/ros_comm/issues/464>`_)
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)
-------------------
* convert to use console bridge from upstream debian package (`ros/rosdistro#4633 <https://github.com/ros/rosdistro/issues/4633>`_)
1.11.4 (2014-06-16)
-------------------
1.11.3 (2014-05-21)
-------------------
1.11.2 (2014-05-08)
-------------------
1.11.1 (2014-05-07)
-------------------
* add lz4 compression to rosbag (Python and C++) (`#356 <https://github.com/ros/ros_comm/issues/356>`_)
* move rosbag dox to rosbag_storage (`#389 <https://github.com/ros/ros_comm/issues/389>`_)
1.11.0 (2014-03-04)
-------------------
1.10.0 (2014-02-11)
-------------------
* remove use of __connection header
1.9.54 (2014-01-27)
-------------------
1.9.53 (2014-01-14)
-------------------
1.9.52 (2014-01-08)
-------------------
1.9.51 (2014-01-07)
-------------------
* move several client library independent parts from ros_comm into roscpp_core, split rosbag storage specific stuff from client library usage (`#299 <https://github.com/ros/ros_comm/issues/299>`_)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include/rosbag/bag.h | /*********************************************************************
* 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.
*********************************************************************/
#ifndef ROSBAG_BAG_H
#define ROSBAG_BAG_H
#include "rosbag/macros.h"
#include "rosbag/buffer.h"
#include "rosbag/chunked_file.h"
#include "rosbag/constants.h"
#include "rosbag/exceptions.h"
#include "rosbag/structures.h"
#include "ros/header.h"
#include "ros/time.h"
#include "ros/message_traits.h"
#include "ros/protobuffer_traits.h"
#include "ros/message_event.h"
#include "ros/serialization.h"
#include "ros/serialization_protobuffer.h"
//#include "ros/subscription_callback_helper.h"
#include <ios>
#include <map>
#include <queue>
#include <set>
#include <stdexcept>
#include <boost/format.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include "console_bridge/console.h"
namespace rosbag {
namespace bagmode
{
//! The possible modes to open a bag in
enum BagMode
{
Write = 1,
Read = 2,
Append = 4
};
}
typedef bagmode::BagMode BagMode;
class MessageInstance;
class View;
class Query;
class ROSBAG_DECL Bag
{
friend class MessageInstance;
friend class View;
public:
Bag();
//! Open a bag file
/*!
* \param filename The bag file to open
* \param mode The mode to use (either read, write or append)
*
* Can throw BagException
*/
Bag(std::string const& filename, uint32_t mode = bagmode::Read);
~Bag();
//! Open a bag file.
/*!
* \param filename The bag file to open
* \param mode The mode to use (either read, write or append)
*
* Can throw BagException
*/
void open(std::string const& filename, uint32_t mode = bagmode::Read);
//! Close the bag file
void close();
std::string getFileName() const; //!< Get the filename of the bag
BagMode getMode() const; //!< Get the mode the bag is in
uint32_t getMajorVersion() const; //!< Get the major-version of the open bag file
uint32_t getMinorVersion() const; //!< Get the minor-version of the open bag file
uint64_t getSize() const; //!< Get the current size of the bag file (a lower bound)
void setCompression(CompressionType compression); //!< Set the compression method to use for writing chunks
CompressionType getCompression() const; //!< Get the compression method to use for writing chunks
void setChunkThreshold(uint32_t chunk_threshold); //!< Set the threshold for creating new chunks
uint32_t getChunkThreshold() const; //!< Get the threshold for creating new chunks
//! Write a message into the bag file
/*!
* \param topic The topic name
* \param event The message event to be added
*
* Can throw BagIOException
*/
template<class T>
void write(std::string const& topic, ros::MessageEvent<T> const& event,
std::string datatype = "", std::string md5sum = "", std::string msg_def = "");
//! Write a message into the bag file
/*!
* \param topic The topic name
* \param time Timestamp of the message
* \param msg The message to be added
* \param connection_header A connection header.
*
* Can throw BagIOException
*/
template<class T>
void write(std::string const& topic, ros::Time const& time, T const& msg,
boost::shared_ptr<ros::M_string> connection_header = boost::shared_ptr<ros::M_string>(),
std::string datatype = "", std::string md5sum = "", std::string msg_def = "");
//! Write a message into the bag file
/*!
* \param topic The topic name
* \param time Timestamp of the message
* \param msg The message to be added
* \param connection_header A connection header.
*
* Can throw BagIOException
*/
template<class T>
void write(std::string const& topic, ros::Time const& time, boost::shared_ptr<T const> const& msg,
boost::shared_ptr<ros::M_string> connection_header = boost::shared_ptr<ros::M_string>(),
std::string datatype = "", std::string md5sum = "", std::string msg_def = "");
//! Write a message into the bag file
/*!
* \param topic The topic name
* \param time Timestamp of the message
* \param msg The message to be added
* \param connection_header A connection header.
*
* Can throw BagIOException
*/
template<class T>
void write(std::string const& topic, ros::Time const& time, boost::shared_ptr<T> const& msg,
boost::shared_ptr<ros::M_string> connection_header = boost::shared_ptr<ros::M_string>(),
std::string datatype = "", std::string md5sum = "", std::string msg_def = "");
private:
// This helper function actually does the write with an arbitrary serializable message
template<class T>
void doWrite(std::string const& topic, ros::Time const& time, T const& msg, boost::shared_ptr<ros::M_string> const& connection_header,
std::string datatype = "", std::string md5sum = "", std::string msg_def = "");
void openRead (std::string const& filename);
void openWrite (std::string const& filename);
void openAppend(std::string const& filename);
void closeWrite();
template<class T>
boost::shared_ptr<T> instantiateBuffer(IndexEntry const& index_entry) const; //!< deserializes the message held in record_buffer_
void startWriting();
void stopWriting();
void startReadingVersion102();
void startReadingVersion200();
// Writing
void writeVersion();
void writeFileHeaderRecord();
void writeConnectionRecord(ConnectionInfo const* connection_info);
void appendConnectionRecordToBuffer(Buffer& buf, ConnectionInfo const* connection_info);
template<class T>
void writeMessageDataRecord(uint32_t conn_id, ros::Time const& time, T const& msg);
void writeIndexRecords();
void writeConnectionRecords();
void writeChunkInfoRecords();
void startWritingChunk(ros::Time time);
void writeChunkHeader(CompressionType compression, uint32_t compressed_size, uint32_t uncompressed_size);
void stopWritingChunk();
// Reading
void readVersion();
void readFileHeaderRecord();
void readConnectionRecord();
void readChunkHeader(ChunkHeader& chunk_header) const;
void readChunkInfoRecord();
void readConnectionIndexRecord200();
void readTopicIndexRecord102();
void readMessageDefinitionRecord102();
void readMessageDataRecord102(uint64_t offset, ros::Header& header) const;
ros::Header readMessageDataHeader(IndexEntry const& index_entry);
uint32_t readMessageDataSize(IndexEntry const& index_entry) const;
template<typename Stream>
void readMessageDataIntoStream(IndexEntry const& index_entry, Stream& stream) const;
void decompressChunk(uint64_t chunk_pos) const;
void decompressRawChunk(ChunkHeader const& chunk_header) const;
void decompressBz2Chunk(ChunkHeader const& chunk_header) const;
void decompressLz4Chunk(ChunkHeader const& chunk_header) const;
uint32_t getChunkOffset() const;
// Record header I/O
void writeHeader(ros::M_string const& fields);
void writeDataLength(uint32_t data_len);
void appendHeaderToBuffer(Buffer& buf, ros::M_string const& fields);
void appendDataLengthToBuffer(Buffer& buf, uint32_t data_len);
void readHeaderFromBuffer(Buffer& buffer, uint32_t offset, ros::Header& header, uint32_t& data_size, uint32_t& bytes_read) const;
void readMessageDataHeaderFromBuffer(Buffer& buffer, uint32_t offset, ros::Header& header, uint32_t& data_size, uint32_t& bytes_read) const;
bool readHeader(ros::Header& header) const;
bool readDataLength(uint32_t& data_size) const;
bool isOp(ros::M_string& fields, uint8_t reqOp) const;
// Header fields
template<typename T>
std::string toHeaderString(T const* field) const;
std::string toHeaderString(ros::Time const* field) const;
template<typename T>
bool readField(ros::M_string const& fields, std::string const& field_name, bool required, T* data) const;
bool readField(ros::M_string const& fields, std::string const& field_name, unsigned int min_len, unsigned int max_len, bool required, std::string& data) const;
bool readField(ros::M_string const& fields, std::string const& field_name, bool required, std::string& data) const;
bool readField(ros::M_string const& fields, std::string const& field_name, bool required, ros::Time& data) const;
ros::M_string::const_iterator checkField(ros::M_string const& fields, std::string const& field,
unsigned int min_len, unsigned int max_len, bool required) const;
// Low-level I/O
void write(char const* s, std::streamsize n);
void write(std::string const& s);
void read(char* b, std::streamsize n) const;
void seek(uint64_t pos, int origin = std::ios_base::beg) const;
private:
BagMode mode_;
mutable ChunkedFile file_;
int version_;
CompressionType compression_;
uint32_t chunk_threshold_;
uint32_t bag_revision_;
uint64_t file_size_;
uint64_t file_header_pos_;
uint64_t index_data_pos_;
uint32_t connection_count_;
uint32_t chunk_count_;
// Current chunk
bool chunk_open_;
ChunkInfo curr_chunk_info_;
uint64_t curr_chunk_data_pos_;
std::map<std::string, uint32_t> topic_connection_ids_;
std::map<ros::M_string, uint32_t> header_connection_ids_;
std::map<uint32_t, ConnectionInfo*> connections_;
std::vector<ChunkInfo> chunks_;
std::map<uint32_t, std::multiset<IndexEntry> > connection_indexes_;
std::map<uint32_t, std::multiset<IndexEntry> > curr_chunk_connection_indexes_;
mutable Buffer header_buffer_; //!< reusable buffer in which to assemble the record header before writing to file
mutable Buffer record_buffer_; //!< reusable buffer in which to assemble the record data before writing to file
mutable Buffer chunk_buffer_; //!< reusable buffer to read chunk into
mutable Buffer decompress_buffer_; //!< reusable buffer to decompress chunks into
mutable Buffer outgoing_chunk_buffer_; //!< reusable buffer to read chunk into
mutable Buffer* current_buffer_;
mutable uint64_t decompressed_chunk_; //!< position of decompressed chunk
};
} // namespace rosbag
#include "rosbag/message_instance.h"
namespace rosbag {
// Templated method definitions
template<class T>
void Bag::write(std::string const& topic, ros::MessageEvent<T> const& event,
std::string datatype, std::string md5sum, std::string msg_def) {
doWrite(topic, event.getReceiptTime(), *event.getMessage(), event.getConnectionHeaderPtr());
}
template<class T>
void Bag::write(std::string const& topic, ros::Time const& time, T const& msg, boost::shared_ptr<ros::M_string> connection_header,
std::string datatype, std::string md5sum, std::string msg_def) {
doWrite(topic, time, msg, connection_header, datatype, md5sum, msg_def);
}
template<class T>
void Bag::write(std::string const& topic, ros::Time const& time, boost::shared_ptr<T const> const& msg, boost::shared_ptr<ros::M_string> connection_header,
std::string datatype, std::string md5sum, std::string msg_def) {
doWrite(topic, time, *msg, connection_header);
}
template<class T>
void Bag::write(std::string const& topic, ros::Time const& time, boost::shared_ptr<T> const& msg, boost::shared_ptr<ros::M_string> connection_header,
std::string datatype, std::string md5sum, std::string msg_def) {
doWrite(topic, time, *msg, connection_header);
}
template<typename T>
std::string Bag::toHeaderString(T const* field) const {
return std::string((char*) field, sizeof(T));
}
template<typename T>
bool Bag::readField(ros::M_string const& fields, std::string const& field_name, bool required, T* data) const {
ros::M_string::const_iterator i = checkField(fields, field_name, sizeof(T), sizeof(T), required);
if (i == fields.end())
return false;
memcpy(data, i->second.data(), sizeof(T));
return true;
}
template<typename Stream>
void Bag::readMessageDataIntoStream(IndexEntry const& index_entry, Stream& stream) const {
ros::Header header;
uint32_t data_size;
uint32_t bytes_read;
switch (version_)
{
case 200:
{
decompressChunk(index_entry.chunk_pos);
readMessageDataHeaderFromBuffer(*current_buffer_, index_entry.offset, header, data_size, bytes_read);
if (data_size > 0)
memcpy(stream.advance(data_size), current_buffer_->getData() + index_entry.offset + bytes_read, data_size);
break;
}
case 102:
{
readMessageDataRecord102(index_entry.chunk_pos, header);
data_size = record_buffer_.getSize();
if (data_size > 0)
memcpy(stream.advance(data_size), record_buffer_.getData(), data_size);
break;
}
default:
throw BagFormatException((boost::format("Unhandled version: %1%") % version_).str());
}
}
template<class T>
boost::shared_ptr<T> Bag::instantiateBuffer(IndexEntry const& index_entry) const {
switch (version_)
{
case 200:
{
decompressChunk(index_entry.chunk_pos);
// Read the message header
ros::Header header;
uint32_t data_size;
uint32_t bytes_read;
readMessageDataHeaderFromBuffer(*current_buffer_, index_entry.offset, header, data_size, bytes_read);
// Read the connection id from the header
uint32_t connection_id;
readField(*header.getValues(), CONNECTION_FIELD_NAME, true, &connection_id);
std::map<uint32_t, ConnectionInfo*>::const_iterator connection_iter = connections_.find(connection_id);
if (connection_iter == connections_.end())
throw BagFormatException((boost::format("Unknown connection ID: %1%") % connection_id).str());
ConnectionInfo* connection_info = connection_iter->second;
boost::shared_ptr<T> p = boost::make_shared<T>();
ros::serialization::PreDeserializeParams<T> predes_params;
predes_params.message = p;
predes_params.connection_header = connection_info->header;
ros::serialization::PreDeserialize<T>::notify(predes_params);
// Deserialize the message
ros::serialization::IStream s(current_buffer_->getData() + index_entry.offset + bytes_read, data_size);
ros::serialization::deserialize(s, *p);
return p;
}
case 102:
{
// Read the message record
ros::Header header;
readMessageDataRecord102(index_entry.chunk_pos, header);
ros::M_string& fields = *header.getValues();
// Read the connection id from the header
std::string topic, latching("0"), callerid;
readField(fields, TOPIC_FIELD_NAME, true, topic);
readField(fields, LATCHING_FIELD_NAME, false, latching);
readField(fields, CALLERID_FIELD_NAME, false, callerid);
std::map<std::string, uint32_t>::const_iterator topic_conn_id_iter = topic_connection_ids_.find(topic);
if (topic_conn_id_iter == topic_connection_ids_.end())
throw BagFormatException((boost::format("Unknown topic: %1%") % topic).str());
uint32_t connection_id = topic_conn_id_iter->second;
std::map<uint32_t, ConnectionInfo*>::const_iterator connection_iter = connections_.find(connection_id);
if (connection_iter == connections_.end())
throw BagFormatException((boost::format("Unknown connection ID: %1%") % connection_id).str());
ConnectionInfo* connection_info = connection_iter->second;
boost::shared_ptr<T> p = boost::make_shared<T>();
// Create a new connection header, updated with the latching and callerid values
boost::shared_ptr<ros::M_string> message_header(boost::make_shared<ros::M_string>());
for (ros::M_string::const_iterator i = connection_info->header->begin(); i != connection_info->header->end(); i++)
(*message_header)[i->first] = i->second;
(*message_header)["latching"] = latching;
(*message_header)["callerid"] = callerid;
ros::serialization::PreDeserializeParams<T> predes_params;
predes_params.message = p;
predes_params.connection_header = message_header;
ros::serialization::PreDeserialize<T>::notify(predes_params);
// Deserialize the message
ros::serialization::IStream s(record_buffer_.getData(), record_buffer_.getSize());
ros::serialization::deserialize(s, *p);
return p;
}
default:
throw BagFormatException((boost::format("Unhandled version: %1%") % version_).str());
}
}
template<class T>
void Bag::doWrite(std::string const& topic, ros::Time const& time,
T const& msg, boost::shared_ptr<ros::M_string> const& connection_header,
std::string datatype, std::string md5sum, std::string msg_def) {
if (time < ros::TIME_MIN)
{
throw BagException("Tried to insert a message with time less than ros::TIME_MIN");
}
// Whenever we write we increment our revision
bag_revision_++;
// Get ID for connection header
ConnectionInfo* connection_info = NULL;
uint32_t conn_id = 0;
if (!connection_header) {
// No connection header: we'll manufacture one, and store by topic
std::map<std::string, uint32_t>::iterator topic_connection_ids_iter = topic_connection_ids_.find(topic);
if (topic_connection_ids_iter == topic_connection_ids_.end()) {
conn_id = connections_.size();
topic_connection_ids_[topic] = conn_id;
}
else {
conn_id = topic_connection_ids_iter->second;
connection_info = connections_[conn_id];
}
}
else {
// Store the connection info by the address of the connection header
// Add the topic name to the connection header, so that when we later search by
// connection header, we can disambiguate connections that differ only by topic name (i.e.,
// same callerid, same message type), #3755. This modified connection header is only used
// for our bookkeeping, and will not appear in the resulting .bag.
ros::M_string connection_header_copy(*connection_header);
connection_header_copy["topic"] = topic;
std::map<ros::M_string, uint32_t>::iterator header_connection_ids_iter = header_connection_ids_.find(connection_header_copy);
if (header_connection_ids_iter == header_connection_ids_.end()) {
conn_id = connections_.size();
header_connection_ids_[connection_header_copy] = conn_id;
}
else {
conn_id = header_connection_ids_iter->second;
connection_info = connections_[conn_id];
}
}
{
// Seek to the end of the file (needed in case previous operation was a read)
seek(0, std::ios::end);
file_size_ = file_.getOffset();
// Write the chunk header if we're starting a new chunk
if (!chunk_open_)
startWritingChunk(time);
// Write connection info record, if necessary
if (connection_info == NULL) {
connection_info = new ConnectionInfo();
connection_info->id = conn_id;
connection_info->topic = topic;
if (std::string(ros::message_traits::datatype(msg)) == "*") {
connection_info->datatype = datatype;
connection_info->md5sum = md5sum;
connection_info->msg_def = msg_def;
}
else {
connection_info->datatype = std::string(ros::message_traits::datatype(msg));
connection_info->md5sum = std::string(ros::message_traits::md5sum(msg));
connection_info->msg_def = std::string(ros::message_traits::definition(msg));
}
if (connection_header != NULL) {
connection_info->header = connection_header;
}
else {
connection_info->header = boost::make_shared<ros::M_string>();
if (connection_info->datatype == "*") {
(*connection_info->header)["type"] = datatype;
(*connection_info->header)["md5sum"] = md5sum;
(*connection_info->header)["message_definition"] = msg_def;
}
else {
(*connection_info->header)["type"] = connection_info->datatype;
(*connection_info->header)["md5sum"] = connection_info->md5sum;
(*connection_info->header)["message_definition"] = connection_info->msg_def;
}
}
connections_[conn_id] = connection_info;
writeConnectionRecord(connection_info);
appendConnectionRecordToBuffer(outgoing_chunk_buffer_, connection_info);
}
// Add to topic indexes
IndexEntry index_entry;
index_entry.time = time;
index_entry.chunk_pos = curr_chunk_info_.pos;
index_entry.offset = getChunkOffset();
std::multiset<IndexEntry>& chunk_connection_index = curr_chunk_connection_indexes_[connection_info->id];
chunk_connection_index.insert(chunk_connection_index.end(), index_entry);
std::multiset<IndexEntry>& connection_index = connection_indexes_[connection_info->id];
connection_index.insert(connection_index.end(), index_entry);
// Increment the connection count
curr_chunk_info_.connection_counts[connection_info->id]++;
// Write the message data
writeMessageDataRecord(conn_id, time, msg);
// Check if we want to stop this chunk
uint32_t chunk_size = getChunkOffset();
logDebug(" curr_chunk_size=%d (threshold=%d)", chunk_size, chunk_threshold_);
if (chunk_size > chunk_threshold_) {
// Empty the outgoing chunk
stopWritingChunk();
outgoing_chunk_buffer_.setSize(0);
// We no longer have a valid curr_chunk_info
curr_chunk_info_.pos = -1;
}
}
}
template<class T>
void Bag::writeMessageDataRecord(uint32_t conn_id, ros::Time const& time, T const& msg) {
ros::M_string header;
header[OP_FIELD_NAME] = toHeaderString(&OP_MSG_DATA);
header[CONNECTION_FIELD_NAME] = toHeaderString(&conn_id);
header[TIME_FIELD_NAME] = toHeaderString(&time);
// Assemble message in memory first, because we need to write its length
uint32_t msg_ser_len = ros::serialization::serializationLength(msg);
record_buffer_.setSize(msg_ser_len);
ros::serialization::OStream s(record_buffer_.getData(), msg_ser_len);
// todo: serialize into the outgoing_chunk_buffer & remove record_buffer_
ros::serialization::serialize(s, msg);
// We do an extra seek here since writing our data record may
// have indirectly moved our file-pointer if it was a
// MessageInstance for our own bag
seek(0, std::ios::end);
file_size_ = file_.getOffset();
logDebug("Writing MSG_DATA [%llu:%d]: conn=%d sec=%d nsec=%d data_len=%d",
(unsigned long long) file_.getOffset(), getChunkOffset(), conn_id, time.sec, time.nsec, msg_ser_len);
writeHeader(header);
writeDataLength(msg_ser_len);
write((char*) record_buffer_.getData(), msg_ser_len);
// todo: use better abstraction than appendHeaderToBuffer
appendHeaderToBuffer(outgoing_chunk_buffer_, header);
appendDataLengthToBuffer(outgoing_chunk_buffer_, msg_ser_len);
uint32_t offset = outgoing_chunk_buffer_.getSize();
outgoing_chunk_buffer_.setSize(outgoing_chunk_buffer_.getSize() + msg_ser_len);
memcpy(outgoing_chunk_buffer_.getData() + offset, record_buffer_.getData(), msg_ser_len);
// Update the current chunk time range
if (time > curr_chunk_info_.end_time)
curr_chunk_info_.end_time = time;
else if (time < curr_chunk_info_.start_time)
curr_chunk_info_.start_time = time;
}
} // namespace rosbag
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include/rosbag/query.h | /*********************************************************************
* 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.
*********************************************************************/
#ifndef ROSBAG_QUERY_H
#define ROSBAG_QUERY_H
#include "ros/time.h"
#include <vector>
#include <map>
#include <set>
#include <boost/function.hpp>
#include "rosbag/macros.h"
#include "rosbag/structures.h"
namespace rosbag {
class Bag;
class ROSBAG_DECL Query
{
public:
//! The base query takes an optional time-range
/*!
* param start_time the beginning of the time_range for the query
* param end_time the end of the time_range for the query
*/
Query(boost::function<bool(ConnectionInfo const*)>& query,
ros::Time const& start_time = ros::TIME_MIN,
ros::Time const& end_time = ros::TIME_MAX);
boost::function<bool(ConnectionInfo const*)> const& getQuery() const; //!< Get the query functor
ros::Time const& getStartTime() const; //!< Get the start-time
ros::Time const& getEndTime() const; //!< Get the end-time
private:
boost::function<bool(ConnectionInfo const*)> query_;
ros::Time start_time_;
ros::Time end_time_;
};
class ROSBAG_DECL TopicQuery
{
public:
TopicQuery(std::string const& topic);
TopicQuery(std::vector<std::string> const& topics);
bool operator()(ConnectionInfo const*) const;
private:
std::vector<std::string> topics_;
};
class ROSBAG_DECL TypeQuery
{
public:
TypeQuery(std::string const& type);
TypeQuery(std::vector<std::string> const& types);
bool operator()(ConnectionInfo const*) const;
private:
std::vector<std::string> types_;
};
//! Pairs of queries and the bags they come from (used internally by View)
struct ROSBAG_DECL BagQuery
{
BagQuery(Bag const* _bag, Query const& _query, uint32_t _bag_revision);
Bag const* bag;
Query query;
uint32_t bag_revision;
};
struct ROSBAG_DECL MessageRange
{
MessageRange(std::multiset<IndexEntry>::const_iterator const& _begin,
std::multiset<IndexEntry>::const_iterator const& _end,
ConnectionInfo const* _connection_info,
BagQuery const* _bag_query);
std::multiset<IndexEntry>::const_iterator begin;
std::multiset<IndexEntry>::const_iterator end;
ConnectionInfo const* connection_info;
BagQuery const* bag_query; //!< pointer to vector of queries in View
};
//! The actual iterator data structure
struct ROSBAG_DECL ViewIterHelper
{
ViewIterHelper(std::multiset<IndexEntry>::const_iterator _iter, MessageRange const* _range);
std::multiset<IndexEntry>::const_iterator iter;
MessageRange const* range; //!< pointer to vector of ranges in View
};
struct ROSBAG_DECL ViewIterHelperCompare
{
bool operator()(ViewIterHelper const& a, ViewIterHelper const& b);
};
} // namespace rosbag
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include/rosbag/chunked_file.h | /*********************************************************************
* 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.
********************************************************************/
#ifndef ROSBAG_CHUNKED_FILE_H
#define ROSBAG_CHUNKED_FILE_H
#include <ios>
#include <stdint.h>
#include <string>
#include "macros.h"
#include <boost/shared_ptr.hpp>
#include <bzlib.h>
#include "rosbag/stream.h"
namespace rosbag {
//! ChunkedFile reads and writes files which contain interleaved chunks of compressed and uncompressed data.
class ROSBAG_DECL ChunkedFile
{
friend class Stream;
public:
ChunkedFile();
~ChunkedFile();
void openWrite (std::string const& filename); //!< open file for writing
void openRead (std::string const& filename); //!< open file for reading
void openReadWrite(std::string const& filename); //!< open file for reading & writing
void close(); //!< close the file
std::string getFileName() const; //!< return path of currently open file
uint64_t getOffset() const; //!< return current offset from the beginning of the file
uint32_t getCompressedBytesIn() const; //!< return the number of bytes written to current compressed stream
bool isOpen() const; //!< return true if file is open for reading or writing
bool good() const; //!< return true if hasn't reached end-of-file and no error
void setReadMode(CompressionType type);
void setWriteMode(CompressionType type);
// File I/O
void write(std::string const& s);
void write(void* ptr, size_t size); //!< write size bytes from ptr to the file
void read(void* ptr, size_t size); //!< read size bytes from the file into ptr
std::string getline();
bool truncate(uint64_t length);
void seek(uint64_t offset, int origin = std::ios_base::beg); //!< seek to given offset from origin
void decompress(CompressionType compression, uint8_t* dest, unsigned int dest_len, uint8_t* source, unsigned int source_len);
private:
void open(std::string const& filename, std::string const& mode);
void clearUnused();
private:
std::string filename_; //!< path to file
FILE* file_; //!< file pointer
uint64_t offset_; //!< current position in the file
uint64_t compressed_in_; //!< number of bytes written to current compressed stream
char* unused_; //!< extra data read by compressed stream
int nUnused_; //!< number of bytes of extra data read by compressed stream
boost::shared_ptr<StreamFactory> stream_factory_;
boost::shared_ptr<Stream> read_stream_;
boost::shared_ptr<Stream> write_stream_;
};
} // namespace rosbag
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include/rosbag/exceptions.h | /*********************************************************************
* 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.
*********************************************************************/
#ifndef ROSBAG_EXCEPTIONS_H
#define ROSBAG_EXCEPTIONS_H
#include <ros/exception.h>
namespace rosbag {
//! Base class for rosbag exceptions
class BagException : public ros::Exception
{
public:
BagException(std::string const& msg) : ros::Exception(msg) { }
};
//! Exception thrown when on IO problems
class BagIOException : public BagException
{
public:
BagIOException(std::string const& msg) : BagException(msg) { }
};
//! Exception thrown on problems reading the bag format
class BagFormatException : public BagException
{
public:
BagFormatException(std::string const& msg) : BagException(msg) { }
};
//! Exception thrown on problems reading the bag index
class BagUnindexedException : public BagException
{
public:
BagUnindexedException() : BagException("Bag unindexed") { }
};
} // namespace rosbag
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include/rosbag/stream.h | /*********************************************************************
* 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.
********************************************************************/
#ifndef ROSBAG_STREAM_H
#define ROSBAG_STREAM_H
#include <ios>
#include <stdint.h>
#include <string>
#include <boost/shared_ptr.hpp>
#include <bzlib.h>
#include <roslz4/lz4s.h>
#include "rosbag/exceptions.h"
#include "rosbag/macros.h"
namespace rosbag {
namespace compression
{
enum CompressionType
{
Uncompressed = 0,
BZ2 = 1,
LZ4 = 2,
};
}
typedef compression::CompressionType CompressionType;
class ChunkedFile;
class ROSBAG_DECL Stream
{
public:
Stream(ChunkedFile* file);
virtual ~Stream();
virtual CompressionType getCompressionType() const = 0;
virtual void write(void* ptr, size_t size) = 0;
virtual void read (void* ptr, size_t size) = 0;
virtual void decompress(uint8_t* dest, unsigned int dest_len, uint8_t* source, unsigned int source_len) = 0;
virtual void startWrite();
virtual void stopWrite();
virtual void startRead();
virtual void stopRead();
protected:
FILE* getFilePointer();
uint64_t getCompressedIn();
void setCompressedIn(uint64_t nbytes);
void advanceOffset(uint64_t nbytes);
char* getUnused();
int getUnusedLength();
void setUnused(char* unused);
void setUnusedLength(int nUnused);
void clearUnused();
protected:
ChunkedFile* file_;
};
class ROSBAG_DECL StreamFactory
{
public:
StreamFactory(ChunkedFile* file);
boost::shared_ptr<Stream> getStream(CompressionType type) const;
private:
boost::shared_ptr<Stream> uncompressed_stream_;
boost::shared_ptr<Stream> bz2_stream_;
boost::shared_ptr<Stream> lz4_stream_;
};
class ROSBAG_DECL UncompressedStream : public Stream
{
public:
UncompressedStream(ChunkedFile* file);
CompressionType getCompressionType() const;
void write(void* ptr, size_t size);
void read(void* ptr, size_t size);
void decompress(uint8_t* dest, unsigned int dest_len, uint8_t* source, unsigned int source_len);
};
/*!
* BZ2Stream uses libbzip2 (http://www.bzip.org) for reading/writing compressed data in the BZ2 format.
*/
class ROSBAG_DECL BZ2Stream : public Stream
{
public:
BZ2Stream(ChunkedFile* file);
CompressionType getCompressionType() const;
void startWrite();
void write(void* ptr, size_t size);
void stopWrite();
void startRead();
void read(void* ptr, size_t size);
void stopRead();
void decompress(uint8_t* dest, unsigned int dest_len, uint8_t* source, unsigned int source_len);
private:
int verbosity_; //!< level of debugging output (0-4; 0 default). 0 is silent, 4 is max verbose debugging output
int block_size_100k_; //!< compression block size (1-9; 9 default). 9 is best compression, most memory
int work_factor_; //!< compression behavior for worst case, highly repetitive data (0-250; 30 default)
BZFILE* bzfile_; //!< bzlib compressed file stream
int bzerror_; //!< last error from bzlib
};
// LZ4Stream reads/writes compressed datat in the LZ4 format
// https://code.google.com/p/lz4/
class ROSBAG_DECL LZ4Stream : public Stream
{
public:
LZ4Stream(ChunkedFile* file);
~LZ4Stream();
CompressionType getCompressionType() const;
void startWrite();
void write(void* ptr, size_t size);
void stopWrite();
void startRead();
void read(void* ptr, size_t size);
void stopRead();
void decompress(uint8_t* dest, unsigned int dest_len, uint8_t* source, unsigned int source_len);
private:
void writeStream(int action);
char *buff_;
int buff_size_;
int block_size_id_;
roslz4_stream lz4s_;
};
} // namespace rosbag
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include/rosbag/view.h | /*********************************************************************
* 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.
*********************************************************************/
#ifndef ROSBAG_VIEW_H
#define ROSBAG_VIEW_H
#include <boost/function.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include "rosbag/message_instance.h"
#include "rosbag/query.h"
#include "rosbag/macros.h"
#include "rosbag/structures.h"
namespace rosbag {
class ROSBAG_DECL View
{
friend class Bag;
public:
//! An iterator that points to a MessageInstance from a bag
/*!
* This iterator stores the MessageInstance that it is returning a
* reference to. If you increment the iterator that
* MessageInstance is destroyed. You should never store the
* pointer to this reference.
*/
class iterator : public boost::iterator_facade<iterator,
MessageInstance,
boost::forward_traversal_tag>
{
public:
iterator(iterator const& i);
iterator();
~iterator();
protected:
iterator(View* view, bool end = false);
private:
friend class View;
friend class boost::iterator_core_access;
void populate();
void populateSeek(std::multiset<IndexEntry>::const_iterator iter);
bool equal(iterator const& other) const;
void increment();
MessageInstance& dereference() const;
private:
View* view_;
std::vector<ViewIterHelper> iters_;
uint32_t view_revision_;
mutable MessageInstance* message_instance_;
};
typedef iterator const_iterator;
struct TrueQuery {
bool operator()(ConnectionInfo const*) const { return true; };
};
//! Create a view on a bag
/*!
* param reduce_overlap If multiple views return the same messages, reduce them to a single message
*/
View(bool const& reduce_overlap = false);
//! Create a view on a bag
/*!
* param bag The bag file on which to run this query
* param start_time The beginning of the time range for the query
* param end_time The end of the time range for the query
* param reduce_overlap If multiple views return the same messages, reduce them to a single message
*/
View(Bag const& bag, ros::Time const& start_time = ros::TIME_MIN, ros::Time const& end_time = ros::TIME_MAX, bool const& reduce_overlap = false);
//! Create a view and add a query
/*!
* param bag The bag file on which to run this query
* param query The actual query to evaluate which connections to include
* param start_time The beginning of the time range for the query
* param end_time The end of the time range for the query
* param reduce_overlap If multiple views return the same messages, reduce them to a single message
*/
View(Bag const& bag, boost::function<bool(ConnectionInfo const*)> query,
ros::Time const& start_time = ros::TIME_MIN, ros::Time const& end_time = ros::TIME_MAX, bool const& reduce_overlap = false);
~View();
iterator begin();
iterator end();
uint32_t size();
//! Add a query to a view
/*!
* param bag The bag file on which to run this query
* param start_time The beginning of the time range for the query
* param end_time The end of the time range for the query
*/
void addQuery(Bag const& bag, ros::Time const& start_time = ros::TIME_MIN, ros::Time const& end_time = ros::TIME_MAX);
//! Add a query to a view
/*!
* param bag The bag file on which to run this query
* param query The actual query to evaluate which connections to include
* param start_time The beginning of the time range for the query
* param end_time The end of the time range for the query
*/
void addQuery(Bag const& bag, boost::function<bool(ConnectionInfo const*)> query,
ros::Time const& start_time = ros::TIME_MIN, ros::Time const& end_time = ros::TIME_MAX);
std::vector<const ConnectionInfo*> getConnections();
ros::Time getBeginTime();
ros::Time getEndTime();
protected:
friend class iterator;
void updateQueries(BagQuery* q);
void update();
MessageInstance* newMessageInstance(ConnectionInfo const* connection_info, IndexEntry const& index, Bag const& bag);
private:
View(View const& view);
View& operator=(View const& view);
protected:
std::vector<MessageRange*> ranges_;
std::vector<BagQuery*> queries_;
uint32_t view_revision_;
uint32_t size_cache_;
uint32_t size_revision_;
bool reduce_overlap_;
};
} // namespace rosbag
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include/rosbag/constants.h | /*********************************************************************
* 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.
*********************************************************************/
#ifndef ROSBAG_CONSTANTS_H
#define ROSBAG_CONSTANTS_H
#include <string>
#include <stdint.h>
namespace rosbag {
// Bag file version to write
static const std::string VERSION = "2.0";
// Header field delimiter
static const unsigned char FIELD_DELIM = '=';
// Current header fields
static const std::string OP_FIELD_NAME = "op";
static const std::string TOPIC_FIELD_NAME = "topic";
static const std::string VER_FIELD_NAME = "ver";
static const std::string COUNT_FIELD_NAME = "count";
static const std::string INDEX_POS_FIELD_NAME = "index_pos"; // 1.2+
static const std::string CONNECTION_COUNT_FIELD_NAME = "conn_count"; // 2.0+
static const std::string CHUNK_COUNT_FIELD_NAME = "chunk_count"; // 2.0+
static const std::string CONNECTION_FIELD_NAME = "conn"; // 2.0+
static const std::string COMPRESSION_FIELD_NAME = "compression"; // 2.0+
static const std::string SIZE_FIELD_NAME = "size"; // 2.0+
static const std::string TIME_FIELD_NAME = "time"; // 2.0+
static const std::string START_TIME_FIELD_NAME = "start_time"; // 2.0+
static const std::string END_TIME_FIELD_NAME = "end_time"; // 2.0+
static const std::string CHUNK_POS_FIELD_NAME = "chunk_pos"; // 2.0+
// Legacy header fields
static const std::string MD5_FIELD_NAME = "md5"; // <2.0
static const std::string TYPE_FIELD_NAME = "type"; // <2.0
static const std::string DEF_FIELD_NAME = "def"; // <2.0
static const std::string SEC_FIELD_NAME = "sec"; // <2.0
static const std::string NSEC_FIELD_NAME = "nsec"; // <2.0
static const std::string LATCHING_FIELD_NAME = "latching"; // <2.0
static const std::string CALLERID_FIELD_NAME = "callerid"; // <2.0
// Current "op" field values
static const unsigned char OP_MSG_DATA = 0x02;
static const unsigned char OP_FILE_HEADER = 0x03;
static const unsigned char OP_INDEX_DATA = 0x04;
static const unsigned char OP_CHUNK = 0x05;
static const unsigned char OP_CHUNK_INFO = 0x06;
static const unsigned char OP_CONNECTION = 0x07;
// Legacy "op" field values
static const unsigned char OP_MSG_DEF = 0x01;
// Bytes reserved for file header record (4KB)
static const uint32_t FILE_HEADER_LENGTH = 4 * 1024;
// Index data record version to write
static const uint32_t INDEX_VERSION = 1;
// Chunk info record version to write
static const uint32_t CHUNK_INFO_VERSION = 1;
// Compression types
static const std::string COMPRESSION_NONE = "none";
static const std::string COMPRESSION_BZ2 = "bz2";
static const std::string COMPRESSION_LZ4 = "lz4";
} // namespace rosbag
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include/rosbag/buffer.h | /*********************************************************************
* 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.
********************************************************************/
#ifndef ROSBAG_BUFFER_H
#define ROSBAG_BUFFER_H
#include <stdint.h>
#include "macros.h"
namespace rosbag {
class ROSBAG_DECL Buffer
{
public:
Buffer();
~Buffer();
uint8_t* getData();
uint32_t getCapacity() const;
uint32_t getSize() const;
void setSize(uint32_t size);
private:
void ensureCapacity(uint32_t capacity);
private:
uint8_t* buffer_;
uint32_t capacity_;
uint32_t size_;
};
} // namespace rosbag
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include/rosbag/bag_player.h | /*********************************************************************
* Software License Agreement (BSD License)
*
* 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 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 ROSBAG_BAG_PLAYER_H
#define ROSBAG_BAG_PLAYER_H
#include <boost/foreach.hpp>
#include "rosbag/bag.h"
#include "rosbag/view.h"
namespace rosbag
{
// A helper struct
struct BagCallback
{
virtual ~BagCallback() {};
virtual void call(MessageInstance m) = 0;
};
// A helper class for the callbacks
template<class T>
class BagCallbackT : public BagCallback
{
public:
typedef boost::function<void (const boost::shared_ptr<const T>&)> Callback;
BagCallbackT(Callback cb) :
cb_(cb)
{}
void call(MessageInstance m) {
cb_(m.instantiate<T>());
}
private:
Callback cb_;
};
/* A class for playing back bag files at an API level. It supports
relatime, as well as accelerated and slowed playback. */
class BagPlayer
{
public:
/* Constructor expecting the filename of a bag */
BagPlayer(const std::string &filename) throw(BagException);
/* Register a callback for a specific topic and type */
template<class T>
void register_callback(const std::string &topic,
typename BagCallbackT<T>::Callback f);
/* Unregister a callback for a topic already registered */
void unregister_callback(const std::string &topic);
/* Set the time in the bag to start.
* Default is the first message */
void set_start(const ros::Time &start);
/* Set the time in the bag to stop.
* Default is the last message */
void set_end(const ros::Time &end);
/* Set the speed to playback. 1.0 is the default.
* 2.0 would be twice as fast, 0.5 is half realtime. */
void set_playback_speed(double scale);
/* Start playback of the bag file using the parameters previously
set */
void start_play();
/* Get the current time of the playback */
ros::Time get_time();
// Destructor
virtual ~BagPlayer();
// The bag file interface loaded in the constructor.
Bag bag;
private:
ros::Time real_time(const ros::Time &msg_time);
std::map<std::string, BagCallback *> cbs_;
ros::Time bag_start_;
ros::Time bag_end_;
ros::Time last_message_time_;
double playback_speed_;
ros::Time play_start_;
};
template<class T>
void BagPlayer::register_callback(const std::string &topic,
typename BagCallbackT<T>::Callback cb) {
cbs_[topic] = new BagCallbackT<T>(cb);
}
}
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include/rosbag/macros.h | /*
* Copyright (C) 2008, Willow Garage, Inc.
*
* 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 names of Stanford University or 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 ROSBAG_MACROS_H_
#define ROSBAG_MACROS_H_
#include <ros/macros.h> // for the DECL's
// 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 rosbag_EXPORTS // we are building a shared lib/dll
#define ROSBAG_DECL ROS_HELPER_EXPORT
#else // we are using shared lib/dll
#define ROSBAG_DECL ROS_HELPER_IMPORT
#endif
#else // ros is being built around static libraries
#define ROSBAG_DECL
#endif
#endif /* ROSBAG_MACROS_H_ */
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include/rosbag/message_instance.h | /*********************************************************************
* 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.
*********************************************************************/
#ifndef ROSBAG_MESSAGE_INSTANCE_H
#define ROSBAG_MESSAGE_INSTANCE_H
#include <ros/message_traits.h>
#include <ros/serialization.h>
//#include <ros/ros.h>
#include <ros/time.h>
#include "rosbag/structures.h"
#include "rosbag/macros.h"
namespace rosbag {
class Bag;
//! A class pointing into a bag file
/*!
* The MessageInstance class itself is fairly light weight. It
* simply contains a pointer to a bag-file and the index_entry
* necessary to get access to the corresponding data.
*
* It adheres to the necessary ros::message_traits to be directly
* serializable.
*/
class ROSBAG_DECL MessageInstance
{
friend class View;
public:
ros::Time const& getTime() const;
std::string const& getTopic() const;
std::string const& getDataType() const;
std::string const& getMD5Sum() const;
std::string const& getMessageDefinition() const;
boost::shared_ptr<ros::M_string> getConnectionHeader() const;
std::string getCallerId() const;
bool isLatching() const;
//! Test whether the underlying message of the specified type.
/*!
* returns true iff the message is of the template type
*/
template<class T>
bool isType() const;
//! Templated call to instantiate a message
/*!
* returns NULL pointer if incompatible
*/
template<class T>
boost::shared_ptr<T> instantiate() const;
//! Write serialized message contents out to a stream
template<typename Stream>
void write(Stream& stream) const;
//! Size of serialized message
uint32_t size() const;
private:
MessageInstance(ConnectionInfo const* connection_info, IndexEntry const& index, Bag const& bag);
ConnectionInfo const* connection_info_;
IndexEntry const index_entry_;
Bag const* bag_;
};
} // namespace rosbag
namespace ros {
namespace message_traits {
template<>
struct MD5Sum<rosbag::MessageInstance>
{
static const char* value(const rosbag::MessageInstance& m) { return m.getMD5Sum().c_str(); }
};
template<>
struct DataType<rosbag::MessageInstance>
{
static const char* value(const rosbag::MessageInstance& m) { return m.getDataType().c_str(); }
};
template<>
struct Definition<rosbag::MessageInstance>
{
static const char* value(const rosbag::MessageInstance& m) { return m.getMessageDefinition().c_str(); }
};
} // namespace message_traits
namespace serialization
{
template<>
struct Serializer<rosbag::MessageInstance>
{
template<typename Stream>
inline static void write(Stream& stream, const rosbag::MessageInstance& m) {
m.write(stream);
}
inline static uint32_t serializedLength(const rosbag::MessageInstance& m) {
return m.size();
}
};
} // namespace serialization
} // namespace ros
#include "rosbag/bag.h"
namespace rosbag {
template<class T>
bool MessageInstance::isType() const {
char const* md5sum = ros::message_traits::MD5Sum<T>::value();
return md5sum == std::string("*") || md5sum == getMD5Sum();
}
template<class T>
boost::shared_ptr<T> MessageInstance::instantiate() const {
if (!isType<T>())
return boost::shared_ptr<T>();
return bag_->instantiateBuffer<T>(index_entry_);
}
template<typename Stream>
void MessageInstance::write(Stream& stream) const {
bag_->readMessageDataIntoStream(index_entry_, stream);
}
} // namespace rosbag
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/include/rosbag/structures.h | /*********************************************************************
* 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.
*********************************************************************/
#ifndef ROSBAG_STRUCTURES_H
#define ROSBAG_STRUCTURES_H
#include <map>
#include <vector>
#include "ros/time.h"
#include "ros/datatypes.h"
#include "macros.h"
namespace rosbag {
struct ROSBAG_DECL ConnectionInfo
{
ConnectionInfo() : id(-1) { }
uint32_t id;
std::string topic;
std::string datatype;
std::string md5sum;
std::string msg_def;
boost::shared_ptr<ros::M_string> header;
};
struct ChunkInfo
{
ros::Time start_time; //! earliest timestamp of a message in the chunk
ros::Time end_time; //! latest timestamp of a message in the chunk
uint64_t pos; //! absolute byte offset of chunk record in bag file
std::map<uint32_t, uint32_t> connection_counts; //! number of messages in each connection stored in the chunk
};
struct ROSBAG_DECL ChunkHeader
{
std::string compression; //! chunk compression type, e.g. "none" or "bz2" (see constants.h)
uint32_t compressed_size; //! compressed size of the chunk in bytes
uint32_t uncompressed_size; //! uncompressed size of the chunk in bytes
};
struct ROSBAG_DECL IndexEntry
{
ros::Time time; //! timestamp of the message
uint64_t chunk_pos; //! absolute byte offset of the chunk record containing the message
uint32_t offset; //! relative byte offset of the message record (either definition or data) in the chunk
bool operator<(IndexEntry const& b) const { return time < b.time; }
};
struct ROSBAG_DECL IndexEntryCompare
{
bool operator()(ros::Time const& a, IndexEntry const& b) const { return a < b.time; }
bool operator()(IndexEntry const& a, ros::Time const& b) const { return a.time < b; }
};
} // namespace rosbag
#endif
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/src/message_instance.cpp | // 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.
#include "rosbag/message_instance.h"
#include "ros/message_event.h"
using std::string;
using ros::Time;
using boost::shared_ptr;
namespace rosbag {
MessageInstance::MessageInstance(ConnectionInfo const* connection_info, IndexEntry const& index_entry, Bag const& bag) :
connection_info_(connection_info), index_entry_(index_entry), bag_(&bag)
{
}
Time const& MessageInstance::getTime() const { return index_entry_.time; }
string const& MessageInstance::getTopic() const { return connection_info_->topic; }
string const& MessageInstance::getDataType() const { return connection_info_->datatype; }
string const& MessageInstance::getMD5Sum() const { return connection_info_->md5sum; }
string const& MessageInstance::getMessageDefinition() const { return connection_info_->msg_def; }
shared_ptr<ros::M_string> MessageInstance::getConnectionHeader() const { return connection_info_->header; }
string MessageInstance::getCallerId() const {
ros::M_string::const_iterator header_iter = connection_info_->header->find("callerid");
return header_iter != connection_info_->header->end() ? header_iter->second : string("");
}
bool MessageInstance::isLatching() const {
ros::M_string::const_iterator header_iter = connection_info_->header->find("latching");
return header_iter != connection_info_->header->end() && header_iter->second == "1";
}
uint32_t MessageInstance::size() const {
return bag_->readMessageDataSize(index_entry_);
}
} // namespace rosbag
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/src/query.cpp | // 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.
#include "rosbag/query.h"
#include "rosbag/bag.h"
#include <boost/foreach.hpp>
#define foreach BOOST_FOREACH
using std::map;
using std::string;
using std::vector;
using std::multiset;
namespace rosbag {
// Query
Query::Query(boost::function<bool(ConnectionInfo const*)>& query, ros::Time const& start_time, ros::Time const& end_time)
: query_(query), start_time_(start_time), end_time_(end_time)
{
}
boost::function<bool(ConnectionInfo const*)> const& Query::getQuery() const {
return query_;
}
ros::Time const& Query::getStartTime() const { return start_time_; }
ros::Time const& Query::getEndTime() const { return end_time_; }
// TopicQuery
TopicQuery::TopicQuery(std::string const& topic) {
topics_.push_back(topic);
}
TopicQuery::TopicQuery(std::vector<std::string> const& topics) : topics_(topics) { }
bool TopicQuery::operator()(ConnectionInfo const* info) const {
foreach(string const& topic, topics_)
if (topic == info->topic)
return true;
return false;
}
// TypeQuery
TypeQuery::TypeQuery(std::string const& type) {
types_.push_back(type);
}
TypeQuery::TypeQuery(std::vector<std::string> const& types) : types_(types) { }
bool TypeQuery::operator()(ConnectionInfo const* info) const {
foreach(string const& type, types_)
if (type == info->datatype)
return true;
return false;
}
// BagQuery
BagQuery::BagQuery(Bag const* _bag, Query const& _query, uint32_t _bag_revision) : bag(_bag), query(_query), bag_revision(_bag_revision) {
}
// MessageRange
MessageRange::MessageRange(std::multiset<IndexEntry>::const_iterator const& _begin,
std::multiset<IndexEntry>::const_iterator const& _end,
ConnectionInfo const* _connection_info,
BagQuery const* _bag_query)
: begin(_begin), end(_end), connection_info(_connection_info), bag_query(_bag_query)
{
}
// ViewIterHelper
ViewIterHelper::ViewIterHelper(std::multiset<IndexEntry>::const_iterator _iter, MessageRange const* _range)
: iter(_iter), range(_range)
{
}
bool ViewIterHelperCompare::operator()(ViewIterHelper const& a, ViewIterHelper const& b) {
return (a.iter)->time > (b.iter)->time;
}
} // namespace rosbag
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/src/bag.cpp | // 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.
#include "rosbag/bag.h"
#include "rosbag/message_instance.h"
#include "rosbag/query.h"
#include "rosbag/view.h"
#if defined(_MSC_VER)
#include <stdint.h> // only on v2010 and later -> is this enough for msvc and linux?
#else
#include <inttypes.h>
#endif
#include <signal.h>
#include <assert.h>
#include <iomanip>
#include <boost/foreach.hpp>
#include "console_bridge/console.h"
#define foreach BOOST_FOREACH
using std::map;
using std::priority_queue;
using std::string;
using std::vector;
using std::multiset;
using boost::format;
using boost::shared_ptr;
using ros::M_string;
using ros::Time;
namespace rosbag {
Bag::Bag() :
mode_(bagmode::Write),
version_(0),
compression_(compression::Uncompressed),
chunk_threshold_(768 * 1024), // 768KB chunks
bag_revision_(0),
file_size_(0),
file_header_pos_(0),
index_data_pos_(0),
connection_count_(0),
chunk_count_(0),
chunk_open_(false),
curr_chunk_data_pos_(0),
current_buffer_(0),
decompressed_chunk_(0)
{
}
Bag::Bag(string const& filename, uint32_t mode) :
compression_(compression::Uncompressed),
chunk_threshold_(768 * 1024), // 768KB chunks
bag_revision_(0),
file_size_(0),
file_header_pos_(0),
index_data_pos_(0),
connection_count_(0),
chunk_count_(0),
chunk_open_(false),
curr_chunk_data_pos_(0),
current_buffer_(0),
decompressed_chunk_(0)
{
open(filename, mode);
}
Bag::~Bag() {
close();
}
void Bag::open(string const& filename, uint32_t mode) {
mode_ = (BagMode) mode;
if (mode_ & bagmode::Append)
openAppend(filename);
else if (mode_ & bagmode::Write)
openWrite(filename);
else if (mode_ & bagmode::Read)
openRead(filename);
else
throw BagException((format("Unknown mode: %1%") % (int) mode).str());
// Determine file size
uint64_t offset = file_.getOffset();
seek(0, std::ios::end);
file_size_ = file_.getOffset();
seek(offset);
}
void Bag::openRead(string const& filename) {
file_.openRead(filename);
readVersion();
switch (version_) {
case 102: startReadingVersion102(); break;
case 200: startReadingVersion200(); break;
default:
throw BagException((format("Unsupported bag file version: %1%.%2%") % getMajorVersion() % getMinorVersion()).str());
}
}
void Bag::openWrite(string const& filename) {
file_.openWrite(filename);
startWriting();
}
void Bag::openAppend(string const& filename) {
file_.openReadWrite(filename);
readVersion();
if (version_ != 200)
throw BagException((format("Bag file version %1%.%2% is unsupported for appending") % getMajorVersion() % getMinorVersion()).str());
startReadingVersion200();
// Truncate the file to chop off the index
file_.truncate(index_data_pos_);
index_data_pos_ = 0;
// Rewrite the file header, clearing the index position (so we know if the index is invalid)
seek(file_header_pos_);
writeFileHeaderRecord();
// Seek to the end of the file
seek(0, std::ios::end);
}
void Bag::close() {
if (!file_.isOpen())
return;
if (mode_ & bagmode::Write || mode_ & bagmode::Append)
closeWrite();
file_.close();
topic_connection_ids_.clear();
header_connection_ids_.clear();
for (map<uint32_t, ConnectionInfo*>::iterator i = connections_.begin(); i != connections_.end(); i++)
delete i->second;
connections_.clear();
chunks_.clear();
connection_indexes_.clear();
curr_chunk_connection_indexes_.clear();
}
void Bag::closeWrite() {
stopWriting();
}
string Bag::getFileName() const { return file_.getFileName(); }
BagMode Bag::getMode() const { return mode_; }
uint64_t Bag::getSize() const { return file_size_; }
uint32_t Bag::getChunkThreshold() const { return chunk_threshold_; }
void Bag::setChunkThreshold(uint32_t chunk_threshold) {
if (file_.isOpen() && chunk_open_)
stopWritingChunk();
chunk_threshold_ = chunk_threshold;
}
CompressionType Bag::getCompression() const { return compression_; }
void Bag::setCompression(CompressionType compression) {
if (file_.isOpen() && chunk_open_)
stopWritingChunk();
if (!(compression == compression::Uncompressed ||
compression == compression::BZ2 ||
compression == compression::LZ4)) {
throw BagException(
(format("Unknown compression type: %i") % compression).str());
}
compression_ = compression;
}
// Version
void Bag::writeVersion() {
string version = string("#ROSBAG V") + VERSION + string("\n");
logDebug("Writing VERSION [%llu]: %s", (unsigned long long) file_.getOffset(), version.c_str());
version_ = 200;
write(version);
}
void Bag::readVersion() {
string version_line = file_.getline();
file_header_pos_ = file_.getOffset();
char logtypename[100];
int version_major, version_minor;
#if defined(_MSC_VER)
if (sscanf_s(version_line.c_str(), "#ROS%s V%d.%d", logtypename, sizeof(logtypename), &version_major, &version_minor) != 3)
#else
if (sscanf(version_line.c_str(), "#ROS%99s V%d.%d", logtypename, &version_major, &version_minor) != 3)
#endif
throw BagIOException("Error reading version line");
version_ = version_major * 100 + version_minor;
logDebug("Read VERSION: version=%d", version_);
}
uint32_t Bag::getMajorVersion() const { return version_ / 100; }
uint32_t Bag::getMinorVersion() const { return version_ % 100; }
//
void Bag::startWriting() {
writeVersion();
file_header_pos_ = file_.getOffset();
writeFileHeaderRecord();
}
void Bag::stopWriting() {
if (chunk_open_)
stopWritingChunk();
seek(0, std::ios::end);
index_data_pos_ = file_.getOffset();
writeConnectionRecords();
writeChunkInfoRecords();
seek(file_header_pos_);
writeFileHeaderRecord();
}
void Bag::startReadingVersion200() {
// Read the file header record, which points to the end of the chunks
readFileHeaderRecord();
// Seek to the end of the chunks
seek(index_data_pos_);
// Read the connection records (one for each connection)
for (uint32_t i = 0; i < connection_count_; i++)
readConnectionRecord();
// Read the chunk info records
for (uint32_t i = 0; i < chunk_count_; i++)
readChunkInfoRecord();
// Read the connection indexes for each chunk
foreach(ChunkInfo const& chunk_info, chunks_) {
curr_chunk_info_ = chunk_info;
seek(curr_chunk_info_.pos);
// Skip over the chunk data
ChunkHeader chunk_header;
readChunkHeader(chunk_header);
seek(chunk_header.compressed_size, std::ios::cur);
// Read the index records after the chunk
for (unsigned int i = 0; i < chunk_info.connection_counts.size(); i++)
readConnectionIndexRecord200();
}
// At this point we don't have a curr_chunk_info anymore so we reset it
curr_chunk_info_ = ChunkInfo();
}
void Bag::startReadingVersion102() {
try
{
// Read the file header record, which points to the start of the topic indexes
readFileHeaderRecord();
}
catch (BagFormatException ex) {
throw BagUnindexedException();
}
// Get the length of the file
seek(0, std::ios::end);
uint64_t filelength = file_.getOffset();
// Seek to the beginning of the topic index records
seek(index_data_pos_);
// Read the topic index records, which point to the offsets of each message in the file
while (file_.getOffset() < filelength)
readTopicIndexRecord102();
// Read the message definition records (which are the first entry in the topic indexes)
for (map<uint32_t, multiset<IndexEntry> >::const_iterator i = connection_indexes_.begin(); i != connection_indexes_.end(); i++) {
multiset<IndexEntry> const& index = i->second;
IndexEntry const& first_entry = *index.begin();
logDebug("Reading message definition for connection %d at %llu", i->first, (unsigned long long) first_entry.chunk_pos);
seek(first_entry.chunk_pos);
readMessageDefinitionRecord102();
}
}
// File header record
void Bag::writeFileHeaderRecord() {
connection_count_ = connections_.size();
chunk_count_ = chunks_.size();
logDebug("Writing FILE_HEADER [%llu]: index_pos=%llu connection_count=%d chunk_count=%d",
(unsigned long long) file_.getOffset(), (unsigned long long) index_data_pos_, connection_count_, chunk_count_);
// Write file header record
M_string header;
header[OP_FIELD_NAME] = toHeaderString(&OP_FILE_HEADER);
header[INDEX_POS_FIELD_NAME] = toHeaderString(&index_data_pos_);
header[CONNECTION_COUNT_FIELD_NAME] = toHeaderString(&connection_count_);
header[CHUNK_COUNT_FIELD_NAME] = toHeaderString(&chunk_count_);
boost::shared_array<uint8_t> header_buffer;
uint32_t header_len;
ros::Header::write(header, header_buffer, header_len);
uint32_t data_len = 0;
if (header_len < FILE_HEADER_LENGTH)
data_len = FILE_HEADER_LENGTH - header_len;
write((char*) &header_len, 4);
write((char*) header_buffer.get(), header_len);
write((char*) &data_len, 4);
// Pad the file header record out
if (data_len > 0) {
string padding;
padding.resize(data_len, ' ');
write(padding);
}
}
void Bag::readFileHeaderRecord() {
ros::Header header;
uint32_t data_size;
if (!readHeader(header) || !readDataLength(data_size))
throw BagFormatException("Error reading FILE_HEADER record");
M_string& fields = *header.getValues();
if (!isOp(fields, OP_FILE_HEADER))
throw BagFormatException("Expected FILE_HEADER op not found");
// Read index position
readField(fields, INDEX_POS_FIELD_NAME, true, (uint64_t*) &index_data_pos_);
if (index_data_pos_ == 0)
throw BagUnindexedException();
// Read topic and chunks count
if (version_ >= 200) {
readField(fields, CONNECTION_COUNT_FIELD_NAME, true, &connection_count_);
readField(fields, CHUNK_COUNT_FIELD_NAME, true, &chunk_count_);
}
logDebug("Read FILE_HEADER: index_pos=%llu connection_count=%d chunk_count=%d",
(unsigned long long) index_data_pos_, connection_count_, chunk_count_);
// Skip the data section (just padding)
seek(data_size, std::ios::cur);
}
uint32_t Bag::getChunkOffset() const {
if (compression_ == compression::Uncompressed)
return file_.getOffset() - curr_chunk_data_pos_;
else
return file_.getCompressedBytesIn();
}
void Bag::startWritingChunk(Time time) {
// Initialize chunk info
curr_chunk_info_.pos = file_.getOffset();
curr_chunk_info_.start_time = time;
curr_chunk_info_.end_time = time;
// Write the chunk header, with a place-holder for the data sizes (we'll fill in when the chunk is finished)
writeChunkHeader(compression_, 0, 0);
// Turn on compressed writing
file_.setWriteMode(compression_);
// Record where the data section of this chunk started
curr_chunk_data_pos_ = file_.getOffset();
chunk_open_ = true;
}
void Bag::stopWritingChunk() {
// Add this chunk to the index
chunks_.push_back(curr_chunk_info_);
// Get the uncompressed and compressed sizes
uint32_t uncompressed_size = getChunkOffset();
file_.setWriteMode(compression::Uncompressed);
uint32_t compressed_size = file_.getOffset() - curr_chunk_data_pos_;
// Rewrite the chunk header with the size of the chunk (remembering current offset)
uint64_t end_of_chunk_pos = file_.getOffset();
seek(curr_chunk_info_.pos);
writeChunkHeader(compression_, compressed_size, uncompressed_size);
// Write out the indexes and clear them
seek(end_of_chunk_pos);
writeIndexRecords();
curr_chunk_connection_indexes_.clear();
// Clear the connection counts
curr_chunk_info_.connection_counts.clear();
// Flag that we're starting a new chunk
chunk_open_ = false;
}
void Bag::writeChunkHeader(CompressionType compression, uint32_t compressed_size, uint32_t uncompressed_size) {
ChunkHeader chunk_header;
switch (compression) {
case compression::Uncompressed: chunk_header.compression = COMPRESSION_NONE; break;
case compression::BZ2: chunk_header.compression = COMPRESSION_BZ2; break;
case compression::LZ4: chunk_header.compression = COMPRESSION_LZ4;
//case compression::ZLIB: chunk_header.compression = COMPRESSION_ZLIB; break;
}
chunk_header.compressed_size = compressed_size;
chunk_header.uncompressed_size = uncompressed_size;
logDebug("Writing CHUNK [%llu]: compression=%s compressed=%d uncompressed=%d",
(unsigned long long) file_.getOffset(), chunk_header.compression.c_str(), chunk_header.compressed_size, chunk_header.uncompressed_size);
M_string header;
header[OP_FIELD_NAME] = toHeaderString(&OP_CHUNK);
header[COMPRESSION_FIELD_NAME] = chunk_header.compression;
header[SIZE_FIELD_NAME] = toHeaderString(&chunk_header.uncompressed_size);
writeHeader(header);
writeDataLength(chunk_header.compressed_size);
}
void Bag::readChunkHeader(ChunkHeader& chunk_header) const {
ros::Header header;
if (!readHeader(header) || !readDataLength(chunk_header.compressed_size))
throw BagFormatException("Error reading CHUNK record");
M_string& fields = *header.getValues();
if (!isOp(fields, OP_CHUNK))
throw BagFormatException("Expected CHUNK op not found");
readField(fields, COMPRESSION_FIELD_NAME, true, chunk_header.compression);
readField(fields, SIZE_FIELD_NAME, true, &chunk_header.uncompressed_size);
logDebug("Read CHUNK: compression=%s size=%d uncompressed=%d (%f)", chunk_header.compression.c_str(), chunk_header.compressed_size, chunk_header.uncompressed_size, 100 * ((double) chunk_header.compressed_size) / chunk_header.uncompressed_size);
}
// Index records
void Bag::writeIndexRecords() {
for (map<uint32_t, multiset<IndexEntry> >::const_iterator i = curr_chunk_connection_indexes_.begin(); i != curr_chunk_connection_indexes_.end(); i++) {
uint32_t connection_id = i->first;
multiset<IndexEntry> const& index = i->second;
// Write the index record header
uint32_t index_size = index.size();
M_string header;
header[OP_FIELD_NAME] = toHeaderString(&OP_INDEX_DATA);
header[CONNECTION_FIELD_NAME] = toHeaderString(&connection_id);
header[VER_FIELD_NAME] = toHeaderString(&INDEX_VERSION);
header[COUNT_FIELD_NAME] = toHeaderString(&index_size);
writeHeader(header);
writeDataLength(index_size * 12);
logDebug("Writing INDEX_DATA: connection=%d ver=%d count=%d", connection_id, INDEX_VERSION, index_size);
// Write the index record data (pairs of timestamp and position in file)
foreach(IndexEntry const& e, index) {
write((char*) &e.time.sec, 4);
write((char*) &e.time.nsec, 4);
write((char*) &e.offset, 4);
logDebug(" - %d.%d: %d", e.time.sec, e.time.nsec, e.offset);
}
}
}
void Bag::readTopicIndexRecord102() {
ros::Header header;
uint32_t data_size;
if (!readHeader(header) || !readDataLength(data_size))
throw BagFormatException("Error reading INDEX_DATA header");
M_string& fields = *header.getValues();
if (!isOp(fields, OP_INDEX_DATA))
throw BagFormatException("Expected INDEX_DATA record");
uint32_t index_version;
string topic;
uint32_t count = 0;
readField(fields, VER_FIELD_NAME, true, &index_version);
readField(fields, TOPIC_FIELD_NAME, true, topic);
readField(fields, COUNT_FIELD_NAME, true, &count);
logDebug("Read INDEX_DATA: ver=%d topic=%s count=%d", index_version, topic.c_str(), count);
if (index_version != 0)
throw BagFormatException((format("Unsupported INDEX_DATA version: %1%") % index_version).str());
uint32_t connection_id;
map<string, uint32_t>::const_iterator topic_conn_id_iter = topic_connection_ids_.find(topic);
if (topic_conn_id_iter == topic_connection_ids_.end()) {
connection_id = connections_.size();
logDebug("Creating connection: id=%d topic=%s", connection_id, topic.c_str());
ConnectionInfo* connection_info = new ConnectionInfo();
connection_info->id = connection_id;
connection_info->topic = topic;
connections_[connection_id] = connection_info;
topic_connection_ids_[topic] = connection_id;
}
else
connection_id = topic_conn_id_iter->second;
multiset<IndexEntry>& connection_index = connection_indexes_[connection_id];
for (uint32_t i = 0; i < count; i++) {
IndexEntry index_entry;
uint32_t sec;
uint32_t nsec;
read((char*) &sec, 4);
read((char*) &nsec, 4);
read((char*) &index_entry.chunk_pos, 8); //<! store position of the message in the chunk_pos field as it's 64 bits
index_entry.time = Time(sec, nsec);
index_entry.offset = 0;
logDebug(" - %d.%d: %llu", sec, nsec, (unsigned long long) index_entry.chunk_pos);
if (index_entry.time < ros::TIME_MIN || index_entry.time > ros::TIME_MAX)
{
logError("Index entry for topic %s contains invalid time.", topic.c_str());
} else
{
connection_index.insert(connection_index.end(), index_entry);
}
}
}
void Bag::readConnectionIndexRecord200() {
ros::Header header;
uint32_t data_size;
if (!readHeader(header) || !readDataLength(data_size))
throw BagFormatException("Error reading INDEX_DATA header");
M_string& fields = *header.getValues();
if (!isOp(fields, OP_INDEX_DATA))
throw BagFormatException("Expected INDEX_DATA record");
uint32_t index_version;
uint32_t connection_id;
uint32_t count = 0;
readField(fields, VER_FIELD_NAME, true, &index_version);
readField(fields, CONNECTION_FIELD_NAME, true, &connection_id);
readField(fields, COUNT_FIELD_NAME, true, &count);
logDebug("Read INDEX_DATA: ver=%d connection=%d count=%d", index_version, connection_id, count);
if (index_version != 1)
throw BagFormatException((format("Unsupported INDEX_DATA version: %1%") % index_version).str());
uint64_t chunk_pos = curr_chunk_info_.pos;
multiset<IndexEntry>& connection_index = connection_indexes_[connection_id];
for (uint32_t i = 0; i < count; i++) {
IndexEntry index_entry;
index_entry.chunk_pos = chunk_pos;
uint32_t sec;
uint32_t nsec;
read((char*) &sec, 4);
read((char*) &nsec, 4);
read((char*) &index_entry.offset, 4);
index_entry.time = Time(sec, nsec);
logDebug(" - %d.%d: %llu+%d", sec, nsec, (unsigned long long) index_entry.chunk_pos, index_entry.offset);
if (index_entry.time < ros::TIME_MIN || index_entry.time > ros::TIME_MAX)
{
logError("Index entry for topic %s contains invalid time. This message will not be loaded.", connections_[connection_id]->topic.c_str());
} else
{
connection_index.insert(connection_index.end(), index_entry);
}
}
}
// Connection records
void Bag::writeConnectionRecords() {
for (map<uint32_t, ConnectionInfo*>::const_iterator i = connections_.begin(); i != connections_.end(); i++) {
ConnectionInfo const* connection_info = i->second;
writeConnectionRecord(connection_info);
}
}
void Bag::writeConnectionRecord(ConnectionInfo const* connection_info) {
logDebug("Writing CONNECTION [%llu:%d]: topic=%s id=%d",
(unsigned long long) file_.getOffset(), getChunkOffset(), connection_info->topic.c_str(), connection_info->id);
M_string header;
header[OP_FIELD_NAME] = toHeaderString(&OP_CONNECTION);
header[TOPIC_FIELD_NAME] = connection_info->topic;
header[CONNECTION_FIELD_NAME] = toHeaderString(&connection_info->id);
header[TYPE_FIELD_NAME] = connection_info->datatype;
header[MD5_FIELD_NAME] = connection_info->md5sum;
header[DEF_FIELD_NAME] = connection_info->msg_def;
(*connection_info->header)["type"] = connection_info->datatype;
(*connection_info->header)["md5sum"] = connection_info->md5sum;
(*connection_info->header)["message_definition"] = connection_info->msg_def;
writeHeader(header);
writeHeader(*connection_info->header);
}
void Bag::appendConnectionRecordToBuffer(Buffer& buf, ConnectionInfo const* connection_info) {
M_string header;
header[OP_FIELD_NAME] = toHeaderString(&OP_CONNECTION);
header[TOPIC_FIELD_NAME] = connection_info->topic;
header[CONNECTION_FIELD_NAME] = toHeaderString(&connection_info->id);
appendHeaderToBuffer(buf, header);
appendHeaderToBuffer(buf, *connection_info->header);
}
void Bag::readConnectionRecord() {
ros::Header header;
if (!readHeader(header))
throw BagFormatException("Error reading CONNECTION header");
M_string& fields = *header.getValues();
if (!isOp(fields, OP_CONNECTION))
throw BagFormatException("Expected CONNECTION op not found");
uint32_t id;
readField(fields, CONNECTION_FIELD_NAME, true, &id);
string topic;
readField(fields, TOPIC_FIELD_NAME, true, topic);
ros::Header connection_header;
if (!readHeader(connection_header))
throw BagFormatException("Error reading connection header");
// If this is a new connection, update connections
map<uint32_t, ConnectionInfo*>::iterator key = connections_.find(id);
if (key == connections_.end()) {
ConnectionInfo* connection_info = new ConnectionInfo();
connection_info->id = id;
connection_info->topic = topic;
connection_info->header = boost::make_shared<M_string>();
for (M_string::const_iterator i = connection_header.getValues()->begin(); i != connection_header.getValues()->end(); i++)
(*connection_info->header)[i->first] = i->second;
connection_info->msg_def = (*connection_info->header)["message_definition"];
connection_info->datatype = (*connection_info->header)["type"];
connection_info->md5sum = (*connection_info->header)["md5sum"];
connections_[id] = connection_info;
logDebug("Read CONNECTION: topic=%s id=%d", topic.c_str(), id);
}
}
void Bag::readMessageDefinitionRecord102() {
ros::Header header;
uint32_t data_size;
if (!readHeader(header) || !readDataLength(data_size))
throw BagFormatException("Error reading message definition header");
M_string& fields = *header.getValues();
if (!isOp(fields, OP_MSG_DEF))
throw BagFormatException("Expected MSG_DEF op not found");
string topic, md5sum, datatype, message_definition;
readField(fields, TOPIC_FIELD_NAME, true, topic);
readField(fields, MD5_FIELD_NAME, 32, 32, true, md5sum);
readField(fields, TYPE_FIELD_NAME, true, datatype);
readField(fields, DEF_FIELD_NAME, 0, UINT_MAX, true, message_definition);
ConnectionInfo* connection_info;
map<string, uint32_t>::const_iterator topic_conn_id_iter = topic_connection_ids_.find(topic);
if (topic_conn_id_iter == topic_connection_ids_.end()) {
uint32_t id = connections_.size();
logDebug("Creating connection: topic=%s md5sum=%s datatype=%s", topic.c_str(), md5sum.c_str(), datatype.c_str());
connection_info = new ConnectionInfo();
connection_info->id = id;
connection_info->topic = topic;
connections_[id] = connection_info;
topic_connection_ids_[topic] = id;
}
else
connection_info = connections_[topic_conn_id_iter->second];
connection_info->msg_def = message_definition;
connection_info->datatype = datatype;
connection_info->md5sum = md5sum;
connection_info->header = boost::make_shared<ros::M_string>();
(*connection_info->header)["type"] = connection_info->datatype;
(*connection_info->header)["md5sum"] = connection_info->md5sum;
(*connection_info->header)["message_definition"] = connection_info->msg_def;
logDebug("Read MSG_DEF: topic=%s md5sum=%s datatype=%s", topic.c_str(), md5sum.c_str(), datatype.c_str());
}
void Bag::decompressChunk(uint64_t chunk_pos) const {
if (curr_chunk_info_.pos == chunk_pos) {
current_buffer_ = &outgoing_chunk_buffer_;
return;
}
current_buffer_ = &decompress_buffer_;
if (decompressed_chunk_ == chunk_pos)
return;
// Seek to the start of the chunk
seek(chunk_pos);
// Read the chunk header
ChunkHeader chunk_header;
readChunkHeader(chunk_header);
// Read and decompress the chunk. These assume we are at the right place in the stream already
if (chunk_header.compression == COMPRESSION_NONE)
decompressRawChunk(chunk_header);
else if (chunk_header.compression == COMPRESSION_BZ2)
decompressBz2Chunk(chunk_header);
else if (chunk_header.compression == COMPRESSION_LZ4)
decompressLz4Chunk(chunk_header);
else
throw BagFormatException("Unknown compression: " + chunk_header.compression);
decompressed_chunk_ = chunk_pos;
}
void Bag::readMessageDataRecord102(uint64_t offset, ros::Header& header) const {
logDebug("readMessageDataRecord: offset=%llu", (unsigned long long) offset);
seek(offset);
uint32_t data_size;
uint8_t op;
do {
if (!readHeader(header) || !readDataLength(data_size))
throw BagFormatException("Error reading header");
readField(*header.getValues(), OP_FIELD_NAME, true, &op);
}
while (op == OP_MSG_DEF);
if (op != OP_MSG_DATA)
throw BagFormatException((format("Expected MSG_DATA op, got %d") % op).str());
record_buffer_.setSize(data_size);
file_.read((char*) record_buffer_.getData(), data_size);
}
// Reading this into a buffer isn't completely necessary, but we do it anyways for now
void Bag::decompressRawChunk(ChunkHeader const& chunk_header) const {
assert(chunk_header.compression == COMPRESSION_NONE);
assert(chunk_header.compressed_size == chunk_header.uncompressed_size);
logDebug("compressed_size: %d uncompressed_size: %d", chunk_header.compressed_size, chunk_header.uncompressed_size);
decompress_buffer_.setSize(chunk_header.compressed_size);
file_.read((char*) decompress_buffer_.getData(), chunk_header.compressed_size);
// todo check read was successful
}
void Bag::decompressBz2Chunk(ChunkHeader const& chunk_header) const {
assert(chunk_header.compression == COMPRESSION_BZ2);
CompressionType compression = compression::BZ2;
logDebug("compressed_size: %d uncompressed_size: %d", chunk_header.compressed_size, chunk_header.uncompressed_size);
chunk_buffer_.setSize(chunk_header.compressed_size);
file_.read((char*) chunk_buffer_.getData(), chunk_header.compressed_size);
decompress_buffer_.setSize(chunk_header.uncompressed_size);
file_.decompress(compression, decompress_buffer_.getData(), decompress_buffer_.getSize(), chunk_buffer_.getData(), chunk_buffer_.getSize());
// todo check read was successful
}
void Bag::decompressLz4Chunk(ChunkHeader const& chunk_header) const {
assert(chunk_header.compression == COMPRESSION_LZ4);
CompressionType compression = compression::LZ4;
logDebug("lz4 compressed_size: %d uncompressed_size: %d",
chunk_header.compressed_size, chunk_header.uncompressed_size);
chunk_buffer_.setSize(chunk_header.compressed_size);
file_.read((char*) chunk_buffer_.getData(), chunk_header.compressed_size);
decompress_buffer_.setSize(chunk_header.uncompressed_size);
file_.decompress(compression, decompress_buffer_.getData(), decompress_buffer_.getSize(), chunk_buffer_.getData(), chunk_buffer_.getSize());
// todo check read was successful
}
ros::Header Bag::readMessageDataHeader(IndexEntry const& index_entry) {
ros::Header header;
uint32_t data_size;
uint32_t bytes_read;
switch (version_)
{
case 200:
decompressChunk(index_entry.chunk_pos);
readMessageDataHeaderFromBuffer(*current_buffer_, index_entry.offset, header, data_size, bytes_read);
return header;
case 102:
readMessageDataRecord102(index_entry.chunk_pos, header);
return header;
default:
throw BagFormatException((format("Unhandled version: %1%") % version_).str());
}
}
// NOTE: this loads the header, which is unnecessary
uint32_t Bag::readMessageDataSize(IndexEntry const& index_entry) const {
ros::Header header;
uint32_t data_size;
uint32_t bytes_read;
switch (version_)
{
case 200:
decompressChunk(index_entry.chunk_pos);
readMessageDataHeaderFromBuffer(*current_buffer_, index_entry.offset, header, data_size, bytes_read);
return data_size;
case 102:
readMessageDataRecord102(index_entry.chunk_pos, header);
return record_buffer_.getSize();
default:
throw BagFormatException((format("Unhandled version: %1%") % version_).str());
}
}
void Bag::writeChunkInfoRecords() {
foreach(ChunkInfo const& chunk_info, chunks_) {
// Write the chunk info header
M_string header;
uint32_t chunk_connection_count = chunk_info.connection_counts.size();
header[OP_FIELD_NAME] = toHeaderString(&OP_CHUNK_INFO);
header[VER_FIELD_NAME] = toHeaderString(&CHUNK_INFO_VERSION);
header[CHUNK_POS_FIELD_NAME] = toHeaderString(&chunk_info.pos);
header[START_TIME_FIELD_NAME] = toHeaderString(&chunk_info.start_time);
header[END_TIME_FIELD_NAME] = toHeaderString(&chunk_info.end_time);
header[COUNT_FIELD_NAME] = toHeaderString(&chunk_connection_count);
logDebug("Writing CHUNK_INFO [%llu]: ver=%d pos=%llu start=%d.%d end=%d.%d",
(unsigned long long) file_.getOffset(), CHUNK_INFO_VERSION, (unsigned long long) chunk_info.pos,
chunk_info.start_time.sec, chunk_info.start_time.nsec,
chunk_info.end_time.sec, chunk_info.end_time.nsec);
writeHeader(header);
writeDataLength(8 * chunk_connection_count);
// Write the topic names and counts
for (map<uint32_t, uint32_t>::const_iterator i = chunk_info.connection_counts.begin(); i != chunk_info.connection_counts.end(); i++) {
uint32_t connection_id = i->first;
uint32_t count = i->second;
write((char*) &connection_id, 4);
write((char*) &count, 4);
logDebug(" - %d: %d", connection_id, count);
}
}
}
void Bag::readChunkInfoRecord() {
// Read a CHUNK_INFO header
ros::Header header;
uint32_t data_size;
if (!readHeader(header) || !readDataLength(data_size))
throw BagFormatException("Error reading CHUNK_INFO record header");
M_string& fields = *header.getValues();
if (!isOp(fields, OP_CHUNK_INFO))
throw BagFormatException("Expected CHUNK_INFO op not found");
// Check that the chunk info version is current
uint32_t chunk_info_version;
readField(fields, VER_FIELD_NAME, true, &chunk_info_version);
if (chunk_info_version != CHUNK_INFO_VERSION)
throw BagFormatException((format("Expected CHUNK_INFO version %1%, read %2%") % CHUNK_INFO_VERSION % chunk_info_version).str());
// Read the chunk position, timestamp, and topic count fields
ChunkInfo chunk_info;
readField(fields, CHUNK_POS_FIELD_NAME, true, &chunk_info.pos);
readField(fields, START_TIME_FIELD_NAME, true, chunk_info.start_time);
readField(fields, END_TIME_FIELD_NAME, true, chunk_info.end_time);
uint32_t chunk_connection_count = 0;
readField(fields, COUNT_FIELD_NAME, true, &chunk_connection_count);
logDebug("Read CHUNK_INFO: chunk_pos=%llu connection_count=%d start=%d.%d end=%d.%d",
(unsigned long long) chunk_info.pos, chunk_connection_count,
chunk_info.start_time.sec, chunk_info.start_time.nsec,
chunk_info.end_time.sec, chunk_info.end_time.nsec);
// Read the topic count entries
for (uint32_t i = 0; i < chunk_connection_count; i ++) {
uint32_t connection_id, connection_count;
read((char*) &connection_id, 4);
read((char*) &connection_count, 4);
logDebug(" %d: %d messages", connection_id, connection_count);
chunk_info.connection_counts[connection_id] = connection_count;
}
chunks_.push_back(chunk_info);
}
// Record I/O
bool Bag::isOp(M_string& fields, uint8_t reqOp) const {
uint8_t op = 0xFF; // nonexistent op
readField(fields, OP_FIELD_NAME, true, &op);
return op == reqOp;
}
void Bag::writeHeader(M_string const& fields) {
boost::shared_array<uint8_t> header_buffer;
uint32_t header_len;
ros::Header::write(fields, header_buffer, header_len);
write((char*) &header_len, 4);
write((char*) header_buffer.get(), header_len);
}
void Bag::writeDataLength(uint32_t data_len) {
write((char*) &data_len, 4);
}
void Bag::appendHeaderToBuffer(Buffer& buf, M_string const& fields) {
boost::shared_array<uint8_t> header_buffer;
uint32_t header_len;
ros::Header::write(fields, header_buffer, header_len);
uint32_t offset = buf.getSize();
buf.setSize(buf.getSize() + 4 + header_len);
memcpy(buf.getData() + offset, &header_len, 4);
offset += 4;
memcpy(buf.getData() + offset, header_buffer.get(), header_len);
}
void Bag::appendDataLengthToBuffer(Buffer& buf, uint32_t data_len) {
uint32_t offset = buf.getSize();
buf.setSize(buf.getSize() + 4);
memcpy(buf.getData() + offset, &data_len, 4);
}
//! \todo clean this up
void Bag::readHeaderFromBuffer(Buffer& buffer, uint32_t offset, ros::Header& header, uint32_t& data_size, uint32_t& bytes_read) const {
assert(buffer.getSize() > 8);
uint8_t* start = (uint8_t*) buffer.getData() + offset;
uint8_t* ptr = start;
// Read the header length
uint32_t header_len;
memcpy(&header_len, ptr, 4);
ptr += 4;
// Parse the header
string error_msg;
bool parsed = header.parse(ptr, header_len, error_msg);
if (!parsed)
throw BagFormatException("Error parsing header");
ptr += header_len;
// Read the data size
memcpy(&data_size, ptr, 4);
ptr += 4;
bytes_read = ptr - start;
}
void Bag::readMessageDataHeaderFromBuffer(Buffer& buffer, uint32_t offset, ros::Header& header, uint32_t& data_size, uint32_t& total_bytes_read) const {
(void)buffer;
total_bytes_read = 0;
uint8_t op = 0xFF;
do {
logDebug("reading header from buffer: offset=%d", offset);
uint32_t bytes_read;
readHeaderFromBuffer(*current_buffer_, offset, header, data_size, bytes_read);
offset += bytes_read;
total_bytes_read += bytes_read;
readField(*header.getValues(), OP_FIELD_NAME, true, &op);
}
while (op == OP_MSG_DEF || op == OP_CONNECTION);
if (op != OP_MSG_DATA)
throw BagFormatException("Expected MSG_DATA op not found");
}
bool Bag::readHeader(ros::Header& header) const {
// Read the header length
uint32_t header_len;
read((char*) &header_len, 4);
// Read the header
header_buffer_.setSize(header_len);
read((char*) header_buffer_.getData(), header_len);
// Parse the header
string error_msg;
bool parsed = header.parse(header_buffer_.getData(), header_len, error_msg);
if (!parsed)
return false;
return true;
}
bool Bag::readDataLength(uint32_t& data_size) const {
read((char*) &data_size, 4);
return true;
}
M_string::const_iterator Bag::checkField(M_string const& fields, string const& field, unsigned int min_len, unsigned int max_len, bool required) const {
M_string::const_iterator fitr = fields.find(field);
if (fitr == fields.end()) {
if (required)
throw BagFormatException("Required '" + field + "' field missing");
}
else if ((fitr->second.size() < min_len) || (fitr->second.size() > max_len))
throw BagFormatException((format("Field '%1%' is wrong size (%2% bytes)") % field % (uint32_t) fitr->second.size()).str());
return fitr;
}
bool Bag::readField(M_string const& fields, string const& field_name, bool required, string& data) const {
return readField(fields, field_name, 1, UINT_MAX, required, data);
}
bool Bag::readField(M_string const& fields, string const& field_name, unsigned int min_len, unsigned int max_len, bool required, string& data) const {
M_string::const_iterator fitr = checkField(fields, field_name, min_len, max_len, required);
if (fitr == fields.end())
return false;
data = fitr->second;
return true;
}
bool Bag::readField(M_string const& fields, string const& field_name, bool required, Time& data) const {
uint64_t packed_time;
if (!readField(fields, field_name, required, &packed_time))
return false;
uint64_t bitmask = (1LL << 33) - 1;
data.sec = (uint32_t) (packed_time & bitmask);
data.nsec = (uint32_t) (packed_time >> 32);
return true;
}
std::string Bag::toHeaderString(Time const* field) const {
uint64_t packed_time = (((uint64_t) field->nsec) << 32) + field->sec;
return toHeaderString(&packed_time);
}
// Low-level I/O
void Bag::write(string const& s) { write(s.c_str(), s.length()); }
void Bag::write(char const* s, std::streamsize n) { file_.write((char*) s, n); }
void Bag::read(char* b, std::streamsize n) const { file_.read(b, n); }
void Bag::seek(uint64_t pos, int origin) const { file_.seek(pos, origin); }
} // namespace rosbag
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/src/bz2_stream.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 "rosbag/chunked_file.h"
#include <iostream>
#include <cstring>
#include "console_bridge/console.h"
using std::string;
namespace rosbag {
BZ2Stream::BZ2Stream(ChunkedFile* file) :
Stream(file),
verbosity_(0),
block_size_100k_(9),
work_factor_(30),
bzfile_(NULL),
bzerror_(0)
{ }
CompressionType BZ2Stream::getCompressionType() const {
return compression::BZ2;
}
void BZ2Stream::startWrite() {
bzfile_ = BZ2_bzWriteOpen(&bzerror_, getFilePointer(), block_size_100k_, verbosity_, work_factor_);
switch (bzerror_) {
case BZ_OK: break;
default: {
BZ2_bzWriteClose(&bzerror_, bzfile_, 0, NULL, NULL);
throw BagException("Error opening file for writing compressed stream");
}
}
setCompressedIn(0);
}
void BZ2Stream::write(void* ptr, size_t size) {
BZ2_bzWrite(&bzerror_, bzfile_, ptr, size);
switch (bzerror_) {
case BZ_IO_ERROR: throw BagException("BZ_IO_ERROR: error writing the compressed file");
}
setCompressedIn(getCompressedIn() + size);
}
void BZ2Stream::stopWrite() {
unsigned int nbytes_in;
unsigned int nbytes_out;
BZ2_bzWriteClose(&bzerror_, bzfile_, 0, &nbytes_in, &nbytes_out);
switch (bzerror_) {
case BZ_IO_ERROR: throw BagIOException("BZ_IO_ERROR");
}
advanceOffset(nbytes_out);
setCompressedIn(0);
}
void BZ2Stream::startRead() {
bzfile_ = BZ2_bzReadOpen(&bzerror_, getFilePointer(), verbosity_, 0, getUnused(), getUnusedLength());
switch (bzerror_) {
case BZ_OK: break;
default: {
BZ2_bzReadClose(&bzerror_, bzfile_);
throw BagException("Error opening file for reading compressed stream");
}
}
clearUnused();
}
void BZ2Stream::read(void* ptr, size_t size) {
BZ2_bzRead(&bzerror_, bzfile_, ptr, size);
advanceOffset(size);
switch (bzerror_) {
case BZ_OK: return;
case BZ_STREAM_END:
if (getUnused() || getUnusedLength() > 0)
logError("unused data already available");
else {
char* unused;
int nUnused;
BZ2_bzReadGetUnused(&bzerror_, bzfile_, (void**) &unused, &nUnused);
setUnused(unused);
setUnusedLength(nUnused);
}
return;
case BZ_IO_ERROR: throw BagIOException("BZ_IO_ERROR: error reading from compressed stream"); break;
case BZ_UNEXPECTED_EOF: throw BagIOException("BZ_UNEXPECTED_EOF: compressed stream ended before logical end-of-stream detected"); break;
case BZ_DATA_ERROR: throw BagIOException("BZ_DATA_ERROR: data integrity error detected in compressed stream"); break;
case BZ_DATA_ERROR_MAGIC: throw BagIOException("BZ_DATA_ERROR_MAGIC: stream does not begin with requisite header bytes"); break;
case BZ_MEM_ERROR: throw BagIOException("BZ_MEM_ERROR: insufficient memory available"); break;
}
}
void BZ2Stream::stopRead() {
BZ2_bzReadClose(&bzerror_, bzfile_);
switch (bzerror_) {
case BZ_IO_ERROR: throw BagIOException("BZ_IO_ERROR");
}
}
void BZ2Stream::decompress(uint8_t* dest, unsigned int dest_len, uint8_t* source, unsigned int source_len) {
int result = BZ2_bzBuffToBuffDecompress((char*) dest, &dest_len, (char*) source, source_len, 0, verbosity_);
switch (result) {
case BZ_OK: break;
case BZ_CONFIG_ERROR: throw BagException("library has been mis-compiled"); break;
case BZ_PARAM_ERROR: throw BagException("dest is NULL or destLen is NULL or small != 0 && small != 1 or verbosity < 0 or verbosity > 4"); break;
case BZ_MEM_ERROR: throw BagException("insufficient memory is available"); break;
case BZ_OUTBUFF_FULL: throw BagException("size of the compressed data exceeds *destLen"); break;
case BZ_DATA_ERROR: throw BagException("data integrity error was detected in the compressed data"); break;
case BZ_DATA_ERROR_MAGIC: throw BagException("compressed data doesn't begin with the right magic bytes"); break;
case BZ_UNEXPECTED_EOF: throw BagException("compressed data ends unexpectedly"); break;
}
}
} // namespace rosbag
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/src/lz4_stream.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 "rosbag/chunked_file.h"
#include <iostream>
#include <cstring>
#include "console_bridge/console.h"
using std::string;
namespace rosbag {
LZ4Stream::LZ4Stream(ChunkedFile* file)
: Stream(file), block_size_id_(6) {
buff_size_ = roslz4_blockSizeFromIndex(block_size_id_) + 64;
buff_ = new char[buff_size_];
}
LZ4Stream::~LZ4Stream() {
delete[] buff_;
}
CompressionType LZ4Stream::getCompressionType() const {
return compression::LZ4;
}
void LZ4Stream::startWrite() {
setCompressedIn(0);
int ret = roslz4_compressStart(&lz4s_, block_size_id_);
switch(ret) {
case ROSLZ4_OK: break;
case ROSLZ4_MEMORY_ERROR: throw BagIOException("ROSLZ4_MEMORY_ERROR: insufficient memory available"); break;
case ROSLZ4_PARAM_ERROR: throw BagIOException("ROSLZ4_PARAM_ERROR: bad block size"); break;
default: throw BagException("Unhandled return code");
}
lz4s_.output_next = buff_;
lz4s_.output_left = buff_size_;
}
void LZ4Stream::write(void* ptr, size_t size) {
lz4s_.input_left = size;
lz4s_.input_next = (char*) ptr;
writeStream(ROSLZ4_RUN);
setCompressedIn(getCompressedIn() + size);
}
void LZ4Stream::writeStream(int action) {
int ret = ROSLZ4_OK;
while (lz4s_.input_left > 0 ||
(action == ROSLZ4_FINISH && ret != ROSLZ4_STREAM_END)) {
ret = roslz4_compress(&lz4s_, action);
switch(ret) {
case ROSLZ4_OK: break;
case ROSLZ4_OUTPUT_SMALL:
if (lz4s_.output_next - buff_ == buff_size_) {
throw BagIOException("ROSLZ4_OUTPUT_SMALL: output buffer is too small");
} else {
// There's data to be written in buff_; this will free up space
break;
}
case ROSLZ4_STREAM_END: break;
case ROSLZ4_PARAM_ERROR: throw BagIOException("ROSLZ4_PARAM_ERROR: bad block size"); break;
case ROSLZ4_ERROR: throw BagIOException("ROSLZ4_ERROR: compression error"); break;
default: throw BagException("Unhandled return code");
}
// If output data is ready, write to disk
int to_write = lz4s_.output_next - buff_;
if (to_write > 0) {
if (fwrite(buff_, 1, to_write, getFilePointer()) != static_cast<size_t>(to_write)) {
throw BagException("Problem writing data to disk");
}
advanceOffset(to_write);
lz4s_.output_next = buff_;
lz4s_.output_left = buff_size_;
}
}
}
void LZ4Stream::stopWrite() {
writeStream(ROSLZ4_FINISH);
setCompressedIn(0);
roslz4_compressEnd(&lz4s_);
}
void LZ4Stream::startRead() {
int ret = roslz4_decompressStart(&lz4s_);
switch(ret) {
case ROSLZ4_OK: break;
case ROSLZ4_MEMORY_ERROR: throw BagException("ROSLZ4_MEMORY_ERROR: insufficient memory available"); break;
default: throw BagException("Unhandled return code");
}
if (getUnusedLength() > buff_size_) {
throw BagException("Too many unused bytes to decompress");
}
// getUnused() could be pointing to part of buff_, so don't use memcpy
memmove(buff_, getUnused(), getUnusedLength());
lz4s_.input_next = buff_;
lz4s_.input_left = getUnusedLength();
clearUnused();
}
void LZ4Stream::read(void* ptr, size_t size) {
// Setup stream by filling buffer with data from file
int to_read = buff_size_ - lz4s_.input_left;
char *input_start = buff_ + lz4s_.input_left;
int nread = fread(input_start, 1, to_read, getFilePointer());
if (ferror(getFilePointer())) {
throw BagIOException("Problem reading from file");
}
lz4s_.input_next = buff_;
lz4s_.input_left += nread;
lz4s_.output_next = (char*) ptr;
lz4s_.output_left = size;
// Decompress. If reach end of stream, store unused data
int ret = roslz4_decompress(&lz4s_);
switch (ret) {
case ROSLZ4_OK: break;
case ROSLZ4_STREAM_END:
if (getUnused() || getUnusedLength() > 0)
logError("unused data already available");
else {
setUnused(lz4s_.input_next);
setUnusedLength(lz4s_.input_left);
}
return;
case ROSLZ4_ERROR: throw BagException("ROSLZ4_ERROR: decompression error"); break;
case ROSLZ4_MEMORY_ERROR: throw BagException("ROSLZ4_MEMORY_ERROR: insufficient memory available"); break;
case ROSLZ4_OUTPUT_SMALL: throw BagException("ROSLZ4_OUTPUT_SMALL: output buffer is too small"); break;
case ROSLZ4_DATA_ERROR: throw BagException("ROSLZ4_DATA_ERROR: malformed data to decompress"); break;
default: throw BagException("Unhandled return code");
}
if (feof(getFilePointer())) {
throw BagIOException("Reached end of file before reaching end of stream");
}
size_t total_out = lz4s_.output_next - (char*)ptr;
advanceOffset(total_out);
// Shift input buffer if there's unconsumed data
if (lz4s_.input_left > 0) {
memmove(buff_, lz4s_.input_next, lz4s_.input_left);
}
}
void LZ4Stream::stopRead() {
roslz4_decompressEnd(&lz4s_);
}
void LZ4Stream::decompress(uint8_t* dest, unsigned int dest_len, uint8_t* source, unsigned int source_len) {
unsigned int actual_dest_len = dest_len;
int ret = roslz4_buffToBuffDecompress((char*)source, source_len,
(char*)dest, &actual_dest_len);
switch(ret) {
case ROSLZ4_OK: break;
case ROSLZ4_ERROR: throw BagException("ROSLZ4_ERROR: decompression error"); break;
case ROSLZ4_MEMORY_ERROR: throw BagException("ROSLZ4_MEMORY_ERROR: insufficient memory available"); break;
case ROSLZ4_OUTPUT_SMALL: throw BagException("ROSLZ4_OUTPUT_SMALL: output buffer is too small"); break;
case ROSLZ4_DATA_ERROR: throw BagException("ROSLZ4_DATA_ERROR: malformed data to decompress"); break;
default: throw BagException("Unhandled return code");
}
if (actual_dest_len != dest_len) {
throw BagException("Decompression size mismatch in LZ4 chunk");
}
}
} // namespace rosbag
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/src/chunked_file.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 "rosbag/chunked_file.h"
#include <iostream>
#include <boost/format.hpp>
#include <boost/make_shared.hpp>
//#include <ros/ros.h>
#ifdef _WIN32
# ifdef __MINGW32__
# define fseeko fseeko64
# define ftello ftello64
// not sure if we need a ftruncate here yet or not
# else
# include <io.h>
# define fseeko _fseeki64
# define ftello _ftelli64
# define fileno _fileno
# define ftruncate _chsize
# endif
#endif
using std::string;
using boost::format;
using boost::shared_ptr;
using ros::Exception;
namespace rosbag {
ChunkedFile::ChunkedFile() :
file_(NULL),
offset_(0),
compressed_in_(0),
unused_(NULL),
nUnused_(0)
{
stream_factory_ = boost::make_shared<StreamFactory>(this);
}
ChunkedFile::~ChunkedFile() {
close();
}
void ChunkedFile::openReadWrite(string const& filename) { open(filename, "r+b"); }
void ChunkedFile::openWrite (string const& filename) { open(filename, "w+b"); }
void ChunkedFile::openRead (string const& filename) { open(filename, "rb"); }
void ChunkedFile::open(string const& filename, string const& mode) {
// Check if file is already open
if (file_)
throw BagIOException((format("File already open: %1%") % filename_.c_str()).str());
// Open the file
if (mode == "r+b") {
// Read + write requires file to exists. Create a new file if it doesn't exist.
#if defined(_MSC_VER) && (_MSC_VER >= 1400 )
fopen_s( &file_, filename.c_str(), "r" );
#else
file_ = fopen(filename.c_str(), "r");
#endif
if (file_ == NULL)
#if defined(_MSC_VER) && (_MSC_VER >= 1400 )
fopen_s( &file_, filename.c_str(), "w+b" );
#else
file_ = fopen(filename.c_str(), "w+b");
#endif
else {
fclose(file_);
#if defined(_MSC_VER) && (_MSC_VER >= 1400 )
fopen_s( &file_, filename.c_str(), "w+b" );
#else
file_ = fopen(filename.c_str(), "r+b");
#endif
}
}
else
#if defined(_MSC_VER) && (_MSC_VER >= 1400 )
fopen_s( &file_, filename.c_str(), mode.c_str() );
#else
file_ = fopen(filename.c_str(), mode.c_str());
#endif
if (!file_)
throw BagIOException((format("Error opening file: %1%") % filename.c_str()).str());
read_stream_ = boost::make_shared<UncompressedStream>(this);
write_stream_ = boost::make_shared<UncompressedStream>(this);
filename_ = filename;
offset_ = ftello(file_);
}
bool ChunkedFile::good() const {
return feof(file_) == 0 && ferror(file_) == 0;
}
bool ChunkedFile::isOpen() const { return file_ != NULL; }
string ChunkedFile::getFileName() const { return filename_; }
void ChunkedFile::close() {
if (!file_)
return;
// Close any compressed stream by changing to uncompressed mode
setWriteMode(compression::Uncompressed);
// Close the file
int success = fclose(file_);
if (success != 0)
throw BagIOException((format("Error closing file: %1%") % filename_.c_str()).str());
file_ = NULL;
filename_.clear();
clearUnused();
}
// Read/write modes
void ChunkedFile::setWriteMode(CompressionType type) {
if (!file_)
throw BagIOException("Can't set compression mode before opening a file");
if (type != write_stream_->getCompressionType()) {
write_stream_->stopWrite();
shared_ptr<Stream> stream = stream_factory_->getStream(type);
stream->startWrite();
write_stream_ = stream;
}
}
void ChunkedFile::setReadMode(CompressionType type) {
if (!file_)
throw BagIOException("Can't set compression mode before opening a file");
if (type != read_stream_->getCompressionType()) {
read_stream_->stopRead();
shared_ptr<Stream> stream = stream_factory_->getStream(type);
stream->startRead();
read_stream_ = stream;
}
}
void ChunkedFile::seek(uint64_t offset, int origin) {
if (!file_)
throw BagIOException("Can't seek - file not open");
setReadMode(compression::Uncompressed);
int success = fseeko(file_, offset, origin);
if (success != 0)
throw BagIOException("Error seeking");
offset_ = ftello(file_);
}
uint64_t ChunkedFile::getOffset() const { return offset_; }
uint32_t ChunkedFile::getCompressedBytesIn() const { return compressed_in_; }
void ChunkedFile::write(string const& s) { write((void*) s.c_str(), s.size()); }
void ChunkedFile::write(void* ptr, size_t size) { write_stream_->write(ptr, size); }
void ChunkedFile::read(void* ptr, size_t size) { read_stream_->read(ptr, size); }
bool ChunkedFile::truncate(uint64_t length) {
int fd = fileno(file_);
return ftruncate(fd, length) == 0;
}
//! \todo add error handling
string ChunkedFile::getline() {
char buffer[1024];
if(fgets(buffer, 1024, file_))
{
string s(buffer);
offset_ += s.size();
return s;
}
else
return string("");
}
void ChunkedFile::decompress(CompressionType compression, uint8_t* dest, unsigned int dest_len, uint8_t* source, unsigned int source_len) {
stream_factory_->getStream(compression)->decompress(dest, dest_len, source, source_len);
}
void ChunkedFile::clearUnused() {
unused_ = NULL;
nUnused_ = 0;
}
} // namespace rosbag
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/src/view.cpp | // 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.
#include "rosbag/view.h"
#include "rosbag/bag.h"
#include "rosbag/message_instance.h"
#include <boost/foreach.hpp>
#include <set>
#include <assert.h>
#define foreach BOOST_FOREACH
using std::map;
using std::string;
using std::vector;
using std::multiset;
namespace rosbag {
// View::iterator
View::iterator::iterator() : view_(NULL), view_revision_(0), message_instance_(NULL) { }
View::iterator::~iterator()
{
if (message_instance_ != NULL)
delete message_instance_;
}
View::iterator::iterator(View* view, bool end) : view_(view), view_revision_(0), message_instance_(NULL) {
if (view != NULL && !end)
populate();
}
View::iterator::iterator(const iterator& i) : view_(i.view_), iters_(i.iters_), view_revision_(i.view_revision_), message_instance_(NULL) { }
void View::iterator::populate() {
assert(view_ != NULL);
iters_.clear();
foreach(MessageRange const* range, view_->ranges_)
if (range->begin != range->end)
iters_.push_back(ViewIterHelper(range->begin, range));
std::sort(iters_.begin(), iters_.end(), ViewIterHelperCompare());
view_revision_ = view_->view_revision_;
}
void View::iterator::populateSeek(multiset<IndexEntry>::const_iterator iter) {
assert(view_ != NULL);
iters_.clear();
foreach(MessageRange const* range, view_->ranges_) {
multiset<IndexEntry>::const_iterator start = std::lower_bound(range->begin, range->end, iter->time, IndexEntryCompare());
if (start != range->end)
iters_.push_back(ViewIterHelper(start, range));
}
std::sort(iters_.begin(), iters_.end(), ViewIterHelperCompare());
while (iter != iters_.back().iter)
increment();
view_revision_ = view_->view_revision_;
}
bool View::iterator::equal(View::iterator const& other) const {
// We need some way of verifying these are actually talking about
// the same merge_queue data since we shouldn't be able to compare
// iterators from different Views.
if (iters_.empty())
return other.iters_.empty();
if (other.iters_.empty())
return false;
return iters_.back().iter == other.iters_.back().iter;
}
void View::iterator::increment() {
assert(view_ != NULL);
// Our message instance is no longer valid
if (message_instance_ != NULL)
{
delete message_instance_;
message_instance_ = NULL;
}
view_->update();
// Note, updating may have blown away our message-ranges and
// replaced them in general the ViewIterHelpers are no longer
// valid, but the iterator it stores should still be good.
if (view_revision_ != view_->view_revision_)
populateSeek(iters_.back().iter);
if (view_->reduce_overlap_)
{
std::multiset<IndexEntry>::const_iterator last_iter = iters_.back().iter;
while (iters_.back().iter == last_iter)
{
iters_.back().iter++;
if (iters_.back().iter == iters_.back().range->end)
iters_.pop_back();
std::sort(iters_.begin(), iters_.end(), ViewIterHelperCompare());
}
} else {
iters_.back().iter++;
if (iters_.back().iter == iters_.back().range->end)
iters_.pop_back();
std::sort(iters_.begin(), iters_.end(), ViewIterHelperCompare());
}
}
MessageInstance& View::iterator::dereference() const {
ViewIterHelper const& i = iters_.back();
if (message_instance_ == NULL)
message_instance_ = view_->newMessageInstance(i.range->connection_info, *(i.iter), *(i.range->bag_query->bag));
return *message_instance_;
}
// View
View::View(bool const& reduce_overlap) : view_revision_(0), size_cache_(0), size_revision_(0), reduce_overlap_(reduce_overlap) { }
View::View(Bag const& bag, ros::Time const& start_time, ros::Time const& end_time, bool const& reduce_overlap) : view_revision_(0), size_cache_(0), size_revision_(0), reduce_overlap_(reduce_overlap) {
addQuery(bag, start_time, end_time);
}
View::View(Bag const& bag, boost::function<bool(ConnectionInfo const*)> query, ros::Time const& start_time, ros::Time const& end_time, bool const& reduce_overlap) : view_revision_(0), size_cache_(0), size_revision_(0), reduce_overlap_(reduce_overlap) {
addQuery(bag, query, start_time, end_time);
}
View::~View() {
foreach(MessageRange* range, ranges_)
delete range;
foreach(BagQuery* query, queries_)
delete query;
}
ros::Time View::getBeginTime()
{
update();
ros::Time begin = ros::TIME_MAX;
foreach (rosbag::MessageRange* range, ranges_)
{
if (range->begin->time < begin)
begin = range->begin->time;
}
return begin;
}
ros::Time View::getEndTime()
{
update();
ros::Time end = ros::TIME_MIN;
foreach (rosbag::MessageRange* range, ranges_)
{
std::multiset<IndexEntry>::const_iterator e = range->end;
e--;
if (e->time > end)
end = e->time;
}
return end;
}
//! Simply copy the merge_queue state into the iterator
View::iterator View::begin() {
update();
return iterator(this);
}
//! Default constructed iterator signifies end
View::iterator View::end() { return iterator(this, true); }
uint32_t View::size() {
update();
if (size_revision_ != view_revision_)
{
size_cache_ = 0;
foreach (MessageRange* range, ranges_)
{
size_cache_ += std::distance(range->begin, range->end);
}
size_revision_ = view_revision_;
}
return size_cache_;
}
void View::addQuery(Bag const& bag, ros::Time const& start_time, ros::Time const& end_time) {
if ((bag.getMode() & bagmode::Read) != bagmode::Read)
throw BagException("Bag not opened for reading");
boost::function<bool(ConnectionInfo const*)> query = TrueQuery();
queries_.push_back(new BagQuery(&bag, Query(query, start_time, end_time), bag.bag_revision_));
updateQueries(queries_.back());
}
void View::addQuery(Bag const& bag, boost::function<bool(ConnectionInfo const*)> query, ros::Time const& start_time, ros::Time const& end_time) {
if ((bag.getMode() & bagmode::Read) != bagmode::Read)
throw BagException("Bag not opened for reading");
queries_.push_back(new BagQuery(&bag, Query(query, start_time, end_time), bag.bag_revision_));
updateQueries(queries_.back());
}
void View::updateQueries(BagQuery* q) {
for (map<uint32_t, ConnectionInfo*>::const_iterator i = q->bag->connections_.begin(); i != q->bag->connections_.end(); i++) {
ConnectionInfo const* connection = i->second;
// Skip if the query doesn't evaluate to true
if (!q->query.getQuery()(connection))
continue;
map<uint32_t, multiset<IndexEntry> >::const_iterator j = q->bag->connection_indexes_.find(connection->id);
// Skip if the bag doesn't have the corresponding index
if (j == q->bag->connection_indexes_.end())
continue;
multiset<IndexEntry> const& index = j->second;
// lower_bound/upper_bound do a binary search to find the appropriate range of Index Entries given our time range
std::multiset<IndexEntry>::const_iterator begin = std::lower_bound(index.begin(), index.end(), q->query.getStartTime(), IndexEntryCompare());
std::multiset<IndexEntry>::const_iterator end = std::upper_bound(index.begin(), index.end(), q->query.getEndTime(), IndexEntryCompare());
// Make sure we are at the right beginning
while (begin != index.begin() && begin->time >= q->query.getStartTime())
{
begin--;
if (begin->time < q->query.getStartTime())
{
begin++;
break;
}
}
if (begin != end)
{
// todo: make faster with a map of maps
bool found = false;
for (vector<MessageRange*>::iterator k = ranges_.begin(); k != ranges_.end(); k++) {
MessageRange* r = *k;
// If the topic and query are already in our ranges, we update
if (r->bag_query == q && r->connection_info->id == connection->id) {
r->begin = begin;
r->end = end;
found = true;
break;
}
}
if (!found)
ranges_.push_back(new MessageRange(begin, end, connection, q));
}
}
view_revision_++;
}
void View::update() {
foreach(BagQuery* query, queries_) {
if (query->bag->bag_revision_ != query->bag_revision) {
updateQueries(query);
query->bag_revision = query->bag->bag_revision_;
}
}
}
std::vector<const ConnectionInfo*> View::getConnections()
{
std::vector<const ConnectionInfo*> connections;
foreach(MessageRange* range, ranges_)
{
connections.push_back(range->connection_info);
}
return connections;
}
MessageInstance* View::newMessageInstance(ConnectionInfo const* connection_info, IndexEntry const& index, Bag const& bag)
{
return new MessageInstance(connection_info, index, bag);
}
} // namespace rosbag
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/src/buffer.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 <stdlib.h>
#include <assert.h>
#include "rosbag/buffer.h"
//#include <ros/ros.h>
namespace rosbag {
Buffer::Buffer() : buffer_(NULL), capacity_(0), size_(0) { }
Buffer::~Buffer() {
free(buffer_);
}
uint8_t* Buffer::getData() { return buffer_; }
uint32_t Buffer::getCapacity() const { return capacity_; }
uint32_t Buffer::getSize() const { return size_; }
void Buffer::setSize(uint32_t size) {
size_ = size;
ensureCapacity(size);
}
void Buffer::ensureCapacity(uint32_t capacity) {
if (capacity <= capacity_)
return;
if (capacity_ == 0)
capacity_ = capacity;
else {
while (capacity_ < capacity)
capacity_ *= 2;
}
buffer_ = (uint8_t*) realloc(buffer_, capacity_);
assert(buffer_);
}
} // namespace rosbag
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/src/stream.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 "rosbag/stream.h"
#include "rosbag/chunked_file.h"
//#include <ros/ros.h>
using boost::shared_ptr;
namespace rosbag {
// StreamFactory
StreamFactory::StreamFactory(ChunkedFile* file) :
uncompressed_stream_(new UncompressedStream(file)),
bz2_stream_ (new BZ2Stream(file)),
lz4_stream_ (new LZ4Stream(file))
{
}
shared_ptr<Stream> StreamFactory::getStream(CompressionType type) const {
switch (type) {
case compression::Uncompressed: return uncompressed_stream_;
case compression::BZ2: return bz2_stream_;
case compression::LZ4: return lz4_stream_;
default: return shared_ptr<Stream>();
}
}
// Stream
Stream::Stream(ChunkedFile* file) : file_(file) { }
Stream::~Stream() { }
void Stream::startWrite() { }
void Stream::stopWrite() { }
void Stream::startRead() { }
void Stream::stopRead() { }
FILE* Stream::getFilePointer() { return file_->file_; }
uint64_t Stream::getCompressedIn() { return file_->compressed_in_; }
void Stream::setCompressedIn(uint64_t nbytes) { file_->compressed_in_ = nbytes; }
void Stream::advanceOffset(uint64_t nbytes) { file_->offset_ += nbytes; }
char* Stream::getUnused() { return file_->unused_; }
int Stream::getUnusedLength() { return file_->nUnused_; }
void Stream::setUnused(char* unused) { file_->unused_ = unused; }
void Stream::setUnusedLength(int nUnused) { file_->nUnused_ = nUnused; }
void Stream::clearUnused() { file_->clearUnused(); }
} // namespace rosbag
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/src/uncompressed_stream.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 "rosbag/chunked_file.h"
#include <iostream>
#include <cstring>
#include <boost/format.hpp>
using std::string;
using boost::format;
using ros::Exception;
namespace rosbag {
UncompressedStream::UncompressedStream(ChunkedFile* file) : Stream(file) { }
CompressionType UncompressedStream::getCompressionType() const {
return compression::Uncompressed;
}
void UncompressedStream::write(void* ptr, size_t size) {
size_t result = fwrite(ptr, 1, size, getFilePointer());
if (result != size)
throw BagIOException((format("Error writing to file: writing %1% bytes, wrote %2% bytes") % size % result).str());
advanceOffset(size);
}
void UncompressedStream::read(void* ptr, size_t size) {
size_t nUnused = (size_t) getUnusedLength();
char* unused = getUnused();
if (nUnused > 0) {
// We have unused data from the last compressed read
if (nUnused == size) {
// Copy the unused data into the buffer
memcpy(ptr, unused, nUnused);
clearUnused();
}
else if (nUnused < size) {
// Copy the unused data into the buffer
memcpy(ptr, unused, nUnused);
// Still have data to read
size -= nUnused;
// Read the remaining data from the file
int result = fread((char*) ptr + nUnused, 1, size, getFilePointer());
if ((size_t) result != size)
throw BagIOException((format("Error reading from file + unused: wanted %1% bytes, read %2% bytes") % size % result).str());
advanceOffset(size);
clearUnused();
}
else {
// nUnused_ > size
memcpy(ptr, unused, size);
setUnused(unused + size);
setUnusedLength(nUnused - size);
}
}
// No unused data - read from stream
int result = fread(ptr, 1, size, getFilePointer());
if ((size_t) result != size)
throw BagIOException((format("Error reading from file: wanted %1% bytes, read %2% bytes") % size % result).str());
advanceOffset(size);
}
void UncompressedStream::decompress(uint8_t* dest, unsigned int dest_len, uint8_t* source, unsigned int source_len) {
if (dest_len < source_len)
throw BagException("dest_len not large enough");
memcpy(dest, source, source_len);
}
} // namespace rosbag
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage | apollo_public_repos/apollo-platform/ros/ros_comm/rosbag_storage/src/bag_player.cpp | #include "rosbag/bag_player.h"
#define foreach BOOST_FOREACH
namespace rosbag
{
BagPlayer::BagPlayer(const std::string &fname) throw(BagException) {
bag.open(fname, rosbag::bagmode::Read);
ros::Time::init();
View v(bag);
bag_start_ = v.getBeginTime();
bag_end_ = v.getEndTime();
last_message_time_ = ros::Time(0);
playback_speed_ = 1.0;
}
BagPlayer::~BagPlayer() {
bag.close();
}
ros::Time BagPlayer::get_time() {
return last_message_time_;
}
void BagPlayer::set_start(const ros::Time &start) {
bag_start_ = start;
}
void BagPlayer::set_end(const ros::Time &end) {
bag_end_ = end;
}
void BagPlayer::set_playback_speed(double scale) {
if (scale > 0.0)
playback_speed_ = scale;
}
ros::Time BagPlayer::real_time(const ros::Time &msg_time) {
return play_start_ + (msg_time - bag_start_) * (1 / playback_speed_);
}
void BagPlayer::start_play() {
std::vector<std::string> topics;
std::pair<std::string, BagCallback *> cb;
foreach(cb, cbs_)
topics.push_back(cb.first);
View view(bag, TopicQuery(topics), bag_start_, bag_end_);
play_start_ = ros::Time::now();
foreach(MessageInstance const m, view)
{
if (cbs_.find(m.getTopic()) == cbs_.end())
continue;
ros::Time::sleepUntil(real_time(m.getTime()));
last_message_time_ = m.getTime(); /* this is the recorded time */
cbs_[m.getTopic()]->call(m);
}
}
void BagPlayer::unregister_callback(const std::string &topic) {
delete cbs_[topic];
cbs_.erase(topic);
}
}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rostopic/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.3)
project(rostopic)
find_package(catkin REQUIRED)
catkin_package()
catkin_python_setup()
catkin_install_python(PROGRAMS scripts/rostopic
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
if(CATKIN_ENABLE_TESTING)
find_package(rostest)
add_rostest(test/rostopic.test)
#add_rostest(test/rostopic2.test)
catkin_add_nosetests(test/test_rostopic_command_line_offline.py)
endif()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rostopic/package.xml | <package>
<name>rostopic</name>
<version>1.11.21</version>
<description>
rostopic contains the rostopic command-line tool for displaying
debug information about
ROS <a href="http://www.ros.org/wiki/Topics">Topics</a>, including
publishers, subscribers, publishing rate,
and ROS <a href="http://www.ros.org/wiki/Messages">Messages</a>. It also
contains an experimental Python library for getting information about
and interacting with topics dynamically. This library is for
internal-use only as the code API may change, though it does provide
examples of how to implement dynamic subscription and publication
behaviors in ROS.
</description>
<maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer>
<license>BSD</license>
<url>http://ros.org/wiki/rostopic</url>
<author>Ken Conley</author>
<buildtool_depend version_gte="0.5.78">catkin</buildtool_depend>
<build_depend>rostest</build_depend>
<run_depend version_gte="0.5.4">genpy</run_depend>
<run_depend>rosbag</run_depend>
<run_depend>rospy</run_depend>
<export>
<rosdoc config="rosdoc.yaml"/>
</export>
</package>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rostopic/rosdoc.yaml | - builder: epydoc
config: epydoc.config
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rostopic/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=['rostopic'],
package_dir={'': 'src'},
scripts=['scripts/rostopic'],
requires=['genmsg', 'genpy', 'roslib', 'rospkg']
)
setup(**d)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rostopic/.tar | {!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/rostopic/1.11.21-0.tar.gz',
!!python/unicode 'version': ros_comm-release-release-indigo-rostopic-1.11.21-0}
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/rostopic/CHANGELOG.rst | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package rostopic
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
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 "rostopic delay" to measure message delay compared to the input from real world (`#719 <https://github.com/ros/ros_comm/pull/719>`_)
* add option to perform keyword substitution for messages published with "rostopic pub" (`#702 <https://github.com/ros/ros_comm/pull/702>`_)
* add wall-time option for rostopic hz (`#674 <https://github.com/ros/ros_comm/pull/674>`_)
1.11.16 (2015-11-09)
--------------------
1.11.15 (2015-10-13)
--------------------
* add warning to rostopic hz about simulated time (`#672 <https://github.com/ros/ros_comm/pull/672>`_)
1.11.14 (2015-09-19)
--------------------
* support specifying multiple array indices (`#606 <https://github.com/ros/ros_comm/pull/606>`_)
* fix string type check if variable is unicode
1.11.13 (2015-04-28)
--------------------
1.11.12 (2015-04-27)
--------------------
* fix command parsing for rosservice and rostopic to not accept arbitrary substrings of 'list' (`#609 <https://github.com/ros/ros_comm/issues/609>`_)
1.11.11 (2015-04-16)
--------------------
1.11.10 (2014-12-22)
--------------------
* add support for fixed-width floating-point and integer array values (`#400 <https://github.com/ros/ros_comm/issues/400>`_)
1.11.9 (2014-08-18)
-------------------
1.11.8 (2014-08-04)
-------------------
* fix handling of array index when being part of the topic (`#480 <https://github.com/ros/ros_comm/issues/480>`_)
* support splice arguments in 'rostopic echo' (`#480 <https://github.com/ros/ros_comm/issues/480>`_)
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 (`#426 <https://github.com/ros/ros_comm/issues/426>`_, `#427 <https://github.com/ros/ros_comm/issues/427>`_)
1.11.3 (2014-05-21)
-------------------
* add publisher queue_size to rostopic
1.11.2 (2014-05-08)
-------------------
1.11.1 (2014-05-07)
-------------------
* add check for message fields when determining message type (`#376 <https://github.com/ros/ros_comm/issues/376>`_)
1.11.0 (2014-03-04)
-------------------
* make rostest in CMakeLists optional (`ros/rosdistro#3010 <https://github.com/ros/rosdistro/issues/3010>`_)
* 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)
-------------------
* fix wrong time in csv export when using 'rostopic echo -p -b' (`#330 <https://github.com/ros/ros_comm/issues/330>`_)
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)
-------------------
* fix access to array fields by index (regression of `#242 <https://github.com/ros/ros_comm/issues/242>`_ in 1.9.47)
1.9.47 (2013-07-03)
-------------------
* fix 'rostopic echo' for submessages of type uint8[] (`#242 <https://github.com/ros/ros_comm/issues/242>`_)
* 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)
-------------------
1.9.43 (2013-03-13)
-------------------
1.9.42 (2013-03-08)
-------------------
* fix missing run_depend on rosbag (`#179 <https://github.com/ros/ros_comm/issues/179>`_)
1.9.41 (2013-01-24)
-------------------
1.9.40 (2013-01-13)
-------------------
* add support for boolean in 'rostopic -p' (`#3948 <https://code.ros.org/trac/ros/ticket/3948>`_)
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/rostopic/epydoc.config | [epydoc]
name: rostopic
modules: rostopic
inheritance: included
url: http://ros.org/wiki/rostopic
frames: no
private: no
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rostopic | apollo_public_repos/apollo-platform/ros/ros_comm/rostopic/test/test_rostopic.py | #!/usr/bin/env python
# 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.
import os
import sys
import unittest
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
import time
import rostest
import rospy
import std_msgs.msg
from subprocess import Popen, PIPE, check_call, call
from contextlib import contextmanager
@contextmanager
def fakestdout():
realstdout = sys.stdout
fakestdout = StringIO()
sys.stdout = fakestdout
yield fakestdout
sys.stdout = realstdout
def todict(s):
d = {}
for l in s.split('\n'):
key, p, val = l.partition(':')
if p:
d[key] = val.strip()
return d
class TestRostopic(unittest.TestCase):
def __init__(self, *args):
unittest.TestCase.__init__(self, *args)
self.vals = set()
# wait for network to initialize
rospy.init_node('test')
topics = ['/chatter', '/foo/chatter', '/bar/chatter']
subs = [rospy.Subscriber(t, std_msgs.msg.String, self.callback, i) for i, t in enumerate(topics)]
all = set(range(0, len(topics)))
timeout_t = time.time() + 10.
while time.time() < timeout_t and self.vals != all and not rospy.is_shutdown():
time.sleep(0.1)
[s.unregister() for s in subs]
if rospy.is_shutdown():
self.fail("shutdown")
def test_offline(self):
import rostopic
orig_uri = os.environ['ROS_MASTER_URI']
os.environ['ROS_MASTER_URI'] = 'http://fake_host:12356'
try:
c = 'rostopic'
try:
rostopic._rostopic_cmd_list([c, 'list'])
self.fail("should have raised ROSTopicIOException")
except rostopic.ROSTopicIOException: pass
try:
rostopic._rostopic_cmd_info([c, 'info', '/chatter'])
self.fail("should have raised ROSTopicIOException")
except rostopic.ROSTopicIOException: pass
try:
rostopic._rostopic_cmd_type([c, 'type', '/chatter'])
self.fail("should have raised ROSTopicIOException")
except rostopic.ROSTopicIOException: pass
try:
rostopic._rostopic_cmd_find([c, 'find', 'std_msgs/String'])
self.fail("should have raised ROSTopicIOException")
except rostopic.ROSTopicIOException: pass
finally:
os.environ['ROS_MASTER_URI'] = orig_uri
def test_cmd_type(self):
import rostopic
cmd = 'rostopic'
s = '/rosout_agg'
t = 'rosgraph_msgs/Log'
try:
rostopic.rostopicmain([cmd, 'type', 'fake'])
self.fail("should have exited")
except SystemExit as e:
self.assertNotEquals(0, e.code)
for s in ['/chatter', 'chatter', 'foo/chatter', '/bar/chatter']:
with fakestdout() as b:
rostopic.rostopicmain([cmd, 'type', s])
v = b.getvalue().strip()
self.assertEquals('std_msgs/String', v)
def test_main(self):
import rostopic
c = 'rostopic'
try:
rostopic.rostopicmain([c])
self.fail("should have exited with error")
except SystemExit as e:
self.assertNotEquals(0, e.code)
try:
rostopic.rostopicmain([c, 'foo'])
self.fail("should have exited with error")
except SystemExit as e:
self.assertNotEquals(0, e.code)
def test_cmd_pub(self):
import rostopic
cmd = 'rostopic'
# we can't actually test functional behavior because rostopic
# needs control over a node, though we can probably change the
# source code to just check for the existing node.
invalid = [['-r', '--once', '/foo', 'std_msgs/String', 'hello'],
['-r', 'a', '/foo', 'std_msgs/String', 'hello'],
['-r', '--', '-1', '/foo', 'std_msgs/String', 'hello'],
[],
['/foo'],
['/foo', 'std_msgs/String', 'a: b: !!c: d: e'],
]
for i in invalid:
try:
rostopic.rostopicmain([cmd, 'pub'] + i)
self.fail("should have exited with error"+str(i))
except SystemExit as e:
self.assert_(e.code != 0)
def test_full_usage(self):
import rostopic
try:
rostopic._fullusage()
self.fail("should have caused system exit")
except SystemExit: pass
def test_get_topic_type(self):
import rostopic
self.assertEquals((None, None, None), rostopic.get_topic_type('/fake', blocking=False))
t, n, f = rostopic.get_topic_type('/rosout', blocking=False)
self.assertEquals('rosgraph_msgs/Log', t)
self.assertEquals('/rosout', n)
self.assert_(f is None)
t, n, f = rostopic.get_topic_type('/rosout/name', blocking=False)
self.assertEquals('rosgraph_msgs/Log', t)
self.assertEquals('/rosout', n)
self.failIf(f is None)
from rosgraph_msgs.msg import Log
self.assertEquals("bob", f(Log(name="bob")))
def test_get_topic_class(self):
import rostopic
self.assertEquals((None, None, None), rostopic.get_topic_class('/fake'))
from rosgraph_msgs.msg import Log
c, n, f = rostopic.get_topic_class('/rosout')
self.assertEquals(Log, c)
self.assertEquals('/rosout', n)
self.assert_(f is None)
c, n, f = rostopic.get_topic_class('/rosout/name')
self.assertEquals(c, Log)
self.assertEquals('/rosout', n)
self.failIf(f is None)
self.assertEquals("bob", f(Log(name="bob")))
def test_cmd_info(self):
import rostopic
cmd = 'rostopic'
try:
rostopic.rostopicmain([cmd, 'info'])
self.fail("should have exited with error")
except SystemExit: pass
try:
rostopic.rostopicmain([cmd, 'info', '/fake_topic'])
self.fail("should have exited with error")
except SystemExit: pass
try:
rostopic.rostopicmain([cmd, 'info', '/chatter', '/bar/chatter'])
self.fail("should have exited with error")
except SystemExit: pass
with fakestdout() as b:
rostopic.rostopicmain([cmd, 'info', 'rosout'])
v = b.getvalue()
for s in ["Publishers:", "Subscribers", "Type: rosgraph_msgs/Log", " * /rosout"]:
self.assert_(s in v, "failed on %s: %s"%(s, v))
with fakestdout() as b:
rostopic.rostopicmain([cmd, 'info', '/chatter'])
v = b.getvalue()
for s in ["Publishers:", "Subscribers", "Type: std_msgs/String", " * /talker"]:
self.assert_(s in v, "failed on %s: %s"%(s, v))
def test_cmd_find(self):
import rostopic
cmd = 'rostopic'
try:
rostopic.rostopicmain([cmd, 'find'])
self.fail("arg parsing should have failed")
except SystemExit: pass
try:
rostopic.rostopicmain([cmd, 'find', 'std_msgs/String', 'std_msgs/Int32'])
self.fail("arg parsing should have failed")
except SystemExit: pass
with fakestdout() as b:
rostopic.rostopicmain([cmd, 'find', 'std_msgs/String'])
d = [x for x in b.getvalue().split('\n') if x.strip()]
v = ['/foo/chatter', '/bar/chatter', '/chatter']
self.assertEquals(set(v), set(d))
def callback(self, msg, val):
self.vals.add(val)
def test_cmd_list(self):
import rostopic
cmd = 'rostopic'
s = '/add_two_ints'
# test failures
for invalid in [['-ps'], ['-b' 'file.bag', '-s'], ['-b' 'file.bag', '-p']]:
try:
rostopic.rostopicmain([cmd, 'list'] + invalid)
self.fail("should have failed")
except SystemExit: pass
# test main entry
rostopic.rostopicmain([cmd, 'list'])
# test directly
topics = ['/chatter', '/foo/chatter', '/bar/chatter', '/rosout', '/rosout_agg']
with fakestdout() as b:
rostopic.rostopicmain([cmd, 'list'])
v = [x.strip() for x in b.getvalue().split('\n') if x.strip()]
self.failIf(set(topics)-set(v))
# publishers-only
topics = ['/chatter', '/foo/chatter', '/bar/chatter', '/rosout', '/rosout_agg']
with fakestdout() as b:
rostopic.rostopicmain([cmd, 'list', '-p'])
v = [x.strip() for x in b.getvalue().split('\n') if x.strip()]
self.failIf(set(topics)-set(v))
self.failIf('/clock' in v)
# subscribers-only
topics = ['/rosout']
with fakestdout() as b:
rostopic.rostopicmain([cmd, 'list', '-s'])
v = [x.strip() for x in b.getvalue().split('\n') if x.strip()]
self.failIf(set(topics)-set(v), "%s vs. %s"%(topics, v))
self.failIf('/chatter' in v)
# turn on verbosity, not checking output as it's not as stable
with fakestdout() as b:
rostopic.rostopicmain([cmd, 'list', '-v'])
v = b.getvalue()
self.assert_("Published topics:" in v)
self.assert_("Subscribed topics:" in v)
with fakestdout() as b:
rostopic.rostopicmain([cmd, 'list', '-vs'])
v = b.getvalue()
self.failIf("Published topics:" in v)
self.assert_("Subscribed topics:" in v)
with fakestdout() as b:
rostopic.rostopicmain([cmd, 'list', '-vp'])
v = b.getvalue()
self.assert_("Published topics:" in v)
self.failIf("Subscribed topics:" in v)
# test with multiple topic names
try:
rostopic.rostopicmain([cmd, 'list', 'rosout', 'rosout_agg'])
self.fail("should have caused parser error")
except SystemExit:
pass
# test with resolved names
for n in topics:
with fakestdout() as b:
rostopic.rostopicmain([cmd, 'list', n])
self.assertEquals(n, b.getvalue().strip())
# test with relative names
with fakestdout() as b:
rostopic.rostopicmain([cmd, 'list', 'rosout'])
self.assertEquals('/rosout', b.getvalue().strip())
# test with namespaces
with fakestdout() as b:
rostopic.rostopicmain([cmd, 'list', '/foo'])
self.assertEquals('/foo/chatter', b.getvalue().strip())
with fakestdout() as b:
rostopic.rostopicmain([cmd, 'list', 'bar'])
self.assertEquals('/bar/chatter', b.getvalue().strip())
NAME = 'test_rostopic'
if __name__ == '__main__':
rostest.unitrun('test_rostopic', NAME, TestRostopic, sys.argv, coverage_packages=['rostopic'])
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rostopic | apollo_public_repos/apollo-platform/ros/ros_comm/rostopic/test/test_rostopic_command_line_offline.py | #!/usr/bin/env python
# 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.
import os
import sys
import unittest
import time
from subprocess import Popen, PIPE, check_call, call
class TestRostopicOffline(unittest.TestCase):
def setUp(self):
pass
## test that the rosmsg command works
def test_cmd_help(self):
cmd = 'rostopic'
sub = ['bw', 'echo', 'hz', 'delay', 'info', 'list', 'pub', 'type','find']
output = Popen([cmd], stdout=PIPE).communicate()[0]
self.assert_('Commands' in output)
output = Popen([cmd, '-h'], stdout=PIPE).communicate()[0]
self.assert_('Commands' in output)
# make sure all the commands are in the usage
for c in sub:
cmd_sub = "%s %s"%(cmd, c)
self.assert_(cmd_sub in output, "'%s' is not in help: \n%s"%(cmd_sub, output))
for c in sub:
output = Popen([cmd, c, '-h'], stdout=PIPE, stderr=PIPE).communicate()
self.assert_("usage:" in output[0].lower(), output)
# make sure usage refers to the command
self.assert_("%s %s"%(cmd, c) in output[0], output)
# test no args on commands that require args
for c in ['bw', 'echo', 'hz', 'delay', 'info', 'pub', 'type', 'find']:
output = Popen([cmd, c], stdout=PIPE, stderr=PIPE).communicate()
self.assert_("usage:" in output[0].lower() or "usage:" in output[1].lower(), output)
# make sure usage refers to the command
self.assert_("%s %s"%(cmd, c) in output[1], output)
def test_offline(self):
cmd = 'rostopic'
# point at a different 'master'
env = os.environ.copy()
env['ROS_MASTER_URI'] = 'http://localhost:11312'
kwds = { 'env': env, 'stdout': PIPE, 'stderr': PIPE}
msg = "ERROR: Unable to communicate with master!\n"
output = Popen([cmd, 'bw', 'chatter'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
output = Popen([cmd, 'echo', 'chatter'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
output = Popen([cmd, 'hz', 'chatter'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
output = Popen([cmd, 'delay', 'chatter'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
output = Popen([cmd, 'list'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
output = Popen([cmd, 'pub', 'chatter', 'std_msgs/String', 'hello'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
output = Popen([cmd, 'type', 'chatter'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
output = Popen([cmd, 'type', 'std_msgs/String'], **kwds).communicate()
self.assert_(output[1].endswith(msg))
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rostopic | apollo_public_repos/apollo-platform/ros/ros_comm/rostopic/test/rostopic2.test | <launch>
<node name="talker" pkg="rospy" type="talker.py" />
<group ns="foo">
<node name="talker" pkg="rospy" type="talker.py" />
</group>
<group ns="bar">
<node name="talker" pkg="rospy" type="talker.py" />
</group>
<test test-name="rostopic_unit" pkg="rostopic" type="test_rostopic.py" />
</launch>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rostopic | apollo_public_repos/apollo-platform/ros/ros_comm/rostopic/test/rostopic.test | <launch>
<node name="talker" pkg="rospy" type="talker.py" />
<group ns="foo">
<node name="talker" pkg="rospy" type="talker.py" />
</group>
<group ns="bar">
<node name="talker" pkg="rospy" type="talker.py" />
</group>
<test test-name="rostopic_command_line_online" pkg="rostopic" type="check_rostopic_command_line_online.py" />
</launch>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rostopic | apollo_public_repos/apollo-platform/ros/ros_comm/rostopic/test/check_rostopic_command_line_online.py | #!/usr/bin/env python
# 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.
import os
import signal
import sys
import time
import unittest
import rospy
import rostest
import std_msgs.msg
from subprocess import Popen, PIPE, check_call, call
def run_for(cmd, secs):
popen = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True)
timeout_t = time.time() + secs
while time.time() < timeout_t:
time.sleep(0.1)
os.kill(popen.pid, signal.SIGKILL)
class TestRostopicOnline(unittest.TestCase):
def setUp(self):
self.vals = set()
self.msgs = {}
def callback(self, msg, val):
self.vals.add(val)
self.msgs[val] = msg
def test_rostopic(self):
topics = ['/chatter', '/foo/chatter', '/bar/chatter']
# wait for network to initialize
rospy.init_node('test')
for i, t in enumerate(topics):
rospy.Subscriber(t, std_msgs.msg.String, self.callback, i)
all = set(range(0, len(topics)))
timeout_t = time.time() + 10.
while time.time() < timeout_t and self.vals != all:
time.sleep(0.1)
# network is initialized
cmd = 'rostopic'
names = ['/chatter', 'foo/chatter']
# list
# - we aren't matching against the core services as those can make the test suites brittle
output = Popen([cmd, 'list'], stdout=PIPE).communicate()[0]
output = output.decode()
l = set(output.split())
for t in topics:
self.assert_(t in l)
for name in names:
# type
output = Popen([cmd, 'type', name], stdout=PIPE).communicate()[0]
output = output.decode()
self.assertEquals('std_msgs/String', output.strip())
# find
output = Popen([cmd, 'find', 'std_msgs/String'], stdout=PIPE).communicate()[0]
output = output.decode()
values = [n.strip() for n in output.split('\n') if n.strip()]
self.assertEquals(set(values), set(topics))
#echo
# test with -c option to get command to terminate
count = 3
output = Popen([cmd, 'echo', name, '-n', str(count)], stdout=PIPE).communicate()[0]
output = output.decode()
values = [n.strip() for n in output.split('\n') if n.strip()]
values = [n for n in values if n != '---']
self.assertEquals(count, len(values), "wrong number of echos in output:\n"+str(values))
for n in values:
self.assert_('data: hello world ' in n, n)
if 0:
#bw
stdout, stderr = run_for([cmd, 'bw', name], 3.)
self.assert_('average:' in stdout, "OUTPUT: %s\n%s"%(stdout,stderr))
# hz
stdout, stderr = run_for([cmd, 'hz', name], 2.)
self.assert_('average rate:' in stdout)
# delay
stdout, stderr = run_for([cmd, 'delay', name], 2.)
self.assert_('average rate:' in stdout)
# pub
# - pub wait until ctrl-C, so we have to wait then kill it
if 1:
s = 'hello'
t = '/pub/chatter'
key = len(topics)
rospy.Subscriber(t, std_msgs.msg.String, self.callback, key)
#TODO: correct popen call
args = [cmd, 'pub', t, 'std_msgs/String', s]
popen = Popen(args, stdout=PIPE, stderr=PIPE, close_fds=True)
# - give rostopic pub 5 seconds to send us a message
all = set(range(0, key+1))
timeout_t = time.time() + 5.
while time.time() < timeout_t and self.vals != all:
time.sleep(0.1)
# - check published value
msg = self.msgs[key]
self.assertEquals(s, msg.data)
os.kill(popen.pid, signal.SIGKILL)
# test with dictionary
t = '/pub2/chatter'
key = len(topics)+1
rospy.Subscriber(t, std_msgs.msg.String, self.callback, key)
args = [cmd, 'pub', t, 'std_msgs/String', "{data: %s}"%s]
popen = Popen(args, stdout=PIPE, stderr=PIPE, close_fds=True)
# - give rostopic pub 5 seconds to send us a message
all = set(range(0, key+2))
timeout_t = time.time() + 5.
while time.time() < timeout_t and self.vals != all:
time.sleep(0.1)
# - check published value
try:
msg = self.msgs[key]
except KeyError:
self.fail("no message received on "+str(key))
self.assertEquals(s, msg.data)
os.kill(popen.pid, signal.SIGKILL)
PKG = 'test_rostopic'
NAME = 'test_rostopic_command_line_online'
if __name__ == '__main__':
rostest.run(PKG, NAME, TestRostopicOnline, sys.argv)
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rostopic | apollo_public_repos/apollo-platform/ros/ros_comm/rostopic/scripts/rostopic | #!/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 rostopic
rostopic.rostopicmain()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm/rostopic/src | apollo_public_repos/apollo-platform/ros/ros_comm/rostopic/src/rostopic/__init__.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.
#
# Revision $Id$
# make sure we aren't using floor division
from __future__ import division, print_function
NAME='rostopic'
import os
import sys
import math
import socket
import time
import traceback
import yaml
import google.protobuf.message
try:
from xmlrpc.client import Fault
except ImportError:
from xmlrpclib import Fault
from operator import itemgetter
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
import genpy
import roslib.message
import rosgraph
#TODO: lazy-import rospy or move rospy-dependent routines to separate location
import rospy
class ROSTopicException(Exception):
"""
Base exception class of rostopic-related errors
"""
pass
class ROSTopicIOException(ROSTopicException):
"""
rostopic errors related to network I/O failures
"""
pass
def _check_master():
"""
Make sure that master is available
:raises: :exc:`ROSTopicException` If unable to successfully communicate with master
"""
try:
rosgraph.Master('/rostopic').getPid()
except socket.error:
raise ROSTopicIOException("Unable to communicate with master!")
def _master_get_topic_types(master):
try:
val = master.getTopicTypes()
except Fault:
#TODO: remove, this is for 1.1
sys.stderr.write("WARNING: rostopic is being used against an older version of ROS/roscore\n")
val = master.getPublishedTopics('/')
return val
class ROSTopicHz(object):
"""
ROSTopicHz receives messages for a topic and computes frequency stats
"""
def __init__(self, window_size, filter_expr=None, use_wtime=False):
import threading
self.lock = threading.Lock()
self.last_printed_tn = 0
self.msg_t0 = -1.
self.msg_tn = 0
self.times =[]
self.filter_expr = filter_expr
self.use_wtime = use_wtime
# can't have infinite window size due to memory restrictions
if window_size < 0:
window_size = 50000
self.window_size = window_size
def callback_hz(self, m):
"""
ros sub callback
:param m: Message instance
"""
# #694: ignore messages that don't match filter
if self.filter_expr is not None and not self.filter_expr(m):
return
with self.lock:
curr_rostime = rospy.get_rostime() if not self.use_wtime else \
rospy.Time.from_sec(time.time())
# time reset
if curr_rostime.is_zero():
if len(self.times) > 0:
print("time has reset, resetting counters")
self.times = []
return
curr = curr_rostime.to_sec() if not self.use_wtime else \
rospy.Time.from_sec(time.time()).to_sec()
if self.msg_t0 < 0 or self.msg_t0 > curr:
self.msg_t0 = curr
self.msg_tn = curr
self.times = []
else:
self.times.append(curr - self.msg_tn)
self.msg_tn = curr
#only keep statistics for the last 10000 messages so as not to run out of memory
if len(self.times) > self.window_size - 1:
self.times.pop(0)
def print_hz(self):
"""
print the average publishing rate to screen
"""
if not self.times:
return
elif self.msg_tn == self.last_printed_tn:
print("no new messages")
return
with self.lock:
#frequency
# kwc: In the past, the rate decayed when a publisher
# dies. Now, we use the last received message to perform
# the calculation. This change was made because we now
# report a count and keep track of last_printed_tn. This
# makes it easier for users to see when a publisher dies,
# so the decay is no longer necessary.
n = len(self.times)
#rate = (n - 1) / (rospy.get_time() - self.msg_t0)
mean = sum(self.times) / n
rate = 1./mean if mean > 0. else 0
#std dev
std_dev = math.sqrt(sum((x - mean)**2 for x in self.times) /n)
# min and max
max_delta = max(self.times)
min_delta = min(self.times)
self.last_printed_tn = self.msg_tn
print("average rate: %.3f\n\tmin: %.3fs max: %.3fs std dev: %.5fs window: %s"%(rate, min_delta, max_delta, std_dev, n+1))
def _sleep(duration):
rospy.rostime.wallsleep(duration)
def _rostopic_hz(topic, window_size=-1, filter_expr=None, use_wtime=False):
"""
Periodically print the publishing rate of a topic to console until
shutdown
:param topic: topic name, ``str``
:param window_size: number of messages to average over, -1 for infinite, ``int``
:param filter_expr: Python filter expression that is called with m, the message instance
"""
msg_class, real_topic, _ = get_topic_class(topic, blocking=True) #pause hz until topic is published
if rospy.is_shutdown():
return
rospy.init_node(NAME, anonymous=True)
rt = ROSTopicHz(window_size, filter_expr=filter_expr, use_wtime=use_wtime)
# we use a large buffer size as we don't know what sort of messages we're dealing with.
# may parameterize this in the future
if filter_expr is not None:
# have to subscribe with topic_type
sub = rospy.Subscriber(real_topic, msg_class, rt.callback_hz)
else:
sub = rospy.Subscriber(real_topic, rospy.AnyMsg, rt.callback_hz)
print("subscribed to [%s]"%real_topic)
if rospy.get_param('use_sim_time', False):
print("WARNING: may be using simulated time",file=sys.stderr)
while not rospy.is_shutdown():
_sleep(1.0)
rt.print_hz()
class ROSTopicDelay(object):
def __init__(self, window_size):
import threading
self.lock = threading.Lock()
self.last_msg_tn = 0
self.msg_t0 = -1.
self.msg_tn = 0
self.delays = []
# can't have infinite window size due to memory restrictions
if window_size < 0:
window_size = 50000
self.window_size = window_size
def callback_delay(self, msg):
if not msg._has_header:
rospy.logerr('msg does not have header')
return
with self.lock:
curr_rostime = rospy.get_rostime()
# time reset
if curr_rostime.is_zero():
if len(self.delays) > 0:
print("time has reset, resetting counters")
self.delays = []
return
curr = curr_rostime.to_sec()
if self.msg_t0 < 0 or self.msg_t0 > curr:
self.msg_t0 = curr
self.msg_tn = curr
self.delays = []
else:
self.delays.append(curr_rostime.to_time() -
msg.header.stamp.to_time())
self.msg_tn = curr
if len(self.delays) > self.window_size - 1:
self.delays.pop(0)
def get_delay(self):
if self.msg_tn == self.last_msg_tn:
return
with self.lock:
if not self.delays:
return
n = len(self.delays)
mean = sum(self.delays) / n
rate = 1. / mean if mean > 0 else 0
std_dev = math.sqrt(sum((x - mean)**2 for x in self.delays) / n)
max_delta = max(self.delays)
min_delta = min(self.delays)
self.last_msg_tn = self.msg_tn
return mean, min_delta, max_delta, std_dev, n + 1
def print_delay(self):
"""
print the average publishing delay to screen
"""
if not self.delays:
return
ret = self.get_delay()
if ret is None:
print("no new messages")
return
delay, min_delta, max_delta, std_dev, window = ret
print("average delay: %.3f\n\tmin: %.3fs max: %.3fs std dev: %.5fs window: %s"%(delay, min_delta, max_delta, std_dev, window))
def _rostopic_delay(topic, window_size=-1):
"""
Periodically print the publishing delay of a topic to console until
shutdown
:param topic: topic name, ``str``
:param window_size: number of messages to average over, -1 for infinite, ``int``
"""
# pause hz until topic is published
msg_class, real_topic, _ = get_topic_class(topic, blocking=True)
if issubclass(msg_class, google.protobuf.message.Message):
print("Protobuf message has no header, not support sub-command 'delay'")
return
if rospy.is_shutdown():
return
rospy.init_node(NAME, anonymous=True)
rt = ROSTopicDelay(window_size)
sub = rospy.Subscriber(real_topic, msg_class, rt.callback_delay)
print("subscribed to [%s]" % real_topic)
if rospy.get_param('use_sim_time', False):
print("WARNING: may be using simulated time",file=sys.stderr)
while not rospy.is_shutdown():
_sleep(1.0)
rt.print_delay()
class ROSTopicBandwidth(object):
def __init__(self, window_size=100):
import threading
self.lock = threading.Lock()
self.last_printed_tn = 0
self.sizes =[]
self.times =[]
self.window_size = window_size or 100
def callback(self, data):
"""ros sub callback"""
with self.lock:
try:
t = time.time()
self.times.append(t)
self.sizes.append(len(data._buff)) #AnyMsg instance
assert(len(self.times) == len(self.sizes))
if len(self.times) > self.window_size:
self.times.pop(0)
self.sizes.pop(0)
except:
traceback.print_exc()
def print_bw(self):
"""print the average publishing rate to screen"""
if len(self.times) < 2:
return
with self.lock:
n = len(self.times)
tn = time.time()
t0 = self.times[0]
total = sum(self.sizes)
bytes_per_s = total / (tn - t0)
mean = total / n
#std_dev = math.sqrt(sum((x - mean)**2 for x in self.sizes) /n)
# min and max
max_s = max(self.sizes)
min_s = min(self.sizes)
#min/max and even mean are likely to be much smaller, but for now I prefer unit consistency
if bytes_per_s < 1000:
bw, mean, min_s, max_s = ["%.2fB"%v for v in [bytes_per_s, mean, min_s, max_s]]
elif bytes_per_s < 1000000:
bw, mean, min_s, max_s = ["%.2fKB"%(v/1000) for v in [bytes_per_s, mean, min_s, max_s]]
else:
bw, mean, min_s, max_s = ["%.2fMB"%(v/1000000) for v in [bytes_per_s, mean, min_s, max_s]]
print("average: %s/s\n\tmean: %s min: %s max: %s window: %s"%(bw, mean, min_s, max_s, n))
def _isstring_type(t):
valid_types = [str]
try:
valid_types.append(unicode)
except NameError:
pass
return t in valid_types
def _rostopic_bw(topic, window_size=-1):
"""
periodically print the received bandwidth of a topic to console until
shutdown
"""
_check_master()
_, real_topic, _ = get_topic_type(topic, blocking=True) #pause hz until topic is published
if rospy.is_shutdown():
return
# #3543 disable all auto-subscriptions to /clock
rospy.init_node(NAME, anonymous=True, disable_rostime=True)
rt = ROSTopicBandwidth(window_size)
# we use a large buffer size as we don't know what sort of messages we're dealing with.
# may parameterize this in the future
sub = rospy.Subscriber(real_topic, rospy.AnyMsg, rt.callback)
print("subscribed to [%s]"%real_topic)
while not rospy.is_shutdown():
_sleep(1.0)
rt.print_bw()
# code adapted from rqt_plot
def msgevalgen(pattern):
"""
Generates a function that returns the relevant field(s) (aka 'subtopic(s)') of a Message object
:param pattern: subtopic, e.g. /x[2:]/y[:-1]/z, ``str``
:returns: function that converts a message into the desired value, ``fn(Message) -> value``
"""
evals = [] # list of (field_name, slice_object) pairs
fields = [f for f in pattern.split('/') if f]
for f in fields:
if '[' in f:
field_name, rest = f.split('[', 1)
if not rest.endswith(']'):
print("missing closing ']' in slice spec '%s'" % f, file=sys.stderr)
return None
rest = rest[:-1] # slice content, removing closing bracket
try:
array_index_or_slice_object = _get_array_index_or_slice_object(rest)
except AssertionError as e:
print("field '%s' has invalid slice argument '%s': %s"
% (field_name, rest, str(e)), file=sys.stderr)
return None
evals.append((field_name, array_index_or_slice_object))
else:
evals.append((f, None))
def msgeval(msg, evals):
for i, (field_name, slice_object) in enumerate(evals):
try: # access field first
msg = getattr(msg, field_name)
except AttributeError:
print("no field named %s in %s" % (field_name, pattern), file=sys.stderr)
return None
if slice_object is not None: # access slice
try:
msg = msg.__getitem__(slice_object)
except IndexError as e:
print("%s: %s" % (str(e), pattern), file=sys.stderr)
return None
# if a list is returned here (i.e. not only a single element accessed),
# we need to recursively call msg_eval() with the rest of evals
# in order to handle nested slices
if isinstance(msg, list):
rest = evals[i + 1:]
return [msgeval(m, rest) for m in msg]
return msg
return (lambda msg: msgeval(msg, evals)) if evals else None
def _get_array_index_or_slice_object(index_string):
assert index_string != '', 'empty array index'
index_string_parts = index_string.split(':')
if len(index_string_parts) == 1:
try:
array_index = int(index_string_parts[0])
except ValueError:
assert False, "non-integer array index step '%s'" % index_string_parts[0]
return array_index
slice_args = [None, None, None]
if index_string_parts[0] != '':
try:
slice_args[0] = int(index_string_parts[0])
except ValueError:
assert False, "non-integer slice start '%s'" % index_string_parts[0]
if index_string_parts[1] != '':
try:
slice_args[1] = int(index_string_parts[1])
except ValueError:
assert False, "non-integer slice stop '%s'" % index_string_parts[1]
if len(index_string_parts) > 2 and index_string_parts[2] != '':
try:
slice_args[2] = int(index_string_parts[2])
except ValueError:
assert False, "non-integer slice step '%s'" % index_string_parts[2]
if len(index_string_parts) > 3:
assert False, 'too many slice arguments'
return slice(*slice_args)
def _get_nested_attribute(msg, nested_attributes):
value = msg
for attr in nested_attributes.split('/'):
value = getattr(value, attr)
return value
def _get_topic_type(topic):
"""
subroutine for getting the topic type
:returns: topic type, real topic name and fn to evaluate the message instance
if the topic points to a field within a topic, e.g. /rosout/msg, ``(str, str, fn)``
"""
try:
val = _master_get_topic_types(rosgraph.Master('/rostopic'))
except socket.error:
raise ROSTopicIOException("Unable to communicate with master!")
# exact match first, followed by prefix match
matches = [(t, t_type) for t, t_type in val if t == topic]
if not matches:
matches = [(t, t_type) for t, t_type in val if topic.startswith(t+'/')]
# choose longest match
matches.sort(key=itemgetter(0), reverse=True)
# try to ignore messages which don't have the field specified as part of the topic name
while matches:
t, t_type = matches[0]
msg_class = roslib.message.get_message_class(t_type)
if not msg_class:
# if any class is not fetchable skip ignoring any message types
break
msg = msg_class()
nested_attributes = topic[len(t) + 1:].rstrip('/')
nested_attributes = nested_attributes.split('[')[0]
if nested_attributes == '':
break
try:
_get_nested_attribute(msg, nested_attributes)
except AttributeError:
# ignore this type since it does not have the requested field
matches.pop(0)
continue
matches = [(t, t_type)]
break
if matches:
t, t_type = matches[0]
if t_type == rosgraph.names.ANYTYPE:
return None, None, None
return t_type, t, msgevalgen(topic[len(t):])
else:
return None, None, None
# NOTE: this is used externally by rxplot
def get_topic_type(topic, blocking=False):
"""
Get the topic type.
:param topic: topic name, ``str``
:param blocking: (default False) block until topic becomes available, ``bool``
:returns: topic type, real topic name and fn to evaluate the message instance
if the topic points to a field within a topic, e.g. /rosout/msg. fn is None otherwise. ``(str, str, fn)``
:raises: :exc:`ROSTopicException` If master cannot be contacted
"""
topic_type, real_topic, msg_eval = _get_topic_type(topic)
if topic_type:
return topic_type, real_topic, msg_eval
elif blocking:
sys.stderr.write("WARNING: topic [%s] does not appear to be published yet\n"%topic)
while not rospy.is_shutdown():
topic_type, real_topic, msg_eval = _get_topic_type(topic)
if topic_type:
return topic_type, real_topic, msg_eval
else:
_sleep(0.1)
return None, None, None
def get_topic_class(topic, blocking=False):
"""
Get the topic message class
:returns: message class for topic, real topic
name, and function for evaluating message objects into the subtopic
(or ``None``). ``(Message, str, str)``
:raises: :exc:`ROSTopicException` If topic type cannot be determined or loaded
"""
topic_type, real_topic, msg_eval = get_topic_type(topic, blocking=blocking)
if topic_type is None:
return None, None, None
msg_class = roslib.message.get_message_class(topic_type)
if not msg_class:
raise ROSTopicException("Cannot load message class for [%s]. Are your messages built?" % topic_type)
return msg_class, real_topic, msg_eval
def _str_plot_fields(val, f, field_filter):
"""
get CSV representation of fields used by _str_plot
:returns: list of fields as a CSV string, ``str``
"""
s = _sub_str_plot_fields(val, f, field_filter)
if s is not None:
return "time,"+s
else:
return 'time,'
def _sub_str_plot_fields(val, f, field_filter):
"""recursive helper function for _str_plot_fields"""
# CSV
type_ = type(val)
if type_ in (bool, int, float) or \
isinstance(val, genpy.TVal):
return f
# duck-type check for messages
elif hasattr(val, "_slot_types"):
if field_filter is not None:
fields = list(field_filter(val))
else:
fields = val.__slots__
sub = (_sub_str_plot_fields(_convert_getattr(val, a, t), f+"."+a, field_filter) for a,t in zip(val.__slots__, val._slot_types) if a in fields)
sub = [s for s in sub if s is not None]
if sub:
return ','.join([s for s in sub])
elif _isstring_type(type_):
return f
elif type_ in (list, tuple):
if len(val) == 0:
return None
val0 = val[0]
type0 = type(val0)
# no arrays of arrays
if type0 in (bool, int, float) or \
isinstance(val0, genpy.TVal):
return ','.join(["%s%s"%(f,x) for x in range(0,len(val))])
elif _isstring_type(type0):
return ','.join(["%s%s"%(f,x) for x in range(0,len(val))])
elif hasattr(val0, "_slot_types"):
labels = ["%s%s"%(f,x) for x in range(0,len(val))]
sub = [s for s in [_sub_str_plot_fields(v, sf, field_filter) for v,sf in zip(val, labels)] if s]
if sub:
return ','.join([s for s in sub])
return None
def _str_plot(val, time_offset=None, current_time=None, field_filter=None, type_information=None, fixed_numeric_width=None):
"""
Convert value to matlab/octave-friendly CSV string representation.
:param val: message
:param current_time: current :class:`genpy.Time` to use if message does not contain its own timestamp.
:param time_offset: (optional) for time printed for message, print as offset against this :class:`genpy.Time`
:param field_filter: filter the fields that are strified for Messages, ``fn(Message)->iter(str)``
:returns: comma-separated list of field values in val, ``str``
"""
s = _sub_str_plot(val, time_offset, field_filter)
if s is None:
s = ''
if time_offset is not None:
time_offset = time_offset.to_nsec()
else:
time_offset = 0
if current_time is not None:
return "%s,%s"%(current_time.to_nsec()-time_offset, s)
elif getattr(val, "_has_header", False):
return "%s,%s"%(val.header.stamp.to_nsec()-time_offset, s)
else:
return "%s,%s"%(rospy.get_rostime().to_nsec()-time_offset, s)
def _sub_str_plot(val, time_offset, field_filter):
"""Helper routine for _str_plot."""
# CSV
type_ = type(val)
if type_ == bool:
return '1' if val else '0'
elif type_ in (int, float) or \
isinstance(val, genpy.TVal):
if time_offset is not None and isinstance(val, genpy.Time):
return str(val-time_offset)
else:
return str(val)
elif hasattr(val, "_slot_types"):
if field_filter is not None:
fields = list(field_filter(val))
else:
fields = val.__slots__
sub = (_sub_str_plot(_convert_getattr(val, f, t), time_offset, field_filter) for f,t in zip(val.__slots__, val._slot_types) if f in fields)
sub = [s for s in sub if s is not None]
if sub:
return ','.join(sub)
elif _isstring_type(type_):
return val
elif type_ in (list, tuple):
if len(val) == 0:
return None
val0 = val[0]
# no arrays of arrays
type0 = type(val0)
if type0 == bool:
return ','.join([('1' if v else '0') for v in val])
elif type0 in (int, float) or \
isinstance(val0, genpy.TVal):
return ','.join([str(v) for v in val])
elif _isstring_type(type0):
return ','.join([v for v in val])
elif hasattr(val0, "_slot_types"):
sub = [s for s in [_sub_str_plot(v, time_offset, field_filter) for v in val] if s is not None]
if sub:
return ','.join([s for s in sub])
return None
# copied from roslib.message
def _convert_getattr(val, f, t):
"""
Convert atttribute types on the fly, if necessary. This is mainly
to convert uint8[] fields back to an array type.
"""
attr = getattr(val, f)
if _isstring_type(type(attr)) and 'uint8[' in t:
return [ord(x) for x in attr]
else:
return attr
class CallbackEcho(object):
"""
Callback instance that can print callback data in a variety of
formats. Used for all variants of rostopic echo
"""
def __init__(self, topic, msg_eval, plot=False, filter_fn=None,
echo_clear=False, echo_all_topics=False,
offset_time=False, count=None,
field_filter_fn=None, fixed_numeric_width=None):
"""
:param plot: if ``True``, echo in plotting-friendly format (csv), ``bool``
:param filter_fn: function that evaluates to ``True`` if message is to be echo'd, ``fn(topic, msg)``
:param echo_all_topics: (optional) if ``True``, echo all messages in bag, ``bool``
:param offset_time: (optional) if ``True``, display time as offset from current time, ``bool``
:param count: number of messages to echo, ``None`` for infinite, ``int``
:param field_filter_fn: filter the fields that are strified for Messages, ``fn(Message)->iter(str)``
:param fixed_numeric_width: fixed width for numeric values, ``None`` for automatic, ``int``
"""
if topic and topic[-1] == '/':
topic = topic[:-1]
self.topic = topic
self.msg_eval = msg_eval
self.plot = plot
self.filter_fn = filter_fn
self.fixed_numeric_width = fixed_numeric_width
self.prefix = ''
self.suffix = '\n---' if not plot else ''# same as YAML document separator, bug #3291
self.echo_all_topics = echo_all_topics
self.offset_time = offset_time
# done tracks when we've exceeded the count
self.done = False
self.max_count = count
self.count = 0
# determine which strifying function to use
if plot:
#TODOXXX: need to pass in filter function
self.str_fn = _str_plot
self.sep = ''
else:
#TODOXXX: need to pass in filter function
self.str_fn = self.custom_strify_message
if echo_clear:
self.prefix = '\033[2J\033[;H'
self.field_filter=field_filter_fn
# first tracks whether or not we've printed anything yet. Need this for printing plot fields.
self.first = True
# cache
self.last_topic = None
self.last_msg_eval = None
def custom_strify_message(self, val, indent='', time_offset=None, current_time=None, field_filter=None, type_information=None, fixed_numeric_width=None):
# ensure to print uint8[] as array of numbers instead of string
if type_information and type_information.startswith('uint8['):
val = [ord(x) for x in val]
return genpy.message.strify_message(val, indent=indent, time_offset=time_offset, current_time=current_time, field_filter=field_filter, fixed_numeric_width=fixed_numeric_width)
def callback(self, data, callback_args, current_time=None):
"""
Callback to pass to rospy.Subscriber or to call
manually. rospy.Subscriber constructor must also pass in the
topic name as an additional arg
:param data: Message
:param topic: topic name, ``str``
:param current_time: override calculation of current time, :class:`genpy.Time`
"""
topic = callback_args['topic']
type_information = callback_args.get('type_information', None)
if self.filter_fn is not None and not self.filter_fn(data):
return
if self.max_count is not None and self.count >= self.max_count:
self.done = True
return
try:
msg_eval = self.msg_eval
if topic == self.topic:
pass
elif self.topic.startswith(topic + '/'):
# self.topic is actually a reference to topic field, generate msgeval
if topic == self.last_topic:
# use cached eval
msg_eval = self.last_msg_eval
else:
# generate msg_eval and cache
self.last_msg_eval = msg_eval = msgevalgen(self.topic[len(topic):])
self.last_topic = topic
elif not self.echo_all_topics:
return
if msg_eval is not None:
data = msg_eval(data)
# data can be None if msg_eval returns None
if data is not None:
# NOTE: we do all prints using direct writes to sys.stdout, which works better with piping
self.count += 1
# print fields header for plot
if self.plot and self.first:
sys.stdout.write("%"+_str_plot_fields(data, 'field', self.field_filter)+'\n')
self.first = False
if self.offset_time:
sys.stdout.write(self.prefix+\
self.str_fn(data, time_offset=rospy.get_rostime(),
current_time=current_time, field_filter=self.field_filter, type_information=type_information, fixed_numeric_width=self.fixed_numeric_width) + \
self.suffix + '\n')
else:
sys.stdout.write(self.prefix+\
self.str_fn(data,
current_time=current_time, field_filter=self.field_filter, type_information=type_information, fixed_numeric_width=self.fixed_numeric_width) + \
self.suffix + '\n')
# we have to flush in order before piping to work
sys.stdout.flush()
# #2778 : have to check count after incr to set done flag
if self.max_count is not None and self.count >= self.max_count:
self.done = True
except IOError:
self.done = True
except:
# set done flag so we exit
self.done = True
traceback.print_exc()
def _rostopic_type(topic):
"""
Print ROS message type of topic to screen
:param topic: topic name, ``str``
"""
t, _, _ = get_topic_type(topic, blocking=False)
if t:
print(t)
else:
sys.stderr.write('unknown topic type [%s]\n'%topic)
sys.exit(1)
def _rostopic_echo_bag(callback_echo, bag_file):
"""
:param callback_echo: :class:`CallbackEcho` instance to invoke on new messages in bag file
:param bag_file: name of bag file to echo messages from or ``None``, ``str``
"""
if not os.path.exists(bag_file):
raise ROSTopicException("bag file [%s] does not exist"%bag_file)
first = True
import rosbag
with rosbag.Bag(bag_file) as b:
for t, msg, timestamp in b.read_messages():
# bag files can have relative paths in them, this respects any
# dynamic renaming
if t[0] != '/':
t = rosgraph.names.script_resolve_name('rostopic', t)
callback_echo.callback(msg, {'topic': t}, current_time=timestamp)
# done is set if there is a max echo count
if callback_echo.done:
break
def _rostopic_echo(topic, callback_echo, bag_file=None, echo_all_topics=False):
"""
Print new messages on topic to screen.
:param topic: topic name, ``str``
:param bag_file: name of bag file to echo messages from or ``None``, ``str``
"""
# we have to init a node regardless and bag echoing can print timestamps
if bag_file:
# initialize rospy time due to potential timestamp printing
rospy.rostime.set_rostime_initialized(True)
_rostopic_echo_bag(callback_echo, bag_file)
else:
_check_master()
rospy.init_node(NAME, anonymous=True)
msg_class, real_topic, msg_eval = get_topic_class(topic, blocking=True)
if msg_class is None:
# occurs on ctrl-C
return
callback_echo.msg_eval = msg_eval
# extract type information for submessages
type_information = None
if len(topic) > len(real_topic):
subtopic = topic[len(real_topic):]
subtopic = subtopic.strip('/')
if subtopic:
fields = subtopic.split('/')
submsg_class = msg_class
while fields:
field = fields[0].split('[')[0]
del fields[0]
index = submsg_class.__slots__.index(field)
type_information = submsg_class._slot_types[index]
if fields:
submsg_class = roslib.message.get_message_class(type_information.split('[', 1)[0])
if not submsg_class:
raise ROSTopicException("Cannot load message class for [%s]. Are your messages built?" % type_information)
use_sim_time = rospy.get_param('/use_sim_time', False)
sub = rospy.Subscriber(real_topic, msg_class, callback_echo.callback, {'topic': topic, 'type_information': type_information})
if use_sim_time:
# #2950: print warning if nothing received for two seconds
timeout_t = time.time() + 2.
while time.time() < timeout_t and \
callback_echo.count == 0 and \
not rospy.is_shutdown() and \
not callback_echo.done:
_sleep(0.1)
if callback_echo.count == 0 and \
not rospy.is_shutdown() and \
not callback_echo.done:
sys.stderr.write("WARNING: no messages received and simulated time is active.\nIs /clock being published?\n")
while not rospy.is_shutdown() and not callback_echo.done:
_sleep(0.1)
_caller_apis = {}
def get_api(master, caller_id):
"""
Get XML-RPC API of node
:param master: XML-RPC handle to ROS Master, :class:`xmlrpclib.ServerProxy`
:param caller_id: node name, ``str``
:returns: XML-RPC URI of node, ``str``
:raises: :exc:`ROSTopicIOException` If unable to communicate with master
"""
caller_api = _caller_apis.get(caller_id, None)
if not caller_api:
try:
caller_api = master.lookupNode(caller_id)
_caller_apis[caller_id] = caller_api
except socket.error:
raise ROSTopicIOException("Unable to communicate with master!")
except rosgraph.MasterError:
caller_api = 'unknown address %s'%caller_id
return caller_api
def _rostopic_list_bag(bag_file, topic=None):
"""
Prints topics in bag file to screen
:param bag_file: path to bag file, ``str``
:param topic: optional topic name to match. Will print additional information just about messagese in this topic, ``str``
"""
import rosbag
if not os.path.exists(bag_file):
raise ROSTopicException("bag file [%s] does not exist"%bag_file)
with rosbag.Bag(bag_file) as b:
if topic:
# create string for namespace comparison
topic_ns = rosgraph.names.make_global_ns(topic)
count = 0
earliest = None
latest = None
for top, msg, t in b.read_messages(raw=True):
if top == topic or top.startswith(topic_ns):
count += 1
if earliest == None:
earliest = t
latest = t
if rospy.is_shutdown():
break
import time
earliest, latest = [time.strftime("%d %b %Y %H:%M:%S", time.localtime(t.to_time())) for t in (earliest, latest)]
print("%s message(s) from %s to %s"%(count, earliest, latest))
else:
topics = set()
for top, msg, _ in b.read_messages(raw=True):
if top not in topics:
print(top)
topics.add(top)
if rospy.is_shutdown():
break
def _sub_rostopic_list(master, pubs, subs, publishers_only, subscribers_only, verbose, indent=''):
def topic_type(t, topic_types):
matches = [t_type for t_name, t_type in topic_types if t_name == t]
if matches:
return matches[0]
return 'unknown type'
if verbose:
topic_types = _master_get_topic_types(master)
if not subscribers_only:
print("\n%sPublished topics:"%indent)
for t, l in pubs:
if len(l) > 1:
print(indent+" * %s [%s] %s publishers"%(t, topic_type(t, topic_types), len(l)))
else:
print(indent+" * %s [%s] 1 publisher"%(t, topic_type(t, topic_types)))
if not publishers_only:
print(indent)
print(indent+"Subscribed topics:")
for t,l in subs:
if len(l) > 1:
print(indent+" * %s [%s] %s subscribers"%(t, topic_type(t, topic_types), len(l)))
else:
print(indent+" * %s [%s] 1 subscriber"%(t, topic_type(t, topic_types)))
print('')
else:
if publishers_only:
topics = [t for t,_ in pubs]
elif subscribers_only:
topics = [t for t,_ in subs]
else:
topics = list(set([t for t,_ in pubs] + [t for t,_ in subs]))
topics.sort()
print('\n'.join(["%s%s"%(indent, t) for t in topics]))
# #3145
def _rostopic_list_group_by_host(master, pubs, subs):
"""
Build up maps for hostname to topic list per hostname
:returns: publishers host map, subscribers host map, ``{str: set(str)}, {str: set(str)}``
"""
def build_map(master, state, uricache):
tmap = {}
for topic, tnodes in state:
for p in tnodes:
if not p in uricache:
uricache[p] = master.lookupNode(p)
uri = uricache[p]
puri = urlparse(uri)
if not puri.hostname in tmap:
tmap[puri.hostname] = []
# recreate the system state data structure, but for a single host
matches = [l for x, l in tmap[puri.hostname] if x == topic]
if matches:
matches[0].append(p)
else:
tmap[puri.hostname].append((topic, [p]))
return tmap
uricache = {}
host_pub_topics = build_map(master, pubs, uricache)
host_sub_topics = build_map(master, subs, uricache)
return host_pub_topics, host_sub_topics
def _rostopic_list(topic, verbose=False,
subscribers_only=False, publishers_only=False,
group_by_host=False):
"""
Print topics to screen
:param topic: topic name to list information or None to match all topics, ``str``
:param verbose: print additional debugging information, ``bool``
:param subscribers_only: print information about subscriptions only, ``bool``
:param publishers_only: print information about subscriptions only, ``bool``
:param group_by_host: group topic list by hostname, ``bool``
"""
# #1563
if subscribers_only and publishers_only:
raise ROSTopicException("cannot specify both subscribers- and publishers-only")
master = rosgraph.Master('/rostopic')
try:
state = master.getSystemState()
pubs, subs, _ = state
if topic:
# filter based on topic
topic_ns = rosgraph.names.make_global_ns(topic)
subs = (x for x in subs if x[0] == topic or x[0].startswith(topic_ns))
pubs = (x for x in pubs if x[0] == topic or x[0].startswith(topic_ns))
except socket.error:
raise ROSTopicIOException("Unable to communicate with master!")
if group_by_host:
# #3145
host_pub_topics, host_sub_topics = _rostopic_list_group_by_host(master, pubs, subs)
for hostname in set(list(host_pub_topics.keys()) + list(host_sub_topics.keys())): #py3k
pubs, subs = host_pub_topics.get(hostname,[]), host_sub_topics.get(hostname, []),
if (pubs and not subscribers_only) or (subs and not publishers_only):
print("Host [%s]:" % hostname)
_sub_rostopic_list(master, pubs, subs,
publishers_only, subscribers_only,
verbose, indent=' ')
else:
_sub_rostopic_list(master, pubs, subs,
publishers_only, subscribers_only,
verbose)
def get_info_text(topic):
"""
Get human-readable topic description
:param topic: topic name, ``str``
"""
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
import itertools
buff = StringIO()
def topic_type(t, topic_types):
matches = [t_type for t_name, t_type in topic_types if t_name == t]
if matches:
return matches[0]
return 'unknown type'
master = rosgraph.Master('/rostopic')
try:
state = master.getSystemState()
pubs, subs, _ = state
# filter based on topic
subs = [x for x in subs if x[0] == topic]
pubs = [x for x in pubs if x[0] == topic]
topic_types = _master_get_topic_types(master)
except socket.error:
raise ROSTopicIOException("Unable to communicate with master!")
if not pubs and not subs:
raise ROSTopicException("Unknown topic %s"%topic)
buff.write("Type: %s\n\n"%topic_type(topic, topic_types))
if pubs:
buff.write("Publishers: \n")
for p in itertools.chain(*[l for x, l in pubs]):
buff.write(" * %s (%s)\n"%(p, get_api(master, p)))
else:
buff.write("Publishers: None\n")
buff.write('\n')
if subs:
buff.write("Subscribers: \n")
for p in itertools.chain(*[l for x, l in subs]):
buff.write(" * %s (%s)\n"%(p, get_api(master, p)))
else:
buff.write("Subscribers: None\n")
buff.write('\n')
return buff.getvalue()
def _rostopic_info(topic):
"""
Print topic information to screen.
:param topic: topic name, ``str``
"""
print(get_info_text(topic))
##########################################################################################
# COMMAND PROCESSING #####################################################################
def _rostopic_cmd_echo(argv):
def expr_eval(expr):
def eval_fn(m):
return eval(expr)
return eval_fn
args = argv[2:]
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog echo [options] /topic", prog=NAME)
parser.add_option("-b", "--bag",
dest="bag", default=None,
help="echo messages from .bag file", metavar="BAGFILE")
parser.add_option("-p",
dest="plot", default=False,
action="store_true",
help="echo in a plotting friendly format")
parser.add_option("-w",
dest="fixed_numeric_width", default=None, metavar="NUM_WIDTH",
help="fixed width for numeric values")
parser.add_option("--filter",
dest="filter_expr", default=None,
metavar="FILTER-EXPRESSION",
help="Python expression to filter messages that are printed. Expression can use Python builtins as well as m (the message) and topic (the topic name).")
parser.add_option("--nostr",
dest="nostr", default=False,
action="store_true",
help="exclude string fields")
parser.add_option("--noarr",
dest="noarr", default=False,
action="store_true",
help="exclude arrays")
parser.add_option("-c", "--clear",
dest="clear", default=False,
action="store_true",
help="clear screen before printing next message")
parser.add_option("-a", "--all",
dest="all_topics", default=False,
action="store_true",
help="display all message in bag, only valid with -b option")
parser.add_option("-n",
dest="msg_count", default=None, metavar="COUNT",
help="number of messages to echo")
parser.add_option("--offset",
dest="offset_time", default=False,
action="store_true",
help="display time as offsets from current time (in seconds)")
(options, args) = parser.parse_args(args)
if len(args) > 1:
parser.error("you may only specify one input topic")
if options.all_topics and not options.bag:
parser.error("Display all option is only valid when echoing from bag files")
if options.offset_time and options.bag:
parser.error("offset time option is not valid with bag files")
if options.all_topics:
topic = ''
else:
if len(args) == 0:
parser.error("topic must be specified")
topic = rosgraph.names.script_resolve_name('rostopic', args[0])
# suppressing output to keep it clean
#if not options.plot:
# print "rostopic: topic is [%s]"%topic
filter_fn = None
if options.filter_expr:
filter_fn = expr_eval(options.filter_expr)
try:
msg_count = int(options.msg_count) if options.msg_count else None
except ValueError:
parser.error("COUNT must be an integer")
try:
fixed_numeric_width = int(options.fixed_numeric_width) if options.fixed_numeric_width else None
if fixed_numeric_width is not None and fixed_numeric_width < 2:
parser.error("Fixed width for numeric values must be at least 2")
except ValueError:
parser.error("NUM_WIDTH must be an integer")
field_filter_fn = create_field_filter(options.nostr, options.noarr)
callback_echo = CallbackEcho(topic, None, plot=options.plot,
filter_fn=filter_fn,
echo_clear=options.clear, echo_all_topics=options.all_topics,
offset_time=options.offset_time, count=msg_count,
field_filter_fn=field_filter_fn, fixed_numeric_width=fixed_numeric_width)
try:
_rostopic_echo(topic, callback_echo, bag_file=options.bag)
except socket.error:
sys.stderr.write("Network communication failed. Most likely failed to communicate with master.\n")
def create_field_filter(echo_nostr, echo_noarr):
def field_filter(val):
fields = val.__slots__
field_types = val._slot_types
for f, t in zip(val.__slots__, val._slot_types):
if echo_noarr and '[' in t:
continue
elif echo_nostr and 'string' in t:
continue
yield f
return field_filter
def _optparse_topic_only(cmd, argv):
args = argv[2:]
from optparse import OptionParser
parser = OptionParser(usage="usage: %%prog %s /topic"%cmd, prog=NAME)
(options, args) = parser.parse_args(args)
if len(args) == 0:
parser.error("topic must be specified")
if len(args) > 1:
parser.error("you may only specify one input topic")
return rosgraph.names.script_resolve_name('rostopic', args[0])
def _rostopic_cmd_type(argv):
_rostopic_type(_optparse_topic_only('type', argv))
def _rostopic_cmd_hz(argv):
args = argv[2:]
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog hz /topic", prog=NAME)
parser.add_option("-w", "--window",
dest="window_size", default=-1,
help="window size, in # of messages, for calculating rate", metavar="WINDOW")
parser.add_option("--filter",
dest="filter_expr", default=None,
help="only measure messages matching the specified Python expression", metavar="EXPR")
parser.add_option("--wall-time",
dest="use_wtime", default=False, action="store_true",
help="calculates rate using wall time which can be helpful when clock isnt published during simulation")
(options, args) = parser.parse_args(args)
if len(args) == 0:
parser.error("topic must be specified")
if len(args) > 1:
parser.error("you may only specify one input topic")
try:
if options.window_size != -1:
import string
window_size = string.atoi(options.window_size)
else:
window_size = options.window_size
except:
parser.error("window size must be an integer")
topic = rosgraph.names.script_resolve_name('rostopic', args[0])
# #694
if options.filter_expr:
def expr_eval(expr):
def eval_fn(m):
return eval(expr)
return eval_fn
filter_expr = expr_eval(options.filter_expr)
else:
filter_expr = None
_rostopic_hz(topic, window_size=window_size, filter_expr=filter_expr,
use_wtime=options.use_wtime)
def _rostopic_cmd_delay(argv):
args = argv[2:]
import argparse
parser = argparse.ArgumentParser(usage="%(prog)s delay [options] /topic", prog=NAME)
parser.add_argument("topic", help="topic name to be calcurated the delay")
parser.add_argument("-w", "--window",
dest="window_size", default=-1, type=int,
help="window size, in # of messages, for calculating rate")
args = parser.parse_args(args)
topic_name = args.topic
window_size = args.window_size
topic = rosgraph.names.script_resolve_name('rostopic', topic_name)
_rostopic_delay(topic, window_size=window_size)
def _rostopic_cmd_bw(argv=sys.argv):
args = argv[2:]
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog bw /topic", prog=NAME)
parser.add_option("-w", "--window",
dest="window_size", default=None,
help="window size, in # of messages, for calculating rate", metavar="WINDOW")
options, args = parser.parse_args(args)
if len(args) == 0:
parser.error("topic must be specified")
if len(args) > 1:
parser.error("you may only specify one input topic")
try:
if options.window_size:
import string
window_size = string.atoi(options.window_size)
else:
window_size = options.window_size
except:
parser.error("window size must be an integer")
topic = rosgraph.names.script_resolve_name('rostopic', args[0])
_rostopic_bw(topic, window_size=window_size)
def find_by_type(topic_type):
"""
Lookup topics by topic_type
:param topic_type: type of topic to find, ``str``
:returns: list of topic names that use topic_type, ``[str]``
"""
master = rosgraph.Master('/rostopic')
try:
t_list = _master_get_topic_types(master)
except socket.error:
raise ROSTopicIOException("Unable to communicate with master!")
return [t_name for t_name, t_type in t_list if t_type == topic_type]
def _rostopic_cmd_find(argv=sys.argv):
"""
Implements 'rostopic type'
:param argv: command-line args, ``[str]``
"""
args = argv[2:]
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog find msg-type", prog=NAME)
options, args = parser.parse_args(args)
if not len(args):
parser.error("please specify a message type")
if len(args) > 1:
parser.error("you may only specify one message type")
print('\n'.join(find_by_type(args[0])))
def _resource_name_package(name):
"""
pkg/typeName -> pkg, typeName -> None
:param name: package resource name, e.g. 'std_msgs/String', ``str``
:returns: package name of resource, ``str``
"""
if not '/' in name:
return None
return name[:name.find('/')]
def create_publisher(topic_name, topic_type, latch):
"""
Create rospy.Publisher instance from the string topic name and
type. This is a powerful method as it allows creation of
rospy.Publisher and Message instances using the topic and type
names. This enables more dynamic publishing from Python programs.
:param topic_name: name of topic, ``str``
:param topic_type: name of topic type, ``str``
:param latch: latching topic, ``bool``
:returns: topic :class:`rospy.Publisher`, :class:`Message` class
"""
topic_name = rosgraph.names.script_resolve_name('rostopic', topic_name)
try:
msg_class = roslib.message.get_message_class(topic_type)
except:
raise ROSTopicException("invalid topic type: %s"%topic_type)
if msg_class is None:
pkg = _resource_name_package(topic_type)
raise ROSTopicException("invalid message type: %s.\nIf this is a valid message type, perhaps you need to type 'rosmake %s'"%(topic_type, pkg))
# disable /rosout and /rostime as this causes blips in the pubsub network due to rostopic pub often exiting quickly
rospy.init_node('rostopic', anonymous=True, disable_rosout=True, disable_rostime=True)
pub = rospy.Publisher(topic_name, msg_class, latch=latch, queue_size=100)
return pub, msg_class
def _publish_at_rate(pub, msg, rate, verbose=False, substitute_keywords=False, pub_args=None):
"""
Publish message at specified rate. Subroutine of L{publish_message()}.
:param pub: :class:rospy.Publisher` instance for topic
:param msg: message instance to publish
:param rate: publishing rate (hz) or None for just once, ``int``
:param verbose: If ``True``, print more verbose output to stdout, ``bool``
"""
try:
r = rospy.Rate(float(rate))
except ValueError:
raise ROSTopicException("Rate must be a number")
while not rospy.is_shutdown():
if substitute_keywords:
_fillMessageArgs(msg, pub_args)
if verbose:
print("publishing %s"%msg)
pub.publish(msg)
r.sleep()
_ONCE_DELAY = 3.
def _publish_latched(pub, msg, once=False, verbose=False):
"""
Publish and latch message. Subroutine of L{publish_message()}.
:param pub: :class:`rospy.Publisher` instance for topic
:param msg: message instance to publish
:param once: if ``True``, publish message once and then exit after sleep interval, ``bool``
:param verbose: If ``True``, print more verbose output to stdout, ``bool``
"""
try:
pub.publish(msg)
except TypeError as e:
raise ROSTopicException(str(e))
if not once:
rospy.spin()
def publish_message(pub, msg_class, pub_args, rate=None, once=False, verbose=False, substitute_keywords=False):
"""
Create new instance of msg_class, populate with pub_args, and publish. This may
print output to screen.
:param pub: :class:`rospy.Publisher` instance for topic
:param msg_class: Message type, ``Class``
:param pub_args: Arguments to initialize message that is published, ``[val]``
:param rate: publishing rate (hz) or None for just once, ``int``
:param once: publish only once and return, ``bool``
:param verbose: If ``True``, print more verbose output to stdout, ``bool``
"""
msg = msg_class()
_fillMessageArgs(msg, pub_args)
try:
if rate is None:
s = "publishing and latching [%s]"%(msg) if verbose else "publishing and latching message"
if once:
s = s + " for %s seconds"%_ONCE_DELAY
else:
s = s + ". Press ctrl-C to terminate"
print(s)
_publish_latched(pub, msg, once, verbose)
else:
_publish_at_rate(pub, msg, rate, verbose=verbose, substitute_keywords=substitute_keywords, pub_args=pub_args)
except rospy.ROSSerializationException as e:
import rosmsg
# we could just print the message definition, but rosmsg is more readable
raise ROSTopicException("Unable to publish message. One of the fields has an incorrect type:\n"+\
" %s\n\nmsg file:\n%s"%(e, rosmsg.get_msg_text(msg_class._type)))
def _fillMessageArgs(msg, pub_args):
try:
# Populate the message and enable substitution keys for 'now'
# and 'auto'. There is a corner case here: this logic doesn't
# work if you're publishing a Header only and wish to use
# 'auto' with it. This isn't a troubling case, but if we start
# allowing more keys in the future, it could become an actual
# use case. It greatly complicates logic because we'll have to
# do more reasoning over types. to avoid ambiguous cases
# (e.g. a std_msgs/String type, which only has a single string
# field).
# allow the use of the 'now' string with timestamps and 'auto' with header
now = rospy.get_rostime()
import std_msgs.msg
keys = { 'now': now, 'auto': std_msgs.msg.Header(stamp=now) }
genpy.message.fill_message_args(msg, pub_args, keys=keys)
except genpy.MessageException as e:
raise ROSTopicException(str(e)+"\n\nArgs are: [%s]"%genpy.message.get_printable_message_args(msg))
def _rostopic_cmd_pub(argv):
"""
Parse 'pub' command arguments and run command. Will cause a system
exit if command-line argument parsing fails.
:param argv: command-line arguments
:param argv: [str]
:raises: :exc:`ROSTopicException` If call command cannot be executed
"""
args = argv[2:]
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog pub /topic type [args...]", prog=NAME)
parser.add_option("-v", dest="verbose", default=False,
action="store_true",
help="print verbose output")
parser.add_option("-r", "--rate", dest="rate", default=None,
help="publishing rate (hz). For -f and stdin input, this defaults to 10. Otherwise it is not set.")
parser.add_option("-1", "--once", action="store_true", dest="once", default=False,
help="publish one message and exit")
parser.add_option("-f", '--file', dest="file", metavar='FILE', default=None,
help="read args from YAML file (Bagy)")
parser.add_option("-l", '--latch', dest="latch", default=False, action="store_true",
help="enable latching for -f, -r and piped input. This latches the first message.")
parser.add_option("-s", '--substitute-keywords', dest="substitute_keywords", default=False, action="store_true",
help="When publishing with a rate, performs keyword ('now' or 'auto') substitution for each message")
#parser.add_option("-p", '--param', dest="parameter", metavar='/PARAM', default=None,
# help="read args from ROS parameter (Bagy format)")
(options, args) = parser.parse_args(args)
if options.rate is not None:
if options.once:
parser.error("You cannot select both -r and -1 (--once)")
try:
rate = float(options.rate)
except ValueError:
parser.error("rate must be a number")
if rate <= 0:
parser.error("rate must be greater than zero")
else:
# we will default this to 10 for file/stdin later
rate = None
# validate args len
if len(args) == 0:
parser.error("/topic must be specified")
if len(args) == 1:
parser.error("topic type must be specified")
if 0:
if len(args) > 2 and options.parameter:
parser.error("args confict with -p setting")
if len(args) > 2 and options.file:
parser.error("args confict with -f setting")
topic_name, topic_type = args[0], args[1]
if topic_type.find('pb_msgs') >= 0:
print("Protobuf message not support sub-commond 'pub' yet")
exit()
# type-case using YAML
try:
pub_args = []
for arg in args[2:]:
pub_args.append(yaml.load(arg))
except Exception as e:
parser.error("Argument error: "+str(e))
# make sure master is online. we wait until after we've parsed the
# args to do this so that syntax errors are reported first
_check_master()
# if no rate, or explicit latch, we latch
latch = (rate == None) or options.latch
pub, msg_class = create_publisher(topic_name, topic_type, latch)
if 0 and options.parameter:
param_name = rosgraph.names.script_resolve_name('rostopic', options.parameter)
if options.once:
param_publish_once(pub, msg_class, param_name, rate, options.verbose)
else:
param_publish(pub, msg_class, param_name, rate, options.verbose)
elif not pub_args and len(msg_class.__slots__):
if not options.file and sys.stdin.isatty():
parser.error("Please specify message values")
# stdin/file input has a rate by default
if rate is None and not options.latch and not options.once:
rate = 10.
stdin_publish(pub, msg_class, rate, options.once, options.file, options.verbose)
else:
argv_publish(pub, msg_class, pub_args, rate, options.once, options.verbose, substitute_keywords=options.substitute_keywords)
def file_yaml_arg(filename):
"""
:param filename: file name, ``str``
:returns: Iterator that yields pub args (list of args), ``iterator``
:raises: :exc:`ROSTopicException` If filename is invalid
"""
if not os.path.isfile(filename):
raise ROSTopicException("file does not exist: %s"%(filename))
import yaml
def bagy_iter():
try:
with open(filename, 'r') as f:
# load all documents
data = yaml.load_all(f)
for d in data:
yield [d]
except yaml.YAMLError as e:
raise ROSTopicException("invalid YAML in file: %s"%(str(e)))
return bagy_iter
def argv_publish(pub, msg_class, pub_args, rate, once, verbose, substitute_keywords=False):
publish_message(pub, msg_class, pub_args, rate, once, verbose=verbose, substitute_keywords=substitute_keywords)
if once:
# stick around long enough for others to grab
timeout_t = time.time() + _ONCE_DELAY
while not rospy.is_shutdown() and time.time() < timeout_t:
rospy.sleep(0.2)
SUBSCRIBER_TIMEOUT = 5.
def wait_for_subscriber(pub, timeout):
timeout_t = time.time() + timeout
while pub.get_num_connections() == 0 and timeout_t > time.time():
_sleep(0.01)
def param_publish_once(pub, msg_class, param_name, verbose):
if not rospy.has_param(param_name):
raise ROSTopicException("parameter does not exist: %s"%(param_name))
pub_args = rospy.get_param(param_name)
argv_publish(pub, msg_class, pub_args, None, True, verbose)
class _ParamNotifier(object):
def __init__(self, param_name, value=None):
import threading
self.lock = threading.Condition()
self.param_name = param_name
self.updates = []
self.value = None
def __call__(self, key, value):
with self.lock:
# have to address downward if we got notification on sub namespace
if key != self.param_name:
subs = [x for x in key[len(self.param_name):].split('/') if x]
idx = self.value
for s in subs[:-1]:
if s in idx:
idx = idx[s]
else:
idx[s] = {}
idx = idx[s]
idx[subs[-1]] = value
else:
self.value = value
self.updates.append(self.value)
self.lock.notify_all()
def param_publish(pub, msg_class, param_name, rate, verbose):
"""
:param param_name: ROS parameter name, ``str``
:returns: List of msg dicts in file, ``[{str: any}]``
:raises: :exc:`ROSTopicException` If parameter is not set
"""
import rospy
import rospy.impl.paramserver
import rosgraph
if not rospy.has_param(param_name):
raise ROSTopicException("parameter does not exist: %s"%(param_name))
# reach deep into subscription APIs here. Very unstable stuff
# here, don't copy elsewhere!
ps_cache = rospy.impl.paramserver.get_param_server_cache()
notifier = _ParamNotifier(param_name)
ps_cache.set_notifier(notifier)
master = rosgraph.Master(rospy.get_name())
notifier.value = master.subscribeParam(rospy.get_node_uri(), param_name)
pub_args = notifier.value
ps_cache.set(param_name, pub_args)
if type(pub_args) == dict:
pub_args = [pub_args]
elif type(pub_args) != list:
raise ROSTopicException("Parameter [%s] in not a valid type"%(param_name))
r = rospy.Rate(rate) if rate is not None else None
publish = True
while not rospy.is_shutdown():
try:
if publish:
publish_message(pub, msg_class, pub_args, None, True, verbose=verbose)
except ValueError as e:
sys.stderr.write("%s\n"%str(e))
break
if r is not None:
r.sleep()
with notifier.lock:
if notifier.updates:
pub_args = notifier.updates.pop(0)
if type(pub_args) == dict:
pub_args = [pub_args]
else:
publish = False
with notifier.lock:
if not notifier.updates:
notifier.lock.wait(1.)
if notifier.updates:
publish = True
pub_args = notifier.updates.pop(0)
if type(pub_args) == dict:
pub_args = [pub_args]
if rospy.is_shutdown():
break
def stdin_publish(pub, msg_class, rate, once, filename, verbose):
"""
:param filename: name of file to read from instead of stdin, or ``None``, ``str``
"""
if filename:
iterator = file_yaml_arg(filename)
else:
iterator = stdin_yaml_arg
r = rospy.Rate(rate) if rate is not None else None
# stdin publishing can happen really fast, especially if no rate
# is set, so try to make sure someone is listening before we
# publish, though we don't wait too long.
wait_for_subscriber(pub, SUBSCRIBER_TIMEOUT)
for pub_args in iterator():
if rospy.is_shutdown():
break
if pub_args:
if type(pub_args) != list:
pub_args = [pub_args]
try:
# we use 'bool(r) or once' for the once value, which
# controls whether or not publish_message blocks and
# latches until exit. We want to block if the user
# has enabled latching (i.e. rate is none). It would
# be good to reorganize this code more conceptually
# but, for now, this is the best re-use of the
# underlying methods.
publish_message(pub, msg_class, pub_args, None, bool(r) or once, verbose=verbose)
except ValueError as e:
sys.stderr.write("%s\n"%str(e))
break
if r is not None:
r.sleep()
if rospy.is_shutdown() or once:
break
def stdin_yaml_arg():
"""
Iterate over YAML documents in stdin
:returns: for next list of arguments on stdin. Iterator returns a list of args for each call, ``iterator``
"""
import yaml
from select import select
from select import error as select_error
try:
arg = 'x'
rlist = [sys.stdin]
wlist = xlist = []
while not rospy.is_shutdown() and arg != '\n':
buff = ''
while arg != '' and arg.strip() != '---' and not rospy.is_shutdown():
val, _, _ = select(rlist, wlist, xlist, 1.0)
if not val:
continue
# sys.stdin.readline() returns empty string on EOF
arg = sys.stdin.readline()
if arg != '' and arg.strip() != '---':
buff = buff + arg
if arg.strip() == '---': # End of document
try:
loaded = yaml.load(buff.rstrip())
except Exception as e:
sys.stderr.write("Invalid YAML: %s\n"%str(e))
if loaded is not None:
yield loaded
elif arg == '': #EOF
# we don't yield the remaining buffer in this case
# because we don't want to publish partial inputs
return
arg = 'x' # reset
except select_error:
return # most likely ctrl-c interrupt
def _rostopic_cmd_list(argv):
"""
Command-line parsing for 'rostopic list' command.
"""
args = argv[2:]
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog list [/namespace]", prog=NAME)
parser.add_option("-b", "--bag",
dest="bag", default=None,
help="list topics in .bag file", metavar="BAGFILE")
parser.add_option("-v", "--verbose",
dest="verbose", default=False,action="store_true",
help="list full details about each topic")
parser.add_option("-p",
dest="publishers", default=False,action="store_true",
help="list only publishers")
parser.add_option("-s",
dest="subscribers", default=False,action="store_true",
help="list only subscribers")
parser.add_option("--host", dest="hostname", default=False, action="store_true",
help="group by host name")
(options, args) = parser.parse_args(args)
topic = None
if len(args) == 1:
topic = rosgraph.names.script_resolve_name('rostopic', args[0])
elif len(args) > 1:
parser.error("you may only specify one input topic")
if options.bag:
if options.subscribers:
parser.error("-s option is not valid with bags")
elif options.publishers:
parser.error("-p option is not valid with bags")
elif options.hostname:
parser.error("--host option is not valid with bags")
_rostopic_list_bag(options.bag, topic)
else:
if options.subscribers and options.publishers:
parser.error("you may only specify one of -p, -s")
exitval = _rostopic_list(topic, verbose=options.verbose, subscribers_only=options.subscribers, publishers_only=options.publishers, group_by_host=options.hostname) or 0
if exitval != 0:
sys.exit(exitval)
def _rostopic_cmd_info(argv):
"""
Command-line parsing for 'rostopic info' command.
"""
args = argv[2:]
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog info /topic", prog=NAME)
(options, args) = parser.parse_args(args)
if len(args) == 0:
parser.error("you must specify a topic name")
elif len(args) > 1:
parser.error("you may only specify one topic name")
topic = rosgraph.names.script_resolve_name('rostopic', args[0])
exitval = _rostopic_info(topic) or 0
if exitval != 0:
sys.exit(exitval)
def _fullusage():
print("""rostopic is a command-line tool for printing information about ROS Topics.
Commands:
\trostopic bw\tdisplay bandwidth used by topic
\trostopic delay\tdisplay delay of topic from timestamp in header
\trostopic echo\tprint messages to screen
\trostopic find\tfind topics by type
\trostopic hz\tdisplay publishing rate of topic
\trostopic info\tprint information about active topic
\trostopic list\tlist active topics
\trostopic pub\tpublish data to topic
\trostopic type\tprint topic type
Type rostopic <command> -h for more detailed usage, e.g. 'rostopic echo -h'
""")
sys.exit(getattr(os, 'EX_USAGE', 1))
def rostopicmain(argv=None):
import rosbag
if argv is None:
argv=sys.argv
# filter out remapping arguments in case we are being invoked via roslaunch
argv = rospy.myargv(argv)
# process argv
if len(argv) == 1:
_fullusage()
try:
command = argv[1]
if command == 'echo':
_rostopic_cmd_echo(argv)
elif command == 'hz':
_rostopic_cmd_hz(argv)
elif command == 'type':
_rostopic_cmd_type(argv)
elif command == 'list':
_rostopic_cmd_list(argv)
elif command == 'info':
_rostopic_cmd_info(argv)
elif command == 'pub':
_rostopic_cmd_pub(argv)
elif command == 'bw':
_rostopic_cmd_bw(argv)
elif command == 'find':
_rostopic_cmd_find(argv)
elif command == 'delay':
_rostopic_cmd_delay(argv)
else:
_fullusage()
except socket.error:
sys.stderr.write("Network communication failed. Most likely failed to communicate with master.\n")
sys.exit(1)
except rosbag.ROSBagException as e:
sys.stderr.write("ERROR: unable to use bag file: %s\n"%str(e))
sys.exit(1)
except rosgraph.MasterException as e:
# mainly for invalid master URI/rosgraph.masterapi
sys.stderr.write("ERROR: %s\n"%str(e))
sys.exit(1)
except ROSTopicException as e:
sys.stderr.write("ERROR: %s\n"%str(e))
sys.exit(1)
except KeyboardInterrupt: pass
except rospy.ROSInterruptException: pass
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/ros_comm/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.3)
project(ros_comm)
find_package(catkin REQUIRED)
catkin_metapackage()
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/ros_comm/package.xml | <package>
<name>ros_comm</name>
<version>1.11.21</version>
<description>
ROS communications-related packages, including core client libraries (roscpp, rospy) and graph introspection tools (rostopic, rosnode, rosservice, rosparam).
</description>
<maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer>
<license>BSD</license>
<url>http://www.ros.org/wiki/ros_comm</url>
<author email="mquigley@cs.stanford.edu">Morgan Quigley</author>
<author email="berger@willowgarage.com">Eric Berger</author>
<author email="kwc@willowgarage.com">Ken Conley</author>
<author email="rdiankov@cs.cmu.edu">Rosen Diankov</author>
<author email="jfaust@willowgarage.com">Josh Faust</author>
<author email="tfield@willowgarage.com">Tim Field</author>
<author email="tfoote@osrfoundation.org">Tully Foote</author>
<author email="gerkey@willowgarage.com">Brian Gerkey</author>
<author email="leibs@willowgarage.com">Jeremy Leibs</author>
<author email="bhaskara@willowgarage.com">Bhaskara Marthi</author>
<author email="straszheim@willowgarage.com">Troy Straszheim</author>
<author email="wheeler@willowgarage.com">Rob Wheeler</author>
<buildtool_depend>catkin</buildtool_depend>
<run_depend>roscpp</run_depend>
<run_depend>rospy</run_depend>
<run_depend>rosgraph_msgs</run_depend>
<run_depend>std_srvs</run_depend>
<run_depend>ros</run_depend> <!-- Depend on ros for backwards compatability. This will be removed in Hydro -->
<run_depend>rosbag</run_depend>
<run_depend>rosconsole</run_depend>
<run_depend>rosgraph</run_depend>
<run_depend>roslaunch</run_depend>
<run_depend>roslisp</run_depend> <!-- Depend on roslisp to enable lisp message generation in dry packages -->
<run_depend>rosmaster</run_depend>
<run_depend>rosmsg</run_depend>
<run_depend>rosnode</run_depend>
<run_depend>rosout</run_depend>
<run_depend>rosparam</run_depend>
<run_depend>rosservice</run_depend>
<run_depend>rostest</run_depend>
<run_depend>rostopic</run_depend>
<run_depend>topic_tools</run_depend>
<run_depend>message_filters</run_depend>
<run_depend>roswtf</run_depend>
<run_depend>xmlrpcpp</run_depend>
<export>
<metapackage/>
</export>
</package>
| 0 |
apollo_public_repos/apollo-platform/ros/ros_comm | apollo_public_repos/apollo-platform/ros/ros_comm/ros_comm/.tar | {!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/ros_comm/1.11.21-0.tar.gz',
!!python/unicode 'version': ros_comm-release-release-indigo-ros_comm-1.11.21-0}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.