0% found this document useful (0 votes)
9 views31 pages

ROS Notes Module1

The ROS community is a global network of developers and enthusiasts focused on the open-source Robot Operating System, promoting collaboration, support, and innovation in robotics. Key aspects include open-source contributions, active communication platforms, a diverse package ecosystem, and events for knowledge sharing. The computation graph in ROS manages communication between nodes through topics, messages, and services, facilitating seamless operation in robotic systems.

Uploaded by

Aneez Hassan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views31 pages

ROS Notes Module1

The ROS community is a global network of developers and enthusiasts focused on the open-source Robot Operating System, promoting collaboration, support, and innovation in robotics. Key aspects include open-source contributions, active communication platforms, a diverse package ecosystem, and events for knowledge sharing. The computation graph in ROS manages communication between nodes through topics, messages, and services, facilitating seamless operation in robotic systems.

Uploaded by

Aneez Hassan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE 1

Q1. Explain about ROS community

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.

Key Aspects of the ROS Community:

1. Open-Source Collaboration: ROS is open-source, meaning that anyone can contribute


to its codebase, libraries, and tools. The community works together to improve existing
features, develop new tools, and provide support for various hardware platforms.
2. Global Participation: The ROS community spans the globe, with contributors from
universities, research institutions, companies, and individual developers. This broad
participation helps to keep ROS at the cutting edge of robotics technology.
3. Communication and Support:
o Discourse Forum: ROS has an active online forum (ROS Discourse) where
users and developers can ask questions, share projects, and discuss issues. It's
one of the main hubs for collaboration and support.
o ROS Answers: Another key platform is ROS Answers, a Q&A site where users
can ask technical questions and receive answers from community members.
o Meetups and Conferences: There are regular ROS meetups, workshops, and
annual conferences like ROSCon, which bring together developers to share
knowledge, present projects, and discuss the future of ROS.
4. Package Ecosystem: The community creates and maintains thousands of ROS
packages that extend the functionality of the core system. These packages range from
drivers for sensors and actuators to advanced algorithms for SLAM (Simultaneous
Localization and Mapping) and computer vision.
5. Industry and Academia: The ROS community includes both academic institutions
and industry leaders. Many companies, such as Open Robotics (the maintainers of
ROS), contribute to its development, ensuring that ROS remains relevant for both
research and commercial applications.
6. Events and Hackathons: The community organizes events like hackathons, where
developers collaborate to create innovative solutions and test new features. These
events are critical for accelerating the development of new tools and ideas.
7. Learning Resources: The community maintains extensive documentation, tutorials,
and courses to help newcomers learn how to use ROS. Platforms like the ROS Wiki are
essential resources for understanding and using ROS effectively.
8. Diverse Applications: ROS is used in a wide variety of applications, from industrial
robots and drones to healthcare and educational robots. The community actively
explores new applications and helps drive the adoption of ROS in different sectors.

Getting Involved:

If you're interested in joining the ROS community, you can:

• Participate in online discussions via Discourse and ROS Answers.


• Contribute to existing packages or develop your own.
• Attend local ROS meetups or international events like ROSCon.
• Follow the latest ROS developments through the ROS blog and GitHub repository.

The strength of the ROS community lies in its openness and collaboration, making it a key
player in advancing the field of robotics.

Q2. Explain about computation graph.

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.

Key Components of the Computation Graph:

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.

How the Computation Graph Works:

• 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:

Imagine a mobile robot equipped with a camera and a laser scanner:

• The camera node publishes images to the /camera/image topic.


• A visual processing node subscribes to /camera/image to analyze the visual data.
• The laser scanner node publishes distance measurements to the /scan topic.
• A navigation node subscribes to /scan to use the laser data for obstacle detection.
• The robot control node subscribes to both the visual and laser data topics to make
decisions about moving the robot.

Q3. Explain the term workspace.

ROS 2 workspace provides an organized environment for developing, building, and testing
ROS 2 packages.

Key Concepts of a ROS 2 Workspace:

1. What is a ROS 2 Workspace?


o A ROS 2 workspace is a directory where ROS 2 packages are developed, built, and
run.
o It provides a structured environment where multiple packages can coexist, and it
manages their dependencies and build processes.
2. Workspace Structure: A typical ROS 2 workspace contains the following
subdirectories:
o src/ (Source directory):
▪ The src/ directory is where you place the source code for your ROS 2
packages.
▪ Inside the src/ directory, each ROS 2 package has its own folder, following
the ROS 2 package structure (which includes a [Link] file and
[Link] or Python setup files).
o build/:
▪ This directory is automatically generated during the build process. It
contains intermediate build files and is created by the Colcon build tool.
▪ You generally don’t interact with the contents of this folder directly.
o install/:
▪ This directory contains the final binaries, executables, and other files after
the build process is completed. The files in the install/ directory can be
sourced to set up the environment for running ROS 2 nodes.
o log/:
▪ The log/ directory contains logs from the build process and runtime
information from ROS 2 nodes. This is useful for debugging and checking
errors or warnings.

How to Create and Use a ROS 2 Workspace:

1. Create the Workspace Directory:

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.

2. Clone or Create Packages:

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

The colcon build command will:

• Create the build/, install/, and log/ directories.


• Compile the packages in the src/ directory.
• Place the final binaries and executables in the install/ directory.

4. Source the Workspace:

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:

ros2 run <package_name> <executable_name>

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:

1. Source the base workspace (such as a pre-installed ROS 2 distribution):

source /opt/ros/humble/[Link]

2. Source your workspace on top of it:

source ~/ros2_ws/install/[Link]

This allows your workspace to use packages from both the base workspace and your custom
workspace.

Q4. Explain the term ROS2 design

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.

Key Design Goals of ROS 2:

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.

Core Design Changes in ROS 2:


1. DDS as the Communication Middleware:

• 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.

3. Quality of Service (QoS) Policies:

• 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:

• ROS 2 is designed to be platform-agnostic, supporting Linux, Windows, and macOS natively.


This is a significant improvement from ROS 1, which primarily targeted Linux.
• The ability to run on embedded platforms like microcontrollers (via micro-ROS) makes ROS
2 well-suited for IoT and robotics applications where robots may include constrained
hardware components.
7. Services and Actions:

• Like ROS 1, ROS 2 supports services (synchronous, request-response communication) and


introduces improvements to actions (asynchronous, goal-based operations).
• Actions in ROS 2 are used for long-running tasks where feedback is provided during the
task's execution. This is useful in cases like navigation or robotic arm manipulation, where
feedback during task execution is critical.

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.

9. Improved Build System: Colcon:

• 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.

10. Testing and Simulation Support:

• 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.

Q5. Configuring environment in ROS2.

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:

1. Sourcing ROS 2 Setup Files

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.

To source the environment for a specific ROS 2 distribution, use:

source /opt/ros/humble/[Link]
echo "source /opt/ros/humble/[Link]" >> ~/.bashrc

2. Sourcing the Workspace (if applicable)

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:

echo "source ~/ros2_ws/install/[Link]" >> ~/.bashrc


source ~/.bashrc

3. Overlaying multiple workspaces, if applicable.


4. Setting and configuring important environment variables like ROS_DOMAIN_ID,
ROS_DISTRO, and PYTHONPATH.
5. Using rosdep to install dependencies and ensuring that workspaces are properly
built with colcon.

Workspace setup:

mkdir -p ~/ros2_ws/src
cd ~/ros2_ws
colcon build
source install/[Link]

Package creation:

ros2 pkg create <your_package_name> --build-type ament_cmake --


dependencies rclcpp std_msgs

Build workspace:

colcon build

Run nodes:

ros2 run <your_package_name> <node_name>

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:

ROS 2 installed (e.g., ROS 2 Humble).

Turtlesim and rqt installed (if not installed, install them as shown below).

Steps:

1. Install ROS 2, Turtlesim, and rqt (if not already installed)

Install the turtlesim and rqt packages using the following commands (if you haven’t
installed them yet):

sudo apt update

sudo apt install ros-humble-turtlesim rqt

2. Launch Turtlesim

Run the Turtlesim node using ROS 2:

ros2 run turtlesim turtlesim_node

You should see the Turtlesim window with the turtle in the middle of the screen.

3. Control the Turtle using Keyboard

To control the turtle manually, open a new terminal and run the following command to start
the teleop node:

ros2 run turtlesim turtle_teleop_key

Use the keyboard arrow keys to move the turtle around.

4. Visualizing with rqt

Now, you can visualize the data from the turtlesim node using rqt.

In another terminal, run:

rqt

• rqt will open a GUI.


• From the Plugins menu, you can select different visualization tools. Some useful ones for
turtlesim are:
o rqt_topic: Shows the active topics and messages.
o rqt_graph: Shows a graph of the nodes and topics that are communicating.
o rqt_plot: Plots topic data over time.

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:

• Plugins > Visualization > Plot


• In the plot window, add the following topic to plot the turtle's position:

/turtle1/pose/x

/turtle1/pose/y

This will give you a live plot of the turtle’s position (x, y) as it moves.

6. Monitoring Topics with rqt_topic

To monitor the topics in real-time:

• Go to Plugins > Topics > Topic Monitor or run it directly via:

ros2 run rqt_topic rqt_topic

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.

• Go to Plugins > Introspection > Node Graph or run directly:

ros2 run rqt_graph rqt_graph

It will display a graphical representation of the nodes and their connections through
topics.

Q7. What is rqt

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.

Q8. Undestanding nodes

In ROS (Robot Operating System), a node is a fundamental computational unit that


performs a specific task. Nodes are the building blocks of a ROS system and are designed to
communicate with each other to achieve complex functionalities. Each node is a process that
can publish or subscribe to topics, provide or consume services, and interact with other
nodes.

Key Concepts Related to Nodes:

1. What is a Node?

• A node is an executable (typically a script or program) that performs computations in a ROS-


based system.
• A complex robot might have many nodes running simultaneously, each responsible for a
specific task. For example:
o One node could handle sensor data (like reading from a camera).
o Another node could process that data (e.g., detect objects).
o Yet another node could control the robot’s motors.

2. Communication Between Nodes:

Nodes in ROS communicate using three main methods:

• 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:

• A node's lifecycle typically follows:


1. Initialization: The node is created and initialized.
2. Running: The node is executing its main tasks (subscribing, publishing, calling
services, etc.).
3. Shutdown: The node shuts down when it has finished its tasks or is interrupted.

Node Lifecycle Management (ROS 2 feature): In ROS 2, there is an enhanced node


lifecycle management system, where nodes can transition through different states like
Inactive, Active, Error, Finalized, etc.

4. Creating a Node (ROS 2 Example):

Here’s a simple example of creating a node in ROS 2 (Python):

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:

• A node named simple_node is created.


• When launched, it prints a log message "Node has started!" and waits for further
execution.

The program demonstrates how to create and manage a simple ROS 2 node.

Here's a breakdown of the program:

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.

2. from [Link] import Node


This imports the Node class from rclpy. A node is a fundamental component in ROS
2 that can send and receive messages.

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.

3.1. def __init__(self):

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'.

3.2. self.get_logger().info('Node has started!')

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):

The main function serves as the entry point of the program.

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.

4.2. node = SimpleNode()

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).

Another example of a node( program written in the lab)

Q9. Understanding the TOPICS in ROS 2

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.

Here’s a quick overview of how topics work in ROS 2:


1. Publishers and Subscribers

Publisher: A node that sends (publishes) messages to a topic.

Subscriber: A node that receives (subscribes to) messages from a topic.

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.

Common message types include:

std_msgs/msg/String: A string message.

sensor_msgs/msg/Image: An image message.

geometry_msgs/msg/Twist: Used for velocity commands in mobile robots.

3. ROS 2 Topic Commands

ROS 2 provides several commands to interact with topics from the terminal:

List all active topics by using the command

ros2 topic list

This will show all currently available topics.

Get information about a specific topic:

ros2 topic info /topic_name

This provides information about the publishers, subscribers, and message type
associated with the topic.

Echo messages from a topic:

ros2 topic echo /topic_name

This command outputs the messages being published to the specified topic in real
time.

Publish a message to a topic:

ros2 topic pub /topic_name message_type "message_data"

Example: Publish a string to the /chatter topic.

ros2 topic pub /chatter std_msgs/msg/String "data: 'Hello, world!'"


Get the type of messages a topic is using:

ros2 topic type /topic_name

4. Quality of Service (QoS)

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).

Example QoS policies:

• Reliable: Ensures that messages are delivered, even in unreliable networks.


• Best effort: Messages are sent without guaranteeing delivery.
• Durability: Controls whether messages are stored and resent to late subscribers.

5. Graphical Tools

There are graphical tools like rqt and rviz that can visualize topics and help in
debugging and testing.

Q10. Understanding services

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.

Key Concepts of Services in ROS 2

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.

Example of a .srv file:

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.

Consider the turtlesim package

Open a new terminal and run:

ros2 run turtlesim turtlesim_node

Open another terminal and run:

ros2 run turtlesim turtle_teleop_key

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

the turtlesim-specific services


are /clear, /kill, /reset, /spawn, /turtle1/set_pen, /turtle1/teleport_absolute,
and /turtle1/teleport_relative. You may recall interacting with some of these
services using rqt in the Use turtlesim, ros2, and rqt tutorial.

1 ros2 service list

2 ros2 service type

3 ros2 service list -t

4 ros2 service find

5 ros2 interface show


6 ros2 service call

Q11. Understanding parameters in ROS2

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:

Key Concepts of Parameters in ROS2

Parameter Types: ROS2 parameters support a variety of types, including:

o bool: true or false


o integer: Whole numbers like 42
o double: Floating-point numbers like 3.14
o string: Text like "hello"
o array: Arrays of the above types

Parameter Lifecycle: Parameters in ROS2 are part of the node's lifecycle


and can be modified during a node's execution. Nodes can provide services to
allow parameters to be:

o Declared: A node must declare its parameters during or before usage.


o Set: A node can set a new value for an existing parameter.
o Get: A node can retrieve the current value of a parameter.
o List: A node can list all its parameters.

Declaring Parameters: Parameters must be declared before they are used in


a node. This is different from ROS1, where you could implicitly use
parameters without declaration.

Example in Python:

self.declare_parameter('my_param', 'default_value')

Accessing Parameters: You can retrieve parameters using the get_parameter


method.

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

This can be loaded when launching the node.

Oveall we can write

Declare a parameter: self.declare_parameter('param_name',


'default_value')

Get a parameter value: self.get_parameter('param_name').value

Set a parameter: self.set_parameters([[Link](name, type,


value)])

Load parameters from a YAML file: Done during node launch via --ros-
args --params-file param_file.yaml.

YAML (short for YAML Ain't Markup Language) is a human-readable data


serialization format often used for configuration files, data exchange, and
application settings. YAML is designed to be simple and easy to read, making
it popular for situations where data structure needs to be both machine-
readable and human-readable.

[Link] actions in ROS2

In ROS2, actions are a communication mechanism used when a node (client)


wants to request a long-running task from another node (server) and receive
feedback and a result upon completion. Actions are particularly useful when
you want to perform operations that might take a long time, like moving a robot
to a specific location or performing a complex computation.

Key Concepts of Actions in ROS2

1. Action Components: Actions in ROS2 are composed of three main components:


o Goal: The request for an action to be performed, sent by the client to the
server.
o Feedback: Information sent periodically from the server to the client,
describing the progress of the action.
o Result: The final outcome of the action, sent by the server when the action is
completed.

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.

Here’s an example of an .action file, for a simple example like


"MoveToPosition":

# [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:

• Client: A node that sends an action request (goal) to an action server.


• Server: A node that performs the action, sends feedback during execution, and
provides a result when completed.

4. Lifecycle of an Action:

• The client sends a goal to the server.


• The server processes the goal and sends feedback to the client periodically.
• The client can optionally cancel the action if necessary.
• When the action completes, the server sends a result to the client.

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 Tools in ROS2

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.

o List actions: ros2 action list


o Send a goal: ros2 action send_goal /move_to_position
example_interfaces/action/MoveToPosition "{x: 1.0, y: 2.0, z:
3.0}"
o Get action type: ros2 action info /move_to_position

Q13. Using rqt_console to view logs in ROS 2


In ROS 2, rqt_console is a graphical user interface (GUI) tool that can be used to view and
filter log messages. It's particularly helpful for debugging because it provides a way to see log
output in a more readable and searchable format. Here's how to use rqt_console to view logs
in ROS 2:

1. Install rqt_console (if not already installed)

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

To start rqt_console, simply open a new terminal and run:

rqt_console

This will open the rqt_console GUI.

3. Start the ROS 2 nodes

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 can start our ROS 2 nodes normally:

ros2 run <package_name> <node_name>

4. View and Filter Logs

Once rqt_console is running:

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.

5. Change Log Level at Runtime

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:

ros2 param set /<node_name> log_level DEBUG

6. Alternative: Using Command Line to View Logs

While rqt_console is useful for a GUI view, we can also use the command line to view logs:

ros2 run <package_name> <node_name> --ros-args --log-level debug

This will display logs directly in the terminal.

By using rqt_console in combination with these commands, we can efficiently monitor, filter,
and adjust logging output in ROS 2.

Q14. Launching nodes in ROS 2


In ROS 2, launching nodes is typically done using launch files, which offer a convenient way
to manage the lifecycle of multiple nodes, set parameters, remap topics, and configure logging.
Here’s how you can launch nodes in ROS 2:

1. Basic Node Launching from the Command Line

To launch a single node without a launch file, you can directly run a node using the ros2 run
command:

ros2 run <package_name> <node_name>

For example, if you have a node called talker in the package demo_nodes_cpp, you would
run:

ros2 run demo_nodes_cpp talker

2. Creating a ROS 2 Launch File

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:

a. Create a Launch File

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

b. Basic Launch File Example

Here’s a basic example of a ROS 2 launch file that launches a single node:

from launch import LaunchDescription

from launch_ros.actions import Node

def generate_launch_description():

return LaunchDescription([

Node(

package='demo_nodes_cpp',

executable='talker',

name='talker_node',
output='screen',

),

])

package: The package name where your node is located.

executable: The name of the executable for the node.

name: Assign a name to the node.

output: Defines how the output is displayed (in this case, on the screen).

c. Launching the File

To launch this file, run the following command:

ros2 launch <your_package_name> my_launch.py

This will start the node(s) specified in the my_launch.py file.

3. Launching Multiple Nodes

You can launch multiple nodes within the same launch file. Here’s an example:

from launch import LaunchDescription

from launch_ros.actions import Node

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.

4. Setting Parameters and Arguments

We can pass parameters and arguments to nodes through the launch file. Here’s an example
where a parameter is passed to the node:

from launch import LaunchDescription

from launch_ros.actions import Node

def generate_launch_description():

return LaunchDescription([

Node(

package='demo_nodes_cpp',

executable='talker',

name='talker_node',

output='screen',

parameters=[{'my_param': 'value'}]

),

])

This sets the parameter my_param to value for the talker_node.

5. Using Remappings in Launch Files

To remap topics or services, use the remappings argument:

Node(
package='demo_nodes_cpp',

executable='talker',

name='talker_node',

output='screen',

remappings=[

('/chatter', '/my_custom_topic')

This remaps the topic /chatter to /my_custom_topic.

Q15. Recording and playing back data in ROS2

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.

1. Recording Data with ros2 bag

The ros2 bag tool enables you to record data from one or more topics into a bag file for later
use.

a. Basic Recording Command

To record all topics:

ros2 bag record -a

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.

b. Recording Specific Topics

If you only want to record specific topics, list them after the ros2 bag record command:

ros2 bag record /topic1 /topic2

This will record only the specified topics.

c. Record with Duration Limit


You can also limit the recording to a specific duration using the --duration option. For
example, to record for 30 seconds:

ros2 bag record -a --duration 30

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.

For example, to record with compression using zstd:

ros2 bag record -a --compression-mode file --compression-format zstd

This will compress the bag file as it is written.

2. Playing Back Data with ros2 bag

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.

a. Basic Playback Command

To play back a recorded bag file, use:

ros2 bag play <bag_file_directory>

For example:

ros2 bag play rosbag2_2023_10_01-12_00_00

This will replay all the messages stored in the bag file, publishing them back onto their
respective topics in real-time.

b. Control Playback Rate

You can control the playback rate by using the -r option. For example, to play back the data
at twice the normal speed:

ros2 bag play <bag_file_directory> -r 2.0

Or, to play at half speed:

ros2 bag play <bag_file_directory> -r 0.5

c. Looping Playback

To loop the playback indefinitely until manually stopped, use the --loop option:

ros2 bag play <bag_file_directory> --loop


d. Playback from a Specific Time

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:

ros2 bag play <bag_file_directory> --start-offset 5

3. Managing Bag Files

a. Inspecting the Bag File

To see the information about a recorded bag file, such as the topics and message types it
contains, use the info command:

ros2 bag info <bag_file_directory>

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:

ros2 bag record -a --storage-format mcap

You can also convert recorded bags to a different format using ROS 2’s bag conversion tools
(though this functionality is still evolving).

You might also like