Bird
Raised Fist0
ROSframework~20 mins

Creating a service client in ROS - Practice Exercises

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
ROS Service Client Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this ROS service client code?
Consider a ROS service client that calls a service named /add_two_ints which adds two integers. What will be printed if the service returns the sum correctly?
ROS
import rospy
from beginner_tutorials.srv import AddTwoInts

def add_two_ints_client(x, y):
    rospy.wait_for_service('/add_two_ints')
    try:
        add_two_ints = rospy.ServiceProxy('/add_two_ints', AddTwoInts)
        resp = add_two_ints(x, y)
        print(f"Sum is: {resp.sum}")
    except rospy.ServiceException as e:
        print(f"Service call failed: {e}")

if __name__ == '__main__':
    rospy.init_node('add_two_ints_client')
    add_two_ints_client(3, 4)
ASum is: 0
BSum is: 34
CService call failed: Service not available
DSum is: 7
Attempts:
2 left
💡 Hint
Think about what the service is supposed to do with the inputs 3 and 4.
📝 Syntax
intermediate
2:00remaining
Which option correctly creates a ROS service client for a service named '/multiply' with type 'MultiplyTwoInts'?
Select the code snippet that correctly creates a ROS service client for the service '/multiply' with service type 'MultiplyTwoInts'.
Amultiply_client = rospy.Service('/multiply', 'MultiplyTwoInts')
Bmultiply_client = rospy.Service('/multiply', MultiplyTwoInts)
Cmultiply_client = rospy.ServiceProxy('/multiply', MultiplyTwoInts)
Dmultiply_client = rospy.ServiceProxy(MultiplyTwoInts, '/multiply')
Attempts:
2 left
💡 Hint
Remember that ServiceProxy is used to create a client, and the order is (service_name, service_type).
🔧 Debug
advanced
2:00remaining
What error does this ROS service client code raise?
Given the following code snippet, what error will occur when running it if the service '/divide' is not available?
ROS
import rospy
from beginner_tutorials.srv import DivideTwoInts

def divide_client(a, b):
    divide = rospy.ServiceProxy('/divide', DivideTwoInts)
    resp = divide(a, b)
    print(f"Result: {resp.result}")

if __name__ == '__main__':
    rospy.init_node('divide_client')
    divide_client(10, 2)
Arospy.ROSException: Service '/divide' not available
Brospy.ServiceException: Service call failed
CAttributeError: 'NoneType' object has no attribute 'result'
DTypeError: divide() missing 1 required positional argument
Attempts:
2 left
💡 Hint
What happens if you try to call a service that hasn't started yet?
❓ state_output
advanced
2:00remaining
What is the value of variable 'response' after this ROS service client call?
Given the service client call below, what is the type and content of the variable response?
ROS
import rospy
from beginner_tutorials.srv import AddTwoInts

rospy.init_node('test_client')
add_two_ints = rospy.ServiceProxy('/add_two_ints', AddTwoInts)
response = add_two_ints(5, 6)
AAn integer 11
BAn object of type AddTwoIntsResponse with attribute sum=11
CA dictionary {'sum': 11}
DNone
Attempts:
2 left
💡 Hint
ServiceProxy returns a response object, not a simple type.
🧠 Conceptual
expert
2:00remaining
Which statement about ROS service clients is true?
Select the correct statement about ROS service clients.
AA service client must call rospy.wait_for_service before calling the service to ensure it is available.
BA service client can call a service without initializing a ROS node.
CA service client automatically retries calling the service if it fails once.
DA service client can only call services in the same package.
Attempts:
2 left
💡 Hint
Think about what happens if the service is not ready when the client calls it.

Practice

(1/5)
1. What is the main purpose of creating a service client in ROS?
easy
A. To request data or actions from another node and receive a response
B. To publish messages to a topic continuously
C. To subscribe and listen to messages from a topic
D. To launch multiple nodes at once

Solution

  1. Step 1: Understand service client role

    A service client in ROS is used to send a request to another node and wait for a reply.
  2. Step 2: Compare with other communication types

    Publishing and subscribing are for continuous message streams, not request-response.
  3. Final Answer:

    To request data or actions from another node and receive a response -> Option A
  4. Quick Check:

    Service client = request and response [OK]
Hint: Service clients ask and wait for answers, unlike topics [OK]
Common Mistakes:
  • Confusing service clients with publishers or subscribers
  • Thinking service clients launch nodes
  • Assuming service clients send continuous data
2. Which of the following is the correct way to create a service client in ROS Python?
easy
A. client = rospy.ServiceProxy('service_name', ServiceType)
B. client = rospy.ServiceClient('service_name', ServiceType)
C. client = rospy.Service('service_name', ServiceType, callback)
D. client = rospy.Publisher('service_name', ServiceType)

Solution

  1. Step 1: Recall ROS Python service client syntax

    In ROS Python, service clients are created using rospy.ServiceProxy with the service name and type.
  2. Step 2: Identify incorrect options

    ServiceClient does not exist, Service is for servers, Publisher is for topics.
  3. Final Answer:

    client = rospy.ServiceProxy('service_name', ServiceType) -> Option A
  4. Quick Check:

    Service client uses ServiceProxy [OK]
Hint: Service clients use ServiceProxy, servers use Service [OK]
Common Mistakes:
  • Using rospy.ServiceClient which does not exist
  • Confusing service client with service server creation
  • Using Publisher instead of ServiceProxy
3. Given this ROS Python code snippet, what will be printed if the service responds with success=True?
import rospy
from example.srv import ExampleService

def call_service():
    rospy.wait_for_service('example_service')
    client = rospy.ServiceProxy('example_service', ExampleService)
    response = client(42)
    print(response.success)

call_service()
medium
A. 42
B. False
C. None
D. True

Solution

  1. Step 1: Understand the service call and response

    The client calls the service with argument 42 and receives a response object with a 'success' attribute.
  2. Step 2: Identify printed value

    The code prints response.success, which is True as given by the problem statement.
  3. Final Answer:

    True -> Option D
  4. Quick Check:

    response.success = True [OK]
Hint: Print the response attribute, not the request argument [OK]
Common Mistakes:
  • Printing the request argument instead of response
  • Assuming response.success is False by default
  • Confusing service response with None
4. What is wrong with this ROS Python service client code?
import rospy
from example.srv import ExampleService

client = rospy.ServiceProxy('example_service', ExampleService)
response = client(10)
print(response.result)
medium
A. The service name is invalid
B. ServiceProxy should be called with a string, not a service type
C. Missing rospy.init_node() before creating client
D. The response attribute 'result' may not exist

Solution

  1. Step 1: Check ROS node initialization

    ROS nodes must call rospy.init_node() before using any ROS features like ServiceProxy.
  2. Step 2: Verify other parts

    ServiceProxy usage is correct, service name format is valid, response attribute depends on service definition but missing init_node is a critical error.
  3. Final Answer:

    Missing rospy.init_node() before creating client -> Option C
  4. Quick Check:

    Always init node before service client [OK]
Hint: Always call rospy.init_node() before creating clients [OK]
Common Mistakes:
  • Forgetting to initialize the ROS node
  • Confusing service type and name parameters
  • Assuming response attributes without checking service definition
5. You want to create a ROS service client that waits for the service to be available, sends a request asynchronously, and processes the response without blocking the main program. Which approach correctly implements this behavior?
hard
A. Create client with rospy.ServiceProxy, call client() inside a separate thread to avoid blocking
B. Use rospy.wait_for_service(), then call client.call_async() and add a callback to handle response
C. Use rospy.wait_for_service(), then call client() synchronously and block until response
D. Call client() repeatedly in a loop until response is received

Solution

  1. Step 1: Wait for service availability

    Using rospy.wait_for_service() ensures the service is ready before sending requests.
  2. Step 2: Use asynchronous call with callback

    client.call_async() allows sending request without blocking; a callback handles the response smoothly.
  3. Step 3: Avoid blocking main program

    Calling client() synchronously or looping blocks the program; threading is possible but less clean than async calls.
  4. Final Answer:

    Use rospy.wait_for_service(), then call client.call_async() and add a callback to handle response -> Option B
  5. Quick Check:

    Async call with callback = non-blocking client [OK]
Hint: Use call_async() with callback for smooth non-blocking calls [OK]
Common Mistakes:
  • Calling client() synchronously and blocking program
  • Using loops to wait for response instead of async
  • Not waiting for service before calling client
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard