1
$\begingroup$

Rosanswers logo

I would like to get a single message from a topic. Is there a built-in, simple, elegant way to do this? Currently, I am creating a subscriber, and using a threading.Event object to signal when it receives a message, and automatically unregister itself. It works, but it seems unwieldy for a task that I presume to be fairly common.

class SomeClass:
    def __init__(self):
        self.data = None
        self.get_data_subscriber = None
        self.get_data_event = threading.Event()

    def get_data_callback(self, data):
        self.data = data
        self.get_data_subscriber.unregister()
        self.get_data_subscriber = None
        self.get_data_event.set()

    def run(self):
        rospy.init_node('myNodeName', anonymous=True)

        self.get_data_subscriber = rospy.Subscriber('/sometopic', SomeType, self.get_data_callback)

        while True:
            self.get_data_event.wait(0.1)  # sleep 100ms or wakeup sooner if event was set

            # wait() didn't have a return value until python 2.7, so for compatibility, don't rely on the return val.
            # is_set() method was added in python 2.6, so for compatibility, use isSet() instead.
            if self.get_current_pose_event.isSet():
                self.get_current_pose_event.clear()
                break
            if rospy.is_shutdown():
                return

        rospy.loginfo("data is: {}".format(data))
        return

if __name__ == "__main__":
    foo = SomeClass()
    foo.run()

Originally posted by rahvee on ROS Answers with karma: 30 on 2018-05-29

Post score: 0

$\endgroup$

1 Answer 1

1
$\begingroup$

Rosanswers logo

Please see #q270298.

In Python this should be available through rospy.wait_for_message(..) (docs).


Originally posted by gvdhoorn with karma: 86574 on 2018-05-29

This answer was ACCEPTED on the original site

Post score: 6


Original comments

Comment by rahvee on 2018-05-30:
Perfect, thanks!

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.