ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

A version using a callback to make it a drop-in replacement for a rospy.Subscriber(). Based on KindDragon's answer.

Usage:

my_subscriber = GenericMessageSubscriber('topic_name', message_callback)

def message_callback(data):
    # handle your callback exactly as you would do it with a normal Subscriber
    print(data)

Class:

class GenericMessageSubscriber(object):
def __init__(self, topic_name, callback):
    self._binary_sub = rospy.Subscriber(
        topic_name, rospy.AnyMsg, self.generic_message_callback)
    self._callback = callback

def generic_message_callback(self, data):
    assert sys.version_info >= (2,7) #import_module's syntax needs 2.7
    connection_header =  data._connection_header['type'].split('/')
    ros_pkg = connection_header[0] + '.msg'
    msg_type = connection_header[1]
    msg_class = getattr(import_module(ros_pkg), msg_type)
    msg = msg_class().deserialize(data._buff)
    self._callback(msg)