More specifically, change the call to ` add_done_callback ` to:


###  Footer navigation


[ ramezanifar ](/ramezanifar) opened this issue  Oct 10, 2020  · 9 comments


For


Menu


_Check out **[ ROS2 For Beginners ](https://rbcknd.com/ros2-for-beginners) **
and learn ROS2 step by step, in 1 week. _


[ Proudly powered by WordPress ](http://wordpress.org/) ~  Theme: Penscratch
by [ WordPress.com ](http://wordpress.com/themes/penscratch/) .


Comment  *


  * [ Notifications ](/login?return_to=%2Fros2%2Frclpy)
  * [ Fork  213  ](/login?return_to=%2Fros2%2Frclpy)
  * [ Star  245  ](/login?return_to=%2Fros2%2Frclpy)


My solution is to use another function to generate the callback. In your
example, it will be sth like:


Resources


I'm closing this, as the extra ` call_back_arg ` doesn't seem to add much
value.


[ Sign in
](/login?return_to=https%3A%2F%2Fgithub.com%2Fros2%2Frclpy%2Fissues%2F629)


[ Sign up for free ](/join?source=comment-repo) **to join this conversation on
GitHub** . Already have an account? [ Sign in to comment
](/login?return_to=https%3A%2F%2Fgithub.com%2Fros2%2Frclpy%2Fissues%2F629)


All reactions


Sort by »  [ oldest  ](/question/346810/ros2-python-add-arguments-to-
callback/?sort=oldest#sort-top) [ newest  ](/question/346810/ros2-python-add-
arguments-to-callback/?sort=latest#sort-top) [ most voted
](/question/346810/ros2-python-add-arguments-to-callback/?sort=votes#sort-top)


A parameter’s type is actually evaluated after you’ve set the value. If you
had a boolean parameter, and you try to assign a string to it, well it will
work. And then you’ll probably get an exception in your code later on when you
try to use the value.


[ Next > Intel Realsense D435 Setup on Ubuntu 16.04
](https://www.minsung.org/2018/08/intel-realsense-d435-setup-on-ubuntu-16-04/)


  * Tutorials
    * [ ROS ](https://roboticsbackend.com/category/ros/)
    * [ ROS2 ](https://roboticsbackend.com/category/ros2/)
    * [ Raspberry Pi ](https://roboticsbackend.com/category/raspberry-pi/)
    * [ Arduino ](https://roboticsbackend.com/category/arduino/)
  * [ Youtube ](https://www.youtube.com/channel/UCelRThOKlWMnpjqr5EBq6tg?sub_confirmation=1)
  * [ **Courses** ](https://roboticsbackend.com/courses/)
  * [ Contact ](https://roboticsbackend.com/contact/)


[ __ ](/questions/) |


Categories  [ ROS2 Tutorials ](https://roboticsbackend.com/category/ros2/)


**[ ivanpauno ](/ivanpauno) ** commented  Oct 23, 2020


SAVE & ACCEPT


[ @ramezanifar ](https://github.com/ramezanifar) if you think that `
call_back_arg ` would still be useful feel free to left a comment here or
reopen the issue.

---

All reactions


[ More on this topic ](https://stackoverflow.com/questions/19837486/lambda-in-
a-loop)

---

All reactions


[ ROS2 nav2_turorial on win10 ERROR! ](/question/418092/ros2-nav2_turorial-on-
win10-error/)


**[ apockill ](/apockill) ** commented  Jan 22, 2023  •


If you want to easily check what you receive in the callback, you can simply
print all parameters using:


Sorry, something went wrong.


> Hi,
>
> Tried this and it stays with the last value of the multiple subscribers
> done:
>
>
>     for i in range(self.fleet_robots_number):
>                 robot_name = self.fleet_name +"_"+str(i+1)
>                 docked_status_topic_name = robot_name+"/docked_status"
>
>                 qos_profile_subscriber = QoSProfile(depth=1)
>                 qos_profile_subscriber.durability =
> QoSDurabilityPolicy.TRANSIENT_LOCAL
>
>                 # Your own common callback
>                 self.get_logger().error("INIT Subscriber
> =="+str(docked_status_topic_name))
>                 self.create_subscription(   BoolRosMsg,
>                                             docked_status_topic_name,
>                                             lambda msg:
> self.dock_state_clb(msg, robot_name),
>
> qos_profile=qos_profile_subscriber)
>                 self.get_logger().error("INIT Subscriber
> =="+str(docked_status_topic_name)+"....DONE")
>
>         def dock_state_clb(self, msg, in_robot_name):
>             self.get_logger().error("Message in_robot_name=="+str(msg)+",
> from robot="+str(in_robot_name))
>
>
>     Any ideas why? All the callback messages appear with the las
> `robot_name`used to initialise the subscribers.
>


    self.create_subscription(   BoolRosMsg,
                                           docked_status_topic_name,
                                           self.generate_callback(robot_name),
                                           qos_profile=qos_profile_subscriber)

---

All reactions


**
[ >> Learn ROS2 in 1 Week << ](https://rbcknd.com/ros2-for-beginners) **


    >>> def foobar(a,b):
    ...     return a+b
    >>> foobar(1,2) # call normal function
    3

    >>> bind = lambda x: foobar(x, 2) # bind 2 to foobar
    >>> bind(1)
    3

    >>> bind = lambda: foobar(1,2) # bind all elements
    >>> bind()
    3


Close


Sign up for GitHub


[ The Robotics Back-End ](https://roboticsbackend.com/)


Necessary


[ ![@patrickwasp](https://avatars.githubusercontent.com/u/70671760?s=80&v=4)
](/patrickwasp)


Don’t forget to import the Parameter object in your file.


##  Want to learn ROS2?


[ ros2 run - symbol not found on custom msg ](/question/326008/ros2-run-
symbol-not-found-on-custom-msg/)


(FYI, if you use mypy it'll catch these errors!)


To pass more arguments to your callback function in rospy, it is actually
super simple.


So, you will modify the parameter’s value, and in the callback, you’ll
probably want to restart the camera initialization sequence.


We read every piece of feedback, and take your input very seriously.


def callback(data, args): arg1 = args[0] arg2 = args[1] sub =
rospy.Subscriber("topic_name", String, callback, (arg1, arg2))


The parameter battery_percentage_warning has changed, but in the code, the
value inside the self.battery_percentage_warning_ attribute is still the old
one!


####  Privacy Overview


This website uses cookies to improve your experience while you navigate
through the website. Out of these, the cookies that are categorized as
necessary are stored on your browser as they are essential for the working of
basic functionalities of the website. We also use third-party cookies that
help us analyze and understand how you use this website. These cookies will be
stored in your browser only with your consent. You also have the option to
opt-out of these cookies. But opting out of some of these cookies may affect
your browsing experience.


Copy link


    def parameters_callback(self, params):
        for param in params:
            print(vars(param))
        return SetParametersResult(successful=True)


Well, once you’ve successfully setup the rclpy parameters callback, then what
you do inside it is up to you. For 10 different applications you have 10
different ways of processing the data.


As you use SetParameterResult, you need to import it from
“rcl_interfaces.msg”.


    def generate_callback(self, robot_name):
      return lambda msg=self.dock_state_clb(msg, robot_name)


But here I’m going to show you some common use cases, tips, and best practices
so you can get an idea of how to best use the callback.


* [ rclpy ](/questions/scope:all/sort:activity-desc/tags:rclpy/page:1/)


Sorry, something went wrong.


Skip to content


2 followers


#  Passing arguments to Python callback in rospy


When the node is killed and goes out of scope, the parameters callback is
automatically removed.


Advertisement


To see all available qualifiers, see our [ documentation
](https://docs.github.com/search-github/github-code-search/understanding-
github-code-search-syntax) .


[ ](https://github.com/)


[ Sign in
](/login?return_to=https%3A%2F%2Fgithub.com%2Fros2%2Frclpy%2Fissues%2F629)


Now, your parameters callback function looks good and you can update your
parameters in a safe way.


Repositories


Necessary


Explore


Ability to pass argument to ` Node.create_subscription ` method.


##  Stats


Follow


[ ![George V gravatar image](/m/default/media/images/nophoto.png?v=28)
](/users/98540/george-v/)


Hello, I face the same situation as [ @TheConstructAi
](https://github.com/TheConstructAi)


  * [ About ](https://www.minsung.org/about/)
  * [ Publications ](https://www.minsung.org/publications/)
  * [ Research & Robotics ](https://www.minsung.org/research-robotics/)
  * [ School ](https://www.minsung.org/school/)
  * [ Documentations ](https://www.minsung.org/documentations/)


Copy link


Necessary cookies are absolutely essential for the website to function
properly. These cookies ensure basic functionalities and security features of
the website, anonymously.  Cookie  |  Duration  |  Description
---|---|---
cookielawinfo-checkbox-analytics  |  11 months  |  This cookie is set by GDPR
Cookie Consent plugin. The cookie is used to store the user consent for the
cookies in the category "Analytics".
cookielawinfo-checkbox-functional  |  11 months  |  The cookie is set by GDPR
cookie consent to record the user consent for the cookies in the category
"Functional".
cookielawinfo-checkbox-necessary  |  11 months  |  This cookie is set by GDPR
Cookie Consent plugin. The cookies is used to store the user consent for the
cookies in the category "Necessary".
cookielawinfo-checkbox-others  |  11 months  |  This cookie is set by GDPR
Cookie Consent plugin. The cookie is used to store the user consent for the
cookies in the category "Other.
cookielawinfo-checkbox-performance  |  11 months  |  This cookie is set by
GDPR Cookie Consent plugin. The cookie is used to store the user consent for
the cookies in the category "Performance".
viewed_cookie_policy  |  11 months  |  The cookie is set by the GDPR Cookie
Consent plugin and is used to store whether or not user has consented to the
use of cookies. It does not store any personal data.

Functional


  * Tutorials
    * [ ROS ](https://roboticsbackend.com/category/ros/)
    * [ ROS2 ](https://roboticsbackend.com/category/ros2/)
    * [ Raspberry Pi ](https://roboticsbackend.com/category/raspberry-pi/)
    * [ Arduino ](https://roboticsbackend.com/category/arduino/)
  * [ Youtube ](https://www.youtube.com/channel/UCelRThOKlWMnpjqr5EBq6tg?sub_confirmation=1)
  * [ **Courses** ](https://roboticsbackend.com/courses/)
  * [ Contact ](https://roboticsbackend.com/contact/)


// Copyright 2016 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
class MinimalSubscriber : public rclcpp::Node
{
public:
  MinimalSubscriber()
  : Node("minimal_subscriber")
  {
    auto topic_callback =
      [this](std_msgs::msg::String::UniquePtr msg) -> void {
        RCLCPP_INFO(this->get_logger(), "I heard: '%s'", msg->data.c_str());
      };
    subscription_ =
      this->create_subscription<std_msgs::msg::String>("topic", 10, topic_callback);
  }
private:
  rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_;
};
int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<MinimalSubscriber>());
  rclcpp::shutdown();
  return 0;
}


On terminal 1, start the node.


#  Passing argument to Node.create_subscription method  #629


**
[ ROS2 For Beginners
Learn ROS2 in 1 Week ](https://rbcknd.com/ros2-for-beginners) **


##  2  Answers


* 👍  1 reaction


##  Comments


Hey, this is an odd thing with lambdas. Here's the fix:


###  What happens if you change a parameter with no callback


Search


[ ](https://github.com "GitHub") © 2024 GitHub, Inc.


edited


Sorry, something went wrong.


##  Add an rclpy parameter callback


    def camera_monitoring_thread(self):
        if self.restart_camera:
            self.get_logger().info("Restarting camera with port: " + str(self.camera_device_port_))
            self.restart_camera = False

    def parameters_callback(self, params):
        for param in params:
            if param.name == "camera_device_port":
                self.camera_device_port_ = param.value
                self.restart_camera = True
        return SetParametersResult(successful=True)


* 👍  3 reactions


Functional cookies help to perform certain functionalities like sharing the
content of the website on social media platforms, collect feedbacks, and other
third-party features.


We’ll start from this code.


Skip to content


[ ![@evan-
palmer](https://avatars.githubusercontent.com/u/75103118?s=80&u=33c66adb11b022d6d5cae7b7df7411c58bec1c68&v=4)
](/evan-palmer)


To:


Now, let’s test our callback. Open 2 terminals.


[
![@ArjunBalakrishnan](https://avatars.githubusercontent.com/u/15687079?s=80&u=0b8298f132e4daab8b5f5df1de3ba91e3c485695&v=4)
](/ArjunBalakrishnan)


What you’ll get is an array of rclpy Parameter objects. So, by using vars() on
each Parameter you’ll get all the info they contain.


[ ![The Robotics Back-End](https://roboticsbackend.com/wp-
content/uploads/2020/02/cropped-favicon_white-1.png)
](https://roboticsbackend.com/ "The Robotics Back-End")


Search or jump to...


#  ROS2 rclpy Parameter Callback [Tutorial]


Now, for any reason, if you want to remove the callback during the execution,
you can do so with `
self.remove_on_set_parameters_callback(self.parameters_callback) ` . After
that, if you modify a parameter outside the node, the node won’t be notified
anymore.


#  Provide feedback


Other uncategorized cookies are those that are being analyzed and have not
been classified into a category as yet.


Hi,


[ ninamwa ](/users/45886/ninamwa/)
81  ●  10  ●  13  ●  15


[ ROS2 Custom Messages Not Found ](/question/306568/ros2-custom-messages-not-
found/)


node.create_subscription(std_msgs.msg.String, "my_topic", lambda msg: common_callback(msg, other_args), 10)


Copy link


add a comment


Your email address will not be published.  Required fields are marked  *


_You want to learn ROS2 efficiently?_


###  Update class attributes in callback


Sorry, something went wrong.


**[ patrickwasp ](/patrickwasp) ** commented  Jan 22, 2023


self._send_goal_future.add_done_callback( lambda future: self.goal_response_callback(future, "close"))


##  Feature request


Others


[ ros2 ](/ros2) /  **[ rclpy ](/ros2/rclpy) ** Public


[ @TheConstructAi ](https://github.com/TheConstructAi) did you end up figuring
this out?

---

All reactions


Include my email address so I can be contacted


Here are all the available types for Parameters:


##  creating tomorrow | min sung ahn


[ ALL ](/questions/scope:all/sort:activity-desc/page:1/) [ UNANSWERED
](/questions/scope:unanswered/sort:answers-asc/page:1/)


###  Starter code


Already on GitHub? [ Sign in
](/login?return_to=%2Fros2%2Frclpy%2Fissues%2Fnew%2Fchoose) to your account


    * [ All features ](/features)
    * [ Documentation  ](https://docs.github.com)
    * [ GitHub Skills  ](https://skills.github.com/)
    * [ Blog  ](https://github.blog)


Name


[
![@apockill](https://avatars.githubusercontent.com/u/1740412?s=80&u=dbb3f1036aadaca3422451823493dbd6f4fdc157&v=4)
](/apockill)


    for i in range(self.fleet_robots_number):
                robot_name = self.fleet_name +"_"+str(i+1)
                docked_status_topic_name = robot_name+"/docked_status"

                qos_profile_subscriber = QoSProfile(depth=1)
                qos_profile_subscriber.durability = QoSDurabilityPolicy.TRANSIENT_LOCAL

                # Your own common callback
                self.get_logger().error("INIT Subscriber =="+str(docked_status_topic_name))
                self.create_subscription(   BoolRosMsg,
                                            docked_status_topic_name,
                                            lambda msg: self.dock_state_clb(msg, robot_name),
                                            qos_profile=qos_profile_subscriber)
                self.get_logger().error("INIT Subscriber =="+str(docked_status_topic_name)+"....DONE")

        def dock_state_clb(self, msg, in_robot_name):
            self.get_logger().error("Message in_robot_name=="+str(msg)+", from robot="+str(in_robot_name))

    Any ideas why? All the callback messages appear with the las `robot_name`used to initialise the subscribers.

---

👍  3  DSep, KiloNovemberDelta, and manye31 reacted with thumbs up emoji


Toggle navigation


[ ![@ramezanifar](https://avatars.githubusercontent.com/u/11685859?s=80&v=4)
](/ramezanifar)


    $ ros2 param set /test_params_callback_rclpy battery_percentage_warning 2
    Set parameter successful
    $ ros2 param set /test_params_callback_rclpy battery_percentage_warning 3.4
    Set parameter successful
    $ ros2 param set /test_params_callback_rclpy battery_percentage_warning "This is a string, won't work"
    Setting parameter failed


    $ ros2 param set /test_params_callback_rclpy battery_percentage_warning 20.3
    Set parameter successful


[ **answered 2020-03-16 11:58:19 -0500  ** ](/answers/346840/revisions/)


  * [ Engineering ](https://www.minsung.org/category/engineering/)
  * [ Korea ](https://www.minsung.org/category/korea/)
  * [ Linux ](https://www.minsung.org/category/linux/)
  * [ Misc. ](https://www.minsung.org/category/miscellaneous/)
  * [ Programming ](https://www.minsung.org/category/programming/)
  * [ Robotics ](https://www.minsung.org/category/robotics/)
  * [ ROS ](https://www.minsung.org/category/robotics/ros/)
  * [ Sports ](https://www.minsung.org/category/sports/)


* Product


##  Comments


    $ ros2 run my_py_pkg test_py_params_callback
    {'_type_': <Type.DOUBLE: 3>, '_name': 'battery_percentage_warning', '_value': 20.3}


* Open Source


sub  =  rospy  .  Subscriber  (  "topic_name"  ,  String  ,  callback  ,  (
arg1  ,  arg2  )  )

---|---

Of course, rather than a tuple, something like a single “String” could also be
passed directly.


[ New Behavior Tree Action Node not Initializing in ros-planning/navigation2
](/question/380946/new-behavior-tree-action-node-not-initializing-in-ros-
planningnavigation2/)


As you can see, when we send a value with a different type than integer or
double, we get “Setting parameter failed”. In this case, the parameter will
not be updated and the previous value remains.


[ edit ](/s/answers/396901/edit/) flag offensive  delete  [ link
](/question/346810/ros2-python-add-arguments-to-callback/?answer=396901#post-
id-396901 "permanent link") more


[ ![sloretz gravatar
image](/upfiles/avatars/sloretz/resized/32/exclamation_point_icon.png)
](/users/23470/sloretz/)


[ ![ROS2 For Beginners - Step by Step Course](https://roboticsbackend.com/wp-
content/plugins/wp-fastest-cache-premium/pro/images/blank.gif)
](https://rbcknd.com/ros2-for-beginners)


Let’s take a simple example: the camera_device_port. Let’s say you want to
switch to another camera from a different port, or you’ve simply
unplugged/plugged the camera again and the device name has changed from
“/dev/ttyACM0” to “/dev/ttyACM1”.


[ ![@apockill](https://avatars.githubusercontent.com/u/1740412?s=52&v=4)
](/apockill) [
![@ramezanifar](https://avatars.githubusercontent.com/u/11685859?s=52&v=4)
](/ramezanifar) [
![@ArjunBalakrishnan](https://avatars.githubusercontent.com/u/15687079?s=52&v=4)
](/ArjunBalakrishnan) [
![@ivanpauno](https://avatars.githubusercontent.com/u/26796393?s=52&v=4)
](/ivanpauno) [
![@KiloNovemberDelta](https://avatars.githubusercontent.com/u/41945728?s=52&v=4)
](/KiloNovemberDelta) [
![@patrickwasp](https://avatars.githubusercontent.com/u/70671760?s=52&v=4)
](/patrickwasp) [ ![@evan-
palmer](https://avatars.githubusercontent.com/u/75103118?s=52&v=4) ](/evan-
palmer) [
![@TheConstructAi](https://avatars.githubusercontent.com/u/80715513?s=52&v=4)
](/TheConstructAi)


**[ ramezanifar ](/ramezanifar) ** commented  Oct 10, 2020


Projects


###  Check the parameter’s type


Sorry, something went wrong.


Copy link


Password


Pick a username


[ Sign up
](/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-
name%3E%2F%3Crepo-
name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-
repo&source_repo=ros2%2Frclpy)


[ a callback function use itself ](/question/266387/a-callback-function-use-
itself/)


On terminal 1, start the node with [ ros2 run
](https://roboticsbackend.com/ros2-run-and-ros2-node-start-debug-ros2-nodes/)
.


edit


With the rclpy parameters callback functionality, you can also modify
dynamically any parameter while the node is alive, and get notified inside the
code.


  * camera_device_port (string)
  * simulation_mode (bool)
  * battery_percentage_warning (float, could also be int)


**[ ivanpauno ](/ivanpauno) ** commented  Nov 3, 2020


[ Hi there! Please sign in
](/account/signin/?next=/question/346810/ros2-python-add-arguments-to-
callback/) [ help ](/help/ "help")


[ Send an array or a list between nodes? ](/question/411851/send-an-array-or-
a-list-between-nodes/)


On terminal 2, change a parameter’s value.


You can easily check the type with the “type_” attribute, and compare it with
the type you want from the Parameter object. For example:
Parameter.Type.STRING.


None yet


[ about ](/about/) |  [ faq ](/faq/) |  [ help ](/help/ "help") |  [ privacy
policy ](/privacy/) |  [ terms of service ](/terms/)


Development


[ tags ](/tags/) [ users ](/users/) [ badges ](/badges/)


##  Process data inside the rclpy callback


First of all, we create a new method in our node class –
“parameters_callback”. This method will be used as the callback.


**[ ArjunBalakrishnan ](/ArjunBalakrishnan) ** commented  May 10, 2023


##  Use saved searches to filter your results more quickly


arg1  =  args  [  0  ]


  * [ Code  ](/ros2/rclpy)
  * [ Issues  ](/ros2/rclpy/issues)
  * [ Pull requests  ](/ros2/rclpy/pulls)
  * [ Actions  ](/ros2/rclpy/actions)
  * [ Security  ](/ros2/rclpy/security)
  * [ Insights  ](/ros2/rclpy/pulse)


Advertisement cookies are used to provide visitors with relevant ads and
marketing campaigns. These cookies track visitors across websites and collect
information to provide customized ads.


By clicking “Sign up for GitHub”, you agree to our [ terms of service
](https://docs.github.com/terms) and [ privacy statement
](https://docs.github.com/privacy) . We’ll occasionally send you account
related emails.


#  About the Author


And in your subscriber :


Clear


    import rclpy
    from rclpy.node import Node
    from rcl_interfaces.msg import SetParametersResult

    class TestParamsCallback(Node):

        def parameters_callback(self, params):
            # do some actions, validate parameters, update class attributes, etc.
            return SetParametersResult(successful=True)

        def __init__(self):
            super().__init__('test_params_callback_rclpy')
            self.declare_parameter('camera_device_port', '/dev/ttyACM0')
            self.declare_parameter('simulation_mode', False)
            self.declare_parameter('battery_percentage_warning', 15.0)

            self.camera_device_port_ = self.get_parameter('camera_device_port').value
            self.simulation_mode_ = self.get_parameter('simulation_mode').value
            self.battery_percentage_warning_ = self.get_parameter('battery_percentage_warning').value

            self.add_on_set_parameters_callback(self.parameters_callback)

    ...


Seen: **1,974 times**


Now, let’s make a small experiment. Open 2 terminals.


[ rosbag2 doesn't write meta data file ](/question/397687/rosbag2-doesnt-
write-meta-data-file/)


lambda msg=msg: self.dock_state_clb(msg, robot_name),


On terminal 2, modify a parameter.


###  Testing – get all modified params and print them


Analytical cookies are used to understand how visitors interact with the
website. These cookies help provide information on metrics the number of
visitors, bounce rate, traffic source, etc.


In ROS 1, I was able to pass arguments to the callback function of a
subscriber:
` rospy.Subscriber(topic_name, type, call_back, call_back_arg) `
This feature was great because I could define a single callback for multiple
topics (for example, in a for loop I want to create the subscribers in
masses). When the callback was invoked, based on the argument I knew which one
owned the message.
It looks like this option is missing in ROS2, ` Node.create_subscription `
function.
Can we have that?

---

The text was updated successfully, but these errors were encountered:


Copy link


Closed


Email Address


  * BOOL
  * BOOL_ARRAY
  * BYTE_ARRAY
  * DOUBLE
  * DOUBLE_ARRAY
  * INTEGER
  * INTEGER_ARRAY
  * STRING
  * STRING_ARRAY
  * NOT_SET (declared but undefined)


Posted in [ Robotics ](https://www.minsung.org/category/robotics/) , [ ROS
](https://www.minsung.org/category/robotics/ros/) [ Python
](https://www.minsung.org/tag/python/) [ ROS
](https://www.minsung.org/tag/ros/) [ rospy
](https://www.minsung.org/tag/rospy/)


[ ramezanifar ](/ramezanifar) opened this issue  Oct 10, 2020  · 9 comments


You won’t get any error by doing this. But if you change a parameter’s value
after it’s been read by the node, then the node won’t be able to know it if
you don’t notify it. Hence we need to add a callback to notify the node as
soon as the parameter has been modified.


* [ passArguments ](/questions/scope:all/sort:activity-desc/tags:passArguments/page:1/)


Cancel  Create saved search


And one important thing: as you are currently inside a callback, it is not a
good idea to spend too much time there. So, set a flag inside the callback,
and check for that flag in another thread, so you can execute the action and
not block the callback thread.


[ < Previous  Expanding VMware Player Disk Size for Ubuntu
](https://www.minsung.org/2018/07/expanding-vmware-player-disk-size-for-
ubuntu/)


[ ![ROS Answers logo](/m/ros/media/images/logoros.png?v=28) ](/questions/)


Performance cookies are used to understand and analyze the key performance
indexes of the website which helps in delivering a better user experience for
the visitors.


[ question  ](/ros2/rclpy/labels/question) Further information is requested


           lambda msg, in_robot_name=robot_name : self.dock_state_clb (msg, in_robot_name)

---

👍  1  jeffbfr reacted with thumbs up emoji


add a comment


Email  *


Hi there, my name is Min Sung Ahn and my colleagues refer to me as “Min”. I
run this blog from time to time, covering topics mostly in my field of
interest, i.e. robotics, AI, electronics, etc. You can find out more about me
at:
http://www.minsungahn.com


And finally, to register the callback, use the `
add_on_set_parameters_callback(callback) ` method directly on the node object,
using “self”.


No milestone


[ ![ninamwa gravatar image](/m/default/media/images/nophoto.png?v=28)
](/users/45886/ninamwa/) [ ninamwa ](/users/45886/ninamwa/) (  2020-03-17
04:43:16 -0500  )  edit


I think the problem is ` functools.partial ` is providing the first argument
instead of the second. Use keyword arguments to disambiguate.


Sorry, something went wrong.


Menu


#  Passing argument to Node.create_subscription method  #629


**[ Check out the course here ](https://rbcknd.com/ros2-for-beginners) **


Toggle


New issue


    >>> import functools
    >>> def my_func(result, type):
    ...    print(f'Got {result} and {type}')
    ...
    >>> my_func('foo', 'bar')
    Got foo and bar
    >>> functools.partial(my_func, 'close')('foo')
    Got close and foo
    >>> functools.partial(my_func, type='close')('foo')
    Got foo and close


    * [ Learning Pathways  ](https://resources.github.com/learn/pathways/)
    * [ White papers, Ebooks, Webinars  ](https://resources.github.com/)
    * [ Customer Stories ](/customer-stories)
    * [ Partners  ](https://partner.github.com/)


Member


Labels


Thank you, this worked exactly as I wanted! :-)


Even if you’ve checked the type, the value you receive might not be correct
for your application. For example, for the battery_percentage_warning_, you’d
expect to get a value between 0 and 100. If you receive 256.8 instead, well,
this is still a correct value because the type (double) is accepted.


    def parameters_callback(self, params):
        success = False
        for param in params:
            if param.name == "camera_device_port":
                if param.type_ == Parameter.Type.STRING:
                    if param.value.startswith('/dev/tty'):
                        success = True
                        self.camera_device_port_ = param.value
                        self.restart_camera = True
            if param.name == "battery_percentage_warning":
                if param.type_ in [Parameter.Type.DOUBLE, Parameter.Type.INTEGER]:
                    if param.value >= 0.0 and param.value < 100.0:
                        success = True
                        self.battery_percentage_warning_ = param.value
            if param.name == "simulation_mode":
                if param.type_ == Parameter.Type.BOOL:
                    success = True
                    self.simulation_mode_ = param.value
        return SetParametersResult(successful=success)


Website


[ ![ROS2 For Beginners - Step by Step Course](https://roboticsbackend.com/wp-
content/plugins/wp-fastest-cache-premium/pro/images/blank.gif)
](https://rbcknd.com/ros2-for-beginners)


Author


* [ The ReadME Project  GitHub community articles  ](/readme)


Thank you for your help, I tried your solution, however I got "NameError: name
'msg' is not defined".


After watching the video, [ subscribe to the Robotics Back-End Youtube channel
](https://www.youtube.com/c/RoboticsBackEnd?sub_confirmation=1) so you don’t
miss the next tutorials!


Table of Contents


**Want to learn how to program with ROS2?**


* [ ros2 ](/questions/scope:all/sort:activity-desc/tags:ros2/page:1/)


**Have a question about this project?** Sign up for a free GitHub account to
open an issue and contact its maintainers and the community.


All reactions


Assignees


  *[
              2020-03-16 08:05:40 -0500
             ]: 2020-03-16 08:05:40 -0500
  *[
              2020-03-16 11:58:19 -0500
             ]: 2020-03-16 11:58:19 -0500
  *[
             2020-03-17 04:43:16 -0500
            ]: 2020-03-17 04:43:16 -0500
  *[
              2022-03-01 08:13:41 -0500
             ]: 2022-03-01 08:13:41 -0500
  *[
        2020-03-16 08:05:40 -0500
       ]: 2020-03-16 08:05:40 -0500
  *[
        2024-04-14 16:33:27 -0500
       ]: 2024-04-14 16:33:27 -0500


[ sloretz ](/users/23470/sloretz/)
3061  ●  25  ●  86  ●  55


Performance


    node.create_subscription(std_msgs.msg.String, "my_topic", partial(my_callback, my_extra_args=other_args), 10)

---

👍  2  KiloNovemberDelta and joseantoniobecerrapermuy reacted with thumbs up
emoji


Using parameters in ROS2 is a great way to change a node’s configuration at
run time.


Great! Now we know what’s inside the parameters array. Here we have modified
only one param so we get only one.


###  Execute an action


[ ![ninamwa gravatar image](/m/default/media/images/nophoto.png?v=28)
](/users/45886/ninamwa/)


Here’s an example where we validate the type (and sometimes data) for each
parameter we’ve declared.


Copy link


Last updated: **Mar 16 '20**


    * [ Topics ](/topics)
    * [ Trending ](/trending)
    * [ Collections ](/collections)


Milestone


Do you thing that will work for you?

---

All reactions


Sorry, something went wrong.


##  Initialization


If you don't want to import 'functools' you can also do it with lambda
functions:


#  [ minsung.org ](https://www.minsung.org/)


###  Leave a Reply  [ Cancel reply ](/2018/07/passing-arguments-to-python-
callback-in-rospy-ros/#respond)


So, in the callback function, you’ll receive an array of all modified
parameters. You are then free to do anything you want from this information:
modify variables inside your code, do some actions, or even ignore the info.


[ subscribe to rss feed ](/feeds/question/346810/ "subscribe to the rss feed")


You can’t perform that action at this time.


Menu


* [ arguments ](/questions/scope:all/sort:activity-desc/tags:arguments/page:1/)


    * [ Actions  Automate any workflow  ](/features/actions)
    * [ Packages  Host and manage packages  ](/features/packages)
    * [ Security  Find and fix vulnerabilities  ](/features/security)
    * [ Codespaces  Instant dev environments  ](/features/codespaces)
    * [ Copilot  Write better code with AI  ](/features/copilot)
    * [ Code review  Manage code changes  ](/features/code-review)
    * [ Issues  Plan and track work  ](/features/issues)
    * [ Discussions  Collaborate outside of code  ](/features/discussions)


[ July 28, 2018  July 28, 2018  ](https://www.minsung.org/2018/07/passing-
arguments-to-python-callback-in-rospy-ros/) ~  [ Min Sung Ahn
](https://www.minsung.org/author/mshn/)


First time here? Check out the FAQ!


We use cookies on our website to give you the most relevant experience by
remembering your preferences and repeat visits. By clicking “Accept All”, you
consent to the use of ALL the cookies. However, you may visit "Cookie
Settings" to provide a controlled consent.


lambda msg: self.dock_state_clb(msg, robot_name),


* [ Pricing ](/pricing)


     def send_close_gripper_goal(self):
        goal_msg = CloseGripper.Goal()
        self.closegripper_action_client.wait_for_server()
        self._send_goal_future = self.closegripper_action_client.send_goal_async(goal_msg)
        self._send_goal_future.add_done_callback(partial(self.goal_response_callback,"close"))

    def goal_response_callback(self, future,type):
        goal_handle = future.result()
        if not goal_handle.accepted:
            self.get_logger().info('Goal rejected :(')
            return

        self.get_logger().info('Goal accepted :)')
        self._get_result_future = goal_handle.get_result_async()
        self._get_result_future.add_done_callback(self.get_result_callback(type))

    def get_result_callback(self,future,type):
        result = future.result().result
        if type == "open":
            GripperOpen = result.success
            GripperClose = not result.success
        if type == "close":
            GripperClose = result.success
            GripperOpen = not result.success
        print(GripperClose)
        print(GripperOpen)


#  Post navigation


[ ![ gravatar image]() ]() [ ]() (  2024-04-14 16:33:27 -0500  )  edit


Labels


[
![@ivanpauno](https://avatars.githubusercontent.com/u/26796393?s=40&u=8f754ac57482921ea34e7bc6fa3491a127814a74&v=4)
](/ivanpauno) [ ivanpauno ](/ivanpauno) closed this as [ completed
](/ros2/rclpy/issues?q=is%3Aissue+is%3Aclosed+archived%3Afalse+reason%3Acompleted)
Nov 3, 2020


arg2  =  args  [  1  ]


[ ![ROS2 For Beginners - Step by Step Course](https://roboticsbackend.com/wp-
content/uploads/2020/04/ROS2_for_beginners_step_by_step.jpg)
](https://rbcknd.com/ros2-for-beginners)


ROS Resources: [ Documentation ](http://wiki.ros.org/) | [ Support
](http://wiki.ros.org/Support) | [ Discussion Forum
](http://discourse.ros.org/) | [ Index ](http://index.ros.org/) | [ Service
Status ](http://status.ros.org/) | [ ros @ Robotics Stack Exchange
](https://robotics.stackexchange.com/questions/tagged/ros)
---

_Attention:_ Answers.ros.org is deprecated as of August the 11th, 2023. Please
visit [ robotics.stackexchange.com ](http://robotics.stackexchange.com) to ask
a new question. This site will remain online in read-only mode during the
transition and into the foreseeable future. Selected questions and answers
have been migrated, and redirects have been put in place to direct users to
the corresponding questions on Robotics Stack Exchange. Additional details are
[ available here ](https://discourse.ros.org/t/ros-and-gazebo-answers-
migration-to-robotics-stack-exchange-process/31494) .


  * Initialization
    * Starter code
    * What happens if you change a parameter with no callback
  * Add an rclpy parameter callback
    * The code
    * Testing – get all modified params and print them
    * Update class attributes in callback
    * Remove parameters callback
  * Process data inside the rclpy callback
    * Execute an action
    * Check the parameter’s type
    * Validate data
  * Conclusion – rclpy parameter callback


**[ evan-palmer ](/evan-palmer) ** commented  Mar 14, 2023


[ **asked 2020-03-16 08:05:40 -0500  ** ](/questions/346810/revisions/)


def  callback  (  data  ,  args  )  :


So, for some of your parameters you might add an additional step, specific to
your application.


Jump to bottom


Name  *


After you’ve processed the parameter array, you’ll have to return a
SetParameterResult message, containing a boolean flag. This will be up to you
to decide if things were successful or not. We’ll see more examples about that
later in this tutorial.


In this example we get a Parameter object with those attributes:


[ George V ](/users/98540/george-v/)
11  ●  2  ●  2


[
![@KiloNovemberDelta](https://avatars.githubusercontent.com/u/41945728?s=80&u=9f709bd44a972fa667e8064c427456c10ddfd2de&v=4)
](/KiloNovemberDelta)


###  Validate data


You can easily solve this using a lambda, the extra ` call_back_arg ` argument
in ros1 ` Subscriber ` doesn't seem to add much value:


    ...
    from rclpy.parameter import Parameter
    ...

    def parameters_callback(self, params):
        for param in params:
            if param.name == "battery_percentage_warning":
                if param.type_ in [Parameter.Type.DOUBLE, Parameter.Type.INTEGER]:
                    self.battery_percentage_warning_ = param.value
                else:
                    return SetParametersResult(successful=False)
        return SetParametersResult(successful=True)


#  Saved searches


Hi. I am using Python and ROS2 and I want to create two action clients: One
for opening a gripper and one for closing it. The goal_response_callback is
completely similar for both, and the result callback is very similar, it just
changes what parameter to set to true/false. Instead of having two
goal_callbacks and two result_callbacks, i was hoping to just give in an
argument saying if the goal was to open or close the gripper, but i can't seem
to find the correct way to use the callback together with an argument. I have
tried to just give the argument as normal
(self.goal_response_callback("open"), and as a partial function shown in the
code below. Nothing seems to work.


So in your case it would look like:


With those info you have everything you need to update your class attributes
and do some actions.


[ none ](/questions/scope:all/sort:activity-desc/tags:none/page:1/) ×


Cookie Settings  Accept All


And here you can see that if we don’t get a correct type, we return the result
“successful=False”. We only return “succcessful=True” if the type matches what
we expect.


[
![@ivanpauno](https://avatars.githubusercontent.com/u/26796393?s=80&u=8f754ac57482921ea34e7bc6fa3491a127814a74&v=4)
](/ivanpauno)


© 2024 The Robotics Back-End | [ Courses
](https://roboticsbackend.com/courses) | [ Privacy Policy
](https://roboticsbackend.com/privacy-policy/) | [ Contact
](https://roboticsbackend.com/contact/)


[ ![@ramezanifar](https://avatars.githubusercontent.com/u/11685859?s=80&v=4)
](/ramezanifar)


[ question  ](/ros2/rclpy/labels/question) Further information is requested


We set a default value for each parameter. So, if we don’t manually set a
value when we run the node (from the terminal or a [ launch file
](https://roboticsbackend.com/ros2-launch-file-example/) ), the params will
still be defined. After that we get the values for each parameter and we store
them inside some class attributes.


#  Categories


By Solution


[ ROS2 topic list only working once (or any other command)
](/question/354512/ros2-topic-list-only-working-once-or-any-other-command/)


Manage consent


In this tutorial I will show you how to implement a rclpy parameter callback,
and give you some best practices.


Awesome!
Thanks for the hint.

---

All reactions


In this example we’ve decided that we can accept both double and integer
numbers for the battery_percentage_warning_ attribute.


Analytics


* Solutions


##  Related questions


[ **answered 2022-03-01 08:13:41 -0500  ** ](/answers/396901/revisions/)


    * [ Enterprise ](/enterprise)
    * [ Teams ](/team)
    * [ Startups ](/enterprise/startups)
    * [ Education  ](https://education.github.com)


  * [ Terms ](https://docs.github.com/site-policy/github-terms/github-terms-of-service)
  * [ Privacy ](https://docs.github.com/site-policy/privacy-policies/github-privacy-statement)
  * [ Security ](/security)
  * [ Status ](https://www.githubstatus.com/)
  * [ Docs ](https://docs.github.com/)
  * [ Contact ](https://support.github.com?tags=dotcom-footer)
  * Manage cookies
  * Do not share my personal information


  * type_ (pay attention to the additional underscore)
  * name
  * value


Advertisement


Here’s what we’ve added:


Please note: ROS Answers requires javascript to work properly, please enable
javascript in your browser, [ here is how
](https://www.google.com/support/bin/answer.py?answer=23852)


self._send_goal_future.add_done_callback(partial(self.goal_response_callback, type="close"))


After starting a ROS2 node with some parameters, you want to be able to
dynamically change those parameters and get notified inside your code? Well,
the rclpy parameter callback is what you need to use. (if you were using ROS1
before, this is the same as dynamic_reconfigure, but better).


( [ rclcpp callback parameter version for Cpp
](https://roboticsbackend.com/ros2-rclcpp-parameter-callback/) )


No one assigned


All reactions


[ edit ](/s/answers/346840/edit/) flag offensive  delete  [ link
](/question/346810/ros2-python-add-arguments-to-callback/?answer=346840#post-
id-346840 "permanent link") more


    # Terminal 2
    $ ros2 param list
    /test_params_callback_rclpy:
      battery_percentage_warning
      camera_device_port
      simulation_mode
      use_sim_time
    $ ros2 param set /test_params_callback_rclpy battery_percentage_warning 20.3
    Set parameter successful
    $ ros2 param get /test_params_callback_rclpy battery_percentage_warning
    Double value is: 20.3


Let’s add an rclpy parameter callback in our node.


Always Enabled


Here we declare 3 parameters:


8 participants


|  [ Ask Your Question ](/questions/ask/)
---|---|---|---

0


Change


[ Search syntax tips ](https://docs.github.com/search-github/github-code-
search/understanding-github-code-search-syntax)


Query


Member


Closed


You signed in with another tab or window. [ Reload ]() to refresh your
session.  You signed out in another tab or window. [ Reload ]() to refresh
your session.  You switched accounts on another tab or window. [ Reload ]() to
refresh your session.  Dismiss alert


[ How to pass argument values from launch file to python script?
](/question/366071/how-to-pass-argument-values-from-launch-file-to-python-
script/)


Performance


  * [ Code  ](/ros2/rclpy)
  * [ Issues  99  ](/ros2/rclpy/issues)
  * [ Pull requests  33  ](/ros2/rclpy/pulls)
  * [ Actions  ](/ros2/rclpy/actions)
  * [ Security  ](/ros2/rclpy/security)
  * [ Insights  ](/ros2/rclpy/pulse)


* [ GitHub Sponsors  Fund open source developers  ](/sponsors)


Anyone who can tell me the best way to do this? Thanks!


[ ![The Robotics Back-End](https://roboticsbackend.com/wp-
content/uploads/2020/02/favicon_white.png) ](https://roboticsbackend.com/ "The
Robotics Back-End")


* 👍  2 reactions


###  Remove parameters callback


Here is what you’ll see on terminal 1:


**[ TheConstructAi ](/TheConstructAi) ** commented  Sep 28, 2022


First, make sure you know how to [ create an rclpy Node
](https://roboticsbackend.com/write-minimal-ros2-python-node/) and [ how to
declare and get parameters with rclpy ](https://roboticsbackend.com/rclpy-
params-tutorial-get-set-ros2-params-with-python/) .


Analytics


Copy link


** >> Watch this video as an additional resource to this article: **


Make sure to validate both the type and the value from any parameter before
you modify a variable or class attribute. Also, if you need to execute an
action after a parameter has been updated, do the action in a different thread
so the callback can exit quickly.


![MCAP vs ROS 1 Bag Index Performance](/images/blog/mcap-vs-ros1-bag-index-
performance/hero.jpeg)


[ ![Introducing Foxglove Studio’s New Image Panel](/images/blog/introducing-
foxglove-studios-new-image-panel/hero.jpeg) ](/blog/introducing-foxglove-
studios-new-image-panel)


Use 2D annotations and 3D markers to add context to your camera images


##  Resource lookup


    $ rosbag info small.bag
        path:     	small.bag
        version:  	2.0
        duration: 	7.8s
        start:    	Mar 21 2017 19:26:20.10 (1490149580.10)
        end:      	Mar 21 2017 19:26:27.88 (1490149587.88)
        size:     	67.1 MB
        messages: 	1606
        compression:  lz4 [79/79 chunks; 56.23%]
        uncompressed: 119.1 MB @ 15.3 MB/s
        compressed:	67.0 MB @  8.6 MB/s (56.23%)
        types:    	diagnostic_msgs/DiagnosticArray [60810da900de1dd6ddd437c3503511da]
                    radar_driver/RadarTracks    	[6a2de2f790cb8bb0e149d45d297462f8]
                    sensor_msgs/CompressedImage 	[8f7a12909da2c9d3332d540a0977563f]
                    sensor_msgs/PointCloud2     	[1158d486dd51d683ce2f1be655c3c181]
                    sensor_msgs/Range           	[c005c34273dc426c67a020a87bc24148]
                    tf2_msgs/TFMessage          	[94810edda583a504dfda3829e70d7eec]
        topics:   	/diagnostics           	52 msgs	: diagnostic_msgs/DiagnosticArray
                    /image_color/compressed   234 msgs	: sensor_msgs/CompressedImage
                    /radar/points         	156 msgs	: sensor_msgs/PointCloud2
                    /radar/range          	156 msgs	: sensor_msgs/Range
                    /radar/tracks         	156 msgs	: radar_driver/RadarTracks
                    /tf                   	774 msgs	: tf2_msgs/TFMessage
                    /velodyne_points       	78 msgs	: sensor_msgs/PointCloud2


Industries
Pricing
Company
Resources
Login
Start free trial


![](https://assets-global.website-
files.com/6374d6bce94f940eedba934e/65fe6bf941e900427da7d723_grey%20arrow.svg)


This problem with ` rosbag ` cannot easily be fixed. Solving ` rosbag info `
performance would not be technically difficult, but it would require a
breaking change: dropping compression statistics from the printed output.
Since these statistics are quite useful, this is not so easy. An opt-in flag
(i.e “--fast”) could be supported without much trouble, but introducing such
functionality as a non-default behavior would still leave many consumers
impacted.


It was developed by our friends at Foxglove with input from the robotics community to address the shortcomings of existing formats like ROS bags.


##  Never worry about your infra again.


[ Schedule a demo ]()


Â© 2024 Model-Prime


In ROS 1 node names are unique and this is being enforced by shutting down
existing nodes when a new node with the same name is started. In ROS 2 the
uniqueness of node names is not yet enforced.


In MCAP, all the data required to summarize the file is present in the summary
section, and visiting the data section is never necessary. The ` mcap info `
command requires only two seeks: first to the footer, and then to the summary
start. After seeking to the summary start, it reads to the end of the file and
transforms the summary section into the output that it prints.


There are a couple notable changes to tooling between ROS 1 and ROS 2:


If you have any questions about MCAP, or need support adopting it for your
robotics development workflows, feel free to join our community Slack or
contact us directly for help.


In ROS 1 the build tool generates scripts which must be sourced in order to
setup the environment before being able to use the built ROS packages. This
approach only works when the ROS packages are being built with ROS specific
build tool.


In ROS 1 a package with Python code can only use a small subset of the
features available in setup.py files since the setup.py file is being
processed by custom logic from within CMake. In ROS 2 a Python package can use
anything in setup.py files, e.g. entry points since they are being invoked
with ` python3 setup.py install ` .


##  Messages, Services


visualization


In ROS 2 resources can be registered at an index at compile time and then be
queried efficiently at runtime. For more information please see the
documentation of the [ resource index
](https://github.com/ament/ament_cmake/blob/master/ament_cmake_core/doc/resource_index.md)
.


In ROS 1 .msg and .srv files can have the same name but the generated code
collides. The same is the case for the request and response parts of services.


No more writing scripts to extract point cloud files and images from your recordings: just upload your MCAP files to a cloud bucket and let us do the heavy lifting. If your MCAP file can be visualized in Foxglove, we should be able to import it too.


[ All blog posts ](/blog)


Currently ROS 2 does not support namespaces in topic names. This is mostly due
to restrictions of valid characters in DDS topic names. A [ design document
](http://design.ros2.org/articles/topic_and_service_names.html) describes how
this should be added in the future.


The summation of the features above, along with the use of DDS, allows ROS 2
to be superior at real-time processing, especially when deterministic, low-
latency communication is needed.


Except where otherwise noted, these design documents are licensed under [
Creative Commons Attribution 3.0
](http://creativecommons.org/licenses/by/3.0/) .


###  Get in touch


    $ time mcap info small.mcap > /dev/null
        real	0m0.011s
        user	0m0.006s
        sys 	0m0.000s

    $ time mcap info large.mcap > /dev/null
        real	0m0.013s
        user	0m0.016s
        sys 	0m0.000s


ROS 2 currently doesn’t have the concept of actions. It will be added in the
future as a combination of a preemptable server and a feedback publisher.


####  Python


####  C++ standard


This article provides an overview about the changes being made in ROS 2
compared to ROS 1.


###  No non-isolated build


[ Privacy policy ](/privacy-policy)


Here, the differences explode to factors of **54x** and **4458x** . The `
rosbag info ` command is slow enough to be unusable over NFS, for both large
and small files.


For more information please see the [ parameter design
](http://design.ros2.org/articles/ros_parameters.html) article.


Some of the described features are not yet available and are marked with ⏳.


Skip to content
Segments.ai Logo
Solutions


Solutions
Pricing
Contact us
Terms, conditions and data processing
Privacy Policy
My rights
My Privacy Choices
ISO Certified


If you're a new ROS user and looking to choose a data recording format, we
recommend adopting ROS 2 to take advantage of MCAP’s performance. [ MCAP is
the default recording format for ROS 2 ](/blog/mcap-as-the-ros2-default-bag-
format) , has superior summarization and SDK performance, and will receive
more community development attention going forward.


hello@segments.ai


2. _Published by Northern Robotics Laboratory at Université Laval as` TeachA.bag ` : [ https://doi.org/10.55417/fr.2022050 ](https://doi.org/10.55417/fr.2022050) _ ↩


[ ](https://twitter.com/ModelDashPrime) [
](https://www.linkedin.com/company/modelprime/about/)


###  Remove sequence field from Header message


###  Read more:


Email address


src/rosbags	Add bag merging and msgdef migration
4 days ago
tests	Add bag merging and msgdef migration
4 days ago
tools	Increase minimum required Python version to 3.10
4 days ago
.gitignore	Update tooling
2 months ago
.gitlab-ci.yml	Run tests on all supported Python versions
4 days ago
CHANGES.rst	Release 0.10.0
4 days ago
CONTRIBUTING.rst	Add boilerplate
2 years ago
LICENSE.txt	Update tooling
2 months ago
README.rst	Refactor serde and typesys to use explicit stores
1 month ago
pyproject.toml	Add bag merging and msgdef migration
4 days ago
requirements-dev.txt	Update requirements
4 days ago
requirements.txt	Update requirements
4 days ago
 README.rst
pipeline status coverage report python versions PyPI - Downloads
Rosbags
Rosbags is the pure python library for everything rosbag. It contains:
highlevel easy-to-use interfaces,
rosbag2 reader and writer,
rosbag1 reader and writer,
extensible type system with serializers and deserializers,
efficient converter between rosbag1 and rosbag2,
and more.
Rosbags does not have any dependencies on the ROS software stacks and can be used on its own or alongside ROS1 or ROS2.
Rosbags was developed for MARV, which requires a fast, correct, and flexible library to read, manipulate, and write the various rosbag file formats.
Getting started
Rosbags is published on PyPI and does not have any special dependencies. Simply install with pip:
pip install rosbags
Read and deserialize messages from rosbag1 or rosbag2 files:
from pathlib import Path
from rosbags.highlevel import AnyReader
from rosbags.typesys import Stores, get_typestore
bagpath = Path('/home/ros/rosbag_2020_03_24')
# Create a type store to use if the bag has no message definitions.
typestore = get_typestore(Stores.ROS2_FOXY)
# Create reader instance and open for reading.
with AnyReader([bagpath], default_typestore=typestore) as reader:
    connections = [x for x in reader.connections if x.topic == '/imu_raw/Imu']
    for connection, timestamp, rawdata in reader.messages(connections=connections):
         msg = reader.deserialize(rawdata, connection.msgtype)
         print(msg.header.frame_id)
Convert between rosbag versions:
# Convert "foo.bag", result will be "foo/"
rosbags-convert foo.bag
# Convert "bar", result will be "bar.bag"
rosbags-convert bar
# Convert "foo.bag", save the result as "bar"
rosbags-convert foo.bag --dst /path/to/bar
# Convert "bar", save the result as "foo.bag"
rosbags-convert bar --dst /path/to/foo.bag


ROS bags and MCAP files may range from megabytes to hundreds of gigabytes or
larger in size. Reading them off disk or across a network can be prohibitively
expensive, especially if the goal is just to get a high-level summary of their
contents.


  * [ Catkin ](http://wiki.ros.org/catkin) is gone, replaced with [ Ament ](https://docs.ros.org/en/foxy/Concepts/About-Build-System.html) as a build system
  * [ Overlays ](https://docs.ros.org/en/foxy/Tutorials/Beginner-Client-Libraries/Creating-A-Workspace/Creating-A-Workspace.html) allow you to have a secondary workspace that doesnât affect your primary workspace â this is helpful when you want to experiment with new packages without affecting your base configuration (called an âunderlayâ).


##  Eliminating the problem with MCAP


####  Allow multiple nodes per process


Documentation
Read the documentation for further information.
Contributing
Thank you for considering to contribute to rosbags.
To submit issues or create merge requests please follow the instructions provided in the contribution guide.
By contributing to rosbags you accept and agree to the terms and conditions laid out in there.
Development
Clone the repository and setup your local checkout:
git clone https://gitlab.com/ternaris/rosbags.git
cd rosbags
python -m venv venv
. venv/bin/activate
pip install -r requirements-dev.txt
pip install -e .
This creates a new virtual environment with the necessary python dependencies and installs rosbags in editable mode. The rosbags code base uses pytest as its test runner, run the test suite by simply invoking:
pytest
To build the documentation from its source run sphinx-build:
sphinx-build -a docs public
The entry point to the local documentation build should be available under public/index.html.
Support
Professional support is available from Ternaris.


##  ROS 1 vs ROS 2 The Major Differences


Every ROS package is a CMake project. In ROS 2 other build systems can be
easily supported. For now the build tool supports plain Python packages beside
CMake.


read


Authors: [ Dirk Thomas ](https://github.com/dirk-thomas)


For more information about the build system please see the [ ament
](http://design.ros2.org/articles/ament.html) article.


  * [ Community ](/community)
  * [ Newsletter ](/newsletter)
  * [ Schedule a demo ](/demo)
  * [ Contact us ](/contact)


ROS 2 allows for data flow configuration, affecting how data is sent and
received. This includes settings for message reliability, deadline, and
priority, which can ensure that critical messages are delivered on time.Â


[ Robotics Back-End Article.Â ](https://roboticsbackend.com/ros1-vs-
ros2-practical-overview/) [ â ](https://medium.com/@oelmofty/ros2-how-is-it-
better-than-ros1-881632e1979a)


ROS 2 is not backward compatible with ROS 1. Consequently, ROS 1 packages will
likely not work with ROS 2 and would require rework, and other software
youâre accustomed to using with ROS 1 may no longer work. While currently a
major limitation, tools like [ ROSbridge
](http://wiki.ros.org/rosbridge_suite) are enabling improvements.


â


ROS 1 uses a custom serialization format, a custom transport protocol as well
as a custom central discovery mechanism. ROS 2 has an [ abstract middleware
interface ](http://design.ros2.org/articles/ros_middleware_interface.html) ,
through which serialization, transport, and discovery is being provided.
Currently all implementations of this interface are based on the DDS standard.
This enables ROS 2 to provide various [ Quality of Service policies
](http://design.ros2.org/articles/qos.html) which improve communication over
different networks.


In ROS 1 only packages with a manifest file are considered by the build
system. In ROS 2 it is possible to detect packages with supported build system
in folders without a manifest file. If the package follows common practice it
might even be possible to detect some of the missing meta information (like
dependencies).


What is MCAP?
MCAP (short for “message capture”, pronounced “em-cap”) is an open-source container file format optimized for storing timestamped data from multiple sensors (lidar, radar, camera, GPS/IMU, …) and data streams (calibration data, sensor metadata, object detections, …).


  * [ Security ](/security)
  * [ Privacy ](/legal/privacy)
  * [ Terms of Service ](/legal/terms)


ROS 1 uses the ROS Master-Slave Architecture and the XML-RPC middleware. ROS 2
uses Data Distribution Service (DDS), which is designed to provide higher
efficiency and reliability, low latency, and scalability, as well as
configurable quality of service (QoS) parameters. XML-RPC is better for simple
remote procedure calls, while DDSâs added complexity allows it to better
support real-time systems. Because of its distributed nature, DDS also helps
remove communications single-points-of-failure from ROS 2 systems.Â


    $ time rosbag info small.bag > /dev/null
        real	0m0.244s
        user	0m0.105s
        sys 	0m0.042s

    $ time rosbag info large.bag > /dev/null
        real	0m0.547s
        user	0m0.384s
        sys 	0m0.066s


##  Preface


In ROS 2 the generated code uses separate namespaces to guarantee it is
collision-free.


###  C++


In ROS 1 the API’s for nodes and nodelets are different and requires the
developer to decide the mapping of nodes to processes at programming time. In
ROS 2 it is recommended to compile each component into a shared library which
can then be loaded in a separate process or share the same process with other
components (like ROS 1 nodelets). This enables to choose the process layout at
deploy-time.


###  Separated namespaces in C++


Get notified about product updates


ROS 2 is currently being CI tested and supported on Ubuntu Xenial, OS X El
Capitan as well as Windows 10 (see [ ci.ros2.org ](http://ci.ros2.org/) ).


**Sources/Further Reading:** [ **â** ](https://wiki.ros.org/noetic)


In ROS 1 it is not possible to create more than one node in a process. This is
due to the API itself but also because of internal implementation decisions.
In ROS 2 it it possible to create multiple nodes in a process.


In ROS 1 packages can be built without installing them. From the devel space
in combination with the source space the system is already usable. But every
package has to actively support the devel space, e.g. in environment hooks and
CMake code.


© Copyright 2019 – 2024 | Segments.ai All Rights Reserved | Multi-sensor labeling platform for robotics and automotive


Email address


##  Closing advice


â


![Esther Weon](/images/blog/authors/estherweon.webp) Esther Weon  Esther Weon


[ ![Foxglove](/images/logo-white.svg) ](/)


ROS 1 was primarily built for Ubuntu. [ ROS 2 runs on MacOS, Windows, Ubuntu
](https://www.ros.org/reps/rep-2000.html#targeted-platforms) , and other
operating systems.Â


Segments.ai adds MCAP support
At Segments.ai, we’re always looking for ways to make it easier for our automotive and robotics customers to label their multi-sensor data. That’s why we’re excited to announce that we’re adding support for uploading your data in the MCAP format. This functionality is still in beta, so please contact us if you want to try it out.


Comparing performance across indexes, remote storage, and summarization


[ MCAP ](https://mcap.dev/) and [ ROS 1 bag
](http://wiki.ros.org/Bags/Format/2.0) are two broadly-comparable file formats
for recording robotics data. Both formats specify a chunked container
structure that supports heterogeneously-typed messages and includes a trailing
index section to enable summarization.


Type your email*


Last Modified: 2017-06


Whitepaper  Lorem ipsum dolor amet.  [ Case Studies  Lorem ipsum dolor amet.
](/case-study)


We believe MCAP has the potential to become a standardized format and to greatly streamline data management across the industry. Supporting it is part of our commitment to provide the best tools for working with robotics and autonomous vehicle data.


Operating systems mitigate these effects by performing reads through a page
cache. If a page is cached, it can be read from memory instead of from disk.
However, pages are not cached when reading a file for the first time – in that
scenario, disk IO will be required for every read.


Made with  by [ Foxglove ](/about)


  * [ About ](/about)
  * [ Blog ](/blog)
  * [ Careers ](/careers)
  * [ Customers ](/customers)
  * [ Media ](/media)


Schedule a demo


In ROS 2 the environment setup is separated into package-specific scripts and
workspace-specific scripts. Each package provides the necessary scripts to
make itself usable after being built. The build tool only invokes the
workspace-specific scripts which then call the package-specific scripts.


ROS2 rosbags allow for more flexibility with regard to serialization as
compared to ROS 1, which uses its own serialization format. The biggest impact
of changes to the rosbag format from ROS 1 to ROS 2 is potential
incompatibility of ROS 1 bag tooling with ROS 2 rosbags and subsequent impacts
to developer workflows.


Skip to content
GitLab
Why GitLab
Pricing
Contact Sales
Explore
Sign in
Primary navigation
 Search or go to…
Project
R
rosbags
Manage
Plan
Code
Build
Deploy
Operate
Monitor
Analyze
Ternaris
rosbags
R
rosbags
Project ID: 26685855
Project information
Pure Python library to read, modify, convert, and write rosbag files.
cdr
conversion
idl
+ 12 more
169
 Commits
1
 Branch
25
 Tags
README
Apache License 2.0
CHANGELOG
CONTRIBUTING
GitLab Pages
Created on
May 16, 2021
rosbags
user avatar
Release 0.10.0
Marko Durkovic authored 4 days ago
cc620697
Name	Last commit	Last update
.github	Add README for GitHub
1 month ago
.gitlab/issue_templates	Add issue template
2 years ago
.reuse	Add README for GitHub
1 month ago
LICENSES	Update tooling
2 months ago
docs	Refactor serde and typesys to use explicit stores
1 month ago


ROS 1 has two separate libraries - roscpp for C++ and rospy for Python - that
are not at feature parity with each other. In contrast, ROS 2 has a base
library written in C - rcl (ROS client library) - with libraries built on top
of it. This ensures that core functionality is available in different APIs
sooner. This is one of the key reasons that ROS 2 is able to offer more
language support than just Python and C++, such as Java and C#.Â


[ Get started for free ](https://app.foxglove.dev/signup)


###  Architecture


Excitingly, the ROS 2 community has decided to adopt MCAP as the default bag format, starting with the ROS 2 Iron Irwini release in May 2023. This means you can now natively record to MCAP in ROS 2 and leverage its benefits out of the box.


Thank you! Your submission has been received!


![seek calls per chunks in file](/images/blog/mcap-vs-ros1-bag-index-
performance/graph.jpeg)


[ ROS 2 WikiÂ ](https://docs.ros.org/en/rolling/index.html) [ â
](https://roboticsbackend.com/ros1-vs-ros2-practical-overview/)


#####  Reach us


###  Languages


1. _Derived from` NOISY_cut_off_2.bag ` published by Udacity as part of [ its Didi competition ](https://github.com/udacity/didi-competition) _ ↩


In ROS 1 global parameters and node-specific dynamic reconfigure parameters
are two separate concepts. In ROS 2 a unified approach is being used. It is
similar to dynamic reconfigure and a node named “global parameter server” (⏳)
will accept requests to set values unconditionally. In ROS 1 all this
information needs to be polled for changes in ROS 2 changes will be published
to notify other entities.


[ Product ](/product) [ Blog ](/blog) [ Customers ](/customers) [ Pricing
](/pricing) [ Docs ](https://docs.foxglove.dev) [ Download
](https://foxglove.dev/download) [ Sign in ](https://app.foxglove.dev/signin)
[ Get started ](https://app.foxglove.dev/signup)


ROS 1 is targeting Python 2. ROS 2 requires at least Python version 3.5.


[ View Source ](https://github.com/ros2/design/blob/gh-
pages/articles/changes.md) [ Edit in Github
](https://github.com/ros2/design/edit/gh-pages/articles/changes.md)


Toggle navigation  [ ROS 2 Design ](/)


So why does ` rosbag ` need to do so many seeks? Let’s inspect the ` rosbag
info ` output for ` small.bag ` :


[ Share on Twitter
](https://twitter.com/intent/tweet?text=MCAP%20vs%20ROS%201%20Bag%20Index%20Performance%3A%20https%3A%2F%2Ffoxglove.dev%2Fblog%2Fmcap-
vs-ros1-bag-index-performance%20%40foxglove) [ Share on LinkedIn
](http://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ffoxglove.dev%2Fblog%2Fmcap-
vs-ros1-bag-index-performance)


###  Minimal support for packages without manifest


In ROS 2 these types are defined as messages and therefore are consistent
across languages.


References
https://mcap.dev
https://foxglove.dev/blog/introducing-the-mcap-file-format
https://foxglove.dev/blog/mcap-as-the-ros2-default-bag-format
Share this article
Related Posts
Software Tools For Robotics Landscape (2024)
Software Tools For Robotics Landscape (2024)
March 21st, 2024
The 8 Best Point Cloud Labeling Tools for 2024
The 8 Best Point Cloud Labeling Tools for 2024
February 23rd, 2024


Contributors


###  Support catkin_simple use case


In ROS 1 multiple packages can be built in a single CMake context. While this
speeds up the build step, every package needs to ensure that cross package
target dependencies are defined correctly. Additionally all packages share the
same namespace which leads to colliding target names, etc.


###  C and C++


[ Login disabled for now ]()


article


Fast remote summarization was one of MCAP’s design goals.


  * ` small.bag ` 1
    * 67.1 MB in size
    * 79 chunks, 7 topics
    * 1606 messages
  * ` large.bag ` 2
    * 15.7 GB in size
    * 9855 chunks, 58 topics
    * 5304180 messages


Let’s compare the performance of ` rosbag info ` and ` mcap info ` when
reading from local disk vs. over NFS. We’ll use the following bag files for
our comparison:


[ Introducing Foxglove Studio’s New Image Panel  ](/blog/introducing-foxglove-
studios-new-image-panel)


####  Parameters and Dynamic Reconfigure


##  Tools


8 min  read


Bag files and MCAP files are often accessed over remote connections - e.g.
sharing recordings with a Network File System (NFS) file share or an Amazon S3
bucket.


tutorial


Let’s focus on the ` compression ` , ` uncompressed ` , and ` compressed `
lines. Like MCAP, the bag format uses a two-layer index structure in which the
bottom of the file contains an index of chunks, and each chunk is followed by
an index of messages within it. But unlike MCAP, the [ Chunk Info
](http://wiki.ros.org/Bags/Format/2.0#Chunk_info) records that make up the
chunk index [ ](https://mcap.dev/spec#chunk-index-op0x08) contain no
information about compression algorithms or compressed/uncompressed sizes.


For another view, let’s compare seek calls for ` rosbag info ` vs ` mcap info
` as a function of number of chunks in the file.


Open menu


###  Accelerate your Robotics Development


This is necessary in order to calculate the maximum size of a message in
memory, which allows for preallocation of messages with a dynamic sizes. This
is useful for performance and for use cases like real-time.


Consequently, ` mcap info ` ’s performance is largely disconnected from the
size of the file or the number of chunks. While the volume of data read is
still linear with respect to the number of chunks, since there is one [ Chunk
Index ](https://mcap.dev/spec#chunk-index-op0x08) record in the summary
section per chunk, the contribution of each chunk to the summary section size
is negligible. For example, the summary section of ` large.mcap ` , a 12GB
file, is only 820 kB.


###  Company


In ROS 1 every node usually has its own main function. In ROS 2 it is
recommended to subclass from a component which has a life cycle.


Product


The ` rosbag info ` and ` mcap info ` commands allow you to quickly summarize
the contents of a ROS bag or MCAP file, including:


Excessive seeking and reading from different locations on disk is generally
harmful for IO performance:


March 28, 2023


In ROS 1 roslaunch files are defined in XML with very limited capabilities. In
ROS 2 launch file are written in Python which enables to use more complex
logic like conditionals etc. The current state only provides minimal
functionality to run tests using multiple processes.


##  Comparing summarization performance over remote connections


The life cycle can be used by tools like roslaunch to start a system composed
of many components in a deterministic way (⏳).


###  ABI versioning (⏳)


**Changes to the ROS API**


In ROS 1 the package catkin_simple is aiming to make writing the CMake code of
ROS packages easier. In many cases it is not achieving this goal which is
often due to restrictions of the design necessary for support features like
the devel space.


[ ![](https://assets-global.website-
files.com/6374d6bce94f940eedba934e/660a37354810c2bdac1bc267_x-logo.svg)
](https://twitter.com/ModelDashPrime) [ ![](https://assets-global.website-
files.com/6374d6bce94f940eedba934e/660a360e318bdc118b3d3645_linkedin-icon.svg)
](https://www.linkedin.com/company/modelprime/)


##  Footnotes


[ Product ](/product) [ Blog ](/blog) [ Customers ](/customers) [ Pricing
](/pricing) [ Docs ](https://docs.foxglove.dev) [ Download
](https://foxglove.dev/download) [ Sign in ](https://app.foxglove.dev/signin)
[ Get started ](https://app.foxglove.dev/signup)


Get blog posts sent directly to your inbox.


**Real-Time Processing**


articles/changes.md


In ROS 1 various resources (packages, messages, plugins, etc.) are looked up
by crawling the file system based on the ROS_PACKAGE_PATH. This can cause poor
performance when the trees in the ROS_PACKAGE_PATH are large, and caching
produces inconsistent state.


##  Build system


For more information please see the [ node life cycle
](http://design.ros2.org/articles/node_lifecycle.html) article.


Subscribe


###  No devel space


[ Please Login to View Pull Requests
](https://github.com/login/oauth/authorize?client_id=efa6dd8eae9106381720)


In this post, we’ll highlight a less-publicized feature of MCAP over bag
files: improvements in the index structure that enable faster summarization
over remote connections or slow storage devices.


Why MCAP?
MCAP provides several advantages over existing robotics data formats:


  * [ Download ](/download)
  * [ Documentation ](/docs)
  * [ Tutorials ](/tutorials)
  * [ ROS visualization ](/ros)
  * [ Rosbridge ](/rosbridge)
  * [ URDF visualization ](/urdf)


![Esther Weon](/images/blog/authors/estherweon.webp) Esther Weon  ·


#  Changes between ROS 1 and ROS 2


© Open Source Robotics Foundation, Inc.


####  Topic namespaces (⏳)


ROS


Documentation


    $ strace -c -U calls rosbag info large.bag 2>&1 1>/dev/null
            calls syscall
        --------- ----------------
            40217 lseek
            11540 read
        <snip>
        --------- ----------------
            56284 total

    $ strace -c -U calls mcap info large.mcap 2>&1 1>/dev/null
            calls syscall
        --------- ------------------
            183 read
                7 close
                6 fstat
                2 lseek
        <snip>
        --------- ------------------
            518 total


Going off the wall clock execution times reported ( ` real ` in the output),
we can see that the ` mcap info ` command executes 22x and 42x faster than the
` rosbag info ` command. In fact, the MCAP timings are so low that they can be
considered mostly noise.


Each change is described as briefly as possible but giving enough context and
rationale for a reader familiar with ROS 1. If further external information is
available (e.g. other articles) it should be linked to.


In ROS 2 the CMake API was restructured to support this use case.


â **â**


Subscribe


###  The ROS 1 vs ROS 2 Decision Horizon


However, swapping out recording formats on an existing system may be easier
said than done. For users unable to switch and struggling with IO performance,
consider using ` skip_index: True ` in your bag processing scripts. This will
bring the cost of opening bags in line with what you get from ` rosbag info `
– not ideal, but better than the default behavior of the Bag constructor.


In ROS 2 a package must be installed after building it before it can be used.


![](https://assets-global.website-
files.com/6374d6bde94f94030dba937c/642340726de059d158005f4f_DALL%C2%B7E%202023-02-22%2018.48.10%20-%20an%20older%20robot%20fighting%20a%20younger%20robot%20.png)


* [ Contribute ](/contribute.html)


We see that the number of disk seeks executed by ` rosbag info ` grows
linearly in proportion to the number of chunks in the bag file. Meanwhile, the
number of seeks executed by ` mcap info ` appears constant.


###  Optional upper bounds for arrays and strings


Published  June 20, 2023


Many robotics organizations face a decision regarding if or when they should
transition to ROS 2 from ROS 1. There isnât a lot of content that discusses
the major differences between the two versions. You can reference the official
[ ROS 2 design page on the topic;
](http://design.ros2.org/articles/changes.html#:~:text=In%20ROS%201%20the%20developer,haven't%20been%20implemented%20yet.)
Â however, we work to frame some of these differences in the context of what
they mean for you and your robotics organization below.Â


[ Blog ](/blog) [ Careers ](/careers) Schedule a demo


####  Support for real-time


Although this difference is striking, you may intuit that it is partially due
to slow startup of ` rosbag ` ’s Python interpreter.


###  Unify duration and time types


###  Recommendations


##  Packaging


Back to the articles
MCAP vs ROS bag: Simplifying Multi-Modal Sensor Data in Robotics
March 25th, 2024
-
2 min
Avatar photo
Bert De Brabandere
If you work with robotics or autonomous vehicle data, you’re likely familiar with the challenges of efficiently storing and transferring multimodal sensor data. This can cause some headaches when sharing data with external vendors: How do you send over your recordings containing large volumes of lidar, radar, camera, and calibration data? How to package and transform the data to make it compatible with the vendor’s system? That’s where the MCAP format comes in.


[ Twitter  ](https://twitter.com/foxglove) [ GitHub
](https://github.com/foxglove)


[ ROS 1 Wiki ](https://wiki.ros.org/noetic) (Noetic)Â


For more information please see the [ ROS interface definition
](http://design.ros2.org/articles/interface_definition.html) article.


For organizations using ROS 1, it will not be feasible to stay on ROS 1
indefinitely because official support ends in 2025. However, every
organization using ROS 1 today has different considerations when determining
when or how to migrate to ROS 2. Teams should work to understand the effort
and staffing it would take to transition, and work out a timing to execute the
plan in a manner that aligns with the organizational goals and product
development cycle.


4 minutes


One reason for the devel space in ROS 1 is to enable the developer to change
files, e.g. Python code or launch files, and use the modified code directly
without the need to rebuild the package. This benefit is preserved in ROS 2 by
optionally replacing copy operations in the install steps with symlinks.


![José L. Millán](/images/blog/authors/joselmillan.webp) José L. Millán  José
L. Millán


MCAP's most publicized advantage over bag files is its support for arbitrary
message serialization formats (e.g. [ Protobuf ](https://protobuf.dev/) , [
FlatBuffers ](https://flatbuffers.dev/) , [ CDR
](https://github.com/foxglove/cdr#introduction) , etc.), while ROS 1 bags are
constrained to messages serialized in the [ ROS 1 ` msg ` format
](http://wiki.ros.org/msg) .


Teams building from the ground up should start using ROS 2.


The field has been deprecated for a long time and was not set consistently in
ROS 1.


Schedule a demo


If you're a robotics org today and are thinking of migrating, or a startup
taking your first steps, we have a roundup of the biggest differences between
ROS 1 and ROS 2.


###  Features


[ Cookie policy ](/cookies-policy)


We see that ` rosbag info ` is doing a dramatically larger number of disk
seeks and reads than ` mcap info ` .


  * [ Foxglove ](/product)
  * [ MCAP ](/mcap)


###  Subscribe to our newsletter


###  Tooling/Ecosystem


[ ![Installing ROS 2 on macOS with Docker](/images/blog/installing-ros2-on-
macos-with-docker/hero.jpeg) ](/blog/installing-ros2-on-macos-with-docker)


#  ROS 1 vs ROS 2 What are the Biggest Differences?


June 23, 2023  ·  3 min  read


In ROS 1 nodes and topics can be remapped at startup time only. In ROS 2
support for remapping hasn’t been implemented yet (⏳). The goal is to enable
remapping as well as aliasing not only during startup time but also during
runtime.


For organizations deciding between ROS 1 and ROS 2 today, we recommend using
ROS 2. ROS 1 Noetic, the final ROS 1 distroÂ is only officially supported
through 2025 unless youâre willing to only rely on community support. The
migration process typically involves using both versions of ROS until youâve
completely migrated to ROS 2.Â


June 14, 2023  ·  6 min  read


**Tooling**


####  Threading model


Pull Requests


##  Understanding the performance gap


We thought about robotics cloud infra - so you never have to.


ROS 1 rebuilds all downstream packages since it assumes ABI incompatibility.
To avoid this significant overhead a ROS 2 package should be able to declare
its ABI to avoid rebuilding downstream packages whenever possible.


###  Environment setup


##  Platforms and dependencies


**Changes to the Data FormatÂ**


Schedule a demo


**QoS**


In ROS 2 only isolated builds are supported, i.e. every package is built
separately on its own. The install spaces can be either isolated or merged.


Furthermore, the problem extends beyond the ` rosbag info ` command: it
actually results from the [ ` start_reading ` method
](https://github.com/ros/ros_comm/blob/noetic-
devel/tools/rosbag/src/rosbag/bag.py#L2664,L2666) , which is called any time a
bag file is opened. Bag users will pay this cost every time they open a bag
with the Python SDK.


To gather compression statistics, ` rosbag info ` must visit every chunk in
the file to read compression information from the corresponding header. Since
ROS bags are commonly recorded with a default chunk size of 768Kb
(uncompressed), it does not take a very large bag to accumulate a large number
of chunks. On a developer laptop, the effect of this may go largely unnoticed
or get attributed to Python startup. But on remote filesystems, you will
notice significant degradation for bags larger than a few megabytes, since
every chunk will require seeking to and reading an uncached page. The amount
of data in a chunk header is small in comparison to a 4kb page, so we’d be
significantly overfetching to read a small amount of data.


In ROS 1 the duration and time types are defined in the client libraries. The
member names of the data structures are different in C++ (sec, nsec) and
Python (secs, nsecs).


###  Binary packages for Windows (⏳)


[ Installing ROS 2 on macOS with Docker  ](/blog/installing-ros2-on-macos-
with-docker)


[ Schedule a demo ]()


Product


[ Core Services  Search, Metadata, Ingest.  ](https://model-
prime.webflow.io/services#core-services) [ Analytics & BI  Performance and
Business Analytics.  ](https://model-prime.webflow.io/services#analytics-bi) [
**Event Autotagging** Understand your logs at scale.  ](https://model-
prime.webflow.io/services#auto-event-tagging-actions) [ API  Build custom
applications.  ](https://model-prime.webflow.io/services#api) Data Retention
Keep the data that matters.  COMING SOON


**Multi-Threaded Execution**


The core of ROS 1 is targeting C++03 and doesn’t make use of C++11 features in
its API. ROS 2 uses C++11 extensively and uses some parts from C++14. In the
future ROS 2 might start using C++17 as long as it is supported on all major
platforms.


Let’s use ` strace ` to get some clues:


  * For hard disk drives, moving the disk head generally takes at least 5 milliseconds.
  * For all devices, reads happen at the granularity of file system pages, which are generally 4kb. Reading less than 4kb of data will still pull 4kb from disk or over a network if using remote storage.


[ Please Login to View Pull Requests
](https://github.com/login/oauth/authorize?client_id=efa6dd8eae9106381720)


MCAP and ROS
For teams using ROS, MCAP provides an upgrade path from the limitations of existing ROS bag formats. ROS 1 bags are difficult to use with non-ROS tools, while ROS 2 bags using SQLite are not fully self-contained.


####  Node vs. Nodelet


  * Open
  * Closed


Learn more about Robotics Infra, and what weâre up to at Model-Prime.


###  Reusing existing middleware


####  ROS Graph


â **Ecosystem** Â


ROS 1 can only be built from source on Windows (which also only works for a
few ROS packages and is not supported). ROS 2 will provide binary package
based on Chocolatey.


To learn more about MCAP, check out the references section below.


[ Product  ](/services) Docs  [ Careers  ](/careers) [ Blog  ](/blog)


  * [ API ](/docs/data-platform/api/introduction)
  * [ Status ](https://foxglovestatus.com/)
  * [ GitHub ](https://github.com/foxglove)


ROS 1 is only being CI tested on Ubuntu. It is actively supported by the
community on other Linux flavors as well as OS X.


In ROS 2 primitive values in messages can now have default values, set when
the message is constructed. Default values for non-primitive fields, i.e.
array of strings, nested messages, are not yet possible (⏳).


And for ` mcap info ` , also on local disk:


  * Topics and message types
  * Frequencies and message counts per topic
  * Start and end times of messages
  * Compression statistics


Below are the same measurements taken over a remote NFS connection (NFS
throughput from the server to the client is approximately 64Mbps):


Go to Top


####  Actions (⏳)


###  Product


###  Python packages


###  Developers


###  Support other build systems beside CMake


Catch our latest news and features, sent directly to your inbox.


visualization


â


####  Notifications


###  roslaunch (⏳)


  * [ Discussions ](https://github.com/orgs/foxglove/discussions)
  * [ Slack ](/slack)
  * [ Twitter ](https://twitter.com/foxglove)


    $ time rosbag info small.bag > /dev/null
        real	0m8.875s
        user	0m0.242s
        sys	0m0.061s

    $ time rosbag info large.bag > /dev/null
        real	13m45.866s
        user	0m1.449s
        sys 	0m3.825s

    $ time mcap info small.mcap > /dev/null
        real	0m0.162s
        user	0m0.000s
        sys	    0m0.016s

    $ time mcap info large.mcap > /dev/null
        real	0m0.185s
        user	0m0.014s
        sys 	0m0.009s


###  Optional default values in message definitions


##  Build your robots now.


1
Heterogeneous data support: MCAP can store data in multiple serialization formats (Protobuf, ROS, JSON, etc.) in a single file. This allows you to work with data from various sensors and sources in one self-contained format.
2
High-performance writing: MCAP uses an append-only structure optimized for high-throughput data writing. This minimizes disk I/O and reduces the risk of data corruption if recording is interrupted.
3
Efficient data access: MCAP files contain an optional index that enables fast random access and seeking, even over remote connections. This makes it efficient to extract subsets of data for analysis without needing to read the entire file.
4
Broad language support: MCAP has native libraries available in C++, Python, Go, Rust, and other languages, making it easy to integrate into various robotics and automotive software stacks.
5
Self-contained: With MCAP, message schemas are embedded directly in the file alongside the data. Files remain readable even as message definitions evolve, without relying on external dependencies. Optional attachments can also store calibration data and other metadata.
This makes MCAP ideal for recording and sharing high-frequency, multi-modal sensor data in automotive and robotics use cases.


#  MCAP vs ROS 1 Bag Index Performance


Date Written: 2015-09


In ROS 1 all information about the ROS graph must be polled from the master.
In ROS 2 changes will be published instead, e.g. notifications if a parameter
has been changed.


ROS 1 does not support writing real-time code but relies on external
frameworks like Orocos. In ROS 2 it will be possible to write real-time nodes
when using a proper RTOS and with carefully written user code.


![](https://assets-global.website-
files.com/6374d6bde94f94030dba937c/65f93fd7ace7cccc85700018_ros-1-vs-
ros-2-what-are-the-biggest-differences.jpg)


Get in touch


##  Client libraries


Arun Venkatadri


Oops! Something went wrong while submitting the form.


So why is performance of ` rosbag info ` so poor over NFS? And how does ` mcap
info ` do better?


â **The differences between ROS 1 and ROS 2 fall into three main
categories:**


  * Architecture
  * FeaturesÂ
  * Tooling/Ecosystem


###  Across languages


[ Please Login to View Contributors
](https://github.com/login/oauth/authorize?client_id=efa6dd8eae9106381720)


The generated Python code for messages and service is currently using the same
module and class names in ROS 1 and ROS 2. Therefore they can not be imported
both in a single application. This decision might be revisited if required.


##  Ready to try Foxglove?


**Changes to the MiddlewareÂ Â**


###  Platforms


![Wyatt Alt](/images/blog/authors/wyattalt.webp) Wyatt Alt  ·


##  Summarizing ROS 1 and MCAP files


[ ![](https://assets-global.website-
files.com/6374d6bce94f940eedba934e/65fda299604c5ad64c01b131_model-prime-
logo.svg) ](/)


Here are the timings for ` rosbag info ` on local disk:


###  Same names in Python


####  Components with life cycle


â


In ROS 1 the developer can only choose between single-threaded execution or
multi-threaded execution. In ROS 2 more granular execution models are
available in C++ (e.g. across multiple nodes) and custom executors can be
implemented easily. For Python the execution models haven’t been implemented
yet.


ROS 2 supports multiple nodes truly running in parallel, allowing it to
leverage modern multi-core processors far better than ROS 1.Â


Use Docker containers to get started with ROS development


[ Omar Elmoftyâs medium articleÂ ](https://medium.com/@oelmofty/ros2-how-is-
it-better-than-ros1-881632e1979a)


[ support@model-prime.com ](mailto:support@model-prime.com )


true on success


Definition at line [ 613 ](rviz__visual__tools_8cpp_source.html#l00613) of
file [ rviz_visual_tools.cpp ](rviz__visual__tools_8cpp_source.html) .


bool RvizVisualTools::publishPath(const EigenSTL::vector_Vector3d& path, const std::vector<colors>& colors,
                                  double radius, const std::string& ns)
{
  if (path.size() < 2)
  {
    ROS_WARN_STREAM_NAMED(LOGNAME, "Skipping path because " << path.size() << " points passed in.");
    return false;
  }


Definition at line [ 2473 ](rviz__visual__tools_8cpp_source.html#l02473) of
file [ rviz_visual_tools.cpp ](rviz__visual__tools_8cpp_source.html) .


bool rviz_visual_tools::RvizVisualTools::publishMarkers  |  (  |
visualization_msgs::MarkerArray & |  _markers_ |  )  |
---|---|---|---|---|---

Display an array of markers, allows reuse of the ROS publisher.


|  [ scales
](namespacerviz__visual__tools.html#a5b544decae321663ea907bb26338d835)
rviz_visual_tools::RvizVisualTools::intToRvizScale  |  (  |  std::size_t  |
_scale_ |  )  |
---|---|---|---|---|---
static

Used by interfaces that do not directly depend on Rviz Visual Tools, such as
OMPL.


bool RvizVisualTools::publishWireframeCuboid(const Eigen::Isometry3d& pose, double depth, double width, double height,
                                             colors color, const std::string& ns, std::size_t id)
{
  Eigen::Vector3d min_point, max_point;
  min_point << -depth / 2, -width / 2, -height / 2;
  max_point << depth / 2, width / 2, height / 2;
  return publishWireframeCuboid(pose, min_point, max_point, color, ns, id);
}


##  Related questions


commit-config.yaml ".pre-commit-config.yaml")
|
###
[ .pre-commit-config.yaml ](/ros-planning/moveit_visual_tools/blob/ros2/.pre-
commit-config.yaml ".pre-commit-config.yaml")
|
|

###
[ CHANGELOG.rst ](/ros-planning/moveit_visual_tools/blob/ros2/CHANGELOG.rst
"CHANGELOG.rst")
|
###
[ CHANGELOG.rst ](/ros-planning/moveit_visual_tools/blob/ros2/CHANGELOG.rst
"CHANGELOG.rst")
|
|

###
[ CMakeLists.txt ](/ros-planning/moveit_visual_tools/blob/ros2/CMakeLists.txt
"CMakeLists.txt")
|
###
[ CMakeLists.txt ](/ros-planning/moveit_visual_tools/blob/ros2/CMakeLists.txt
"CMakeLists.txt")
|
|

###
[ CONTRIBUTING.md ](/ros-
planning/moveit_visual_tools/blob/ros2/CONTRIBUTING.md "CONTRIBUTING.md")
|
###
[ CONTRIBUTING.md ](/ros-
planning/moveit_visual_tools/blob/ros2/CONTRIBUTING.md "CONTRIBUTING.md")
|
|

###
[ LICENSE ](/ros-planning/moveit_visual_tools/blob/ros2/LICENSE "LICENSE")


##  ◆  cuboid_marker_


|  bool rviz_visual_tools::RvizVisualTools::frame_locking_enabled_ = false
---
protected

Definition at line [ 1081 ](rviz__visual__tools_8h_source.html#l01081) of file
[ rviz_visual_tools.h ](rviz__visual__tools_8h_source.html) .


void RvizVisualTools::printTranslation(const Eigen::Vector3d& translation)
{
  std::cout << "T.xyz = [" << translation.x() << ", " << translation.y() << ", " << translation.z() << "]" << std::endl;
}


bool rviz_visual_tools::RvizVisualTools::publishSphere  |  (  |  const
Eigen::Vector3d & |  _point_ ,
---|---|---|---
|  |  [ colors
](namespacerviz__visual__tools.html#abd3566ac96adb96a35044b029930e6e3) |
_color_ = ` [ BLUE
](namespacerviz__visual__tools.html#abd3566ac96adb96a35044b029930e6e3a6cd27d693df45662c3ecebdc4dc8b671)
` ,
|  |  [ scales
](namespacerviz__visual__tools.html#a5b544decae321663ea907bb26338d835) |
_scale_ = ` [ MEDIUM
](namespacerviz__visual__tools.html#a5b544decae321663ea907bb26338d835a322895c45564210483089d04f6a07473)
` ,
|  |  const std::string & |  _ns_ = ` "Sphere" ` ,
|  |  std::size_t  |  _id_ = ` 0 `
|  )  |  |

Definition at line [ 1115 ](rviz__visual__tools_8cpp_source.html#l01115) of
file [ rviz_visual_tools.cpp ](rviz__visual__tools_8cpp_source.html) .


|  std::string rviz_visual_tools::RvizVisualTools::scaleToString  |  (  |  [
scales ](namespacerviz__visual__tools.html#a5b544decae321663ea907bb26338d835)
|  _scale_ |  )  |
---|---|---|---|---|---
static

Convert an enum to its string name equivalent.


  // Turn into msg
  return publishCylinder(convertPose(pose), color, height, radius, ns);
}


Returns


Definition at line [ 1640 ](rviz__visual__tools_8cpp_source.html#l01640) of
file [ rviz_visual_tools.cpp ](rviz__visual__tools_8cpp_source.html) .


##  ◆  marker_topic_


|
###
[ LICENSE ](/ros-planning/moveit_visual_tools/blob/ros2/LICENSE "LICENSE")
|
|

###
[ MIGRATION.md ](/ros-planning/moveit_visual_tools/blob/ros2/MIGRATION.md
"MIGRATION.md")
|
###
[ MIGRATION.md ](/ros-planning/moveit_visual_tools/blob/ros2/MIGRATION.md
"MIGRATION.md")
|
|

###
[ README.md ](/ros-planning/moveit_visual_tools/blob/ros2/README.md
"README.md")
|
###
[ README.md ](/ros-planning/moveit_visual_tools/blob/ros2/README.md
"README.md")
|
|

###
[ mainpage.dox ](/ros-planning/moveit_visual_tools/blob/ros2/mainpage.dox
"mainpage.dox")
|
###
[ mainpage.dox ](/ros-planning/moveit_visual_tools/blob/ros2/mainpage.dox
"mainpage.dox")
|
|

###
[ moveit_visual_tools.repos ](/ros-
planning/moveit_visual_tools/blob/ros2/moveit_visual_tools.repos
"moveit_visual_tools.repos")


` clear ` (  _self_ )  Â¶


|  double rviz_visual_tools::RvizVisualTools::getGlobalScale  |  (  |  |  )  |
const
---|---|---|---|---
inline

Getter for the global scale used for changing size of all markers.


  // Check if connected to a subscriber
  if (!pub_rviz_markers_waited_ && !pub_rviz_markers_connected_)
  {
    ROS_DEBUG_STREAM_NAMED(LOGNAME, "Waiting for subscribers before publishing markers...");
    waitForSubscriber(pub_rviz_markers_);


bool rviz_visual_tools::RvizVisualTools::publishCone  |  (  |  const
Eigen::Isometry3d & |  _pose_ ,
---|---|---|---
|  |  double  |  _angle_ ,
|  |  [ colors
](namespacerviz__visual__tools.html#abd3566ac96adb96a35044b029930e6e3) |
_color_ = ` [ TRANSLUCENT
](namespacerviz__visual__tools.html#abd3566ac96adb96a35044b029930e6e3ada8357de2c7d31bdc0a27e7814e0ac85)
` ,
|  |  double  |  _scale_ = ` 1.0 `
|  )  |  |

Display a cone of a given angle along the x-axis.


* **center** ( _bool_ _,_ _optional_ _,_ _default=True_ ) â If true, then the rotation is applied to the centered geometry


##  ◆  publishSphere()  [3/11]


##  ◆  publishYArrow()  [3/3]


void RvizVisualTools::setLifetime(double lifetime)
{
  marker_lifetime_ = ros::Duration(lifetime);


true on success


` get_oriented_bounding_box ` (  _self_ )  Â¶


/* Author: Dave Coleman <dave@picknik.ai>, Andy McEvoy
   Desc:   Helper functions for displaying basic shape markers in Rviz
*/


|  [ RemoteControlPtr
](namespacerviz__visual__tools.html#a86b96f423e9a60fd4df818a41e065921)
rviz_visual_tools::RvizVisualTools::remote_control_
---
protected

Definition at line [ 1065 ](rviz__visual__tools_8h_source.html#l01065) of file
[ rviz_visual_tools.h ](rviz__visual__tools_8h_source.html) .


Returns the volume of the bounding box.


](classrviz__visual__tools_1_1RvizVisualTools.html#aa0da55601c15643c069b92f2aa6e265a)
( [ geometry_msgs::Pose
](../../../api/tf/html/c++/namespacetf.html#af31f272a1879787c24c3decb07cdb361)
&cuboid_pose, double &depth, double &width, double &height, [ RandomPoseBounds
](structrviz__visual__tools_1_1RandomPoseBounds.html) pose_bounds= [
RandomPoseBounds ](structrviz__visual__tools_1_1RandomPoseBounds.html) (), [
RandomCuboidBounds ](structrviz__visual__tools_1_1RandomCuboidBounds.html)
cuboid_bounds= [ RandomCuboidBounds
](structrviz__visual__tools_1_1RandomCuboidBounds.html) ())
|  Create a random rectangular cuboid of some shape.  More...

static void  |  [ generateRandomPose
](classrviz__visual__tools_1_1RvizVisualTools.html#a05580bb37e13e531a3248a61459e6541)
( [ geometry_msgs::Pose
](../../../api/tf/html/c++/namespacetf.html#af31f272a1879787c24c3decb07cdb361)
&pose, [ RandomPoseBounds
](structrviz__visual__tools_1_1RandomPoseBounds.html) pose_bounds= [
RandomPoseBounds ](structrviz__visual__tools_1_1RandomPoseBounds.html) ())
|  Create a random pose within bounds of random_pose_bounds_.  More...

static void  |  [ generateRandomPose
](classrviz__visual__tools_1_1RvizVisualTools.html#ade090b45a1697bb5262977994d82fa0f)
(Eigen::Isometry3d &pose, [ RandomPoseBounds
](structrviz__visual__tools_1_1RandomPoseBounds.html) pose_bounds= [
RandomPoseBounds ](structrviz__visual__tools_1_1RandomPoseBounds.html) ())
static [ geometry_msgs::Pose
](../../../api/tf/html/c++/namespacetf.html#af31f272a1879787c24c3decb07cdb361)
|  [ getIdentityPose
](classrviz__visual__tools_1_1RvizVisualTools.html#a0cbba2a8a9f62c38c807c7ecb9de16bf)
()
static [ colors
](namespacerviz__visual__tools.html#abd3566ac96adb96a35044b029930e6e3) |  [
getRandColor
](classrviz__visual__tools_1_1RvizVisualTools.html#ad8ebe848704fbe9e1bebdd42bb087ce9)
()
|  Get a random color from the list of hardcoded enum color types.  More...

static [ colors
](namespacerviz__visual__tools.html#abd3566ac96adb96a35044b029930e6e3) |  [
intToRvizColor


  if (verbose)
  {
    std::cout << "right_axis_vector " << std::endl;
    printTranslation(right_axis_vector);
  }


  triangle_marker_.points.clear();
  triangle_marker_.points.push_back(p[0]);
  triangle_marker_.points.push_back(p[1]);
  triangle_marker_.points.push_back(p[2]);


bool RvizVisualTools::publishSphere(const Eigen::Isometry3d& pose, const std_msgs::ColorRGBA& color,
                                    const geometry_msgs::Vector3 scale, const std::string& ns, std::size_t id)
{
  return publishSphere(convertPose(pose), color, scale, ns, id);
}


converted point with orientation discarded


##  ◆  publishSphere()  [10/11]


  return result;
}


  // This is wrong. It returns only the number of subscribers that have already
  // established their direct connections to this publisher
  int num_existing_subscribers = pub.getNumSubscribers();


// Load arrow ----------------------------------------------------


Eigen::Vector3d RvizVisualTools::convertPoint(const geometry_msgs::Point& point)
{
  Eigen::Vector3d point_eigen;
  point_eigen[0] = point.x;
  point_eigen[1] = point.y;
  point_eigen[2] = point.z;
  return point_eigen;
}


##  ◆  remote_control_


Parameters


##  ◆  publishXYPlane()  [2/2]


  geometry_msgs::Point p[4];
  p[0].x = 0;
  p[0].y = 1.0 * scale;
  p[0].z = 1.0 * scale;


Definition at line [ 2388 ](rviz__visual__tools_8cpp_source.html#l02388) of
file [ rviz_visual_tools.cpp ](rviz__visual__tools_8cpp_source.html) .


bool RvizVisualTools::publishXYPlane(const geometry_msgs::Pose& pose, colors color, double scale)
{
  triangle_marker_.header.stamp = ros::Time::now();
  triangle_marker_.id++;


##  ◆  publishXZPlane()  [2/2]