/
ros2_jupyter.hpp
362 lines (300 loc) · 11.4 KB
/
ros2_jupyter.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
#pragma once
#include <unistd.h>
#include <chrono>
#include <cstring>
#include <memory>
#include <thread>
#include <functional>
#include <xwidgets/xbox.hpp>
#include <xwidgets/xbutton.hpp>
#include <xwidgets/xlabel.hpp>
#include <xwidgets/xtext.hpp>
#include <xwidgets/xtextarea.hpp>
#include <xwidgets/xvalid.hpp>
#include <rclcpp/rclcpp.hpp>
using namespace std::literals::chrono_literals;
struct ROS2Init {
ROS2Init() { ros_init(); }
void ros_init() {
if (rclcpp::ok()) { return; }
int argc = 1;
char *argv[1];
argv[0] = new char[9];
strcpy(argv[0], "jupyter");
rclcpp::init(argc, argv);
}
};
struct CaptureStdCout {
using Func = std::function<void(const std::string&)>;
CaptureStdCout(Func func_): func(func_) {
// do smthg for color
coutbuf = std::cout.rdbuf(); // save old buf
// divert cout to string stream
std::cout.rdbuf(cap_cout.rdbuf());
}
~CaptureStdCout() {
// set the text output as the captured stdout
func(cap_cout.str());
// restore cout
std::cout.rdbuf(coutbuf);
}
std::stringstream cap_cout;
std::streambuf* coutbuf;
Func func;
};
template <class T>
struct simplify_callback { using type = T; };
template <class T>
using simplified_callback = typename simplify_callback<T>::type;
template <class R, class... Args>
struct simplify_callback<R(*)(Args...)>: simplify_callback<R(Args...)> {};
template <class R, class... Args>
struct simplify_callback<R(&)(Args...)>: simplify_callback<R(Args...)> {};
template <class MsgT, class SubT, class CallbackT, class AllocatorT, class MessageMemoryStrategyT, class SimplifiedCallbackT=simplified_callback<CallbackT>>
class ZeusSubscriber {};
template <class MsgT, class SubT, class CallbackT, class AllocatorT, class MessageMemoryStrategyT, class R, class... Args>
class ZeusSubscriber<MsgT, SubT, CallbackT, AllocatorT, MessageMemoryStrategyT, R(Args...)> {
std::function<R(Args...)> m_cb;
std::shared_ptr<SubT> sub;
bool m_append;
rclcpp::Node* m_nh;
std::string m_topic;
rclcpp::QoS m_qos;
rclcpp::SubscriptionOptionsWithAllocator< AllocatorT > m_options;
typename MessageMemoryStrategyT::SharedPtr m_msg_mem_strat;
xw::vbox box;
xw::button button;
xw::textarea textarea;
R cb(Args&&... args) {
CaptureStdCout cap{[this](const auto& data) { update(data); }};
return m_cb(std::forward<Args>(args)...);
}
void update(const std::string& data) {
textarea.value = (m_append ? textarea.value() : "") + data;
}
public:
ZeusSubscriber(rclcpp::Node* nh, const std::string &topic_name, const rclcpp::QoS &qos, CallbackT &&callback,
const rclcpp::SubscriptionOptionsWithAllocator< AllocatorT > &options,
typename MessageMemoryStrategyT::SharedPtr msg_mem_strat, bool append)
: m_cb(callback)
, m_append(append)
, m_nh(nh)
, m_topic(topic_name)
, m_qos(qos)
, m_options(options)
, m_msg_mem_strat(msg_mem_strat) {
toggle();
button.on_click([this] { toggle(); });
button.description = "Start [ " + m_topic + " ]"; // actual start state might not be subscribed... sometimes
box.add(button);
box.add(textarea);
box.display(); // @TODO: adjust width of the box
}
void toggle() {
if (sub) {
std::weak_ptr<SubT> weak_sub { sub };
sub.reset();
if (weak_sub.expired()) {
button.description = "Start [ " + m_topic + " ]";
} else {
button.description = "Someone else shares the subscriber";
button.disabled = true;
}
} else if (!button.disabled()) {
auto func = std::function<R(Args...)>{[this](auto&&...args){ return this->cb(std::forward<Args>(args)...);}};
sub = m_nh->create_subscription<MsgT>(m_topic, m_qos, func, m_options, m_msg_mem_strat);
button.description = "Stop [ " + m_topic + " ]";
}
}
std::weak_ptr<SubT> get_subscriber() {
return sub;
}
// returns true if the subscriber has been shut down
bool try_shutdown() {
sub.reset();
return !sub;
}
};
class ZeusParamWidget{
private:
// widget objects
xw::valid valid;
xw::label lbl_param;
xw::text txt_param;
xw::label lbl_value;
xw::text txt_value;
xw::button btn_wait;
xw::button btn_set;
// widget layout
xw::hbox main_layout;
xw::vbox left_section;
// middle section is just the valid button, no need for layout
xw::vbox right_section;
xw::hbox label_txt_param_layout; // part of left_section
xw::hbox label_txt_value_layout; // part of left_section
// threadding
std::atomic<bool> thr_running;
std::thread thr;
// ros stuff
rclcpp::Node* nh;
rclcpp::Rate rate;
public:
ZeusParamWidget(rclcpp::Node* nh)
: nh(nh)
, rate(200ms)
, valid()
, txt_param()
, btn_wait()
, txt_value()
, btn_set()
, main_layout() {
thr_running = false;
// init compontents
lbl_param.value = "param_name";
txt_param.on_submit([this]() { valid.value = this->nh->has_parameter(txt_param.value); });
lbl_value.value = "param_value";
txt_value.on_submit(std::bind(&ZeusParamWidget::set_param_value, this));
btn_wait.description = "Start Waiting";
btn_wait.on_click([this]() {
if (thr_running) {
stop_thread();
} else {
start_thread();
}
});
btn_set.description = "Set Param";
btn_set.on_click(std::bind(&ZeusParamWidget::set_param_value, this));
// set up layout
// | lbl_param | txt_param | valid | btn_wait
// | lbl_value | txt_value | | btn_set
label_txt_param_layout.add(lbl_param);
label_txt_param_layout.add(txt_param);
label_txt_value_layout.add(lbl_value);
label_txt_value_layout.add(txt_value);
left_section.add(label_txt_param_layout);
left_section.add(label_txt_value_layout);
main_layout.add(left_section);
main_layout.add(valid);
right_section.add(btn_wait);
right_section.add(btn_set);
main_layout.add(right_section);
display();
}
void set_parameter(const std::string& name, const std::string& value) {
txt_param.value = name;
txt_value.value = value;
set_param_value();
}
private:
void display() { main_layout.display(); }
void set_param_value() {
if (!nh->has_parameter(txt_param.value)) {
nh->declare_parameter(txt_param.value, rclcpp::ParameterValue(txt_value.value));
}
auto param = rclcpp::Parameter(txt_param.value, rclcpp::ParameterValue(txt_value.value));
nh->set_parameter(param);
valid.value = nh->has_parameter(txt_param.value);
}
void start_thread() {
thr_running = true;
txt_param.disabled = true;
txt_value.disabled = true;
btn_wait.description = "Stop Waiting";
thr = std::thread(&ZeusParamWidget::thread_loop, this);
}
void thread_loop() {
while (thr_running) {
if (nh->has_parameter(txt_param.value)) {
valid.value = true;
std::string tmp;
nh->get_parameter(txt_param.value, tmp);
txt_value.value = tmp;
} else {
valid.value = false;
txt_value.value = "";
}
rate.sleep();
}
}
void stop_thread() {
thr_running = false;
txt_param.disabled = false;
txt_value.disabled = false;
btn_wait.description = "Start Waiting";
std::this_thread::sleep_for(1s);
if (thr.joinable()) {
thr.join();
}
}
};
template <class NodeType = rclcpp::Node>
class JupyterNodeAdvanced: ROS2Init, public NodeType {
xw::button spin_btn;
xw::valid ros_valid;
xw::hbox disp_box;
std::thread spin_thread;
rclcpp::Rate m_rate;
void toggle(bool skip_check = false) {
if (skip_check == false && rclcpp::ok()) {
std::cout << "shutdown\n";
rclcpp::shutdown();
spin_btn.description = "Start";
} else {
std::cout <<"restart\n";
ros_init();
setup_thread();
spin_btn.description = "Stop";
}
ros_valid.value = rclcpp::ok();
}
void setup_thread() {
if (spin_thread.joinable()) {
// should never happen
spin_thread.join();
}
spin_thread = std::thread([this]{
ros_valid.value = rclcpp::ok();
while(rclcpp::ok()) {
rclcpp::spin_some(getNode());
m_rate.sleep();
}
ros_valid.value = false;
});
}
public:
std::shared_ptr<NodeType> getNode() {
return this->shared_from_this();
}
JupyterNodeAdvanced(double rate = 10): NodeType("interactive_node"), m_rate(rate) {
spin_btn.description = "Stop";
spin_btn.on_click([this]{toggle();});
disp_box.add(spin_btn);
disp_box.add(ros_valid);
disp_box.display();
setup_thread();
}
auto create_param_widgets() {
return std::make_unique<ZeusParamWidget>(this);
}
auto set_parameter(const std::string& name, const std::string& value) {
auto widget = create_param_widgets();
widget->set_parameter(name, value);
return std::move(widget);
}
template<typename MessageT , typename CallbackT , typename AllocatorT = std::allocator<void>, typename CallbackMessageT = typename rclcpp::subscription_traits::has_message_type<CallbackT>::type, typename SubscriptionT = rclcpp::Subscription<CallbackMessageT, AllocatorT>, typename MessageMemoryStrategyT = rclcpp::message_memory_strategy::MessageMemoryStrategy<CallbackMessageT, AllocatorT>>
auto create_subscription(const std::string &topic_name, const rclcpp::QoS &qos, CallbackT &&callback,
const rclcpp::SubscriptionOptionsWithAllocator< AllocatorT > &options=rclcpp::SubscriptionOptionsWithAllocator< AllocatorT >(),
typename MessageMemoryStrategyT::SharedPtr msg_mem_strat=(MessageMemoryStrategyT::create_default()), bool append=false) {
return ZeusSubscriber<MessageT, SubscriptionT, CallbackT, AllocatorT, MessageMemoryStrategyT>(this, topic_name, qos, callback, options, msg_mem_strat, append);
}
template<typename MessageT , typename CallbackT , typename AllocatorT = std::allocator<void>, typename CallbackMessageT = typename rclcpp::subscription_traits::has_message_type<CallbackT>::type, typename SubscriptionT = rclcpp::Subscription<CallbackMessageT, AllocatorT>, typename MessageMemoryStrategyT = rclcpp::message_memory_strategy::MessageMemoryStrategy<CallbackMessageT, AllocatorT>>
auto create_subscription(const std::string &topic_name, const rclcpp::QoS &qos, CallbackT &&callback, bool append_) {
return create_subscription<MessageT>(topic_name, qos, callback,
rclcpp::SubscriptionOptionsWithAllocator< AllocatorT >(), (MessageMemoryStrategyT::create_default()), append_);
}
};
using JupyterNode = JupyterNodeAdvanced<>;
std::shared_ptr<JupyterNode> ros_init() {
static auto node_ptr = std::make_shared<JupyterNode>();
return node_ptr;
}