Fawkes API  Fawkes Development Version
pcl_thread.cpp
1 
2 /***************************************************************************
3  * pcl_thread.cpp - Thread to exchange point clouds
4  *
5  * Created: Mon Nov 07 02:58:40 2011
6  * Copyright 2011 Tim Niemueller [www.niemueller.de]
7  ****************************************************************************/
8 
9 /* This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU Library General Public License for more details.
18  *
19  * Read the full text in the LICENSE.GPL file in the doc directory.
20  */
21 
22 #include "pcl_thread.h"
23 
24 #include <core/threading/mutex_locker.h>
25 #include <ros/ros.h>
26 #include <sensor_msgs/PointCloud2.h>
27 
28 using namespace fawkes;
29 
30 /** @class RosPointCloudThread "pcl_thread.h"
31  * Thread to exchange point clouds between Fawkes and ROS.
32  * @author Tim Niemueller
33  */
34 
35 /** Constructor. */
37 : Thread("RosPointCloudThread", Thread::OPMODE_WAITFORWAKEUP),
38  BlockedTimingAspect(BlockedTimingAspect::WAKEUP_HOOK_WORLDSTATE)
39 {
40 }
41 
42 /** Destructor. */
44 {
45 }
46 
47 void
49 {
50  //pubman_ = new RosPointCloudPublisherManager(rosnode);
51  adapter_ = new PointCloudAdapter(pcl_manager, logger);
52 
53  cfg_ros_research_ival_ = config->get_float("/ros/pcl/ros-search-interval");
54 
55  fawkes_pointcloud_search();
56 
57  ros_pointcloud_search();
58  ros_pointcloud_last_searched_.stamp();
59 }
60 
61 void
63 {
64  for (const std::string &item : ros_pointcloud_available_) {
65  pcl_manager->remove_pointcloud(item.c_str());
66  }
67  for (const std::pair<std::string, fawkes::pcl_utils::StorageAdapter *> &item :
68  ros_pointcloud_available_ref_) {
69  delete item.second;
70  }
71  for (std::pair<std::string, ros::Subscriber> item : ros_pointcloud_subs_) {
72  item.second.shutdown();
73  }
74  delete adapter_;
75 }
76 
77 void
79 {
80  // search ever n sec for new clouds on ROS side
81  fawkes::Time now;
82  now.stamp();
83  if (fawkes::time_diff_sec(*now.get_timeval(), *ros_pointcloud_last_searched_.get_timeval())
84  >= cfg_ros_research_ival_) {
85  ros_pointcloud_last_searched_ = now;
86  ros_pointcloud_search();
87  ros_pointcloud_check_for_listener_in_fawkes();
88  //TODO if fawkes_pointcloud_search() would be called here, a check for clouds from fawkes need to be implemented
89  }
90 
91  // publish clouds fawkes->ros
92  fawkes_pointcloud_publish_to_ros();
93  // publish clouds ros->fawkes (this is done in callbacks)
94 }
95 
96 void
97 RosPointCloudThread::ros_pointcloud_search()
98 {
99  std::list<std::string> ros_pointclouds_new;
100 
101  // get all ROS topics
102  ros::master::V_TopicInfo ros_topics;
103  if (!ros::master::getTopics(ros_topics)) {
104  logger->log_info(name(), "Coulnd't get available ROS topics");
105  return;
106  }
107 
108  // iterate through all topics
109  for (const ros::master::TopicInfo &info : ros_topics) {
110  // only topics of type sensor_msgs/PointCloud2 are important
111  if (0 == info.datatype.compare("sensor_msgs/PointCloud2")) {
112  // check if this is a topic comming from fawkes
113  bool topic_not_from_fawkes = true;
114  for (const std::pair<std::string, PublisherInfo> &fawkes_cloud : fawkes_pubs_) {
115  if (0 == info.name.compare(fawkes_cloud.second.pub.getTopic())) {
116  topic_not_from_fawkes = false;
117  }
118  }
119  if (topic_not_from_fawkes) {
120  ros_pointclouds_new.push_back(info.name);
121  }
122  }
123  }
124 
125  // check for removed clouds
126  std::list<std::string> items_to_remove;
127  for (const std::string &item_old : ros_pointcloud_available_) {
128  bool exists = false;
129  for (std::string item_new : ros_pointclouds_new) {
130  if (0 == item_old.compare(item_new)) {
131  exists = true;
132  break;
133  }
134  }
135  if (!exists) {
136  items_to_remove.push_back(item_old);
137  }
138  }
139  for (const std::string &item : items_to_remove) {
140  logger->log_info(name(), "Pointcloud %s is not available from ROS anymore", item.c_str());
141  ros_pointcloud_available_.remove(item);
142  }
143 
144  // check for new clouds
145  for (const std::string &ros_topic : ros_pointclouds_new) {
146  bool exists = false;
147  for (const std::string &in_list : ros_pointcloud_available_) {
148  if (0 == ros_topic.compare(in_list)) {
149  exists = true;
150  break;
151  }
152  }
153  if (!exists) {
154  logger->log_info(name(), "Pointcloud %s is now available from ROS", ros_topic.c_str());
155  ros_pointcloud_available_.push_back(ros_topic);
156  ros_pointcloud_subs_[ros_topic] = rosnode->subscribe<sensor_msgs::PointCloud2>(
157  ros_topic,
158  1,
159  boost::bind(&RosPointCloudThread::ros_pointcloud_on_data_msg, this, _1, ros_topic));
160  }
161  }
162 }
163 
164 void
165 RosPointCloudThread::ros_pointcloud_check_for_listener_in_fawkes()
166 {
167  for (const std::pair<std::string, fawkes::pcl_utils::StorageAdapter *> &item :
168  ros_pointcloud_available_ref_) {
169  unsigned int use_count = 0;
170  if (item.second->is_pointtype<pcl::PointXYZ>()) {
171  use_count =
173  ->cloud.use_count();
174  } else if (item.second->is_pointtype<pcl::PointXYZRGB>()) {
175  use_count =
177  ->cloud.use_count();
178  } else if (item.second->is_pointtype<pcl::PointXYZI>()) {
179  use_count =
181  ->cloud.use_count();
182  } else {
183  logger->log_error(name(), "Can't detect cloud type");
184  }
185 
186  if (
187  use_count
188  <= 2) { // my internal list, this ref and the pcl_manager have copys of this pointer, if more are used, otheres are listening too
189  std::map<std::string, ros::Subscriber>::iterator element =
190  ros_pointcloud_subs_.find(item.first);
191  if (element != ros_pointcloud_subs_.end()) {
192  element->second.shutdown();
193  ros_pointcloud_subs_.erase(item.first);
194  }
195  } else {
196  ros_pointcloud_subs_[item.first] = rosnode->subscribe<sensor_msgs::PointCloud2>(
197  item.first,
198  1,
199  boost::bind(&RosPointCloudThread::ros_pointcloud_on_data_msg, this, _1, item.first));
200  }
201  }
202 }
203 
204 void
205 RosPointCloudThread::fawkes_pointcloud_search()
206 {
207  std::vector<std::string> pcls = pcl_manager->get_pointcloud_list();
208 
209  std::vector<std::string>::iterator p;
210  for (p = pcls.begin(); p != pcls.end(); ++p) {
211  std::string topic_name = std::string("fawkes_pcls/") + *p;
212  std::string::size_type pos = 0;
213  while ((pos = topic_name.find("-", pos)) != std::string::npos) {
214  topic_name.replace(pos, 1, "_");
215  }
216 
217  PublisherInfo pi;
218  pi.pub = rosnode->advertise<sensor_msgs::PointCloud2>(topic_name, 1);
219 
220  logger->log_info(name(), "Publishing point cloud %s at %s", p->c_str(), topic_name.c_str());
221 
222  std::string frame_id;
223  unsigned int width, height;
224  bool is_dense;
226  adapter_->get_info(*p, width, height, frame_id, is_dense, fieldinfo);
227  pi.msg.header.frame_id = frame_id;
228  pi.msg.width = width;
229  pi.msg.height = height;
230  pi.msg.is_dense = is_dense;
231  pi.msg.fields.clear();
232  pi.msg.fields.resize(fieldinfo.size());
233  for (unsigned int i = 0; i < fieldinfo.size(); ++i) {
234  pi.msg.fields[i].name = fieldinfo[i].name;
235  pi.msg.fields[i].offset = fieldinfo[i].offset;
236  pi.msg.fields[i].datatype = fieldinfo[i].datatype;
237  pi.msg.fields[i].count = fieldinfo[i].count;
238  }
239 
240  fawkes_pubs_[*p] = pi;
241  }
242 }
243 
244 void
245 RosPointCloudThread::fawkes_pointcloud_publish_to_ros()
246 {
247  std::map<std::string, PublisherInfo>::iterator p;
248  for (p = fawkes_pubs_.begin(); p != fawkes_pubs_.end(); ++p) {
249  PublisherInfo &pi = p->second;
250  if (pi.pub.getNumSubscribers() > 0 && pcl_manager->exists_pointcloud(p->first.c_str())) {
251  unsigned int width, height;
252  void * point_data;
253  size_t point_size, num_points;
254  fawkes::Time time;
255  fawkes::Time now(time);
256  std::string frame_id;
257  adapter_->get_data(
258  p->first, frame_id, width, height, time, &point_data, point_size, num_points);
259 
260  if (pi.last_sent != time) {
261  pi.last_sent = time;
262 
263  size_t data_size = point_size * num_points;
264  pi.msg.data.resize(data_size);
265  memcpy(&pi.msg.data[0], point_data, data_size);
266 
267  pi.msg.width = width;
268  pi.msg.height = height;
269  pi.msg.header.frame_id = frame_id;
270  pi.msg.header.stamp.sec = time.get_sec();
271  pi.msg.header.stamp.nsec = time.get_nsec();
272  pi.msg.point_step = point_size;
273  pi.msg.row_step = point_size * pi.msg.width;
274 
275  pi.pub.publish(pi.msg);
276  //} else {
277  // logger->log_debug(name(), "No update for %s, not sending", p->first.c_str());
278  }
279  } else {
280  if (pcl_manager->exists_pointcloud(p->first.c_str())) {
281  adapter_->close(p->first);
282  }
283  }
284  }
285 }
286 
287 void
288 RosPointCloudThread::ros_pointcloud_on_data_msg(const sensor_msgs::PointCloud2ConstPtr &msg,
289  const std::string & topic_name)
290 {
291  // if this is the first time, I need the meta infos, what point-type is send
292  if (!pcl_manager->exists_pointcloud(topic_name.c_str())) {
293  bool r = false, i = false;
294  for (const sensor_msgs::PointField &field : msg->fields) {
295  // logger->log_info(name(), "%s: %s", topic_name.c_str(), field.name.c_str());
296  if (0 == field.name.compare("r")) {
297  r = true;
298  }
299  if (0 == field.name.compare("i")) {
300  i = true;
301  }
302  }
303  if (!r && !i) {
304  logger->log_info(name(), "Adding %s with type XYZ ROS -> FAWKES", topic_name.c_str());
305  add_pointcloud<pcl::PointXYZ>(msg, topic_name);
306  } else if (r && !i) {
307  logger->log_info(name(), "Adding %s with type XYZRGB ROS -> FAWKES", topic_name.c_str());
308  add_pointcloud<pcl::PointXYZRGB>(msg, topic_name);
309  } else if (!r && i) {
310  logger->log_info(name(), "Adding %s with type XYRI ROS -> FAWKES", topic_name.c_str());
311  add_pointcloud<pcl::PointXYZI>(msg, topic_name);
312  } else {
313  logger->log_error(name(), "%s: can't detect point type, using XYZ", topic_name.c_str());
314  add_pointcloud<pcl::PointXYZ>(msg, topic_name);
315  }
316  }
317 
318  // copy data
319  const pcl_utils::StorageAdapter *sa = pcl_manager->get_storage_adapter(topic_name.c_str());
320  if (sa->is_pointtype<pcl::PointXYZ>()) {
321  update_pointcloud<pcl::PointXYZ>(msg, topic_name);
322  } else if (sa->is_pointtype<pcl::PointXYZRGB>()) {
323  update_pointcloud<pcl::PointXYZRGB>(msg, topic_name);
324  } else if (sa->is_pointtype<pcl::PointXYZI>()) {
325  update_pointcloud<pcl::PointXYZI>(msg, topic_name);
326  } else {
327  logger->log_error(name(), "Can't detect cloud type");
328  }
329 
330  ros_pointcloud_check_for_listener_in_fawkes();
331 }
Point cloud adapter class.
Definition: pcl_adapter.h:39
void get_data(const std::string &id, std::string &frame_id, unsigned int &width, unsigned int &height, fawkes::Time &time, void **data_ptr, size_t &point_size, size_t &num_points)
Get current data of point cloud.
void close(const std::string &id)
Close an adapter.
void get_info(const std::string &id, unsigned int &width, unsigned int &height, std::string &frame_id, bool &is_dense, V_PointFieldInfo &pfi)
Get info about point cloud.
std::vector< PointFieldInfo > V_PointFieldInfo
Vector of PointFieldInfo.
Definition: pcl_adapter.h:66
virtual void loop()
Code to execute in the thread.
Definition: pcl_thread.cpp:78
virtual void finalize()
Finalize the thread.
Definition: pcl_thread.cpp:62
RosPointCloudThread()
Constructor.
Definition: pcl_thread.cpp:36
virtual void init()
Initialize the thread.
Definition: pcl_thread.cpp:48
virtual ~RosPointCloudThread()
Destructor.
Definition: pcl_thread.cpp:43
Thread aspect to use blocked timing.
Configuration * config
This is the Configuration member used to access the configuration.
Definition: configurable.h:41
virtual float get_float(const char *path)=0
Get value from configuration which is of type float.
virtual void log_error(const char *component, const char *format,...)=0
Log error message.
virtual void log_info(const char *component, const char *format,...)=0
Log informational message.
Logger * logger
This is the Logger member used to access the logger.
Definition: logging.h:41
PointCloudManager * pcl_manager
Manager to distribute and access point clouds.
Definition: pointcloud.h:47
void remove_pointcloud(const char *id)
Remove the point cloud.
std::vector< std::string > get_pointcloud_list() const
Get list of point cloud IDs.
const pcl_utils::StorageAdapter * get_storage_adapter(const char *id)
Get a storage adapter.
bool exists_pointcloud(const char *id)
Check if point cloud exists.
LockPtr< ros::NodeHandle > rosnode
Central ROS node handle.
Definition: ros.h:47
Thread class encapsulation of pthreads.
Definition: thread.h:46
const char * name() const
Get name of thread.
Definition: thread.h:100
A class for handling time.
Definition: time.h:93
Time & stamp()
Set this time to the current time.
Definition: time.cpp:704
const timeval * get_timeval() const
Obtain the timeval where the time is stored.
Definition: time.h:112
long get_nsec() const
Get nanoseconds.
Definition: time.h:132
long get_sec() const
Get seconds.
Definition: time.h:117
Adapter class for PCL point types.
bool is_pointtype() const
Check if storage adapter is for specified point type.
Fawkes library namespace.
double time_diff_sec(const timeval &a, const timeval &b)
Calculate time difference of two time structs.
Definition: time.h:41