[ROS Q&A] 170 – How can I perform some actions after the program ends?

[ROS Q&A] 170 – How can I perform some actions after the program ends?

Learn how to trigger an event in order to execute some action when our ROS program ends. This is an answer to the following question on ROS Answers:  https://answers.ros.org/question/309529/how-can-i-perform-some-actions-after-the-program-ends/.

Related Resources

Step 1: Get your development environment ready

Either of the following will do:

  1. Use the ROS Development Studio (ROSDS), an online platform for developing for ROS within a PC browser. Easy-peasy. I’m using this option for this post
    1. Once you log in, click on the New ROSject button to create a project that will host your code. Then Click on Open ROSject to launch the development/simulation environment.
    2. To open a “terminal” on ROSDSpick the Shell app from the Tools menu.
    3. You can find the IDE app on the Tools menu.
  2. You have ROS installed on a local PC. Okay, skip to Step 2.

Next step!

Step 2: Create a package with the code given in the post

1. If you are working on ROSDS, please create a ROSject first, as indicated in Step 1.

2. Open a terminal and create a package that holds the Python code:

user:~$ cd catkin_ws/src
user:~/catkin_ws/src$ catkin_create_pkg test_shutdown rospy
Created file test_shutdown/CMakeLists.txt
Created file test_shutdown/package.xml
Created folder test_shutdown/src
Successfully created files in /home/user/catkin_ws/src/test_shutdown. Please adjust the values in package.xml.
user:~/catkin_ws/src$ cd test_shutdown/src
user:~/catkin_ws/src/test_shutdown/src$ touch test_shutdown.py
user:~/catkin_ws/src/test_shutdown/src$ chmod +x test_shutdown.py

3. Open test_shutdown.py in the IDE and paste in the following code:

#!/usr/bin/env python
import rospy
from std_msgs.msg import String

def talker():

    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(10) # 10hz
    while not rospy.is_shutdown():
        hello_str = "hello world %s" % rospy.get_time()
        rospy.loginfo(hello_str)
        pub.publish(hello_str)
        rate.sleep()

try:
    talker()
except rospy.ROSInterruptException:
    rospy.loginfo("TEST")

4. Compile and run the code: go back to the catkin_ws directory and run the following commands

user:~/catkin_ws$ catkin_make
user:~/catkin_ws$ source devel/setup.bash
user:~/catkin_ws$ rospack profile
user:~/catkin_ws$ rosrun test_shutdown test_shutdown.py

(PS: Please run nohup roscore & to start ROS master in the background if you get an error that says “cannot connect to master”)

5. Stop the program with Ctrl + C:

Nothing happened? Yes, nothing happened like the OP explained. The OP expected that the word “TEST” would be printed, but it wasn’t. Let’s fix that next.

Step 3: Modify the code so that it triggers some actions when our ROS program ends

The key tool here is the rospy.on_shutdown() hook, which takes a function that should be called when ROS gets the shutdown signal.

Replace the code in test_shutdown.py with the following code that creates the shutdown hook function and registers it.

#!/usr/bin/env python

import rospy
from std_msgs.msg import String

def talker():

    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(10) # 10hz
    while not rospy.is_shutdown():
        hello_str = "hello world %s" % rospy.get_time()
        rospy.loginfo(hello_str)
        pub.publish(hello_str)
        rate.sleep()

def my_shutdown_hook():
    rospy.loginfo("It's shutdown time!")

try:
    rospy.on_shutdown(my_shutdown_hook)
    talker()
except rospy.ROSInterruptException:
    rospy.loginfo("TEST")

Now run the program again and then stop it with Ctrl + C:

user:~/catkin_ws$ rosrun test_shutdown test_shutdown.py
[INFO] [1586198566.464600]: hello world 1586198566.46
[INFO] [1586198566.564763]: hello world 1586198566.56
^C[INFO] [1586198568.326002]: It's shutdown time!

And that was it! Of course, the shutdown hook could perform more useful tasks, like stopping the robot for example.

Extra: Video of the post

Here below you have a “sights and sounds” version of this post, just in case you prefer it that way. Enjoy!

Feedback

Did you like this post? Do you have any questions about the explanations? Whatever the case, please leave a comment on the comments section below, so we can interact and learn from each other.

If you want to learn about other ROS or ROS2 topics, please let us know in the comments area and we will do a video or post about it.


Edited by Bayode Aderinola

[ROS Q&A] 168 – What are the differences between global and local costmap

[ROS Q&A] 168 – What are the differences between global and local costmap

About:
In the following video, we are going to explain, using a simple example with Summit XL robot, what are the main differences between the global costmap and the local costmap.

// RELATED LINKS
Robot Ignite Academy
ROS Development Studio (ROSDS)


Feedback

Did you like this video? Do you have questions about what is explained? Whatever the case, please leave a comment on the comments section below, so we can interact and learn from each other.

If you want to learn about other ROS topics, please let us know on the comments area and we will do a video about it.

[ROS Q&A] 167 – Test Stereo Camera in ROS

[ROS Q&A] 167 – Test Stereo Camera in ROS

About:
This video shows how to test that a stereo camera is working. This is an answer to the question in ROS ANSWERS

Case Studies – How Softbank engineers learn complex ROS subjects fast

Case Studies – How Softbank engineers learn complex ROS subjects fast

SoftBank Corp. is a Japanese telecom operator, a core company of SoftBank group.

We talk to Tadashi Imokawa, an engineer at SoftBank Corp. in charge of the hardware and software development of the company’s robots, Tomohiko Furutani manager of the AI robot development team about their necessity of learning ROS for robotics, and how they and their team are learning difficult ROS subjects.

Is it both of you that are learning ROS?

Imokawa: Well, we already know ROS, I mean, we know how to do subscribers, create nodes, call action servers… However, sometimes we need to know how a very specific part of ROS works, like for example, how to use a manipulator. In that case, we need to use your academy to learn those subjects.

Why are you learning ROS?

Furutani: We want to make extensive usage of ROS in our robots.

Which ROS methods have you tried?

Imokawa: We used general ROS books. Also, the official ROS wiki page provided by ros.org and we dedicated a lot of time to read the code on the gits of different developers. Learning that way is the traditional way, and it is sometimes very complicated.

Furutani: We also used some subscription services like PackT which provide a lot of books about the subject.

Why do you think those learning methods are complicated?

Imokawa: Because in order to do tests of what we learn, we need to set up a full development environment. That takes time and is complicated. Furthermore, sometimes, it doesn’t work correctly (what you are supposed to obtain and what you actually obtain). It takes a lot of time

Furutani: Yes the testing environment itself takes time, and that sometimes can be very frustrating.

Why did you choose to learn with Robot Ignite Academy?

Imokawa: Well, your academy has some basic and intermediate courses about subjects that we already master. But for more complicated subjects we cannot find much information on the internet, but you have interesting courses teaching those subjects.

Furutani: Also you provide an already working environment for those complicated subjects. When you want to test a complicated ROS subject, you need to have a lot of preparation (complex simulations running, complex code and instructions). Your academy already provides all that ready to start learning.

What are you missing at Robot Ignite Academy?

Imokawa: We feel your service is kind of laggy, specially when we use graphical tools on the web browser.

Furutani: It is probably because we are in Japan and we are far from your servers in Europe.

(By the time this interview is published, Robot Ignite Academy has established a system of replicated academies around the globe for different zones, in order to solve the problem of latency. We have reduced an 83% the latency in countries like Japan, Australia and San Francisco).

SoftBank team with ROS prototype robots

Which ROS subjects are you interested in?

Imokawa: We are specially interesting at ROS Navigation and ROS Manipulation, mainly indoor navigation.

Which computer type (O.S.) are you using to learn ROS?

Furutani: We use Linux Ubuntu machines for programming. But due to security issues, for the learning, we are using Windows computers.

Have you applied what you learned to real robots? Which ones?

Furutani: Not yet. We are still in the process of learning and identifying where to apply it. We are expecting some results in the close future

Thank you for your time!

And for all of you reading this case study, consider the amount of time you will save if you use the Robot Ignite Academy to train your engineers on ROS based robotics. We have courses for learning the basics of ROS, but we also have more advanced courses that teach how to apply it to self-driving cars, drones, deep learning with robots, Reinforcement Learning applied to ROS robots, industrial robots and many more. Just check our current list of courses on this page and give it a free try.

Other companies that use our academy to train their teams

[ROS Q&A] 166 – Spawn Cassie Robot in Gazebo

[ROS Q&A] 166 – Spawn Cassie Robot in Gazebo

This video shows you how to spawn cassie robot in gazebo fully actuated, ready for calibrating the PID and joints limits. This is an answer to the question in ROS ANSWERS: https://goo.gl/N9pcLA

Related resources:

Pin It on Pinterest