How to subscriber for a topic in the same callback function of topic?
Hi,
I want to get updated new sensor value in callback function of subscribed topic. And the the topic I want to subscribe in callback function is same topic.
for ex.
def left_dist(data):
print(data.data)
def callback(data):
rospy.Subscriber("DistSensor", String,left_dist)
if __name__ == '__main__':
rospy.Subscriber("DistSensor", String, callback)
Thank you in avanced.
Asked by Harish_More on 2019-11-19 01:22:00 UTC
Comments
My first response would be: don't do that.
Perhaps if you could explain why you believe you need / want to do this, we can avoid an xy-problem and help you solve the real problem.
Asked by gvdhoorn on 2019-11-19 03:32:00 UTC
What is your use-case that requires this behaviour? When you get new data on "DistSensor" that is when the callback function is executed. So anything inside that callback function uses the data you just received. I think that if you manage to implement this what will happen is:
Either I am misunderstanding the implementation you have in mind or I'm predicting the behaviour wrong, but this seems like a weird system to me. What is the benefit of this over just having
Asked by MCornelis on 2019-11-19 03:44:32 UTC
Hello Sorry for silly questions and mistakes I want to get forward distance from my distance Sensor after that if the distance is less than threshold, then change heading of vehicle to left(which will in callback function). After changing heading Again get the new distance with ref to left side (to check left side occupancy of vehicle). So to get new distance (left side), will I have to again subscribe the same topic or not?
Else, how should I deal with this problem?
Thank you
Asked by Harish_More on 2019-11-19 04:04:57 UTC
You could not do anything on the first run except for saving the distance information as old_data. Then the next time you receive data you compare the new data to old_data and at the end of the callback you do old_data = new_data. This way you always have the data from your previous step.
Asked by MCornelis on 2019-11-19 04:06:47 UTC
Pseudo code of callback function
This is a very simple example, you can do it prettier probably, if you want to store more data-points you might want to look into buffering, but I think this will suffice for what you are trying to do.
If I misunderstood you and you just need to pass the data around then you can ignore the above suggestion. You can simply share the data in the callback to different functions. It will execute all functions with the received data
Asked by MCornelis on 2019-11-19 04:22:23 UTC
Thank you MCornelis. It worked for me.
Asked by Harish_More on 2019-11-21 07:02:51 UTC