SMACC
Loading...
Searching...
No Matches
cp_topic_subscriber.h
Go to the documentation of this file.
1#pragma once
2#include <smacc/component.h>
4#include <boost/optional/optional_io.hpp>
6
7namespace smacc
8{
9namespace components
10{
11
12using namespace smacc::default_events;
13
14template <typename MessageType>
16{
17public:
18 boost::optional<std::string> topicName;
19 boost::optional<int> queueSize;
20
21 typedef MessageType TMessageType;
22
24 {
25 initialized_ = false;
26 }
27
28 CpTopicSubscriber(std::string topicname)
29 {
30 topicName = topicname;
31 }
32
34 {
35 sub_.shutdown();
36 }
37
38 smacc::SmaccSignal<void(const MessageType &)> onFirstMessageReceived_;
39 smacc::SmaccSignal<void(const MessageType &)> onMessageReceived_;
40
41 std::function<void(const MessageType &)> postMessageEvent;
42 std::function<void(const MessageType &)> postInitialMessageEvent;
43
44 template <typename T>
45 boost::signals2::connection onMessageReceived(void (T::*callback)(const MessageType &), T *object)
46 {
47 return this->getStateMachine()->createSignalConnection(onMessageReceived_, callback, object);
48 }
49
50 template <typename T>
51 boost::signals2::connection onFirstMessageReceived(void (T::*callback)(const MessageType &), T *object)
52 {
53 return this->getStateMachine()->createSignalConnection(onFirstMessageReceived_, callback, object);
54 }
55
56 template <typename TOrthogonal, typename TSourceObject>
58 {
59 this->postMessageEvent = [=](auto msg) {
61 event->msgData = msg;
62 this->postEvent(event);
63 };
64
65 this->postInitialMessageEvent = [=](auto msg) {
67 event->msgData = msg;
68 this->postEvent(event);
69 };
70 }
71
72 virtual void initialize()
73 {
74 if (!initialized_)
75 {
76 firstMessage_ = true;
77
78 if (!queueSize)
79 queueSize = 1;
80
81 if (!topicName)
82 {
83 ROS_ERROR("topic client with no topic name set. Skipping subscribing");
84 }
85 else
86 {
87 ROS_INFO_STREAM("[" << this->getName() << "] Subscribing to topic: " << topicName);
88
90 this->initialized_ = true;
91 }
92 }
93 }
94
95protected:
96 ros::NodeHandle nh_;
97
98private:
99 ros::Subscriber sub_;
102
103 void messageCallback(const MessageType &msg)
104 {
105 if (firstMessage_)
106 {
109 firstMessage_ = false;
110 }
111
112 postMessageEvent(msg);
114 }
115};
116}
117}
virtual std::string getName() const
std::function< void(const MessageType &)> postMessageEvent
boost::optional< std::string > topicName
std::function< void(const MessageType &)> postInitialMessageEvent
smacc::SmaccSignal< void(const MessageType &)> onFirstMessageReceived_
boost::signals2::connection onFirstMessageReceived(void(T::*callback)(const MessageType &), T *object)
smacc::SmaccSignal< void(const MessageType &)> onMessageReceived_
void messageCallback(const MessageType &msg)
boost::signals2::connection onMessageReceived(void(T::*callback)(const MessageType &), T *object)