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

Writing a Python node that publishes AND subscribes to topics of different message frequency

asked 2013-01-25 07:52:11 -0600

Ernest gravatar image

Hi,

I'm trying to write a node in Python that subscribes to a topic and listens to another.

One way I have managed to do that is by issuing the publish command in the callback. However, this approach only lets my node publish when a new message comes in from the topic it is subscribed to. So my publisher is "constrained" to the subscribed topic's frequency.

Is there an other way to do this? I've looked online and couldn't find anything.

Thanks in advance, Ernest

edit retag flag offensive close merge delete

3 Answers

Sort by ยป oldest newest most voted
5

answered 2013-01-25 09:30:33 -0600

isherman gravatar image

updated 2013-01-25 09:37:00 -0600

An example might look like this (roughly):

import rospy
from std_msgs.msg import Int32

class Echo(object):
    def __init__(self):
        self.value = 0

        rospy.init_node('echoer')

        self.pub = rospy.Publisher('/out_value', Int32, latch=True)
        rospy.Subscriber('/in_value', Int32, self.update_value)

    def update_value(self, msg):
        self.value = msg.data

    def run(self):
        r = rospy.Rate(10)
        while not rospy.is_shutdown():
            self.pub.publish(self.value)
            r.sleep()
edit flag offensive delete link more

Comments

Do you need to add rospy.Spin() below the subscriber line?

Yantian_Zha gravatar image Yantian_Zha  ( 2016-12-30 15:53:28 -0600 )edit
4

answered 2013-01-25 09:24:21 -0600

In the python publisher tutorial, talker.py shows an example of publishing outside a subscriber callback using a loop at a specified rate.

You can use this sort of publishing scheme when you don't have a sequential processing task. If you have additional subscribers in your python script, they will continue to run at whatever rate the messages come in in their own individual threads.

edit flag offensive delete link more
0

answered 2013-01-25 09:26:58 -0600

You should be able to do thus by setting up your callback for the subscribe and then publishing out of the main loop.

def callback( data ):
     <do stuff>

subscriber = rospy.Subscriber( topic, type, callback )
publisher = rospy.Publisher( topic, type )

while not rospy.is_shutdown():
   <do stuff>
   publisher.publish( msg )
edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2013-01-25 07:52:11 -0600

Seen: 4,959 times

Last updated: Jan 25 '13