rospy.wait_for_message() based on a condition instead of a timeout

asked 2021-08-12 03:37:56 -0600

abhishek47 gravatar image

updated 2021-08-12 03:53:01 -0600

rospy.wait_for_message() is blocking if timeout is None, else throws exception if nothing arrives on the topic before timing out.

Does rospy provide a way to wait for message until a condition is no longer satisfied? I want to make it condition based instead of time based.

Use case: say for example I only want to wait until a variable is a certain value, and if that value changes then no point waiting for message anymore.

The way I'm doing it currently is (note get_result() and foo_int_modifier()):

def __init__(self):
    self.foo_int = 20
    rospy.Subscriber("/topic_str_data", String, self.cb)

def cb(self, str_data):
    self.foo_str = str_data

def get_result(self):
    self.foo_str = None
    self.foo_int = 20

    while self.foo_str is None or self.foo_int >= 10: 
        rospy.sleep(0.1)

    return self.foo_str

def foo_int_modifier(self): # this can get called whenever
    self.foo_int = self.foo_int - 1

Is there a better way to achieve the same outcome as rospy.wait_for_message("/topic_str_data", String, self.foo_int >= 10)? The 3rd argument here being a condition instead of a timeout.

edit retag flag offensive close merge delete