Industrial Logistics Challenge (Online)
Introduction to ROS Python
Lecturer: Thitipong T.
Contents
• ROS Publisher and Subscriber
• Basic Python
• Challenges
• ROS Service and Client
• Introduction Commands
• Basic Python
• Challenges
ROS Publisher and Subscriber
Basic Python
You should have gained a basic understanding of the ROS workspace and package concepts. From the
diagram below, the root of ROS workspace is the catkin_ws. This folder will contain all of the robot package.
ROS Publisher and Subscriber
Basic Python
A ROS package is a fundamental unit of software organization in ROS. It provides a modular and self-
contained structure for managing and distributing ROS-related functionality. A package can contain one or more nodes,
libraries, configuration files, launch files, and any additional resources needed for a specific purpose or task.
To create a new ROS package and build the workspace, follow these steps:
1. Create and open a terminal and navigate to the src folder under the workspace.
$ mkdir -p ~/ros_ws/src
$ cd ~/ros_ws/src
2. Create ROS Package.
$ catkin_create_pkg turtle_training roscpp rospy std_msgs
ROS Publisher and Subscriber
Basic Python
To create a new ROS package and build the workspace, follow these steps:
3. Compile the workspace.
$ cd ~/ros_ws
$ catkin_make
4. Update current environment.
$ source ~/ros_ws/devel/setup.bash
5. If you don’t want to use source command for every terminal (Optional; only 1 time)
$ echo "source ~/ros_ws/devel/setup.bash" >> ~/.bashrc
$ source ~/.bashrc
ROS Publisher and Subscriber
Basic Python
After the package has been created successfully, the python script can be created to control our robot. And
it can be executed with command rosrun.
To create the python script, follow these steps:
1. The python script should be created under the package which keeps in folder scripts. The first command is the
changing directory to the package turtle_training using roscd command.
$ roscd turtle_training
2. Create the folder scripts. (If it is not existed)
$ mkdir scripts
ROS Publisher and Subscriber
Basic Python
To create the python script, follow these steps:
3. Go inside the script folder.
$ cd scripts
4. Create a file name pub.py.
$ touch pub.py
5. Change permissions mode. (to execute)
$ chmod +x pub.py
6. Use commands for editing code (nano, gedit, vi, code, etc.)
$ code pub.py # for editing code with vs code
ROS Publisher and Subscriber
Basic Python
Writing a Simple Publisher and Subscriber with Python
In the context of ROS (Robot Operating System) using the turtlesim simulation environment, a publisher and
subscriber mechanism facilitates communication between different parts of the system. A publisher is a node that
sends messages, for example, the command to move or rotate the turtle, utilizing specific topics like
/turtle1/cmd_vel for velocity commands. A subscriber, on the other hand, listens to messages on a given topic, such
as /turtle1/pose to receive updates on the turtle's position and orientation. This design allows for modular and
decoupled architecture, where, for instance, one node can control the turtle's movement while another monitors its
position, each operating independently yet interacting seamlessly through ROS's communication infrastructure.
ROS Publisher and Subscriber
Basic Python
Writing a Simple Publisher and Subscriber with Python
#!/usr/bin/env python3
import rospy
from geometry_msgs.msg import Twist
from turtlesim.msg import Pose
cmd_vel_ = Twist()
turtle_pose_ = Pose()
Example code: https://gitlab.raikmitl.com/ired-robot/industrial_logistics_online/-/blob/main/pub.py?ref_type=heads
ROS Publisher and Subscriber
Basic Python
Writing a Simple Publisher and Subscriber with Python
def turtlePose(msg):
global turtle_pose_
turtle_pose_ = msg
rospy.loginfo(f'x: {turtle_pose_.x} y: {turtle_pose_.y}')
Example code: https://gitlab.raikmitl.com/ired-robot/industrial_logistics_online/-/blob/main/pub.py?ref_type=heads
ROS Publisher and Subscriber
Basic Python
Writing a Simple Publisher and Subscriber with Python
def main():
global cmd_vel_, turtle_pose_
rospy.init_node(‘turtle_pubsub')
rate = rospy.Rate(10)
rospy.loginfo('Waiting for turtlesim')
rospy.wait_for_message('/turtle1/pose', Pose)
rospy.Subscriber('/turtle1/pose', Pose, turtlePose)
cmd_vel_pub_ = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
while not rospy.is_shutdown():
cmd_vel_.linear.x = 1.0
cmd_vel_pub_.publish(cmd_vel_)
rate.sleep()
Example code: https://gitlab.raikmitl.com/ired-robot/industrial_logistics_online/-/blob/main/pub.py?ref_type=heads
ROS Publisher and Subscriber
Basic Python
Writing a Simple Publisher and Subscriber with Python
if __name__ == '__main__':
try:
main()
except rospy.ROSInterruptException:
pass
Try to run your ROS Python node:
$ rosrun turtle_training pub.py
Example code: https://gitlab.raikmitl.com/ired-robot/industrial_logistics_online/-/blob/main/pub.py?ref_type=heads
ROS Publisher and Subscriber
Challenge 1
Turtle needs to be stopped at position x = 10. Students modify the source code by creating the condition
(if-else) to complete this task and upload the screenshot of completion. (Hint: The variable turtle_pose_.x which
represents the TurtleSim position can be used to create the condition to make it stop by changing the velocity
command by cmd_vel_.linear.x = 0.)
Spacial Challenge
Move the Turtlesim to draw a square by moving it to four positions using Python programming with ROS
publishers and subscribers.
ROS Service and Client
Introduction Commands
Services are another way that nodes can communicate with each other. Services allow nodes to send a
request and receive a response.
Command-line tool
The rosservice command implements a variety of commands that let you discover which services are
currently online from which nodes and further drill down to get specific information about a service, such as its type,
URI, and arguments. You can also call a service directly from the command line.
ROS Service and Client
Introduction Commands
Services are another way that nodes can communicate with each other. Services allow nodes to send a
request and receive a response.
Command-line tool
Start turtlesim_node for checking service available.
$ roscore # terminal 1
$ rosrun turtlesim turtlesim_node #terminal 2
ROS Service and Client
Introduction Commands
Command-line tool
rosservice list command shows us the active services example as turtlesim node provides nine services.
$ rosservice list
ROS Service and Client
Introduction Commands
Command-line tool
rosservice type used to determine the type of a specific ROS service.
$ rosservice type [service name]
Let's find out what type the /clear service is:
$ rosservice type /clear
std_srvs/Empty
This service is empty, this means when the service call is made it takes no arguments (i.e. it sends no data
when making a request and receives no data when receiving a response). Let's call this service using rosservice call:
ROS Service and Client
Introduction Commands
Command-line tool
rosservice call used to call a specific ROS service.
$ rosservice call [service name] [args]
Here we'll call with no arguments because the service is of type empty:
$ rosservice call /clear
This is what we expect, it clears the background of the turtlesim_node.
ROS Service and Client
Introduction Commands
Command-line tool
Let's look at the case where the service has arguments by looking at the information for the service spawn.
$ rosservice type /spawn | rossrv show
float32 x
float32 y
float32 theta
string name
---
string name
This service lets us spawn a new turtle at a given location and orientation. The name field is optional, so
let's not give our new turtle a name and let turtlesim create one for us.
$ rosservice call /spawn 3.0 3.0 1.57 "LLCROS"
name: "LLCROS"
ROS Service and Client
Basic Python
From the previous chapter (Introduction to ROS), a package for using ROS Publish Subscriber was created. In
this chapter, we will study how to write Python for creating a ROS service server and client to control the operation of
turtlesim.
To create the python script, follow these steps:
1. The python script should be created under the package which keeps in folder scripts. The first command is the
changing directory to the package turtle_training using roscd command.
$ roscd turtle_training/scripts
2. Create a file name service.py.
$ touch service.py
ROS Service and Client
Basic Python
To create the python script, follow these steps:
3. Change permissions mode. (to execute)
$ chmod +x service.py
4. Use commands for editing code (nano, gedit, vi, code, etc.)
$ code service.py # for editing code with vs code
ROS Service and Client
Basic Python
Example ROS service server and client with Python.
In the Robot Operating System (ROS), services and clients are used for synchronous communication between
nodes. This means that a service provides some functionality, and a client can request this functionality and wait for
the result. This is different from ROS topics, which are used for asynchronous communication. For the example of
writing Python programs for using the ROS service server and client in this chapter, we will work with turtlesim by
calling the service /turtle1/set_pen to change the color and size of the turtlesim's movement line. We will also
create a service server to be called externally to prepare for sending the movement position using the service name
/turtle1/gotoPose.
ROS Service and Client
Basic Python
Example ROS service server and client with Python.
#!/usr/bin/env python3
import rospy
from turtlesim.srv import SetPen
from turtlesim.srv import TeleportAbsolute, TeleportAbsoluteResponse
def gotoPose(req):
pose_x_ = req.x
pose_y_ = req.y
theta_ = req.theta
rospy.loginfo(f'Service => x: {pose_x_} y: {pose_y_} theta: {theta_}')
return TeleportAbsoluteResponse()
Example code: https://gitlab.raikmitl.com/ired-robot/industrial_logistics_online/-/blob/main/service.py?ref_type=heads
ROS Service and Client
Basic Python
Example ROS service server and client with Python.
def turtleSetPen(r, g, b, width, off):
turtle_setpen_ = rospy.ServiceProxy('/turtle1/set_pen', SetPen)
resp_ = turtle_setpen_(r, g, b, width, off)
return resp_
Example code: https://gitlab.raikmitl.com/ired-robot/industrial_logistics_online/-/blob/main/service.py?ref_type=heads
ROS Service and Client
Basic Python
Example ROS service server and client with Python.
def main():
rospy.init_node('lab2_service')
rate = rospy.Rate(10)
rospy.loginfo("Waiting for turtlesim...")
rospy.wait_for_service('/turtle1/set_pen')
turtleSetPen(0, 0, 255, 5, 0)
rospy.loginfo("Setpen...")
rospy.Service('/turtle1/gotoPose', TeleportAbsolute, gotoPose)
rospy.loginfo("Ready to command gotoPose service.")
Example code: https://gitlab.raikmitl.com/ired-robot/industrial_logistics_online/-/blob/main/service.py?ref_type=heads
ROS Service and Client
Basic Python
Example ROS service server and client with Python.
if __name__ == '__main__':
try:
main()
except rospy.ROSInterruptException:
pass
Example code: https://gitlab.raikmitl.com/ired-robot/industrial_logistics_online/-/blob/main/service.py?ref_type=heads
ROS Service and Client
Basic Python
Try to run rosservice
1. Check that your Turtlesim has already started. (If not, start it.)
$ roscore # terminal 1
$ rosrun turtlesim turtlesim_node # terminal 2
2. Start your service node.
$ rosrun turtle_training service.py
3. Check your ROS Service server with this command. After that, check the output in the terminal running service.py.
$ rosservice call /turtle1/gotoPose 1.5 2.5 3.14
# x y theta
ROS Service and Client
Basic Python
Try to run rosservice
4. Check your ROS service client by trying to move your Turtlesim and observing its path, which will change color. (Use
the command turtle_teleop_key for testing.)
$ rosrun turtlesim turtle_teleop_key
ROS Service and Client
Challenge 1
Use the rosservice command to move the Turtlesim to draw a square by moving it to four positions. (Hint:
check the service type of /turtle1/teleport_absolute and use the rosservice call command to move the Turtlesim).
Spacial Challenge
Move the Turtlesim to four different positions using Python programming and change its path color to black
(RGB: 0, 0, 0). (Hint: check the configuration of your Python scripts and use the guide function to move the Turtlesim).
def turtleGotoPose(x:float, y:float, theta:float):
rospy.wait_for_service(‘/turtle1/teleport_absolute')
rospy.loginfo(f'Goto => x: {x} y: {y} theta: {theta}')
turtle_gotoPose_ = rospy.ServiceProxy(‘/turtle1/teleport_absolute', TeleportAbsolute)
resp_ = turtle_gotoPose_(x, y, theta)
return resp_