-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathinteractive_marker_client.cpp
More file actions
431 lines (370 loc) · 12.6 KB
/
Copy pathinteractive_marker_client.cpp
File metadata and controls
431 lines (370 loc) · 12.6 KB
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// Copyright (c) 2011, Willow Garage, Inc.
// Copyright (c) 2019, Open Source Robotics Foundation, Inc.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// Author: David Gossow
#include <chrono>
#include <format> // NOLINT(build/include_order): cpplint misclassifies the C++20 header as C
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <utility>
#include "rclcpp/rclcpp.hpp"
#include "rmw/qos_profiles.h"
#include "visualization_msgs/msg/interactive_marker_feedback.hpp"
#include "visualization_msgs/msg/interactive_marker_update.hpp"
#include "visualization_msgs/srv/get_interactive_markers.hpp"
#include "interactive_markers/exceptions.hpp"
#include "interactive_markers/interactive_marker_client.hpp"
namespace interactive_markers
{
const size_t MAX_UPDATE_QUEUE_SIZE = 100u;
InteractiveMarkerClient::~InteractiveMarkerClient()
{
}
void InteractiveMarkerClient::connect(const std::string & topic_namespace)
{
changeState(STATE_IDLE);
topic_namespace_ = topic_namespace;
// Terminate any existing connection
disconnect();
// Don't do anything if no namespace is provided
if (topic_namespace_.empty()) {
return;
}
try {
get_interactive_markers_client_ =
rclcpp::create_client<visualization_msgs::srv::GetInteractiveMarkers>(
node_base_interface_,
graph_interface_,
services_interface_,
topic_namespace_ + "/get_interactive_markers",
rclcpp::ServicesQoS(),
nullptr);
feedback_pub_ = rclcpp::create_publisher<visualization_msgs::msg::InteractiveMarkerFeedback>(
topics_interface_,
topic_namespace_ + "/feedback",
feedback_pub_qos_);
update_sub_ = rclcpp::create_subscription<visualization_msgs::msg::InteractiveMarkerUpdate>(
topics_interface_,
topic_namespace_ + "/update",
update_sub_qos_,
std::bind(&InteractiveMarkerClient::processUpdate, this, std::placeholders::_1));
} catch (const rclcpp::exceptions::InvalidNodeError & ex) {
updateStatus(STATUS_ERROR, "Failed to connect: " + std::string(ex.what()));
disconnect();
return;
} catch (const rclcpp::exceptions::NameValidationError & ex) {
updateStatus(STATUS_ERROR, "Failed to connect: " + std::string(ex.what()));
disconnect();
return;
}
updateStatus(STATUS_INFO, "Connected on namespace: " + topic_namespace_);
}
void InteractiveMarkerClient::disconnect()
{
get_interactive_markers_client_.reset();
feedback_pub_.reset();
update_sub_.reset();
reset();
}
void InteractiveMarkerClient::publishFeedback(
visualization_msgs::msg::InteractiveMarkerFeedback feedback)
{
feedback.client_id = client_id_;
feedback_pub_->publish(feedback);
}
void InteractiveMarkerClient::update()
{
if (!get_interactive_markers_client_) {
// Disconnected
return;
}
const bool server_ready = get_interactive_markers_client_->service_is_ready();
switch (state_) {
case STATE_IDLE:
if (server_ready) {
changeState(STATE_INITIALIZE);
}
break;
case STATE_INITIALIZE:
if (!server_ready) {
updateStatus(STATUS_WARN, "Server not available during initialization, resetting");
changeState(STATE_IDLE);
break;
}
// If there's an unexpected error, reset
if (!transformInitialMessage()) {
changeState(STATE_IDLE);
break;
}
if (checkInitializeFinished()) {
changeState(STATE_RUNNING);
}
break;
case STATE_RUNNING:
if (!server_ready) {
updateStatus(STATUS_WARN, "Server not available while running, resetting");
changeState(STATE_IDLE);
break;
}
// If there's an unexpected error, reset
if (!transformUpdateMessages()) {
changeState(STATE_IDLE);
break;
}
pushUpdates();
break;
default:
updateStatus(
STATUS_ERROR, std::format("Invalid state in update: {}", static_cast<int>(getState())));
}
}
void InteractiveMarkerClient::setTargetFrame(const std::string & target_frame)
{
if (target_frame_ == target_frame) {
return;
}
target_frame_ = target_frame;
updateStatus(STATUS_INFO, "Target frame is now " + target_frame_);
// Call reset for change to take effect
// This will cause interactive markers to be requested again from the server
// The additional request might be avoided by doing something else, but this is easier
changeState(STATE_IDLE);
}
void InteractiveMarkerClient::setInitializeCallback(const InitializeCallback & cb)
{
initialize_callback_ = cb;
}
void InteractiveMarkerClient::setUpdateCallback(const UpdateCallback & cb)
{
update_callback_ = cb;
}
void InteractiveMarkerClient::setResetCallback(const ResetCallback & cb)
{
reset_callback_ = cb;
}
void InteractiveMarkerClient::setStatusCallback(const StatusCallback & cb)
{
status_callback_ = cb;
}
void InteractiveMarkerClient::reset()
{
std::unique_lock<std::recursive_mutex> lock(mutex_);
state_ = STATE_IDLE;
first_update_ = true;
initial_response_msg_.reset();
update_queue_.clear();
if (reset_callback_) {
reset_callback_();
}
}
void InteractiveMarkerClient::requestInteractiveMarkers()
{
if (!get_interactive_markers_client_) {
updateStatus(STATUS_ERROR, "Interactive markers requested when client is disconnected");
return;
}
if (!get_interactive_markers_client_->wait_for_service(std::chrono::seconds(1))) {
updateStatus(STATUS_WARN, "Service is not ready during request for interactive markers");
return;
}
updateStatus(STATUS_INFO, "Sending request for interactive markers");
auto callback = std::bind(
&InteractiveMarkerClient::processInitialMessage, this, std::placeholders::_1);
auto request = std::make_shared<visualization_msgs::srv::GetInteractiveMarkers::Request>();
get_interactive_markers_client_->async_send_request(
request,
callback);
request_time_ = clock_->now();
}
void InteractiveMarkerClient::processInitialMessage(
rclcpp::Client<visualization_msgs::srv::GetInteractiveMarkers>::SharedFuture future)
{
updateStatus(STATUS_INFO, "Service response received for initialization");
auto response = future.get();
{
std::unique_lock<std::recursive_mutex> lock(mutex_);
initial_response_msg_ = std::make_shared<InitialMessageContext>(
tf_buffer_core_, target_frame_, response, enable_autocomplete_transparency_);
}
}
void InteractiveMarkerClient::processUpdate(
visualization_msgs::msg::InteractiveMarkerUpdate::ConstSharedPtr msg)
{
// Ignore legacy "keep alive" messages
if (msg->type == msg->KEEP_ALIVE) {
RCLCPP_WARN_ONCE(
logger_,
"KEEP_ALIVE message ignored. "
"Servers are no longer expected to publish this type of message.");
return;
}
if (!first_update_ && msg->seq_num != last_update_sequence_number_ + 1) {
updateStatus(
STATUS_WARN,
std::format(
"Update sequence number is out of order. {} (expected) vs. {} (received)",
last_update_sequence_number_ + 1, msg->seq_num));
// Change state to STATE_IDLE to cause reset
changeState(STATE_IDLE);
return;
}
updateStatus(
STATUS_DEBUG, std::format("Received update with sequence number {}", msg->seq_num));
first_update_ = false;
last_update_sequence_number_ = msg->seq_num;
if (update_queue_.size() > MAX_UPDATE_QUEUE_SIZE) {
updateStatus(
STATUS_WARN,
std::format(
"Update queue too large. Erasing message with sequence number {}",
update_queue_.begin()->msg->seq_num));
update_queue_.pop_back();
}
update_queue_.push_front(
UpdateMessageContext(
tf_buffer_core_, target_frame_, msg, enable_autocomplete_transparency_));
}
bool InteractiveMarkerClient::transformInitialMessage()
{
std::unique_lock<std::recursive_mutex> lock(mutex_);
if (!initial_response_msg_) {
// We haven't received a response yet
return true;
}
try {
initial_response_msg_->getTfTransforms();
} catch (const exceptions::TransformError & e) {
// DEBUG here to reduce spam from repeated resetting
updateStatus(STATUS_DEBUG, std::format("Resetting due to transform error: {}", e.what()));
return false;
}
return true;
}
bool InteractiveMarkerClient::transformUpdateMessages()
{
std::unique_lock<std::recursive_mutex> lock(mutex_);
for (auto it = update_queue_.begin(); it != update_queue_.end(); ++it) {
try {
it->getTfTransforms();
} catch (const exceptions::TransformError & e) {
updateStatus(STATUS_ERROR, std::format("Resetting due to transform error: {}", e.what()));
return false;
}
}
return true;
}
bool InteractiveMarkerClient::checkInitializeFinished()
{
std::unique_lock<std::recursive_mutex> lock(mutex_);
if (!initial_response_msg_) {
// We haven't received a response yet, check for timeout
if ((clock_->now() - request_time_) > request_timeout_) {
updateStatus(
STATUS_WARN, "Did not receive response with interactive markers, resending request...");
requestInteractiveMarkers();
}
return false;
}
const uint64_t & response_sequence_number = initial_response_msg_->msg->sequence_number;
if (!initial_response_msg_->isReady()) {
updateStatus(STATUS_DEBUG, "Initialization: Waiting for TF info");
return false;
}
// Prune old update messages
while (!update_queue_.empty() && update_queue_.back().msg->seq_num <= response_sequence_number) {
updateStatus(
STATUS_DEBUG,
std::format(
"Omitting update with sequence number {}", update_queue_.back().msg->seq_num));
update_queue_.pop_back();
}
if (initialize_callback_) {
initialize_callback_(initial_response_msg_->msg);
}
updateStatus(STATUS_DEBUG, "Initialized");
return true;
}
void InteractiveMarkerClient::pushUpdates()
{
std::unique_lock<std::recursive_mutex> lock(mutex_);
while (!update_queue_.empty() && update_queue_.back().isReady()) {
visualization_msgs::msg::InteractiveMarkerUpdate::SharedPtr msg = update_queue_.back().msg;
updateStatus(
STATUS_DEBUG, std::format("Pushing update with sequence number {}", msg->seq_num));
if (update_callback_) {
update_callback_(msg);
}
update_queue_.pop_back();
}
}
void InteractiveMarkerClient::changeState(const State & new_state)
{
if (state_ == new_state) {
return;
}
updateStatus(STATUS_DEBUG, std::format("Change state to: {}", static_cast<int>(new_state)));
switch (new_state) {
case STATE_IDLE:
reset();
break;
case STATE_INITIALIZE:
requestInteractiveMarkers();
break;
case STATE_RUNNING:
break;
default:
updateStatus(
STATUS_ERROR,
std::format("Invalid state when changing state: {}", static_cast<int>(new_state)));
return;
}
state_ = new_state;
}
void InteractiveMarkerClient::updateStatus(const Status status, const std::string & msg)
{
switch (status) {
case STATUS_DEBUG:
RCLCPP_DEBUG(logger_, "%s", msg.c_str());
break;
case STATUS_INFO:
RCLCPP_INFO(logger_, "%s", msg.c_str());
break;
case STATUS_WARN:
RCLCPP_WARN(logger_, "%s", msg.c_str());
break;
case STATUS_ERROR:
RCLCPP_ERROR(logger_, "%s", msg.c_str());
break;
}
if (status_callback_) {
status_callback_(status, msg);
}
}
} // namespace interactive_markers