mrs_lib
Various reusable classes, functions and utilities for use in MRS projects
dynamic_publisher.hpp
2 {
3 public:
4  impl() = default;
5 
6  impl(const ros::NodeHandle& nh) : m_nh(nh)
7  {
8  }
9 
10  template <class T>
11  void publish(const std::string name, const T& msg)
12  {
13  std::scoped_lock lck(m_mtx);
14  const std::string msg_md5 = ros::message_traits::MD5Sum<T>::value();
15  const std::string msg_datatype = ros::message_traits::DataType<T>::value();
16  if (m_publishers.count(name) == 0)
17  m_publishers.emplace(name, pub_info_t{m_nh.advertise<T>(name, 10), msg_md5, msg_datatype});
18 
19  const auto& pub_info = m_publishers.at(name);
20  if (pub_info.msg_md5 == "*" ||
21  msg_md5 == "*" ||
22  pub_info.msg_md5 == msg_md5)
23  {
24  pub_info.pub.publish(msg);
25  }
26  else
27  {
28  ROS_ERROR_STREAM("[DynamicPublisher]: Trying to publish message of type [" << msg_datatype << "/" << msg_md5
29  << "] on a publisher with type [" << pub_info.datatype << "/" << pub_info.msg_md5 << "], ignoring!");
30  }
31  }
32 
33 private:
34  struct pub_info_t
35  {
36  ros::Publisher pub;
37  std::string msg_md5;
38  std::string datatype;
39  };
40  std::mutex m_mtx;
41  ros::NodeHandle m_nh;
42  std::unordered_map<std::string, pub_info_t> m_publishers;
43 };
44 
45 template <class T>
46 void DynamicPublisher::publish(const std::string name, const T& msg)
47 {
48  m_impl->publish(name, msg);
49 }
DynamicPublisher::impl
Definition: dynamic_publisher.hpp:1