ROS1 integrating the subscriber inside the service in Python

How do I connect the subscriber inside a service server in ROS? as both needs to be defined in separate functions ?

That should not be a problem. Just define the subscriber within the service server code and write a callback function for it. When the service server starts, the subscriber will also activate.

How you wire your logic exactly depends on what you want to do.

I can activate the subscriber within the service code but in regarding the data in the subscriber callback function? how do I use it in the service response function? is there any other way than using classes? thanks for your help

Hi @mkakram ,

You can declare the variable that will receive the subscriber data outside the function scope and use it as a global one inside both the subscriber callback and service function:

Something more or less like below:

callback_value = None

def callback(msg):
    global callback_value
    callback_value = msg

def service_fn():
    global callback_value

I have a more complex example using globals in this repository: Bitbucket

I show in this video the development of such algorithm: [Exploring ROS using a 2 Wheeled Robot] #6: Motion Planning Algorithms - YouTube


1 Like