Week 4 Move Service-Client Python Example¶
Copy all the code below into your move_client.py
file and review the annotations to understand how it all works.
#!/usr/bin/env python3
import rospy # (1)!
from tuos_msgs.srv import SetBool, {BLANK} # (2)!
import sys # (3)!
service_name = "move_service" # (4)!
rospy.init_node(f"{service_name}_client") # (5)!
rospy.wait_for_service(service_name) # (6)!
service = rospy.ServiceProxy(service_name, SetBool) # (7)!
service_request = {BLANK}() # (8)!
service_request.request_signal = True # (9)!
service_response = service(service_request) # (10)!
print(service_response) # (11)!
-
Again, the first step when building a Python node is to import the
rospy
library so that Python and ROS can interact. -
This service client will use the
SetBool
service message from thetuos_msgs
package, so we import the full definition of theSetBool
Service Message, as well as the portion of the message that we will need to use to actually issue a service call. -
We import the Python
sys
module to do some error handling for us, we don't need to worry about too much. -
Define the name of the service that we want to call, and assign this to a variable called
service_name
(for convenience, since we'll refer to this a couple of times). -
Initialise the client node (give it a name).
-
Wait until the service that we want to call is actually running, execution of this node will not progress beyond this point until the service is detected on the ROS network (launched by the Server).
-
Once it is running, we create a connection to it and specify the service message type that it uses (as defined above).
-
Create an instance of the
{BLANK}
part of the service message, and populate this with the data that the server is expecting. -
Remember: Using
...gives us the following:rossrv info
on this service message in a terminal tells us the attribute names for both the Request and Response: -
Use the
rospy.ServiceProxy
instance that we created earlier (calledservice
) to actually send theservice_request
message to the service and obtain a response back from the Server (once it's complete). -
To finish off, we print the response to the terminal to give the user some feedback. Job done!
Fill in the Blank!
Consider the import
statement for the service Server that we created earlier... Which part of the SetBool
Service message was imported here? Now consider that you need to build a client to call this service... which part of the SetBool
Service message is needed in order to call a service?
Note: the same {BLANK}
appears in two places in the code above - the answer is the same in both places!