ROS Notes Module1
ROS Notes Module1
The ROS (Robot Operating System) community is a vibrant and global network of
developers, researchers, and robotics enthusiasts who contribute to the development and
improvement of ROS, an open-source middleware framework for building and programming
robots.
Getting Involved:
The strength of the ROS community lies in its openness and collaboration, making it a key
player in advancing the field of robotics.
In the Robot Operating System (ROS), the computation graph is a fundamental concept that
describes how different processes (nodes) in a ROS-based robotic system communicate with
each other. The computation graph manages the flow of data and coordination among
distributed system components, ensuring that different parts of a robotic system work together
seamlessly.
1. Nodes:
o A node is a process that performs computation. In ROS, nodes are typically
small, modular programs that handle specific tasks (e.g., controlling motors,
processing sensor data).
o Multiple nodes run independently, and each node can be written in different
programming languages (e.g., Python, C++).
o Nodes are the primary units of execution in a ROS system.
2. Topics:
o Topics are named buses over which nodes exchange messages (data). A topic
is associated with a specific type of message (e.g., sensor readings, robot state,
images).
o Publish/Subscribe Pattern: Nodes that produce data "publish" messages to a
topic, and nodes that consume data "subscribe" to that topic. This decouples
the producer and consumer, allowing for flexible and scalable communication.
▪ Publisher: A node that sends data on a specific topic.
▪ Subscriber: A node that receives data from a specific topic.
3. Messages:
o Messages are the data structures used to communicate between nodes. ROS
provides a variety of predefined message types (e.g., std_msgs/String for text,
sensor_msgs/Image for images), but custom message types can also be
created.
o Messages are passed between nodes via topics, enabling real-time
communication.
4. Services:
o While topics are used for continuous data streams, services allow for
synchronous communication between nodes.
o A service defines a request-response pattern. One node sends a request to
another node, which processes it and sends back a response.
o Example: A robot might use a service to ask another node to perform a task,
such as moving to a specific location.
5. Actions:
o Actions extend services by allowing asynchronous, long-running tasks. Actions
follow a goal-feedback-result pattern, where a node sends a goal (e.g., "move to
this position") and receives feedback during task execution, as well as a final
result once the task is completed.
o This is useful for tasks that take a long time, such as robot navigation or arm
manipulation.
6. Master:
o The ROS Master is a central node that manages communication and
coordination between all other nodes in the system.
o It handles the registration of nodes, topics, and services, and ensures that nodes
can discover and communicate with each other.
o Without the ROS Master, nodes wouldn’t know where to publish or subscribe
to topics, or how to find services and actions.
7. Parameter Server:
o The parameter server is a shared, centralized storage for global parameters
that nodes can read and write to. Parameters are typically configuration settings
(e.g., robot dimensions, sensor calibration data).
o Nodes can retrieve parameters from the server as needed, allowing for system-
wide configuration changes without modifying the code in individual nodes.
8. Bags:
o Bags are a mechanism for logging and playing back ROS message data. During
operation, nodes can record their messages into a "bag" file, which can later be
replayed to simulate sensor inputs or troubleshoot issues.
• In a typical ROS system, each node is responsible for a specific task, such as
controlling a motor, processing sensor data, or performing navigation.
• Nodes communicate through topics by publishing and subscribing to data streams. For
example, a camera node might publish image data to a topic, while an image
processing node subscribes to that topic to process the images.
• The ROS Master coordinates this communication by allowing nodes to register
themselves and discover each other.
• Services and actions enable nodes to request specific tasks or initiate long-running
processes, such as moving a robot arm or navigating to a goal.
Example:
ROS 2 workspace provides an organized environment for developing, building, and testing
ROS 2 packages.
You can start by creating the directory structure for your workspace:
mkdir -p ~/ros2_ws/src
cd ~/ros2_ws
Here, ros2_ws is the name of your workspace, and inside it, there is an src/ folder where the
packages will be placed.
You can either create new packages or clone existing ROS 2 packages into the src/
directory:
cd ~/ros2_ws/src
git clone [Link]
3. Build the Workspace:
Once you have packages in the src/ directory, you can use Colcon to build them:
cd ~/ros2_ws
colcon build
After building the workspace, you need to source the environment setup files to use the built
packages:
source ~/ros2_ws/install/[Link]
This sets up the environment variables so that ROS 2 can find your built packages, allowing
you to run ROS 2 nodes, services, and actions.
5. Running Nodes:
Once the workspace is sourced, you can run nodes from your ROS 2 packages:
6. Workspace Overlaying:
In ROS 2, you can have multiple workspaces and "overlay" them on top of each other. This
means you can develop in one workspace and still access packages from another workspace.
To overlay workspaces:
source /opt/ros/humble/[Link]
source ~/ros2_ws/install/[Link]
This allows your workspace to use packages from both the base workspace and your custom
workspace.
The core motivation behind ROS 2 is to meet the demands of modern robotic systems,
especially those requiring distributed, real-time, and secure communication, such as
autonomous vehicles, industrial robots, and multi-robot systems.
1. Distributed Computing: Allow systems to operate across multiple machines with reliable
communication.
2. Real-Time Support: Meet real-time requirements critical for robotic systems in safety-critical
environments.
3. Scalability: Enable systems to scale from small embedded devices to large, complex multi-
robot systems.
4. Security: Ensure that communication between different parts of the robotic system is
secure, especially important in networked and cloud-connected robots.
5. Flexibility in Middleware: Support multiple middleware implementations, allowing users to
choose the best-suited middleware for their application.
6. Improved Abstraction for Cross-Platform Support: ROS 2 is designed to work on a wide
range of platforms, including Linux, Windows, and macOS, and to run on embedded devices.
• Data Distribution Service (DDS) is used as the default middleware for ROS 2, replacing the
custom TCP-based transport in ROS 1.
• DDS is a standardized protocol that provides real-time, scalable, and distributed
communication. It supports the publish/subscribe and request/response communication
patterns, which are central to ROS.
• DDS handles data serialization, discovery of nodes, data transport, and quality of service
(QoS) settings.
2. No Central Master:
• In ROS 1, the ROS Master was a centralized node that handled registration and lookup of
topics, services, and nodes.
• ROS 2 eliminates the need for a central master node by using DDS, where nodes can
automatically discover each other in a distributed network.
• ROS2 design improves fault tolerance, as the system continues to function even if one node
crashes or gets disconnected.
• ROS 2 introduces the concept of QoS settings for topics and services, providing greater
control over how communication happens between nodes.
4. Real-Time Support:
• ROS 2 is designed with real-time systems in mind. By using DDS and providing control over
QoS settings, ROS 2 can achieve deterministic and real-time behavior.
• ROS 2 allows real-time callback execution and executor control, enabling developers to
implement precise scheduling of tasks and guarantee timely responses.
• ROS 2 can run on Real-Time Operating Systems (RTOS), such as RTLinux or QNX, and can
interface with real-time hardware for critical applications.
5. Lifecycle Management:
• ROS 2 introduces managed nodes, which provide a standardized lifecycle for nodes, allowing
more control over their state.
• Managed nodes can transition between states like inactive, active, and finalized. This allows
for clean startup, shutdown, and dynamic reconfiguration of nodes without restarting the
entire system.
6. Cross-Platform Support:
8. Security Features:
• ROS 2 provides a security framework built on top of DDS, offering features like:
o Authentication: Ensures that nodes communicating in the system are who they
claim to be.
o Encryption: Protects the data in transit between nodes.
o Access Control: Limits which nodes can publish or subscribe to certain topics,
providing fine-grained permission management.
• This is critical in networked and cloud-connected robots where secure communication is
necessary to prevent unauthorized access or malicious attacks.
• ROS 2 uses Colcon as its default build system, replacing the catkin_make tool from ROS 1.
• Colcon improves support for building large workspaces and handles more complex
dependencies and packages written in multiple languages (C++, Python, etc.).
• Colcon also provides improved tooling for testing, code quality checks, and documentation
generation.
• ROS 2 provides built-in support for testing and simulation through tools like Gazebo (robot
simulator), which has been enhanced to support ROS 2.
• The ROS 2 Testing Framework offers robust mechanisms for unit testing and system-level
testing, ensuring that components behave as expected in a simulated or real environment.
Configuring the environment in ROS 2 is an important step to ensure that the system can find
the necessary packages, libraries, and tools for working with ROS 2. The environment setup
includes tasks like sourcing setup files, configuring workspaces, and setting up necessary
dependencies. Here's how you can configure the environment in ROS 2:
When you install ROS 2, you need to "source" its environment setup file to set up environment
variables like ROS_DOMAIN_ID, ROS_VERSION, and paths to package directories. This makes
ROS 2 commands available in your terminal and allows ROS to find installed packages.
source /opt/ros/humble/[Link]
echo "source /opt/ros/humble/[Link]" >> ~/.bashrc
If you are working in a custom ROS 2 workspace (such as ros2_ws), you need to source the
workspace's setup file after you build it using colcon. The setup file is usually located in the
install/ directory.
source ~/ros2_ws/install/[Link]
This will configure your environment to use the packages you’ve built in that workspace.
You need to run this every time you open a new terminal or add it to your .bashrc file:
Workspace setup:
mkdir -p ~/ros2_ws/src
cd ~/ros2_ws
colcon build
source install/[Link]
Package creation:
Build workspace:
colcon build
Run nodes:
Following these steps will help you configure your ROS 2 environment.
Q6. How to use turtlesim with ROS 2 and visualize it using rqt.
To use Turtlesim with ROS 2 and visualize it using rqt, you need to install the necessary packages, run
the Turtlesim node, and use rqt to visualize the data. Here’s a step-by-step guide:
Prerequisites:
Turtlesim and rqt installed (if not installed, install them as shown below).
Steps:
Install the turtlesim and rqt packages using the following commands (if you haven’t
installed them yet):
2. Launch Turtlesim
You should see the Turtlesim window with the turtle in the middle of the screen.
To control the turtle manually, open a new terminal and run the following command to start
the teleop node:
Now, you can visualize the data from the turtlesim node using rqt.
rqt
You can visualize various aspects of turtlesim by selecting the appropriate plugins.
5. Plotting Turtle Position
You can use rqt_plot to visualize the turtle’s position as it moves. In the rqt window, go to:
/turtle1/pose/x
/turtle1/pose/y
This will give you a live plot of the turtle’s position (x, y) as it moves.
This will show all active topics (like /turtle1/cmd_vel, /turtle1/pose, etc.) and their
message types.
7. Using rqt_graph
rqt_graph can help you visualize the communication between nodes and topics.
It will display a graphical representation of the nodes and their connections through
topics.
rqt is a Qt-based framework for creating graphical user interfaces (GUIs) in ROS
(Robot Operating System). It provides a flexible platform for viewing, analyzing, and
interacting with various ROS topics, services, and nodes through a collection of plugins.
rqt simplifies working with ROS systems by providing intuitive graphical tools for
visualizing data, monitoring system behavior, and debugging.
1. What is a Node?
• Topics: Nodes can send messages to each other via a publisher-subscriber model.
o Publisher: A node that sends data to a topic.
o Subscriber: A node that listens to and receives data from a topic.
o Example: A node publishing camera data to a /camera topic, while another node
subscribes to that topic to process the images.
• Services: Nodes can request a task from other nodes using services. Services follow a
request-response model.
o Server: The node that provides the service.
o Client: The node that requests the service.
o Example: A node requesting a map from a mapping node.
• Actions: Similar to services but more complex, used when a task may take time and requires
feedback during execution (like robot navigation).
o Goal, Feedback, and Result messages are exchanged between nodes.
o Example: A robot movement action that gives feedback about progress.
3. Node Lifecycle:
import rclpy
from [Link] import Node
class SimpleNode(Node):
def __init__(self):
super().__init__('simple_node')
self.get_logger().info('Node has started!')
def main(args=None):
[Link](args=args)
node = SimpleNode()
[Link](node)
node.destroy_node()
[Link]()
if __name__ == '__main__':
main()
In this example:
The program demonstrates how to create and manage a simple ROS 2 node.
1. import rclpy
The rclpy module is part of the ROS 2 client library for Python. It provides tools to
create nodes, handle topics, services, and communication.
3. class SimpleNode(Node):
This line defines a class SimpleNode that inherits from the Node class. This means
that SimpleNode is a ROS 2 node.
This is the constructor method for the SimpleNode class. It calls the constructor of the
parent Node class using super().__init__('simple_node') and names the node as
'simple_node'.
This line uses the node's built-in logging mechanism to print a message saying that
the node has started. The get_logger() method is provided by the Node class to handle
logging.
4. def main(args=None):
4.1. [Link](args=args)
This initializes the ROS 2 communication layer. ROS 2 needs to be initialized before
you can use its functionality, such as creating nodes or handling messages.
This creates an instance of the SimpleNode class, which represents a ROS 2 node.
4.3. [Link](node)
This keeps the node alive, allowing it to continue executing and responding to events
such as messages, timers, or callbacks. Without this, the node would immediately
terminate.
4.4. node.destroy_node()
This destroys the node when it's no longer needed, cleaning up the resources.
4.5. [Link]()
This shuts down ROS 2. It's necessary to gracefully stop the ROS 2 communication
layer before exiting the program.
5. if __name__ == '__main__':
This ensures that the main() function is called only when the script is executed
directly (not when imported as a module).
In ROS 2 (Robot Operating System 2), topics are used for communication between
nodes in a publish-subscribe architecture. Nodes can publish messages to a topic or
subscribe to a topic to receive messages. This decouples the communication, as nodes
don't need to directly interact with each other.
2. Message Types
Each topic has a message type associated with it, and both publishers and subscribers
of a topic need to use the same message type for the communication to work.
ROS 2 provides several commands to interact with topics from the terminal:
This provides information about the publishers, subscribers, and message type
associated with the topic.
This command outputs the messages being published to the specified topic in real
time.
ROS 2 allows us to configure Quality of Service (QoS) settings for topics, which
control things like message reliability, durability, and lifespan. This is particularly
useful in environments where communication conditions can vary (e.g., wireless
networks, real-time constraints).
5. Graphical Tools
There are graphical tools like rqt and rviz that can visualize topics and help in
debugging and testing.
In ROS 2 (Robot Operating System 2), services are a communication mechanism that
allows nodes to interact in a request-response pattern, which is different from the
publish-subscribe mechanism used for topics. In ROS 2, services are useful when you
need a node to request specific information or an action from another node and wait for
a response.
1. Client-Server Model
o Client: A node that makes a request.
o Server: A node that provides a response based on the request.
oIn a service interaction, the client sends a request to the server, and the server
processes the request and sends back a response.
2. Service Definition
o A service in ROS 2 consists of two parts:
▪ Request: The data sent from the client to the server.
▪ Response: The data sent from the server back to the client.
o These are defined in a .srv file, which specifies the structure of both the
request and response.
srv
int64 a
int64 b
---
int64 sum
This service file defines a request with two integers a and b, and a response with an
integer sum.
3. Synchronous Communication
o Unlike topics (which are asynchronous), services operate synchronously. The
client sends a request and waits (blocks) until the server responds or a timeout
occurs.
4. ROS 2 Service Workflow
o Step 1: Define the service (usually in a .srv file).
o Step 2: Implement a server node that handles incoming requests.
o Step 3: Implement a client node that makes requests to the server.
o Step 4: Deploy the nodes so that the client can send requests, and the server
responds.
Running the ros2 service list command in a new terminal will return a list of
all the services currently active in the system:
/clear
/kill
/reset
/spawn
/teleop_turtle/describe_parameters
/teleop_turtle/get_parameter_types
/teleop_turtle/get_parameters
/teleop_turtle/list_parameters
/teleop_turtle/set_parameters
/teleop_turtle/set_parameters_atomically
/turtle1/set_pen
/turtle1/teleport_absolute
/turtle1/teleport_relative
/turtlesim/describe_parameters
/turtlesim/get_parameter_types
/turtlesim/get_parameters
/turtlesim/list_parameters
/turtlesim/set_parameters
/turtlesim/set_parameters_atomically
In ROS2 (Robot Operating System 2), parameters are a way to configure nodes
by defining specific values for their settings or behaviors at runtime. Parameters
are used to manage things like threshold values, configuration paths, or any
other settings a node may need. Each node can have its own set of parameters,
and these parameters can be loaded dynamically or set via configuration files.
Below is an overview of how parameters work in ROS2:
Example in Python:
self.declare_parameter('my_param', 'default_value')
In Python:
my_param_value =
self.get_parameter('my_param').get_parameter_value().string_value
Setting Parameters: Parameters can be set during the node's execution. For
example, in Python
self.set_parameters([[Link]('my_param',
[Link], '
Parameter Files: Parameters can be loaded from YAML files, which makes it
easy to configure nodes without changing the code. Here’s an example of a
simple parameter YAML file:
my_node:
ros__parameters:
my_param: "some_value"
another_param: 42
Load parameters from a YAML file: Done during node launch via --ros-
args --params-file param_file.yaml.
2. Action Structure: Actions are defined in an .action file, which contains three
sections:
o Goal: The parameters required to perform the action.
o Result: The data returned when the action finishes.
o Feedback: Optional progress updates provided while the action is running.
# [Link]
# Goal definition
float32 x
float32 y
float32 z
---
# Result definition
bool success
---
# Feedback definition
float32 current_x
float32 current_y
float32 current_z
3. Action Communication:
4. Lifecycle of an Action:
5. Action Interface: Similar to topics and services, actions in ROS2 use an action
interface. The .action file defines the structure of the goal, result, and feedback. ROS2
uses the rosidl package to generate the appropriate code for actions from .action files.
Action CLI (Command Line Interface): ROS2 provides a CLI to interact with
actions. You can use the ros2 action commands to list, send, or cancel goals.
Before using rqt_console, ensure it's installed in the ROS 2 environment. We can install it
using:
sudo apt install ros-humble-rqt-console
2. Launch rqt_console
rqt_console
Make sure we have some ROS 2 nodes running that are generating log messages. ROS 2
nodes typically produce logs using various severity levels (DEBUG, INFO, WARN, ERROR,
and FATAL).
We will start seeing log messages from the running ROS 2 nodes.
Use the filter options in rqt_console to narrow down messages by severity level, node, or
message content. This is useful for isolating specific warnings or errors.
If we want to change the log level of a running node, we can do so with ros2 commands. For
example, to set the log level of a node to DEBUG, run:
While rqt_console is useful for a GUI view, we can also use the command line to view logs:
By using rqt_console in combination with these commands, we can efficiently monitor, filter,
and adjust logging output in ROS 2.
To launch a single node without a launch file, you can directly run a node using the ros2 run
command:
For example, if you have a node called talker in the package demo_nodes_cpp, you would
run:
Launch files in ROS 2 are written in Python, which gives them more flexibility compared to
ROS 1’s XML format. Here’s a step-by-step guide for creating and using launch files:
Inside your ROS 2 package, create a folder named launch if it doesn't already exist. Then
create a Python file for your launch configuration, such as my_launch.py.
mkdir -p <your_package_name>/launch
touch <your_package_name>/launch/my_launch.py
Here’s a basic example of a ROS 2 launch file that launches a single node:
def generate_launch_description():
return LaunchDescription([
Node(
package='demo_nodes_cpp',
executable='talker',
name='talker_node',
output='screen',
),
])
output: Defines how the output is displayed (in this case, on the screen).
You can launch multiple nodes within the same launch file. Here’s an example:
def generate_launch_description():
return LaunchDescription([
Node(
package='demo_nodes_cpp',
executable='talker',
name='talker_node',
output='screen',
),
Node(
package='demo_nodes_cpp',
executable='listener',
name='listener_node',
output='screen',
),
])
In this case, both talker and listener nodes from the demo_nodes_cpp package will be
launched simultaneously.
We can pass parameters and arguments to nodes through the launch file. Here’s an example
where a parameter is passed to the node:
def generate_launch_description():
return LaunchDescription([
Node(
package='demo_nodes_cpp',
executable='talker',
name='talker_node',
output='screen',
parameters=[{'my_param': 'value'}]
),
])
Node(
package='demo_nodes_cpp',
executable='talker',
name='talker_node',
output='screen',
remappings=[
('/chatter', '/my_custom_topic')
In ROS 2, recording and playing back data is handled by the ros2 bag command, which allows
you to record messages from topics and then replay them for testing, analysis, or simulation
purposes. This functionality is similar to the rosbag tool in ROS 1, but it has some key
differences in terms of performance and format.
The ros2 bag tool enables you to record data from one or more topics into a bag file for later
use.
This will create a new directory (e.g., rosbag2_2023_10_01-12_00_00) that contains the
recorded data in ROS 2 format. The -a option tells ROS 2 to record all active topics.
If you only want to record specific topics, list them after the ros2 bag record command:
d. Compression (Optional)
To reduce the file size of the recorded bag, you can use compression. ROS 2 supports two
types of compression: zstd and bz2.
Once you’ve recorded your data into a bag file, you can replay it to simulate the same data
flow as when the topics were originally published.
For example:
This will replay all the messages stored in the bag file, publishing them back onto their
respective topics in real-time.
You can control the playback rate by using the -r option. For example, to play back the data
at twice the normal speed:
c. Looping Playback
To loop the playback indefinitely until manually stopped, use the --loop option:
You can also start playing from a specific timestamp using the --start-offset option. For
example, to start playback 5 seconds after the beginning of the bag:
To see the information about a recorded bag file, such as the topics and message types it
contains, use the info command:
This will display details about the topics, message counts, start and end times, and other
metadata.
b. Storage Format
By default, ROS 2 uses the SQLite format for bag files. If needed, you can specify a different
storage backend, such as sqlite3 or mcap, when recording:
You can also convert recorded bags to a different format using ROS 2’s bag conversion tools
(though this functionality is still evolving).