Skip to content

Instantly share code, notes, and snippets.

@pgorczak
Last active February 8, 2019 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pgorczak/01e69eb1ab11f709899187ac02678375 to your computer and use it in GitHub Desktop.
Save pgorczak/01e69eb1ab11f709899187ac02678375 to your computer and use it in GitHub Desktop.
Utility function that gets a single message from a ROS topic
import threading
import rospy
def get_single_msg(topic, type_, timeout=None):
""" Utility function that gets a single message from a ROS topic.
Args:
topic: ROS topic (string).
type_: topic message type.
timeout: max waiting time (None or float in seconds).
Returns:
instance of first received message or None on timeout.
"""
msgs = []
received = threading.Event()
def cb(msg):
msgs.append(msg)
received.set()
sub = rospy.Subscriber(topic, type_, cb, queue_size=1)
no_timeout = received.wait(timeout)
sub.unregister()
if no_timeout:
return msgs[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment