Chapter 5: ROS 2 Packages aur Applications Build Karna
5.1 ROS 2 Package Structure
ROS 2 mein, ek package software ko organize karne ka fundamental unit hai. Ek package ROS nodes, libraries, configuration files, message definitions, aur other related artifacts contain kar sakta hai. Yeh modularity aur reusability promote karte hain, making easier ROS 2 code ko share aur distribute karne ke liye.
colcon Workspaces ka Overview
ROS 2 colcon use karta hai apne primary build tool ke taur par. colcon ek workspace ke concept par operate karta hai, jo ek directory hai containing ek ya more ROS 2 packages. Ek typical workspace structure is tarah dikhta hai:
my_ros2_workspace/
├── src/ # Source directory jahan packages reside karte hain
│ ├── my_python_package/
│ └── my_cpp_package/
├── build/ # Build directory (generated by colcon)
├── install/ # Install directory (generated by colcon)
└── log/ # Log directory (generated by colcon)
src directory jahan aap apne package source folders place karte ho. Jab aap workspace root se colcon build run karte ho, colcon src mein packages detect karega, un ko build karega, aur compiled binaries aur installed files ko build aur install directories mein place karega, respectively.
Standard Package Directory Layout
Jab ke strictly enforce nahi kiya jata, ek common aur recommended layout ek ROS 2 package ke liye include karta hai:
package.xml: Package ke baare mein metadata define karta hai (name, version, description, maintainers, dependencies).CMakeLists.txt(C++ packages ke liye) yasetup.py(Python packages ke liye):colconke liye build instructions.src/: C++ source files contain karta hai.include/: C++ header files contain karta hai.my_python_package/: Python modules contain karta hai.launch/: Launch files contain karta hai (.launch.pyya.launch.xml).config/: YAML configuration files contain karta hai.share/: Non-code resources contain karta hai jaise message definitions, launch files, ya configuration files jo other packages ke liye "install" hone ke zarorat hain.test/: Unit aur integration tests contain karta hai.
5.2 Python mein ROS 2 Packages Create Karna
Python ROS 2 development mein ek popular language hai apne ease of use aur extensive libraries ki wajah se. ros2 pkg create command ek basic package template generate karne ke liye use hota hai.
ros2 pkg create Use Karna
Ek naya Python package create karne ke liye, apne workspace ke src directory mein navigate karo aur run karo:
ros2 pkg create --build-type ament_python my_python_package
Yeh command ek directory my_python_package create karta hai package.xml aur setup.py file ke saath configured ek Python package ke liye.
setup.py aur package.xml Configuration
package.xml: Essential metadata contain karta hai aur build_depends (dependencies jo package ko build karne ke liye zarorat hain) aur exec_depends (dependencies jo package ko run karne ke liye zarorat hain). Ek Python package ke liye,ament_pythonek crucial build tool dependency hai.setup.py: Yeh Python scriptcolconko instruct karta hai kaise apne Python modules aur executables ko build aur install karna. Yeh apne nodes ke entry points define karta hai aur apne package ke Python modules ko list karta hai.
Simple Publisher/Subscriber Nodes Likhna
Ek simple Python node typically:
rclpyaur other necessary ROS 2 message types ko import karta hai.rclpyko initialize karta hai aur ek node create karta hai.- Ek publisher ya subscriber create karta hai.
- Subscribers ke liye ek callback function, ya publishers ke liye ek timer callback implement karta hai.
- Node ko spin karta hai usse alive rakhne aur events process karne ke liye.
Ek Python publisher ka conceptual example:
# Minimal Publisher (Python)
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class MinimalPublisher(Node):
def __init__(self):
super().__init__('minimal_publisher')
self.publisher_ = self.create_publisher(String, 'topic', 10)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
msg = String()
msg.data = 'Hello ROS 2: %d' % self.i
self.publisher_.publish(msg)
self.get_logger().info('Publishing: "%s"' % msg.data)
self.i += 1
def main(args=None):
rclpy.init(args=args)
minimal_publisher = MinimalPublisher()
rclpy.spin(minimal_publisher)
minimal_publisher.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
5.3 C++ mein ROS 2 Packages Create Karna
C++ ROS 2 development ke liye ek other primary language hai, especially performance-critical components ke liye. Python ki tarah, ros2 pkg create C++ packages ke liye scaffolding ke liye use hota hai.
ros2 pkg create Use Karna
Ek naya C++ package create karne ke liye, apne workspace ke src directory mein navigate karo aur run karo:
ros2 pkg create --build-type ament_cmake my_cpp_package --dependencies rclcpp std_msgs
Yeh command ek directory my_cpp_package create karta hai package.xml aur CMakeLists.txt file ke saath, pre-configured ek C++ package ke liye aur rclcpp aur std_msgs ko dependencies ke taur par include karte hue.
CMakeLists.txt aur package.xml Configuration
package.xml: Python ki tarah, metadata aur dependencies define karta hai. C++ packages ke liye,ament_cmakebuild tool dependency hai, aur aap typicallyrclcpp(ROS 2 C++ client library) aur message packages jaisestd_msgspar depend karouge.CMakeLists.txt: Yeh CMake scriptcolconko instruct karta hai kaise apne C++ source files ko executables ya libraries mein compile karna, dependencies handle karna, aur artifacts install karna. Yehament_cmakefunctions use karta hai ROS 2-specific build steps ke liye.
Simple Publisher/Subscriber Nodes Likhna
Ek simple C++ node generally:
rclcpp/rclcpp.hppaur other necessary ROS 2 message headers ko include karta hai.rclcppko initialize karta hai aur ek node create karta hai.- Ek publisher ya subscriber object create karta hai.
- Subscribers ke liye ek callback function, ya publishers ke liye ek timer callback implement karta hai.
- Node ko spin karta hai usse alive rakhne aur events process karne ke liye.
Ek C++ publisher ka conceptual example:
// Minimal Publisher (C++)
#include <chrono>
#include <functional>
#include <memory>
#include <string>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using namespace std::chrono_literals;
class MinimalPublisher : public rclcpp::Node
{
public:
MinimalPublisher()
: Node("minimal_publisher"), count_(0)
{
publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10);
timer_ = this->create_wall_timer(
500ms, std::bind(&MinimalPublisher::timer_callback, this));
}
private:
void timer_callback()
{
auto message = std_msgs::msg::String();
message.data = "Hello ROS 2: " + std::to_string(count_++);
RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", message.data.c_str());
publisher_->publish(message);
}
rclcpp::TimerBase::SharedPtr timer_;
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
size_t count_;
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<MinimalPublisher>());
rclcpp::shutdown();
return 0;
}
5.4 Launch Files aur Parameter Management
ROS 2 launch files ek powerful way provide karte hain multiple nodes ko simultaneously start, configure, aur manage karne ke liye. Yeh typically Python (.launch.py) ya XML (.launch.xml) mein written hote hain aur complex system orchestration allow karte hain.
Launch System (ros2 launch) ka Taaruf
Launch files kar sakte hain:
- Multiple nodes (executables) ko start karna.
- Node parameters set karna.
- Topics ya services ko remap karna.
- Other launch files ko include karna.
- Conditionally nodes ko execute karna arguments ke basis par.
Ek simple Python launch file (my_launch_file.launch.py) ka example:
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
return LaunchDescription([
Node(
package='my_python_package',
executable='talker',
name='sim_talker',
output='screen',
emulate_tty=True
),
Node(
package='my_python_package',
executable='listener',
name='sim_listener',
output='screen',
emulate_tty=True
)
])
Is launch file ko run karne ke liye: ros2 launch my_python_package my_launch_file.launch.py
YAML Use Karna Parameter Files ke Liye
Parameters directly launch files mein set kiye ja sakte hain ya, more commonly, external YAML files se load kiye ja sakte hain. Yeh node ke behavior ko easily modify karne ko allow karta hai code ya launch files change kiye bagair.
Example config/params.yaml:
my_node:
ros__parameters:
some_int_param: 10
some_string_param: "hello"
Parameters ko launch file se load karne ke liye:
from launch import LaunchDescription
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
import os
def generate_launch_description():
params_file = os.path.join(
get_package_share_directory('my_python_package'),
'config',
'params.yaml'
)
return LaunchDescription([
Node(
package='my_python_package',
executable='my_node_with_params',
name='my_configured_node',
output='screen',
emulate_tty=True,
parameters=[params_file]
)
])
Launch Files ko Arguments Pass Karna
Launch files arguments accept kar sakte hain, unhe highly flexible banate hue.
5.5 colcon ke Saath Packages Build aur Run Karna
colcon ek command-line tool hai jo ROS 2 packages ko build, test, aur install karne ke liye use hota hai ek workspace mein.
colcon build, colcon test, colcon clean
colcon build: Workspace mein sabhe packages ko build karta hai, ya specific packages agar--packages-selectuse kiya jaye.colcon build
colcon build --packages-select my_python_packagecolcon test: Packages ke liye tests run karta hai.colcon testcolcon clean: Build, install, aur log directories ko remove karta hai.colcon clean
Workspace Source Karna
Building ke baad, aapko workspace ke install/setup.bash (ya setup.ps1 PowerShell ke liye, setup.zsh Zsh ke liye) file ko "source" karna zarorat hai apne installed packages ke executables, libraries, aur environment variables ko apne shell mein available banana.
source install/setup.bash
Yeh common hai is command ko apne ~/.bashrc mein add karne convenience ke liye.
Executables Run Karna
Once sourced, aap ros2 run use karte hue nodes run kar sakte ho:
ros2 run my_python_package my_talker_node
ros2 run my_cpp_package my_listener_node
5.6 ROS 2 Applications Debug Karna
ROS 2 applications ko debug karna often logging, introspection tools, aur standard debugging techniques ke combination involve karta hai.
Logging Mechanisms (rclpy.logging, rclcpp::Logger)
- ROS 2 built-in logging capabilities provide karta hai dono Python (
rclpy.logging) aur C++ (rclcpp::Logger) mein. - Aap log levels set kar sakte ho (DEBUG, INFO, WARN, ERROR, FATAL) verbosity control karne ke liye.
Example (Python logging):
self.get_logger().info('This is an info message.')
self.get_logger().warn('Something unexpected happened!')
rqt_graph, rqt_console Use Karna
rqt_graph: Ek graphical tool jo ROS 2 computation graph ko visualize karta hai (nodes, topics, services, actions, aur un ke connections). Complex systems ko samajhne ke liye invaluable.rqt_console: ROS 2 log messages ko GUI mein display karta hai, allowing filtering aur highlighting ke liye.
Basic Troubleshooting Techniques
- Check karna agar nodes run ho rahe hain:
ros2 node list - Active topics ko inspect karna:
ros2 topic list,ros2 topic info <topic_name>,ros2 topic echo <topic_name> - Active services ko inspect karna:
ros2 service list,ros2 service info <service_name> - Active actions ko inspect karna:
ros2 action list,ros2 action info <action_name> - Parameters check karna:
ros2 param list,ros2 param get <node_name> <param_name> - Standard debugger use karna (
gdbC++ ke liye,pdbPython ke liye) ya IDE debuggers (jaise VS Code).