JobScheduler  1.1.0
CMJob_RosPublisher.h
1 #pragma once
2 
3 #include <functional>
4 
5 #include "CMJob.h"
6 #include "ros/ros.h"
7 
8 namespace CMJob {
9 
13 template <typename T>
14 class RosPublisher final : public AbstractJob {
15  public:
16  RosPublisher<T>(const ros::NodeHandlePtr& node, const std::string& topic,
17  const size_t& queue_size = 1)
18  : AbstractJob(topic, JobType::Cyclic, false),
19  node_(node),
20  topic_(topic),
21  queue_size_(queue_size) {
22  initMsg(tag<T>{});
23  initPublisher(tag<T>{});
24 
25  this->setCallbackHook(CallbackHook::Out);
26  }
27 
31  void execute(void);
32 
37  void registerCallback(std::function<void(T&)> fp) {
38  user_callback_ = std::bind(fp, std::placeholders::_1);
39  }
40 
47  template <typename M>
48  void registerCallback(void (M::*fp)(T&), M* obj) {
49  user_callback_ = std::bind(fp, obj, std::placeholders::_1);
50  }
51 
52  private:
53  ros::NodeHandlePtr node_ = nullptr;
55  std::string topic_;
56  ros::Publisher pub_;
57  size_t queue_size_ = 1;
59  std::function<void(T&)> user_callback_;
60  T msg_;
62  /* Partial template specialization */
63  template <typename>
64  struct tag {};
65 
66  template <class R>
67  void initPublisher(tag<R>) {
68  this->pub_ =
69  this->node_->template advertise<R>(this->topic_, this->queue_size_);
70  }
71 
72  template <class R>
73  void initPublisher(tag<boost::shared_ptr<R>>) {
74  this->pub_ =
75  this->node_->template advertise<R>(this->topic_, this->queue_size_);
76  }
77 
78  template <class R>
79  void initMsg(tag<R>) {}
80 
81  template <class R>
82  void initMsg(tag<boost::shared_ptr<R>>) {
83  this->msg_ = boost::make_shared<R>();
84  }
85 };
86 
88 // IMPLEMENTATION //
90 
91 template <typename T>
93  if (this->user_callback_ && this->msg_ != nullptr) {
94  this->user_callback_(this->msg_);
95  this->pub_.publish(this->msg_);
96  }
97 
99 }
100 
101 } // namespace CMJob
void registerCallback(void(M::*fp)(T &), M *obj)
register_callback
Definition: CMJob_RosPublisher.h:48
Ros_Publisher provides a job based interfoce for ros publisher.
Definition: CMJob_RosPublisher.h:14
void registerCallback(std::function< void(T &)> fp)
register_callback
Definition: CMJob_RosPublisher.h:37
called periodically at the end of the job
Library for providing a generic interface to handle jobs.
void execute(void)
Execution of the job.
Definition: CMJob_RosPublisher.h:92
virtual void execute()=0
Execution of the job.
Definition: Job.cpp:271
Definition: CMJob.h:16
void setCallbackHook(CallbackHook hook)
setCallbackHook
Definition: Job.cpp:131
AbstractJob(const std::string &name, JobType type, bool sync)
AbstractJob.
Definition: Job.cpp:43
The AbstractJob class provides an interface for jobs.
Definition: CMJob.h:74