ROS

ROS Node

This is like fundamental, I should spend more time on this. How are ROS nodes implemented under the hood?

Resources

Some questions I need to answer:

  • What is Node::SharePtr?
  • Why is it that for the ROS Executor, we need to make this node a shared pointer?

Source code

This is an example ROS node, from ROS Examples

#include <memory>
 
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using std::placeholders::_1;
 
class MinimalSubscriber : public rclcpp::Node
{
  public:
    MinimalSubscriber()
    : Node("minimal_subscriber")
    {
      subscription_ = this->create_subscription<std_msgs::msg::String>(
      "topic", 10, std::bind(&MinimalSubscriber::topic_callback, this, _1));
    }
 
  private:
    void topic_callback(const std_msgs::msg::String & msg) const
    {
      RCLCPP_INFO(this->get_logger(), "I heard: '%s'", msg.data.c_str());
    }
    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;
}

Notice that the subscription is a SharedPtr

More generally, most of everything in ROS with rclcpp is using SharedPtr. This is because of the benefit of automatic memory management: https://answers.ros.org/question/363135/why-is-everything-a-shared_ptr-in-ros2/

Notice also that the callback is a private method.

Member fields:

Publisher

The this->create_publisher returns a shared pointer, which is why we need SharedPtr

rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;

Subscriber

The this->create_subscription also returns a shared pointer, which is why we need SharedPtr

rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_;