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

How to force the subscriber to read the latest message in a topic?

asked 2017-12-29 20:56:19 -0500

nickzhang gravatar image

Hi, My apologies if the question is unclear, I'll elaborate here:

I have a node that publishes real-time image to a topic at 30Hz.

I am writing another node that subscribes to this topic and processes the image (find a target in the image).

The processing time varies, sometimes the algorithm can process images at 10Hz, sometimes 5Hz.

I want my node to process a frame, and after it finishes, get the latest frame and process that.

I tried setting queue_size of my publisher to 1, I thought that would force all old messages to be dropped. However that didn't work. My callback is just processing the old frames that's remained in the pipeline(whose size I don't know how to set)

Can someone help me with this? I'm using python. I'm trying to build a sampling port rather than a queuing port, if this explanation helps.

Another question:

  1. Does ros spawns a new thread for callback function every time a new message is available in a topic?

  2. How many buffers/pipes are there in a publisher->topic->subscriber system?

Thank you!

Nick

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
1

answered 2018-01-02 05:29:14 -0500

You need to set the queue size of your subscriber, not your publisher to 1. According to the rospy Subscriber API docs, the queue size defaults to infinite if not explicitly set, which would explain the behavior you're seeing.

edit flag offensive delete link more

Comments

Hi Stefan. I tried the method proposed and I still have similar problems. could you look into https://answers.ros.org/question/2797... Thanks!

nickzhang gravatar image nickzhang  ( 2018-01-15 19:35:11 -0500 )edit
0

answered 2022-11-23 21:17:42 -0500

To accomplish this you'll want to have your rospy.Subscriber callback simply save the latest message. Then use a rospy.Timer with a separate function that calls your processing code with the latest message on a fixed schedule.

class Node:
    ...
    self.subscriber = rospy.Subscriber(sub_topic, MessageType, self.sub_callback)
    self.publisher = rospy.Publisher(pub_topic, MessageType)
    rospy.Timer(rospy.Duration(1), self.timer_callback)

    def sub_callback(self, message):
        self.latest_message = message

    def timer_callback(self, _):
        self.processing_code(self.latest_message)

    def processing_code(self, message):
        ...
        self.publisher.pub(processed_message)
edit flag offensive delete link more

Question Tools

2 followers

Stats

Asked: 2017-12-29 20:53:22 -0500

Seen: 4,956 times

Last updated: Jan 02 '18