Understanding def shutdownhook(self):

Hello,

I am working on the ROS basics in 5 days course and wanted to better understand what this function does (in Unit 7 Python Classes in ROS):

 def shutdownhook(self): 
    # works better than the rospy.is_shutdown() 
    self.ctrl_c = True 

I see that in the last line of init , the rospy.on_shutdown(self.shutdownhook) method is declared which triggers the MoveBB8 class method shutdownhook(), but what is the point of doing this?

shutdownhook() sets the class attribute ctrl_c = True, but why does it do this? Where is the ctrl_c = True variable used after this?

It looks like the program just closes and doesn’t do anything with that variable, am I understanding this correctly, or am I missing something?

Please let me know if you can point my understanding of this in the right direction, thank you!

1 Like

Hi Ryan,

The following line in def __init__(self) sets def shutdownhook(self) as the function that is called when ROS is shutting down (typically when you press Ctrl + C):

rospy.on_shutdown(self.shutdownhook)

Now when def shutdownhook(self) runs, it sets self.ctrl_c = True. When that happens, the loop in def publish_once_in_cmd_vel(self) is broken, ending the program in effect.

PS: Note that the while loop depends on self.ctrl_c.

def publish_once_in_cmd_vel(self):
        # Note that the while loop depends on self.ctrl_c
        while not self.ctrl_c:
            connections = self.bb8_vel_publisher.get_num_connections()
            if connections > 0:
                self.bb8_vel_publisher.publish(self.cmd)
                rospy.loginfo("Cmd Published")
                break
            else:
                self.rate.sleep()

Thank you @bayodesegun sorry, I missed that part!

At some point, I would like to learn how to run the debugger to see the control flow of a class works. It’s a little bit hard to visualize when you’re not used to it yet.

I had a quick look and wasn’t able to figure it out, but do you know if it is possible to debug Python in Theia? Whenever I tried to run it, it just brings me to a launch.json tab.

Thanks again and please let me know if you have any thoughts about debugging.

Ryan

@rschmalenberg
You’re welcome.

I don’t much about the debugger of the IDE as it is not an area we have focused on.

That said, this is more a case of code comprehension and familiarity with Python, which will improve as you write more programs. For Python classes, you trace the flow from def __init__, from top to bottom, taking note of any initialization and class method called.

Cheers.