ROS message sent but not received

走远了吗. 提交于 2019-12-13 02:24:03

问题


I'm using ROS in my project and I need to send one message from time to time. I have this function:

void RosNetwork::sendMessage(string msg, string channel) {
    _mtx.lock();
    ros::Publisher chatter_pub = _n.advertise<std_msgs::String>(channel.c_str(),10);
    ros::Rate loop_rate(10);
    std_msgs::String msgToSend;
    msgToSend.data = msg.c_str();
    chatter_pub.publish(msgToSend);
    loop_rate.sleep();
    cout << "Message Sent" << endl;
    _mtx.unlock();
}

And I have this in python:

def callbackFirst(data):
    #rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
    print("Received message from first filter")

def callbackSecond(data):
    #rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
    print("Received message from second filter")

def listener():
    rospy.Subscriber("FirstTaskFilter", String, callbackFirst)
    print("subscribed to FirstTaskFilter")
    rospy.Subscriber("SecondTaskFilter", String, callbackSecond)
    print("subscribed to SecondTaskFilter")
    rospy.spin()

The listener is a thread in python. I get to the function sendMessage (I see in the terminal "Message Sent" a lot of times) but I don't see that the python script receives the message.

Update: I tested the python callback with rostopic pub /FirstTaskFilter std_msgs/String "test" and this works perfectly.

Any thought?


回答1:


You are re-advertising the publisher every time and then you are immediately using it to publish something.
This is problematic as it needs some time for the subscribers to subscribe to newly emerging publishers. If you are publishing messages before the subscriber has finished with this, these messages will not arrive.

To avoid this problem, do not advertise a new publisher every time, but do it only once in the constructor of your class and store the publisher in a member variable. Your code could look something like this:

RosNetwork() {
    _chatter_pub = _n.advertise<std_msgs::String>(channel.c_str(),10);
    ros::Duration(1).sleep(); // optional, to make sure no message gets lost
}

void RosNetwork::sendMessage(string msg, string channel) {
    ...
    _chatter_pub.publish(msgToSend);
    ...
}

The one-second-sleep after advertise makes sure that all existing subscribers can subscribe before you start publishing messages. This is only necessary, if it is important that not a single message gets lost. In most practical cases it can be omitted.




回答2:


The proper solution to your problem is to use pub.getNumSubscribers() and wait until that is > 0. Then publish.



来源:https://stackoverflow.com/questions/31812134/ros-message-sent-but-not-received

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!