个人技术分享

一、引言:在某些场景下,需要使用Gazebo场景发布话题数据来模拟真实的数据源,此处仅简单设置发布ROS话题数据,按照预定的频率

#include <gazebo/gazebo.hh>
#include <ros/ros.h>
#include <std_msgs/String.h>

namespace gazebo
{
  class ROSPublisherPlugin : public WorldPlugin
  {
  public:
    void Load(physics::WorldPtr _world, sdf::ElementPtr _sdf) override
    {
      // Initialize ROS node
      ros::NodeHandle nh;

      // Create a ROS publisher
      pub = nh.advertise<std_msgs::String>("gazebo_topic", 10);

      // Create a Gazebo update event connection
      this->updateConnection = event::Events::ConnectWorldUpdateBegin(
          std::bind(&ROSPublisherPlugin::OnUpdate, this));
    }

    void OnUpdate()
    {
      if ((ros::Time::now() - lastPubTime)>= ros::Duration(0.1))
      {
        std_msgs::String msg;
        msg.data = "Hello, world";
        pub.publish(msg);
        lastPubTime = ros::Time::now();
      }
    }

  private:
    ros::Publisher pub;
        ros::Time lastPubTime;
    event::ConnectionPtr updateConnection;
  };

  GZ_REGISTER_WORLD_PLUGIN(ROSPublisherPlugin)
} // namespace gazebo

注:此处通过时间判断进行循环发布

 void OnUpdate()
    {
      if ((ros::Time::now() - lastPubTime)>= ros::Duration(0.1))
      {
        std_msgs::String msg;
        msg.data = "Hello, world";
        pub.publish(msg);
        lastPubTime = ros::Time::now();
      }
    }