-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathsample_infield_correction.cpp
370 lines (339 loc) · 16.2 KB
/
sample_infield_correction.cpp
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
#include <ctime>
#include <rclcpp/rclcpp.hpp>
#include <std_srvs/srv/trigger.hpp>
#include <stdexcept>
#include <zivid_interfaces/srv/infield_correction_capture.hpp>
#include <zivid_interfaces/srv/infield_correction_compute.hpp>
#include <zivid_interfaces/srv/infield_correction_read.hpp>
static const auto read_only_parameter =
rcl_interfaces::msg::ParameterDescriptor{}.set__read_only(true);
[[noreturn]] void fatal_error(const rclcpp::Logger & logger, const std::string & message)
{
RCLCPP_ERROR_STREAM(logger, message);
throw std::runtime_error(message);
}
template <typename List, typename ToStringFunc>
std::string join_list_to_string(const List & list, ToStringFunc && to_string_func)
{
return list.empty()
? std::string()
: std::accumulate(
std::next(std::begin(list)), std::end(list), to_string_func(*std::begin(list)),
[&](const std::string & str, const auto & entry) {
return str + ", " + to_string_func(entry);
});
}
template <typename Enum>
Enum get_parameter_enum(
rclcpp::Node & node, const std::string & name, const std::map<std::string, Enum> & name_value_map)
{
const auto value = node.declare_parameter<std::string>(name, "", read_only_parameter);
const auto it = name_value_map.find(value);
if (it == name_value_map.end()) {
const std::string valid_values =
join_list_to_string(name_value_map, [](auto && pair) { return pair.first; });
fatal_error(
node.get_logger(), "Invalid value for parameter '" + name + "': '" + value +
"'. Expected one of: " + valid_values + ".");
}
RCLCPP_INFO(node.get_logger(), "%s", ("Got parameter " + name + ": " + value).c_str());
return it->second;
}
enum class InfieldCorrectionOperation
{
Verify,
Correct,
CorrectAndWrite,
Read,
Reset,
};
const std::map<std::string, InfieldCorrectionOperation> infield_correction_operation_map = {
{"verify", InfieldCorrectionOperation::Verify},
{"correct", InfieldCorrectionOperation::Correct},
{"correct_and_write", InfieldCorrectionOperation::CorrectAndWrite},
{"read", InfieldCorrectionOperation::Read},
{"reset", InfieldCorrectionOperation::Reset},
};
template <typename ServiceType>
std::shared_ptr<rclcpp::Client<ServiceType>> create_service_client(
const rclcpp::Node::SharedPtr & node, const std::string & service_name)
{
auto client = node->create_client<ServiceType>(service_name);
while (!client->wait_for_service(std::chrono::seconds(3))) {
if (!rclcpp::ok()) {
fatal_error(node->get_logger(), "Client interrupted while waiting for service to appear.");
}
RCLCPP_INFO(
node->get_logger(), "Waiting for the %s service to appear...", client->get_service_name());
}
return client;
}
bool request_trigger_and_print_response(
const rclcpp::Node::SharedPtr & node,
const std::shared_ptr<rclcpp::Client<std_srvs::srv::Trigger>> & client)
{
auto future = client->async_send_request(std::make_shared<std_srvs::srv::Trigger::Request>());
if (rclcpp::spin_until_future_complete(node, future) != rclcpp::FutureReturnCode::SUCCESS) {
fatal_error(node->get_logger(), "Failed to call the infield correction compute service");
}
auto result = future.get();
RCLCPP_INFO(node->get_logger(), "Trigger results (%s):", client->get_service_name());
RCLCPP_INFO(node->get_logger(), " Success: %s", result->success ? "true" : "false");
RCLCPP_INFO(
node->get_logger(), " Message: %s",
result->message.empty() ? "" : (R"(""")" + result->message + R"(""")").c_str());
return result->success;
}
void set_srgb(const std::shared_ptr<rclcpp::Node> & node)
{
auto param_client = std::make_shared<rclcpp::AsyncParametersClient>(node, "zivid_camera");
while (!param_client->wait_for_service(std::chrono::seconds(3))) {
if (!rclcpp::ok()) {
fatal_error(node->get_logger(), "Client interrupted while waiting for service to appear.");
}
RCLCPP_INFO(node->get_logger(), "Waiting for the parameters client to appear...");
}
auto result = param_client->set_parameters({rclcpp::Parameter("color_space", "srgb")});
if (
rclcpp::spin_until_future_complete(node, result, std::chrono::seconds(30)) !=
rclcpp::FutureReturnCode::SUCCESS) {
fatal_error(node->get_logger(), "Failed to set `color_space` parameter");
}
}
std::string capture_status_to_string(
const std::shared_ptr<rclcpp::Node> & node,
const zivid_interfaces::srv::InfieldCorrectionCapture::Response & response)
{
using zivid_interfaces::srv::InfieldCorrectionCapture;
switch (response.status) {
case InfieldCorrectionCapture::Response::STATUS_NOT_SET:
return "STATUS_NOT_SET";
case InfieldCorrectionCapture::Response::STATUS_OK:
return "STATUS_OK";
case InfieldCorrectionCapture::Response::STATUS_DETECTION_FAILED:
return "STATUS_DETECTION_FAILED";
case InfieldCorrectionCapture::Response::STATUS_INVALID_CAPTURE_METHOD:
return "STATUS_INVALID_CAPTURE_METHOD";
case InfieldCorrectionCapture::Response::STATUS_INVALID_ALIGNMENT:
return "STATUS_INVALID_ALIGNMENT";
default:
fatal_error(node->get_logger(), "Invalid status: " + std::to_string(response.status));
}
}
std::string detection_status_to_string(
const std::shared_ptr<rclcpp::Node> & node,
const zivid_interfaces::msg::DetectionResultCalibrationBoard & msg)
{
using zivid_interfaces::msg::DetectionResultCalibrationBoard;
switch (msg.status) {
case DetectionResultCalibrationBoard::STATUS_NOT_SET:
return "STATUS_NOT_SET";
case DetectionResultCalibrationBoard::STATUS_OK:
return "STATUS_OK";
case DetectionResultCalibrationBoard::STATUS_NO_VALID_FIDUCIAL_MARKER_DETECTED:
return "STATUS_NO_VALID_FIDUCIAL_MARKER_DETECTED";
case DetectionResultCalibrationBoard::STATUS_MULTIPLE_VALID_FIDUCIAL_MARKERS_DETECTED:
return "STATUS_MULTIPLE_VALID_FIDUCIAL_MARKERS_DETECTED";
case DetectionResultCalibrationBoard::STATUS_BOARD_DETECTION_FAILED:
return "STATUS_BOARD_DETECTION_FAILED";
case DetectionResultCalibrationBoard::STATUS_INSUFFICIENT_3D_QUALITY:
return "STATUS_INSUFFICIENT_3D_QUALITY";
default:
fatal_error(node->get_logger(), "Invalid status: " + std::to_string(msg.status));
}
}
void print_detection_result_calibration_board(
const std::shared_ptr<rclcpp::Node> & node,
const zivid_interfaces::msg::DetectionResultCalibrationBoard & detection_result)
{
RCLCPP_INFO(node->get_logger(), " Detection result:");
RCLCPP_INFO(
node->get_logger(), " Status: %s",
detection_status_to_string(node, detection_result).c_str());
RCLCPP_INFO(
node->get_logger(), " Status description: %s", detection_result.status_description.c_str());
RCLCPP_INFO(
node->get_logger(), " Centroid in meter: %g, %g, %g", detection_result.centroid.x,
detection_result.centroid.y, detection_result.centroid.z);
RCLCPP_INFO(
node->get_logger(),
" Pose: {{ Position in meter: %g, %g, %g }, { Orientation as quaternion: %g, %g, %g, %g }}",
detection_result.pose.position.x, detection_result.pose.position.y,
detection_result.pose.position.z, detection_result.pose.orientation.x,
detection_result.pose.orientation.y, detection_result.pose.orientation.z,
detection_result.pose.orientation.w);
}
bool request_capture_and_print_response(
const rclcpp::Node::SharedPtr & node,
const std::shared_ptr<rclcpp::Client<zivid_interfaces::srv::InfieldCorrectionCapture>> & client)
{
auto future = client->async_send_request(
std::make_shared<zivid_interfaces::srv::InfieldCorrectionCapture::Request>());
if (rclcpp::spin_until_future_complete(node, future) != rclcpp::FutureReturnCode::SUCCESS) {
fatal_error(node->get_logger(), "Failed to call the infield correction capture service");
}
auto result = future.get();
RCLCPP_INFO(node->get_logger(), "Trigger results (%s):", client->get_service_name());
RCLCPP_INFO(node->get_logger(), " Success: %s", result->success ? "true" : "false");
RCLCPP_INFO(
node->get_logger(), " Message: %s",
result->message.empty() ? "" : (R"(""")" + result->message + R"(""")").c_str());
RCLCPP_INFO(node->get_logger(), " Status: %s", capture_status_to_string(node, *result).c_str());
RCLCPP_INFO(node->get_logger(), " Number of captures: %d", result->number_of_captures);
print_detection_result_calibration_board(node, result->detection_result);
return result->success;
}
void request_infield_correction_compute_and_print_response(
const rclcpp::Node::SharedPtr & node,
const std::shared_ptr<rclcpp::Client<zivid_interfaces::srv::InfieldCorrectionCompute>> & client,
const std::string & name)
{
auto future = client->async_send_request(
std::make_shared<zivid_interfaces::srv::InfieldCorrectionCompute::Request>());
if (rclcpp::spin_until_future_complete(node, future) != rclcpp::FutureReturnCode::SUCCESS) {
fatal_error(node->get_logger(), "Failed to call the infield correction " + name + " service");
}
auto result = future.get();
RCLCPP_INFO(
node->get_logger(), "Infield correction compute results (%s):", client->get_service_name());
RCLCPP_INFO(node->get_logger(), " Success: %s", result->success ? "true" : "false");
RCLCPP_INFO(node->get_logger(), " Number of captures: %d", result->number_of_captures);
RCLCPP_INFO(node->get_logger(), " Trueness errors:");
for (size_t i = 0; i < result->trueness_errors.size(); i++) {
RCLCPP_INFO(
node->get_logger(), " - Capture %zu: %g %%", i + 1, result->trueness_errors[i] * 100.f);
}
RCLCPP_INFO(
node->get_logger(), " Average trueness error: %g %%", result->average_trueness_error * 100.f);
RCLCPP_INFO(
node->get_logger(), " Maximum trueness error: %g %%", result->maximum_trueness_error * 100.f);
RCLCPP_INFO(
node->get_logger(), " Dimension accuracy: %g %%", result->dimension_accuracy * 100.f);
RCLCPP_INFO(node->get_logger(), " Z min: %g m", result->z_min);
RCLCPP_INFO(node->get_logger(), " Z max: %g m", result->z_max);
RCLCPP_INFO(
node->get_logger(), " Message: %s",
result->message.empty() ? "" : (R"(""")" + result->message + R"(""")").c_str());
}
bool request_read_and_print_response(
const rclcpp::Node::SharedPtr & node,
const std::shared_ptr<rclcpp::Client<zivid_interfaces::srv::InfieldCorrectionRead>> & client)
{
auto future = client->async_send_request(
std::make_shared<zivid_interfaces::srv::InfieldCorrectionRead::Request>());
if (rclcpp::spin_until_future_complete(node, future) != rclcpp::FutureReturnCode::SUCCESS) {
fatal_error(node->get_logger(), "Failed to call the infield correction read service");
}
auto result = future.get();
const std::time_t time = result->camera_correction_timestamp.sec;
std::ostringstream oss;
oss << std::put_time(std::localtime(&time), "%c");
const std::string time_str = oss.str();
RCLCPP_INFO(node->get_logger(), "Trigger results (%s):", client->get_service_name());
RCLCPP_INFO(node->get_logger(), " Success: %s", result->success ? "true" : "false");
RCLCPP_INFO(
node->get_logger(), " Message: %s",
result->message.empty() ? "" : (R"(""")" + result->message + R"(""")").c_str());
RCLCPP_INFO(
node->get_logger(), " Has camera correction: %s",
result->has_camera_correction ? "true" : "false");
RCLCPP_INFO(
node->get_logger(), " Camera correction timestamp: %d (%s)",
result->camera_correction_timestamp.sec, time_str.c_str());
return result->success;
}
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
auto node = std::make_shared<rclcpp::Node>("sample_infield_correction");
set_srgb(node);
const InfieldCorrectionOperation operation =
get_parameter_enum(*node, "operation", infield_correction_operation_map);
switch (operation) {
case InfieldCorrectionOperation::Verify: {
RCLCPP_INFO(node->get_logger(), "--- Starting infield correction: Verify ---");
auto start_client =
create_service_client<std_srvs::srv::Trigger>(node, "infield_correction/start");
auto capture_client = create_service_client<zivid_interfaces::srv::InfieldCorrectionCapture>(
node, "infield_correction/capture");
auto compute_client = create_service_client<zivid_interfaces::srv::InfieldCorrectionCompute>(
node, "infield_correction/compute");
if (!request_trigger_and_print_response(node, start_client)) {
fatal_error(node->get_logger(), "Could not start infield correction, aborting.");
}
if (!request_capture_and_print_response(node, capture_client)) {
fatal_error(
node->get_logger(), "Could not perform an infield correction capture, aborting.");
}
request_infield_correction_compute_and_print_response(node, compute_client, "compute");
} break;
case InfieldCorrectionOperation::Correct:
case InfieldCorrectionOperation::CorrectAndWrite: {
RCLCPP_INFO(node->get_logger(), "--- Starting infield correction ---");
auto start_client =
create_service_client<std_srvs::srv::Trigger>(node, "infield_correction/start");
if (!request_trigger_and_print_response(node, start_client)) {
fatal_error(node->get_logger(), "Could not start infield correction, aborting.");
}
auto capture_client = create_service_client<zivid_interfaces::srv::InfieldCorrectionCapture>(
node, "infield_correction/capture");
auto compute_client = create_service_client<zivid_interfaces::srv::InfieldCorrectionCompute>(
node, "infield_correction/compute");
constexpr int wait_seconds = 5;
constexpr int num_successful_captures_target = 3;
RCLCPP_INFO_STREAM(
node->get_logger(), "--- Starting captures, will proceed until " +
std::to_string(num_successful_captures_target) +
" captures have completed with a detected calibration board ---");
bool sleep_before_capture = false;
for (int num_successful_captures = 0;
num_successful_captures < num_successful_captures_target;) {
if (sleep_before_capture) {
RCLCPP_INFO_STREAM(
node->get_logger(), "--- Waiting for " + std::to_string(wait_seconds) +
" seconds before taking the next capture ---");
rclcpp::spin_until_future_complete(
node, std::promise<bool>().get_future(), std::chrono::seconds(wait_seconds));
} else {
sleep_before_capture = true;
}
const bool success = request_capture_and_print_response(node, capture_client);
if (success) {
num_successful_captures += 1;
// Run compute on the gathered captures so far. This provides useful information about the
// expected effect of the correction with the current captures.
request_infield_correction_compute_and_print_response(node, compute_client, "compute");
}
}
RCLCPP_INFO(node->get_logger(), "--- Captures complete ---");
if (operation == InfieldCorrectionOperation::CorrectAndWrite) {
RCLCPP_INFO_STREAM(node->get_logger(), "--- Writing correction results to camera ---");
auto compute_and_write_client =
create_service_client<zivid_interfaces::srv::InfieldCorrectionCompute>(
node, "infield_correction/compute_and_write");
request_infield_correction_compute_and_print_response(
node, compute_and_write_client, "compute and write");
}
} break;
case InfieldCorrectionOperation::Read: {
RCLCPP_INFO(node->get_logger(), "--- Starting infield correction: Read ---");
auto read_client = create_service_client<zivid_interfaces::srv::InfieldCorrectionRead>(
node, "infield_correction/read");
request_read_and_print_response(node, read_client);
} break;
case InfieldCorrectionOperation::Reset: {
RCLCPP_INFO(node->get_logger(), "--- Starting infield correction: Reset ---");
auto reset_client =
create_service_client<std_srvs::srv::Trigger>(node, "infield_correction/reset");
request_trigger_and_print_response(node, reset_client);
} break;
default: {
fatal_error(
node->get_logger(), "Unknown operation: " + std::to_string(static_cast<int>(operation)));
} break;
}
RCLCPP_INFO(node->get_logger(), "Spinning node.. Press Ctrl+C to abort.");
rclcpp::spin(node);
rclcpp::shutdown();
return EXIT_SUCCESS;
}