-
Notifications
You must be signed in to change notification settings - Fork 4.9k
Expand file tree
/
Copy pathMavLinkNodeImpl.cpp
More file actions
617 lines (552 loc) · 20.4 KB
/
MavLinkNodeImpl.cpp
File metadata and controls
617 lines (552 loc) · 20.4 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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "MavLinkNodeImpl.hpp"
#if defined(_WIN32)
#include <Windows.h>
#define AIRSIM_SLEEP_MS(ms) ::Sleep((DWORD)(ms))
#else
#include <thread>
#include <chrono>
#define AIRSIM_SLEEP_MS(ms) std::this_thread::sleep_for(std::chrono::milliseconds(ms))
#endif
#include "Utils.hpp"
#include "MavLinkMessages.hpp"
#include "Semaphore.hpp"
#include "ThreadUtils.hpp"
using namespace mavlink_utils;
using namespace mavlinkcom_impl;
const int heartbeatMilliseconds = 1000;
MavLinkNodeImpl::MavLinkNodeImpl(int localSystemId, int localComponentId)
{
local_system_id = localSystemId;
local_component_id = localComponentId;
}
MavLinkNodeImpl::~MavLinkNodeImpl()
{
close();
}
// start listening to this connection
void MavLinkNodeImpl::connect(std::shared_ptr<MavLinkConnection> connection)
{
has_cap_ = false;
connection_ = connection;
subscription_ = connection_->subscribe([=](std::shared_ptr<MavLinkConnection> con, const MavLinkMessage& msg) {
handleMessage(con, msg);
});
}
// Send heartbeat to drone. You should not do this if some other node is
// already doing it.
void MavLinkNodeImpl::startHeartbeat()
{
if (!heartbeat_running_) {
heartbeat_running_ = true;
Utils::cleanupThread(heartbeat_thread_);
heartbeat_thread_ = std::thread{ &MavLinkNodeImpl::sendHeartbeat, this };
}
}
void MavLinkNodeImpl::sendHeartbeat()
{
CurrentThread::setThreadName("MavLinkThread");
while (heartbeat_running_) {
sendOneHeartbeat();
AIRSIM_SLEEP_MS(heartbeatMilliseconds);
}
}
// this is called for all messages received on the connection.
void MavLinkNodeImpl::handleMessage(std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& msg)
{
unused(connection);
switch (msg.msgid) {
case static_cast<uint8_t>(MavLinkMessageIds::MAVLINK_MSG_ID_HEARTBEAT):
// we received a heartbeat, so let's get the capabilities.
if (!req_cap_) {
req_cap_ = true;
MavCmdRequestAutopilotCapabilities cmd{};
cmd.param1 = 1;
sendCommand(cmd);
}
break;
case static_cast<uint8_t>(MavLinkMessageIds::MAVLINK_MSG_ID_AUTOPILOT_VERSION):
cap_.decode(msg);
has_cap_ = true;
break;
}
// this is for the subclasses to play with. We put nothing here so we are not dependent on the
// subclasses remembering to call this base implementation.
}
// stop listening to the connection.
void MavLinkNodeImpl::close()
{
if (subscription_ != 0 && connection_ != nullptr) {
connection_->unsubscribe(subscription_);
subscription_ = 0;
}
if (heartbeat_running_) {
heartbeat_running_ = false;
if (heartbeat_thread_.joinable()) {
heartbeat_thread_.join();
}
}
if (connection_ != nullptr) {
connection_->close();
}
connection_ = nullptr;
}
AsyncResult<MavLinkAutopilotVersion> MavLinkNodeImpl::getCapabilities()
{
if (has_cap_) {
AsyncResult<MavLinkAutopilotVersion> nowait([=](int state) {
unused(state);
});
nowait.setResult(cap_);
return nowait;
}
auto con = ensureConnection();
AsyncResult<MavLinkAutopilotVersion> result([=](int state) {
con->unsubscribe(state);
});
int subscription = con->subscribe([=](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& m) {
unused(connection);
unused(m);
result.setResult(cap_);
});
result.setState(subscription);
// request capabilities, it will respond with AUTOPILOT_VERSION.
MavCmdRequestAutopilotCapabilities cmd{};
cmd.param1 = 1;
sendCommand(cmd);
return result;
}
AsyncResult<MavLinkHeartbeat> MavLinkNodeImpl::waitForHeartbeat()
{
Utils::log("Waiting for heartbeat from PX4...");
// wait for a heartbeat msg since this will give us the port to send commands to...
//this->setMessageInterval(static_cast<int>(MavLinkMessageIds::MAVLINK_MSG_ID_HEARTBEAT), 1);
auto con = ensureConnection();
AsyncResult<MavLinkHeartbeat> result([=](int state) {
con->unsubscribe(state);
});
int subscription = con->subscribe([=](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& m) {
unused(connection);
if (m.msgid == static_cast<uint8_t>(MavLinkMessageIds::MAVLINK_MSG_ID_HEARTBEAT)) {
MavLinkHeartbeat heartbeat;
heartbeat.decode(m);
result.setResult(heartbeat);
}
});
result.setState(subscription);
return result;
}
void MavLinkNodeImpl::sendOneHeartbeat()
{
MavLinkHeartbeat heartbeat;
// send a heart beat so that the remote node knows we are still alive
// (otherwise drone will trigger a failsafe operation).
heartbeat.autopilot = static_cast<uint8_t>(MAV_AUTOPILOT::MAV_AUTOPILOT_GENERIC);
heartbeat.type = static_cast<uint8_t>(MAV_TYPE::MAV_TYPE_GCS);
heartbeat.mavlink_version = 3;
heartbeat.base_mode = 0; // ignored by PX4
heartbeat.custom_mode = 0; // ignored by PX4
heartbeat.system_status = 0; // ignored by PX4
try {
sendMessage(heartbeat);
}
catch (std::exception& e) {
// ignore any failures here because we are running in our own thread here.
Utils::log(Utils::stringf("Caught and ignoring exception sending heartbeat: %s", e.what()));
}
}
void MavLinkNodeImpl::setMessageInterval(int msgId, int frequency)
{
float intervalMicroseconds = 1000000.0f / frequency;
MavCmdSetMessageInterval cmd{};
cmd.MessageId = static_cast<float>(msgId);
cmd.Interval = intervalMicroseconds;
sendCommand(cmd);
}
union param_value_u
{
int8_t b;
int16_t s;
int32_t i;
uint8_t ub;
uint16_t us;
uint32_t ui;
float f;
};
float UnpackParameter(uint8_t type, float param_value)
{
param_value_u pu;
pu.f = param_value;
float value = 0;
switch (static_cast<MAV_PARAM_TYPE>(type)) {
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT8:
value = static_cast<float>(pu.ub);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT8:
value = static_cast<float>(pu.b);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT16:
value = static_cast<float>(pu.us);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT16:
value = static_cast<float>(pu.s);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT32:
value = static_cast<float>(pu.ui);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT32:
value = static_cast<float>(pu.i);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT64:
// we only have 4 bytes for the value in mavlink_param_value_t, so how does this one work?
value = static_cast<float>(pu.ui);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT64:
// we only have 4 bytes for the value in mavlink_param_value_t, so how does this one work?
value = static_cast<float>(pu.i);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_REAL32:
value = param_value;
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_REAL64:
// we only have 4 bytes for the value in mavlink_param_value_t, so how does this one work?
value = param_value;
break;
default:
break;
}
return value;
}
float PackParameter(uint8_t type, float param_value)
{
param_value_u pu;
pu.f = 0;
switch (static_cast<MAV_PARAM_TYPE>(type)) {
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT8:
pu.ub = static_cast<uint8_t>(param_value);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT8:
pu.b = static_cast<int8_t>(param_value);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT16:
pu.us = static_cast<uint16_t>(param_value);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT16:
pu.s = static_cast<int16_t>(param_value);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT32:
pu.ui = static_cast<uint32_t>(param_value);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT32:
pu.i = static_cast<int32_t>(param_value);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT64:
// we only have 4 bytes for the value in mavlink_param_value_t, so how does this one work?
pu.ui = static_cast<uint32_t>(param_value);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT64:
// we only have 4 bytes for the value in mavlink_param_value_t, so how does this one work?
pu.i = static_cast<int32_t>(param_value);
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_REAL32:
pu.f = param_value;
break;
case MAV_PARAM_TYPE::MAV_PARAM_TYPE_REAL64:
// we only have 4 bytes for the value in mavlink_param_value_t, so how does this one work?
pu.f = param_value;
break;
default:
break;
}
return pu.f;
}
void MavLinkNodeImpl::assertNotPublishingThread()
{
auto con = ensureConnection();
if (con->isPublishThread()) {
throw std::runtime_error("Cannot perform blocking operation on the connection publish thread");
}
}
std::vector<MavLinkParameter> MavLinkNodeImpl::getParamList()
{
std::vector<MavLinkParameter> result;
bool done = false;
Semaphore paramReceived;
bool waiting = false;
size_t paramCount = 0;
auto con = ensureConnection();
assertNotPublishingThread();
int subscription = con->subscribe([&](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& message) {
unused(connection);
if (message.msgid == MavLinkParamValue::kMessageId) {
MavLinkParamValue param;
param.decode(message);
MavLinkParameter p;
p.index = param.param_index;
p.type = param.param_type;
char buf[17];
std::memset(buf, 0, 17);
std::memcpy(buf, param.param_id, 16);
p.name = buf;
p.value = param.param_value;
result.push_back(p);
paramCount = param.param_count;
if (param.param_index == param.param_count - 1) {
done = true;
}
if (waiting) {
paramReceived.post();
}
}
});
//MAVLINK_MSG_ID_PARAM_REQUEST_LIST
MavLinkParamRequestList cmd;
cmd.target_system = getTargetSystemId();
cmd.target_component = getTargetComponentId();
sendMessage(cmd);
while (!done) {
waiting = true;
if (!paramReceived.timed_wait(3000)) {
// timeout, so we'll drop through to the code below which will try and fix this...
done = true;
}
waiting = false;
}
con->unsubscribe(subscription);
// note that UDP does not guarantee delivery of messages, so we have to also check if some parameters are missing and get them individually.
std::vector<size_t> missing;
for (size_t i = 0; i < paramCount; i++) {
// nested loop is inefficient, but it is needed because UDP also doesn't guarantee in-order delivery
bool found = false;
for (auto iter = result.begin(), end = result.end(); iter != end; iter++) {
MavLinkParameter p = *iter;
if (static_cast<size_t>(p.index) == i) {
found = true;
break;
}
}
if (!found) {
missing.push_back(i);
}
}
// ok, now fetch the missing parameters.
for (auto iter = missing.begin(), end = missing.end(); iter != end; iter++) {
size_t index = *iter;
MavLinkParameter r;
if (getParameterByIndex(static_cast<int16_t>(*iter)).wait(2000, &r)) {
result.push_back(r);
}
else {
Utils::log(Utils::stringf("Paremter %d does not seem to exist", index), Utils::kLogLevelWarn);
}
}
std::sort(result.begin(), result.end(), [&](const MavLinkParameter& p1, const MavLinkParameter& p2) {
return p1.name.compare(p2.name) < 0;
});
this->parameters_ = result;
return result;
}
MavLinkParameter MavLinkNodeImpl::getCachedParameter(const std::string& name)
{
if (this->parameters_.size() == 0) {
throw std::runtime_error("Error: please call getParamList during initialization so we have cached snapshot of the parameter values");
}
for (int i = static_cast<int>(this->parameters_.size()) - 1; i >= 0; i--) {
MavLinkParameter p = this->parameters_[i];
if (p.name == name) {
return p;
}
}
throw std::runtime_error(Utils::stringf("Error: parameter name '%s' not found"));
}
AsyncResult<MavLinkParameter> MavLinkNodeImpl::getParameter(const std::string& name)
{
int size = static_cast<int>(name.size());
if (size > 16) {
throw std::runtime_error(Utils::stringf("Error: parameter name '%s' is too long, must be <= 16 chars", name.c_str()));
}
else if (size < 16) {
size++; // we can include the null terminator.
}
auto con = ensureConnection();
AsyncResult<MavLinkParameter> asyncResult([=](int state) {
con->unsubscribe(state);
});
MavLinkParamRequestRead cmd;
std::strncpy(cmd.param_id, name.c_str(), size);
cmd.param_index = -1;
cmd.target_component = getTargetComponentId();
cmd.target_system = getTargetSystemId();
int subscription = con->subscribe([=](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& message) {
unused(connection);
if (message.msgid == MavLinkParamValue::kMessageId) {
MavLinkParamValue param;
param.decode(message);
if (std::strncmp(param.param_id, cmd.param_id, size) == 0) {
MavLinkParameter result;
result.name = name;
result.type = param.param_type;
result.index = param.param_index;
result.value = UnpackParameter(param.param_type, param.param_value);
asyncResult.setResult(result);
}
}
});
asyncResult.setState(subscription);
sendMessage(cmd);
return asyncResult;
}
AsyncResult<MavLinkParameter> MavLinkNodeImpl::getParameterByIndex(int16_t index)
{
auto con = ensureConnection();
AsyncResult<MavLinkParameter> asyncResult([=](int state) {
con->unsubscribe(state);
});
MavLinkParamRequestRead cmd;
cmd.param_id[0] = '\0';
cmd.param_index = index;
cmd.target_component = getTargetComponentId();
cmd.target_system = getTargetSystemId();
int subscription = con->subscribe([=](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& message) {
unused(connection);
if (message.msgid == MavLinkParamValue::kMessageId) {
MavLinkParamValue param;
param.decode(message);
if (param.param_index == index) {
MavLinkParameter result;
char buf[17];
std::memset(buf, 0, 17);
std::memcpy(buf, param.param_id, 16);
result.name = buf;
result.type = param.param_type;
result.index = param.param_index;
result.value = UnpackParameter(param.param_type, param.param_value);
asyncResult.setResult(result);
}
}
});
asyncResult.setState(subscription);
sendMessage(cmd);
return asyncResult;
}
AsyncResult<bool> MavLinkNodeImpl::setParameter(MavLinkParameter p)
{
int size = static_cast<int>(p.name.size());
if (size > 16) {
throw std::runtime_error(Utils::stringf("Error: parameter name '%s' is too long, must be <= 16 chars", p.name.c_str()));
}
else if (size < 16) {
size++; // we can include the null terminator.
}
auto con = ensureConnection();
assertNotPublishingThread();
AsyncResult<bool> result([=](int state) {
con->unsubscribe(state);
});
bool gotit = false;
MavLinkParameter q;
for (size_t i = 0; i < 3; i++) {
if (getParameter(p.name).wait(2000, &q)) {
gotit = true;
break;
}
}
if (!gotit) {
throw std::runtime_error(Utils::stringf("Error: parameter name '%s' was not found", p.name.c_str()));
}
MavLinkParamSet setparam;
setparam.target_component = getTargetComponentId();
setparam.target_system = getTargetSystemId();
std::strncpy(setparam.param_id, p.name.c_str(), size);
setparam.param_type = q.type;
setparam.param_value = PackParameter(q.type, p.value);
sendMessage(setparam);
// confirmation of the PARAM_SET is to receive the updated PARAM_VALUE.
int subscription = con->subscribe([=](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& message) {
unused(connection);
if (message.msgid == MavLinkParamValue::kMessageId) {
MavLinkParamValue param;
param.decode(message);
if (std::strncmp(param.param_id, setparam.param_id, size) == 0) {
bool rc = param.param_value == setparam.param_value;
result.setResult(rc);
}
}
});
result.setState(subscription);
return result;
}
void MavLinkNodeImpl::sendMessage(MavLinkMessageBase& msg)
{
msg.sysid = local_system_id;
msg.compid = local_component_id;
ensureConnection()->sendMessage(msg);
}
void MavLinkNodeImpl::sendMessage(MavLinkMessage& msg)
{
msg.compid = local_component_id;
msg.sysid = local_system_id;
ensureConnection()->sendMessage(msg);
}
void MavLinkNodeImpl::sendCommand(MavLinkCommand& command)
{
MavLinkCommandLong cmd{};
command.pack();
cmd.command = command.command;
cmd.target_system = getTargetSystemId();
cmd.target_component = getTargetComponentId();
cmd.confirmation = 1;
cmd.param1 = command.param1;
cmd.param2 = command.param2;
cmd.param3 = command.param3;
cmd.param4 = command.param4;
cmd.param5 = command.param5;
cmd.param6 = command.param6;
cmd.param7 = command.param7;
try {
sendMessage(cmd);
}
catch (const std::exception& e) {
// silently fail since we are on a background thread here...
unused(e);
}
}
AsyncResult<bool> MavLinkNodeImpl::sendCommandAndWaitForAck(MavLinkCommand& command)
{
auto con = ensureConnection();
AsyncResult<bool> result([=](int state) {
con->unsubscribe(state);
});
uint16_t cmd = command.command;
int subscription = con->subscribe([=](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& message) {
unused(connection);
if (message.msgid == MavLinkCommandAck::kMessageId) {
MavLinkCommandAck ack;
ack.decode(message);
if (ack.command == cmd) {
MAV_RESULT ackResult = static_cast<MAV_RESULT>(ack.result);
if (ackResult == MAV_RESULT::MAV_RESULT_TEMPORARILY_REJECTED) {
Utils::log(Utils::stringf("### command %d result: MAV_RESULT_TEMPORARILY_REJECTED", cmd));
}
else if (ackResult == MAV_RESULT::MAV_RESULT_UNSUPPORTED) {
Utils::log(Utils::stringf("### command %d result: MAV_RESULT_UNSUPPORTED", cmd));
}
else if (ackResult == MAV_RESULT::MAV_RESULT_FAILED) {
Utils::log(Utils::stringf("### command %d result: MAV_RESULT_FAILED", cmd));
}
else if (ackResult == MAV_RESULT::MAV_RESULT_ACCEPTED) {
Utils::log(Utils::stringf("### command %d result: MAV_RESULT_ACCEPTED", cmd));
}
else {
Utils::log(Utils::stringf("### command %d unexpected result: %d", cmd, ackResult));
}
// tell the caller this is complete.
result.setResult(ackResult == MAV_RESULT::MAV_RESULT_ACCEPTED);
}
}
});
result.setState(subscription);
sendCommand(command);
return result;
}