• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mavlink / MAVSDK / 12111769901

02 Dec 2024 02:51AM UTC coverage: 43.587% (+4.9%) from 38.69%
12111769901

Pull #2386

github

web-flow
Merge 522a301e0 into 68856f27a
Pull Request #2386: camera: support multiple cameras within one instance

1366 of 2037 new or added lines in 47 files covered. (67.06%)

47 existing lines in 7 files now uncovered.

13875 of 31833 relevant lines covered (43.59%)

290.84 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

53.73
/src/mavsdk/core/mavlink_command_sender.cpp
1
#include "mavlink_command_sender.h"
2
#include "mavlink_address.h"
3
#include "system_impl.h"
4
#include "unused.h"
5
#include <cmath>
6
#include <future>
7
#include <memory>
8

9
namespace mavsdk {
10

11
MavlinkCommandSender::MavlinkCommandSender(SystemImpl& system_impl) : _system_impl(system_impl)
86✔
12
{
13
    if (const char* env_p = std::getenv("MAVSDK_COMMAND_DEBUGGING")) {
86✔
14
        if (std::string(env_p) == "1") {
×
15
            LogDebug() << "Command debugging is on.";
×
16
            _command_debugging = true;
×
17
        }
18
    }
19

20
    _system_impl.register_mavlink_message_handler(
86✔
21
        MAVLINK_MSG_ID_COMMAND_ACK,
22
        [this](const mavlink_message_t& message) { receive_command_ack(message); },
130✔
23
        this);
24
}
86✔
25

26
MavlinkCommandSender::~MavlinkCommandSender()
86✔
27
{
28
    if (_command_debugging) {
86✔
29
        LogDebug() << "CommandSender destroyed";
×
30
    }
31
    _system_impl.unregister_all_mavlink_message_handlers(this);
86✔
32

33
    LockedQueue<Work>::Guard work_queue_guard(_work_queue);
86✔
34
    for (const auto& work : _work_queue) {
88✔
35
        _system_impl.unregister_timeout_handler(work->timeout_cookie);
2✔
36
    }
37
}
172✔
38

NEW
39
MavlinkCommandSender::Result MavlinkCommandSender::send_command(
×
40
    const MavlinkCommandSender::CommandInt& command, unsigned retries)
41
{
42
    // We wrap the async call with a promise and future.
43
    auto prom = std::make_shared<std::promise<Result>>();
×
44
    auto res = prom->get_future();
×
45

NEW
46
    queue_command_async(
×
47
        command,
NEW
48
        [prom](Result result, float progress) {
×
NEW
49
            UNUSED(progress);
×
50
            // We can only fulfill the promise once in C++11.
51
            // Therefore, we have to ignore the IN_PROGRESS state and wait
52
            // for the final result.
NEW
53
            if (result != Result::InProgress) {
×
NEW
54
                prom->set_value(result);
×
55
            }
NEW
56
        },
×
57
        retries);
58

59
    // Block now to wait for result.
60
    return res.get();
×
61
}
×
62

63
MavlinkCommandSender::Result MavlinkCommandSender::send_command(
5✔
64
    const MavlinkCommandSender::CommandLong& command, unsigned retries)
65
{
66
    // We wrap the async call with a promise and future.
67
    auto prom = std::make_shared<std::promise<Result>>();
5✔
68
    auto res = prom->get_future();
5✔
69

70
    queue_command_async(
5✔
71
        command,
72
        [prom](Result result, float progress) {
6✔
73
            UNUSED(progress);
6✔
74
            // We can only fulfill the promise once in C++11.
75
            // Therefore, we have to ignore the IN_PROGRESS state and wait
76
            // for the final result.
77
            if (result != Result::InProgress) {
6✔
78
                prom->set_value(result);
5✔
79
            }
80
        },
6✔
81
        retries);
82

83
    return res.get();
5✔
84
}
5✔
85

86
void MavlinkCommandSender::queue_command_async(
×
87
    const CommandInt& command, const CommandResultCallback& callback, unsigned retries)
88
{
89
    if (_command_debugging) {
×
90
        LogDebug() << "COMMAND_INT " << static_cast<int>(command.command) << " to send to "
×
91
                   << static_cast<int>(command.target_system_id) << ", "
×
92
                   << static_cast<int>(command.target_component_id);
×
93
    }
94

95
    CommandIdentification identification = identification_from_command(command);
×
96

97
    {
98
        LockedQueue<Work>::Guard work_queue_guard(_work_queue);
×
99
        for (const auto& work : _work_queue) {
×
100
            if (work->identification == identification && callback == nullptr) {
×
101
                if (_command_debugging) {
×
102
                    LogDebug() << "Dropping command " << static_cast<int>(identification.command)
×
103
                               << " that is already being sent";
×
104
                }
105
                return;
×
106
            }
107
        }
108
    }
×
109

110
    auto new_work = std::make_shared<Work>();
×
111
    new_work->timeout_s = _system_impl.timeout_s();
×
112
    new_work->command = command;
×
113
    new_work->identification = identification;
×
114
    new_work->callback = callback;
×
NEW
115
    new_work->retries_to_do = retries;
×
116
    _work_queue.push_back(new_work);
×
117
}
×
118

119
void MavlinkCommandSender::queue_command_async(
128✔
120
    const CommandLong& command, const CommandResultCallback& callback, unsigned retries)
121
{
122
    if (_command_debugging) {
128✔
123
        LogDebug() << "COMMAND_LONG " << static_cast<int>(command.command) << " to send to "
×
124
                   << static_cast<int>(command.target_system_id) << ", "
×
125
                   << static_cast<int>(command.target_component_id);
×
126
    }
127

128
    CommandIdentification identification = identification_from_command(command);
128✔
129

130
    {
131
        LockedQueue<Work>::Guard work_queue_guard(_work_queue);
128✔
132
        for (const auto& work : _work_queue) {
249✔
133
            if (work->identification == identification && callback == nullptr) {
121✔
134
                if (_command_debugging) {
×
135
                    LogDebug() << "Dropping command " << static_cast<int>(identification.command)
×
136
                               << " that is already being sent";
×
137
                }
138
                return;
×
139
            }
140
        }
141
    }
128✔
142

143
    auto new_work = std::make_shared<Work>();
128✔
144
    new_work->timeout_s = _system_impl.timeout_s();
128✔
145
    new_work->command = command;
128✔
146
    new_work->identification = identification;
128✔
147
    new_work->callback = callback;
128✔
148
    new_work->time_started = _system_impl.get_time().steady_time();
128✔
149
    new_work->retries_to_do = retries;
128✔
150
    _work_queue.push_back(new_work);
128✔
151
}
128✔
152

153
void MavlinkCommandSender::receive_command_ack(const mavlink_message_t& message)
130✔
154
{
155
    mavlink_command_ack_t command_ack;
130✔
156
    mavlink_msg_command_ack_decode(&message, &command_ack);
130✔
157

158
    if ((command_ack.target_system &&
127✔
159
         command_ack.target_system != _system_impl.get_own_system_id()) ||
260✔
160
        (command_ack.target_component &&
257✔
161
         command_ack.target_component != _system_impl.get_own_component_id())) {
127✔
162
        if (_command_debugging) {
×
163
            LogDebug() << "Ignoring command ack for command "
×
164
                       << static_cast<int>(command_ack.command) << " from "
×
165
                       << static_cast<int>(message.sysid) << '/' << static_cast<int>(message.compid)
×
166
                       << " to " << static_cast<int>(command_ack.target_system) << '/'
×
167
                       << static_cast<int>(command_ack.target_component);
×
168
        }
169
        return;
×
170
    }
171

172
    LockedQueue<Work>::Guard work_queue_guard(_work_queue);
130✔
173

174
    for (auto it = _work_queue.begin(); it != _work_queue.end(); ++it) {
157✔
175
        const auto& work = *it;
154✔
176

177
        if (!work) {
154✔
178
            LogErr() << "No work available! (should not happen #1)";
×
179
            return;
×
180
        }
181

182
        if (work->identification.command != command_ack.command ||
154✔
183
            (work->identification.target_system_id != 0 &&
127✔
184
             work->identification.target_system_id != message.sysid) ||
408✔
185
            (work->identification.target_component_id != 0 &&
127✔
186
             work->identification.target_component_id != message.compid)) {
127✔
187
            if (_command_debugging) {
27✔
188
                LogDebug() << "Command ack for " << command_ack.command
×
189
                           << " (from: " << std::to_string(message.sysid) << "/"
×
190
                           << std::to_string(message.compid) << ")" << " does not match command "
×
191
                           << work->identification.command
×
192
                           << " (to: " << std::to_string(work->identification.target_system_id)
×
193
                           << "/" << std::to_string(work->identification.target_component_id) << ")"
×
194
                           << " after "
×
195
                           << _system_impl.get_time().elapsed_since_s(work->time_started) << " s";
×
196
            }
197
            continue;
27✔
198
        }
199

200
        if (_command_debugging) {
127✔
201
            LogDebug() << "Received command ack for " << command_ack.command << " with result "
×
202
                       << static_cast<int>(command_ack.result) << " after "
×
203
                       << _system_impl.get_time().elapsed_since_s(work->time_started) << " s";
×
204
        }
205

206
        CommandResultCallback temp_callback = work->callback;
127✔
207
        std::pair<Result, float> temp_result{Result::UnknownError, NAN};
127✔
208

209
        switch (command_ack.result) {
127✔
210
            case MAV_RESULT_ACCEPTED:
72✔
211
                _system_impl.unregister_timeout_handler(work->timeout_cookie);
72✔
212
                temp_result = {Result::Success, 1.0f};
72✔
213
                _work_queue.erase(it);
72✔
214
                break;
72✔
215

216
            case MAV_RESULT_DENIED:
36✔
217
                if (_command_debugging) {
36✔
218
                    LogDebug() << "command denied (" << work->identification.command << ").";
×
219
                    if (work->identification.command == 512) {
×
220
                        LogDebug() << "(message " << work->identification.maybe_param1 << ")";
×
221
                    }
222
                }
223
                _system_impl.unregister_timeout_handler(work->timeout_cookie);
36✔
224
                temp_result = {Result::Denied, NAN};
36✔
225
                _work_queue.erase(it);
36✔
226
                break;
36✔
227

228
            case MAV_RESULT_UNSUPPORTED:
16✔
229
                if (_command_debugging) {
16✔
230
                    LogDebug() << "command unsupported (" << work->identification.command << ").";
×
231
                }
232
                _system_impl.unregister_timeout_handler(work->timeout_cookie);
16✔
233
                temp_result = {Result::Unsupported, NAN};
16✔
234
                _work_queue.erase(it);
16✔
235
                break;
16✔
236

237
            case MAV_RESULT_TEMPORARILY_REJECTED:
2✔
238
                if (_command_debugging) {
2✔
239
                    LogDebug() << "command temporarily rejected (" << work->identification.command
×
240
                               << ").";
×
241
                }
242
                _system_impl.unregister_timeout_handler(work->timeout_cookie);
2✔
243
                temp_result = {Result::TemporarilyRejected, NAN};
2✔
244
                _work_queue.erase(it);
2✔
245
                break;
2✔
246

247
            case MAV_RESULT_FAILED:
×
248
                if (_command_debugging) {
×
249
                    LogDebug() << "command failed (" << work->identification.command << ").";
×
250
                }
251
                _system_impl.unregister_timeout_handler(work->timeout_cookie);
×
252
                temp_result = {Result::Failed, NAN};
×
253
                _work_queue.erase(it);
×
254
                break;
×
255

256
            case MAV_RESULT_IN_PROGRESS:
1✔
257
                if (_command_debugging) {
1✔
258
                    if (static_cast<int>(command_ack.progress) != 255) {
×
259
                        LogDebug() << "progress: " << static_cast<int>(command_ack.progress)
×
260
                                   << " % (" << work->identification.command << ").";
×
261
                    }
262
                }
263
                // If we get a progress update, we can raise the timeout
264
                // to something higher because we know the initial command
265
                // has arrived.
266
                _system_impl.unregister_timeout_handler(work->timeout_cookie);
1✔
267
                work->timeout_cookie = _system_impl.register_timeout_handler(
2✔
268
                    [this, identification = work->identification] {
1✔
269
                        receive_timeout(identification);
×
270
                    },
×
271
                    3.0);
272

273
                temp_result = {
1✔
274
                    Result::InProgress, static_cast<float>(command_ack.progress) / 100.0f};
1✔
275
                break;
1✔
276

277
            case MAV_RESULT_CANCELLED:
×
278
                if (_command_debugging) {
×
279
                    LogDebug() << "command cancelled (" << work->identification.command << ").";
×
280
                }
281
                _system_impl.unregister_timeout_handler(work->timeout_cookie);
×
282
                temp_result = {Result::Cancelled, NAN};
×
283
                _work_queue.erase(it);
×
284
                break;
×
285

286
            default:
×
287
                LogWarn() << "Received unknown ack.";
×
288
                break;
×
289
        }
290

291
        if (temp_callback != nullptr) {
127✔
292
            call_callback(temp_callback, temp_result.first, temp_result.second);
127✔
293
        }
294

295
        return;
127✔
296
    }
127✔
297

298
    if (_command_debugging) {
3✔
299
        LogDebug() << "Received ack from " << static_cast<int>(message.sysid) << '/'
×
300
                   << static_cast<int>(message.compid)
×
301
                   << " for not-existing command: " << static_cast<int>(command_ack.command)
×
302
                   << "! Ignoring...";
×
303
    } else {
304
        LogWarn() << "Received ack for not-existing command: "
6✔
305
                  << static_cast<int>(command_ack.command) << "! Ignoring...";
6✔
306
    }
307
}
130✔
308

309
void MavlinkCommandSender::receive_timeout(const CommandIdentification& identification)
1✔
310
{
311
    if (_command_debugging) {
1✔
312
        LogDebug() << "Got timeout!";
×
313
    }
314
    bool found_command = false;
1✔
315
    CommandResultCallback temp_callback = nullptr;
1✔
316
    std::pair<Result, float> temp_result{Result::UnknownError, NAN};
1✔
317

318
    LockedQueue<Work>::Guard work_queue_guard(_work_queue);
1✔
319

320
    for (auto it = _work_queue.begin(); it != _work_queue.end(); ++it) {
2✔
321
        const auto& work = *it;
1✔
322

323
        if (!work) {
1✔
324
            LogErr() << "No work available! (should not happen #2)";
×
325
            return;
×
326
        }
327

328
        if (work->identification != identification) {
1✔
329
            continue;
×
330
        }
331

332
        found_command = true;
1✔
333

334
        if (work->retries_to_do > 0) {
1✔
335
            // We're not sure the command arrived, let's retransmit.
336
            LogWarn() << "sending again after "
2✔
337
                      << _system_impl.get_time().elapsed_since_s(work->time_started)
2✔
338
                      << " s, retries to do: " << work->retries_to_do << "  ("
1✔
339
                      << work->identification.command << ").";
3✔
340

341
            if (work->identification.command == MAV_CMD_REQUEST_MESSAGE) {
1✔
342
                LogWarn() << "Request was for msg ID: " << work->identification.maybe_param1;
1✔
343
            }
344

345
            if (!send_mavlink_message(work->command)) {
1✔
346
                LogErr() << "connection send error in retransmit (" << work->identification.command
×
347
                         << ").";
×
348
                temp_callback = work->callback;
×
349
                temp_result = {Result::ConnectionError, NAN};
×
350
                _work_queue.erase(it);
×
351
                break;
×
352
            } else {
353
                --work->retries_to_do;
1✔
354
                work->timeout_cookie = _system_impl.register_timeout_handler(
2✔
355
                    [this, identification = work->identification] {
1✔
356
                        receive_timeout(identification);
×
357
                    },
×
358
                    work->timeout_s);
1✔
359
            }
360
        } else {
361
            // We have tried retransmitting, giving up now.
362
            if (work->identification.command == 512) {
×
363
                uint8_t target_sysid;
364
                uint8_t target_compid;
365
                if (auto command_int = std::get_if<CommandInt>(&work->command)) {
×
366
                    target_sysid = command_int->target_system_id;
×
367
                    target_compid = command_int->target_component_id;
×
368
                } else if (auto command_long = std::get_if<CommandLong>(&work->command)) {
×
369
                    target_sysid = command_long->target_system_id;
×
370
                    target_compid = command_long->target_component_id;
×
371
                } else {
372
                    LogErr() << "No command, that's awkward";
×
373
                    continue;
×
374
                }
NEW
375
                LogWarn() << "Retrying failed for REQUEST_MESSAGE command for message: "
×
NEW
376
                          << work->identification.maybe_param1 << ", to ("
×
NEW
377
                          << std::to_string(target_sysid) << "/" << std::to_string(target_compid)
×
NEW
378
                          << ")";
×
379
            } else {
NEW
380
                LogWarn() << "Retrying failed for command: " << work->identification.command << ")";
×
381
            }
382

383
            temp_callback = work->callback;
×
384
            temp_result = {Result::Timeout, NAN};
×
385
            _work_queue.erase(it);
×
386
            break;
×
387
        }
388
    }
389

390
    if (temp_callback != nullptr) {
1✔
391
        call_callback(temp_callback, temp_result.first, temp_result.second);
×
392
    }
393

394
    if (!found_command) {
1✔
395
        LogWarn() << "Timeout for not-existing command: "
×
396
                  << static_cast<int>(identification.command) << "! Ignoring...";
×
397
    }
398
}
1✔
399

400
void MavlinkCommandSender::do_work()
9,623✔
401
{
402
    LockedQueue<Work>::Guard work_queue_guard(_work_queue);
9,623✔
403

404
    for (const auto& work : _work_queue) {
9,789✔
405
        if (work->already_sent) {
216✔
406
            continue;
25✔
407
        }
408

409
        bool already_being_sent = false;
191✔
410
        for (const auto& other_work : _work_queue) {
464✔
411
            // Ignore itself:
412
            if (other_work == work) {
336✔
413
                continue;
128✔
414
            }
415

416
            // Check if command with same command ID is already being sent.
417
            if (other_work->already_sent &&
300✔
418
                other_work->identification.command == work->identification.command) {
92✔
419
                if (_command_debugging) {
63✔
420
                    LogDebug() << "Command " << static_cast<int>(work->identification.command)
×
421
                               << " is already being sent, waiting...";
×
422
                }
423
                already_being_sent = true;
63✔
424
                break;
63✔
425
            }
426
        }
427

428
        if (already_being_sent) {
191✔
429
            continue;
63✔
430
        }
431

432
        // LogDebug() << "sending it the first time (" << work->mavlink_command << ")";
433
        work->time_started = _system_impl.get_time().steady_time();
128✔
434

435
        {
436
            if (!send_mavlink_message(work->command)) {
128✔
437
                LogErr() << "connection send error (" << work->identification.command << ")";
×
438
                // In this case we try again after the timeout. Chances are slim it will work next
439
                // time though.
440
            } else {
441
                if (_command_debugging) {
128✔
442
                    LogDebug() << "Sent command " << static_cast<int>(work->identification.command);
×
443
                }
444
            }
445
        }
446

447
        work->already_sent = true;
128✔
448

449
        work->timeout_cookie = _system_impl.register_timeout_handler(
256✔
450
            [this, identification = work->identification] { receive_timeout(identification); },
129✔
451
            work->timeout_s);
128✔
452
    }
453
}
9,647✔
454

455
void MavlinkCommandSender::call_callback(
127✔
456
    const CommandResultCallback& callback, Result result, float progress) const
457
{
458
    if (!callback) {
127✔
459
        return;
×
460
    }
461

462
    // It seems that we need to queue the callback on the thread pool otherwise
463
    // we lock ourselves out when we send a command in the callback receiving a command result.
464
    auto temp_callback = callback;
127✔
465
    _system_impl.call_user_callback(
254✔
466
        [temp_callback, result, progress]() { temp_callback(result, progress); });
467
}
127✔
468

469
bool MavlinkCommandSender::send_mavlink_message(const Command& command) const
129✔
470
{
471
    if (auto command_int = std::get_if<CommandInt>(&command)) {
129✔
472
        return _system_impl.queue_message([&](MavlinkAddress mavlink_address, uint8_t channel) {
×
473
            mavlink_message_t message;
474
            mavlink_msg_command_int_pack_chan(
×
475
                mavlink_address.system_id,
×
476
                mavlink_address.component_id,
×
477
                channel,
478
                &message,
479
                command_int->target_system_id,
×
480
                command_int->target_component_id,
×
481
                command_int->frame,
×
482
                command_int->command,
×
483
                command_int->current,
×
484
                command_int->autocontinue,
×
485
                maybe_reserved(command_int->params.maybe_param1),
×
486
                maybe_reserved(command_int->params.maybe_param2),
×
487
                maybe_reserved(command_int->params.maybe_param3),
×
488
                maybe_reserved(command_int->params.maybe_param4),
×
489
                command_int->params.x,
×
490
                command_int->params.y,
×
491
                maybe_reserved(command_int->params.maybe_z));
×
492
            return message;
×
493
        });
×
494

495
    } else if (auto command_long = std::get_if<CommandLong>(&command)) {
129✔
496
        return _system_impl.queue_message([&](MavlinkAddress mavlink_address, uint8_t channel) {
258✔
497
            mavlink_message_t message;
498
            mavlink_msg_command_long_pack_chan(
1,032✔
499
                mavlink_address.system_id,
129✔
500
                mavlink_address.component_id,
129✔
501
                channel,
502
                &message,
503
                command_long->target_system_id,
1,032✔
504
                command_long->target_component_id,
129✔
505
                command_long->command,
129✔
506
                command_long->confirmation,
129✔
507
                maybe_reserved(command_long->params.maybe_param1),
129✔
508
                maybe_reserved(command_long->params.maybe_param2),
129✔
509
                maybe_reserved(command_long->params.maybe_param3),
129✔
510
                maybe_reserved(command_long->params.maybe_param4),
129✔
511
                maybe_reserved(command_long->params.maybe_param5),
129✔
512
                maybe_reserved(command_long->params.maybe_param6),
129✔
513
                maybe_reserved(command_long->params.maybe_param7));
129✔
514
            return message;
129✔
515
        });
129✔
516
    } else {
517
        return false;
×
518
    }
519
}
520

521
float MavlinkCommandSender::maybe_reserved(const std::optional<float>& maybe_param) const
903✔
522
{
523
    if (maybe_param) {
903✔
524
        return maybe_param.value();
150✔
525

526
    } else {
527
        if (_system_impl.autopilot() == Autopilot::ArduPilot) {
753✔
528
            return 0.0f;
×
529
        } else {
530
            return NAN;
753✔
531
        }
532
    }
533
}
534

535
} // namespace mavsdk
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc