Summer 2015 MultiRobot Systems with ROS Lesson 2

Summer 2015 Multi-Robot Systems with ROS Lesson 2 Teaching Assistant: Roi Yehoshua roiyeho@gmail. com

Agenda • • Simulating multiple robots in Stage Collision avoidance Robots synchronization Creating custom messages (C)2015 Roi Yehoshua

ROS Stage Simulator • Stage simulates a population of mobile robots, sensors and objects in a 2 D bitmapped environment • Stage is designed to support research of multi-agent autonomous systems, so it provides fairly simple, computationally cheap models of lots of devices rather than attempting to emulate any device with great fidelity • Multi-Robot Patrolling Task - Simulation in Stage/ROS (C)2015 Roi Yehoshua

Stage World Files • The world file is a description of the world that Stage must simulate • It describes robots, sensors, actuators, moveable and immovable objects • Sample world files can be found at the /world subdirectory in ros_stage package (C)2015 Roi Yehoshua

Simulating Multiple Robots in Stage • First, you need to build a model of every robot you need in the world file • For example, let’s add 3 more robots to willowerratic. world • First we will copy it to the home directory and change its name to willow_multi_erratic. world – Notice that you also need to copy willow-full. pgm $ cd ~ $ cp /opt/ros/indigo/share/stage_ros/world/willow-erratic. world willow-multierratic. world $ cp /opt/ros/indigo/share/stage_ros/world/willow-full. pgm. (C)2015 Roi Yehoshua

Simulating Multiple Robots in Stage • Now add the following lines at the end of the file willow-multi-erratic. world # robots erratic( pose [ -11. 5 23. 5 0 0 ] name "robot 0" color "blue") erratic( pose [ -13. 5 23. 5 0 0 ] name "robot 1" color "red") erratic( pose [ -11. 5 21. 5 0 0 ] name "robot 2" color "green") erratic( pose [ -13. 5 21. 5 0 0 ] name "robot 3" color "magenta") # block( pose [ -13. 924 25. 020 0 180. 000 ] color "red") • Then run again the stage simulator rosrun stage_ros stageros willow-multi-erratic. world (C)2015 Roi Yehoshua

Simulating Multiple Robots in Stage (C)2015 Roi Yehoshua

Simulating Multiple Robots in Stage • Each robot subscribes and publishes its own topics (C)2015 Roi Yehoshua

Simulating Multiple Robots in Stage • You can move one of the robots by publishing to /robot_X/cmd_vel topic • For example, to make robot 2 move forward type: rostopic pub /robot_2/cmd_vel -r 10 geometry_msgs/Twist '{linear: {x: 0. 2}}' (C)2015 Roi Yehoshua

Simulating Multiple Robots in Stage (C)2015 Roi Yehoshua

Creating a ROS Package • Now we will create a ROS node that will make one of the robots move forward • The ID of the robot will be given as a commandline argument to the node (C)2015 Roi Yehoshua

catkin Workspace • Make sure you have a catkin workspace ready • If you don’t have, run the following commands: $ mkdir catkin_ws/src $ cd catkin_ws/src $ catkin_init_workspace $ cd. . $ catkin_make • And add the following line to your bashrc source ~/catkin_ws/devel/setup. bash (C)2015 Roi Yehoshua

Creating a ROS Package • Create a new ROS package called stage_multi $ cd ~/catkin_ws/src $ catkin_create_pkg stage_multi std_msgs rospy roscpp • Create a world subdirectory in the package and copy the world files into it $ mkdir ~/catkin_ws/src/stage_multi/world $ cp ~/willow-multi-erratic. world ~/catkin_ws/src/stage_multi/world $ cp ~/willow-full. pgm ~/catkin_ws/src/stage_multi/world (C)2015 Roi Yehoshua

Creating a ROS Package • Now compile the package and create an Eclipse project file for it: $ cd ~/catkin_ws $ catkin_make --force-cmake -G"Eclipse CDT 4 - Unix Makefiles" (C)2015 Roi Yehoshua

Directory Structure (C)2015 Roi Yehoshua

Import the Project into Eclipse • Now start Eclipse • Choose catkin_ws folder as the workspace folder (C)2015 Roi Yehoshua

Import the Project into Eclipse • Choose File --> Import --> General --> Existing Projects into Workspace (C)2015 Roi Yehoshua

Import the Project into Eclipse • Now choose the ~/catkin_ws/build folder (C)2015 Roi Yehoshua

Project Structure • Open the "Source directory" within the project so that you can edit the source code (C)2015 Roi Yehoshua

Add New Source File • Right click on src and select New –> Source File, and create a file named move_robot. cpp (C)2015 Roi Yehoshua

ROS Init • A version of ros: : init() must be called before using any of the rest of the ROS system • Typical call in the main() function: ros: : init(argc, argv, "Node name"); • Node names must be unique in a running system • We will make the node names unique by concatenating the robot’s number to the end of the node name • For that purpose we will need to supply the robot’s number as a command-line argument (C)2015 Roi Yehoshua

move_robot. cpp (1) #include "ros/ros. h" #include "geometry_msgs/Twist. h" #include <string> using namespace std; #define MAX_ROBOTS_NUM 20 #define FORWARD_SPEED 0. 2 int robot_id; ros: : Publisher cmd_vel_pub; // publisher for movement commands void move_forward(); (C)2015 Roi Yehoshua

move_robot. cpp (2) int main(int argc, char **argv) { if (argc < 2) { ROS_ERROR("You must specify robot id. "); return -1; } char *id = argv[1]; robot_id = atoi(id); // Check that robot id is between 0 and MAX_ROBOTS_NUM if (robot_id > MAX_ROBOTS_NUM || robot_id < 0 ) { ROS_ERROR("The robot's ID must be an integer number between 0 an 19"); return -1; } ROS_INFO("moving robot no. %d", robot_id); // Create a unique node name string node_name = "move_robot_"; node_name += id; cout << node_name; ros: : init(argc, argv, node_name); ros: : Node. Handle nh; (C)2015 Roi Yehoshua

move_robot. cpp (3) // cmd_vel_topic = "robot_X/cmd_vel" string cmd_vel_topic_name = "robot_"; cmd_vel_topic_name += id; cmd_vel_topic_name += "/cmd_vel"; cmd_vel_pub = nh. advertise<geometry_msgs: : Twist>(cmd_vel_topic_name, 10); move_forward(); return 0; } (C)2015 Roi Yehoshua

move_forward function void move_forward() { // Drive forward at a given speed. geometry_msgs: : Twist cmd_vel; cmd_vel. linear. x = FORWARD_SPEED; cmd_vel. angular. z = 0. 0; // Loop at 10 Hz, publishing movement commands until we shut down ros: : Rate rate(10); while (ros: : ok()) // Keep spinning loop until user presses Ctrl+C { cmd_vel_pub. publish(cmd_vel); rate. sleep(); } // Stop the robot geometry_msgs: : Twist stop_cmd_vel; stop_cmd_vel. linear. x = 0. 0; stop_cmd_vel. angular. z = 0. 0; cmd_vel_pub. publish(stop_cmd_vel); ROS_INFO("robot no. %d stopped", robot_id); } (C)2015 Roi Yehoshua

Compiling the Node • Before building your node, you should modify the generated CMake. Lists. txt in the package • Change the lines marked in red: cmake_minimum_required(VERSION 2. 8. 3) project(stage_multi) … ## Declare a cpp executable add_executable(multi_sync src/Sync. Robots. cpp) ## Add cmake target dependencies of the executable/library ## as an example, message headers may need to be generated before nodes # add_dependencies(stage_multi_node stage_multi_generate_messages_cpp) ## Specify libraries to link a library or executable target against target_link_libraries(move_robot ${catkin_LIBRARIES}) • After changing the file call catkin_make (C)2015 Roi Yehoshua

Running the Node Inside Eclipse • Create a new launch configuration, by clicking on Run --> Run configurations. . . --> C/C++ Application (double click or click on New). • Select the correct binary on the main tab (use the Browse… button) ~/catkin_ws/devel/lib/stage_multi/move_robot • Make sure roscore and stage are running • Click Run (C)2015 Roi Yehoshua

Running the Node Inside Eclipse (C)2015 Roi Yehoshua

Setting Command Line Arguments (C)2015 Roi Yehoshua

Running the Node Inside Eclipse (C)2015 Roi Yehoshua

Running the Node Inside Eclipse (C)2015 Roi Yehoshua

Running the Node Inside Eclipse (C)2015 Roi Yehoshua

Launch File • Now we will create a launch file that will make all the 4 robots move forward • We will use the args attribute in the <node> tag to specify the command line arguments • Create a launch subdirectory in stage_multi package • Add stage_multi. launch file to this directory and copy the following code (C)2015 Roi Yehoshua

Launch File <launch> <node name="stage" pkg="stage_ros" type="stageros" args="$(find stage_multi)/world/willow-multi-erratic. world"/> <node name="move_robot_0" pkg="stage_multi" type="move_robot" args="0" output="screen"/> <node name="move_robot_1" pkg="stage_multi" type="move_robot" args="1" output="screen"/> <node name="move_robot_2" pkg="stage_multi" type="move_robot" args="2" output="screen"/> <node name="move_robot_3" pkg="stage_multi" type="move_robot" args="3" output="screen"/> </launch> • Note that the node names must be unique (C)2015 Roi Yehoshua

Launch File • Run the launch file using the following command: roslaunch stage_multi. launch (C)2015 Roi Yehoshua

Launch File (C)2015 Roi Yehoshua

Launch File • The robots will eventually bump into the obstacles: (C)2015 Roi Yehoshua

Reading Sensors • Now we will make the robots move until they sense an obstacle – Will they be able to sense each other as obstacles? • For that purpose we will use the laser data published on the topic /base_scan • The message type used to send information of the laser is sensor_msgs/Laser. Scan (C)2015 Roi Yehoshua

move_robot. cpp (1) #include "ros/ros. h" #include "geometry_msgs/Twist. h" #include "sensor_msgs/Laser. Scan. h" #include <string> using namespace std; #define #define MAX_ROBOTS_NUM 20 FORWARD_SPEED 0. 2 MIN_SCAN_ANGLE -60. 0/180*M_PI MAX_SCAN_ANGLE +60. 0/180*M_PI MIN_PROXIMITY_RANGE 0. 5 int robot_id; ros: : Publisher cmd_vel_pub; // publisher for movement commands ros: : Subscriber laser_scan_sub; // subscriber to the robot's laser scan topic bool keep. Moving = true; void move_forward(); void scan. Callback(const sensor_msgs: : Laser. Scan: : Const. Ptr& scan); (C)2015 Roi Yehoshua

move_robot. cpp (2) int main(int argc, char **argv) { if (argc < 2) { ROS_ERROR("You must specify robot id. "); return -1; } char *id = argv[1]; robot_id = atoi(id); . . . // subscribe to robot's laser scan topic "robot_X/base_scan" string laser_scan_topic_name = "robot_"; laser_scan_topic_name += id; laser_scan_topic_name += "/base_scan"; laser_scan_sub = nh. subscribe(laser_scan_topic_name, 1, &scan. Callback); move_forward(); return 0; } (C)2015 Roi Yehoshua

move_robot. cpp (2) void move_forward() { // Drive forward at a given speed. geometry_msgs: : Twist cmd_vel; cmd_vel. linear. x = FORWARD_SPEED; cmd_vel. angular. z = 0. 0; // Loop at 10 Hz, publishing movement commands until we shut down ros: : Rate rate(10); while (ros: : ok() && keep. Moving) // Keep spinning loop until user presses Ctrl+C { cmd_vel_pub. publish(cmd_vel); ros: : spin. Once(); // Need to call this function often to allow ROS to process incoming messages rate. sleep(); }. . . } (C)2015 Roi Yehoshua

scan. Callback // Process the incoming laser scan message void scan. Callback(const sensor_msgs: : Laser. Scan: : Const. Ptr& scan) { // Find the closest range between the defined minimum and maximum angles int min. Index = ceil((MIN_SCAN_ANGLE - scan->angle_min) / scan>angle_increment); int max. Index = floor((MAX_SCAN_ANGLE - scan->angle_min) / scan>angle_increment); float closest. Range = scan->ranges[min. Index]; for (int curr. Index = min. Index + 1; curr. Index <= max. Index; curr. Index++) { if (scan->ranges[curr. Index] < closest. Range) { closest. Range = scan->ranges[curr. Index]; } } //ROS_INFO_STREAM("Closest range: " << closest. Range); if (closest. Range < MIN_PROXIMITY_RANGE) { keep. Moving = false; } } (C)2015 Roi Yehoshua

Reading Sensors (C)2015 Roi Yehoshua

Collision Avoidance • All models in Stage (including lasers and robot bases) have heights • A sensor will only "see" other models at the same height • In Stage. world examples, the robots have lasers mounted on their tops in such a way that a robot's laser only sees other robots' lasers, not their bases • This is the correct result for such a robot configuration, since in the real world, the laser planes don't intersect the robot bases. • If you want to simulate a different (perhaps less realistic) kind of robot, you can adjust the laser heights (C)2015 Roi Yehoshua
![Collision Avoidance define erratic position ( #size [0. 415 0. 392 0. 25] size Collision Avoidance define erratic position ( #size [0. 415 0. 392 0. 25] size](http://slidetodoc.com/presentation_image_h2/6676bd2003c85f26979b3ed0b8817780/image-45.jpg)
Collision Avoidance define erratic position ( #size [0. 415 0. 392 0. 25] size [0. 35 0. 25] origin [-0. 05 0 0 0] gui_nose 1 drive "diff" topurg(pose [ 0. 050 0. 000 -0. 1 0. 000 ]) ) (C)2015 Roi Yehoshua

Collision Avoidance (C)2015 Roi Yehoshua

Collision Avoidance • A more difficult problem related to collision avoidance is that when two lasers see each other directly, they often get "dazzled", and the data are discarded. • Laser-based obstacle avoidance among a group of homogeneous robots is difficult • Can you think of a solution to this problem? (C)2015 Roi Yehoshua

Robots Synchronization • One important aspect of multi-robot systems is the need of coordination and synchronization of behavior between robots in the team • We will now make our robots wait for each other before they start moving (C)2015 Roi Yehoshua

Robots Synchronization • First we will create a shared topic called team_status • Each robot when ready – will publish a ready status message to the shared topic • In addition, we will create a monitor node that will listen for the ready messages • When all ready messages arrive, the monitor node will publish a broadcast message that will let the robots know that the team is ready and they can start moving (C)2015 Roi Yehoshua

Robot. Status Message • We will start by creating a new ROS message type for the ready messages called Robot. Status • The structure of the message will be: Header header int 32 robot_id bool is_ready • The header contains a timestamp and coordinate frame information that are commonly used in ROS (C)2015 Roi Yehoshua

Message Header • stamp specifies the publishing time • frame_id specifies the point of reference for data contained in that message (C)2015 Roi Yehoshua

Message Field Types Field types can be: • a built-in type, such as "float 32 pan" or "string name" • names of Message descriptions defined on their own, such as "geometry_msgs/Pose. Stamped" • fixed- or variable-length arrays (lists) of the above, such as "float 32[] ranges" or "Point 32[10] points“ • the special Header type, which maps to std_msgs/Header (C)2015 Roi Yehoshua

Built-In Types (C)2015 Roi Yehoshua

msg Files • msg files are simple text files that describe the fields of a ROS message • They are used to generate source code for messages in different languages • Stored in the msg directory of your package (C)2015 Roi Yehoshua

Create a Message • First create a new package called multi_sync $ cd ~/catkin_ws/src $ catkin_create_pkg multi_sync std_msgs rospy roscpp • Copy the world subdirectory from the stage_multi package we created in the last lesson to the new package • Now create a subdirectory msg and the file Robot. Status. msg within it $ cd ~/catkin_ws/src/multi_sync $ mkdir msg $ gedit msg/Robot. Status. msg (C)2015 Roi Yehoshua

Create a Message Type • Add the following lines to Robot. Status. msg: Header header int 32 robot_id bool is_ready • Now we need to make sure that the msg files are turned into source code for C++, Python, and other languages (C)2015 Roi Yehoshua

package. xml • Open package. xml, and add the following two lines to it <build_depend>roscpp</build_depend> <build_depend>rospy</build_depend> <build_depend>std_msgs</build_depend> <build_depend>message_generation</build_depend> <run_depend>roscpp</run_depend> <run_depend>rospy</run_depend> <run_depend>std_msgs</run_depend> <run_depend>message_runtime</run_depend> • Note that at build time, we need "message_generation", while at runtime, we need "message_runtime" (C)2015 Roi Yehoshua

CMake. Lists • Add the message_generation dependency to the find package call so that you can generate messages: find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs message_generation ) • Also make sure you export the message runtime dependency: catkin_package( # INCLUDE_DIRS include # LIBRARIES multi_sync CATKIN_DEPENDS roscpp rospy std_msgs message_runtime # DEPENDS system_lib ) (C)2015 Roi Yehoshua

CMake. Lists • Find the following block of code: ## Generate messages in the 'msg' folder # add_message_files( # FILES # Message 1. msg # Message 2. msg #) • Uncomment it by removing the # symbols and then replace the stand in Message*. msg files with your. msg file, such that it looks like this: add_message_files( FILES Robot. Status. msg ) (C)2015 Roi Yehoshua

CMake. Lists • Now we must ensure the generate_messages() function is called • Uncomment these lines: # generate_messages( # DEPENDENCIES # std_msgs #) • So it looks like: generate_messages( DEPENDENCIES std_msgs ) (C)2015 Roi Yehoshua

Compiling a package with custom messages • If you need to compile nodes that depend on custom messages in the same package, you need to run catkin_make with the following argument: catkin_make -j 4 • Otherwise catkin_make tries to compile the library without waiting for all the message headers to be generated (C)2015 Roi Yehoshua

Using rosmsg • That's all you need to do to create a msg • Let's make sure that ROS can see it using the rosmsg show command: $ rosmsg show [message type] (C)2015 Roi Yehoshua

Create a Message • Now we need to make our package: $ cd ~/catkin_ws $ catkin_make • During the build, source files will be created from the. msg file: (C)2015 Roi Yehoshua

Create a Message • Any. msg file in the msg directory will generate code for use in all supported languages. • The C++ message header file will be generated in ~/catkin_ws/devel/include/multi_sync/ (C)2015 Roi Yehoshua

Robot. Status. h #include <std_msgs/Header. h> namespace multi_sync { template <class Container. Allocator> struct Robot. Status_ { typedef Robot. Status_<Container. Allocator> Type; Robot. Status_() : header() , robot_id(0) , is_ready(false) { } typedef : : std_msgs: : Header_<Container. Allocator> _header_type header; _header_type; typedef uint 32_t _robot_id_type; _robot_id_type robot_id; typedef uint 8_t _is_ready_type; _is_ready_type is_ready; typedef boost: : shared_ptr< : : multi_sync: : Robot. Status_<Container. Allocator> > Ptr; typedef boost: : shared_ptr< : : multi_sync: : Robot. Status_<Container. Allocator> const> Const. Ptr; boost: : shared_ptr<std: : map<std: : string, std: : string> > __connection_header; }; // struct Robot. Status_ typedef : : multi_sync: : Robot. Status_<std: : allocator<void> > Robot. Status; (C)2015 Roi Yehoshua

Importing Messages • Copy move_robot. cpp from the last lesson to the package • Now import the Robot. Status header file by adding the following line: #include <multi_sync/Robot. Status. h> • Note that messages are put into a namespace that matches the name of the package (C)2015 Roi Yehoshua

Team Status Messages • We will use a shared topic called team_status to receive status messages from other team members • Each robot will have both a publisher and a listener object to this topic • Add the following global (class) variables: ros: : Subscriber team_status_sub; ros: : Publisher team_status_pub; (C)2015 Roi Yehoshua

Team Status Messages • In the main() function initialize the publisher and the listener: team_status_pub = nh. advertise<multi_sync: : Robot. Status>("team_status", 10); team_status_sub = nh. subscribe("team_status", 1, &team. Status. Callback); • Then call a function that will publish a ready status message (before calling move_forward): publish. Ready. Status(); • After that call a function that will wait for all the other team members to become ready: wait. For. Team(); (C)2015 Roi Yehoshua

Publishing Ready Status Message • Add the following function that will publish a status message when the robot is ready: void publish. Ready. Status() { multi_sync: : Robot. Status status_msg; status_msg. header. stamp = ros: : Time: : now(); status_msg. robot_id = robot_id; status_msg. is_ready = true; // Wait for the publisher to connect to subscribers sleep(1. 0); team_status_pub. publish(status_msg); ROS_INFO("Robot %d published ready status", robot_id); } • Note that the publisher needs some time to connect to the subscribers, thus you need to wait between creating the publisher and sending the first message (C)2015 Roi Yehoshua

Waiting for Team • First add a global (class) boolean variable that will indicate that all robots are ready: bool team. Ready = false; • Now add the following function: void wait. For. Team() { ros: : Rate loop. Rate(1); // Wait until all robots are ready. . . while (!team. Ready) { ROS_INFO("Robot %d: waiting for team", robot_id); ros: : spin. Once(); loop. Rate. sleep(); } } – ros: : spin. Once() will call the team status callbacks waiting to be called at that point in time. (C)2015 Roi Yehoshua

Receiving Team Ready Status • Add the following callback function to move_robot. cpp that will receive a team ready message from the monitor node: void team. Status. Callback(const multi_sync: : Robot. Status: : Const. Ptr& status_msg) { // Check if message came from monitor if (status_msg->header. frame_id == "monitor") { ROS_INFO("Robot %d: Team is ready. Let's move!", robot_id); team. Ready = true; } } (C)2015 Roi Yehoshua

Compiling the Node • Uncomment the following lines in CMake. Lists. txt: cmake_minimum_required(VERSION 2. 8. 3) project(multi_sync) … ## Declare a cpp executable add_executable(move_robot_sync src/move_robot. cpp) ## Specify libraries to link a library or executable target against target_link_libraries(move_robot_sync ${catkin_LIBRARIES} ) • Then call catkin_make (C)2015 Roi Yehoshua

Launch File • Create a launch file named multi_sync. launch in /launch subdirectory and add the following lines: <launch> <node name="stage" pkg="stage_ros" type="stageros" args="$(find multi_sync)/world/willow-multi-erratic. world"/> <node name="move_robot_0" pkg="multi_sync" type="move_robot" args="0" output="screen"/> <node name="move_robot_1" pkg="multi_sync" type="move_robot" args="1" output="screen"/> <node name="move_robot_2" pkg="multi_sync" type="move_robot" args="2" output="screen"/> <node name="move_robot_3" pkg="multi_sync" type="move_robot" args="3" output="screen"/> </launch> (C)2015 Roi Yehoshua

Running the move_robot nodes (C)2015 Roi Yehoshua

Ready status messages • Type rostopic echo /team_status to watch the ready messages: (C)2015 Roi Yehoshua

Homework (not for submission) • Create a monitor node that will listen for the ready messages and announce when all robots are ready (C)2015 Roi Yehoshua
- Slides: 76