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

mavlink / MAVSDK / 6736239309

02 Nov 2023 05:35PM UTC coverage: 31.229% (+0.07%) from 31.159%
6736239309

push

github

web-flow
Merge pull request #2170 from Jaeyoung-Lim/pr-fix-do-reposition

Request mode change for action MAV_CMD_DO_REPOSITION

1 of 1 new or added line in 1 file covered. (100.0%)

7906 of 25316 relevant lines covered (31.23%)

23.6 hits per line

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

54.36
/src/mavsdk/core/mavsdk_impl.cpp
1
#include "mavsdk_impl.h"
2

3
#include <algorithm>
4
#include <mutex>
5

6
#include "connection.h"
7
#include "tcp_connection.h"
8
#include "udp_connection.h"
9
#include "system.h"
10
#include "system_impl.h"
11
#include "serial_connection.h"
12
#include "cli_arg.h"
13
#include "version.h"
14
#include "server_component_impl.h"
15
#include "mavlink_channels.h"
16
#include "callback_list.tpp"
17

18
namespace mavsdk {
19

20
template class CallbackList<>;
21

22
MavsdkImpl::MavsdkImpl() : timeout_handler(time), call_every_handler(time)
21✔
23
{
24
    LogInfo() << "MAVSDK version: " << mavsdk_version;
21✔
25

26
    if (const char* env_p = std::getenv("MAVSDK_CALLBACK_DEBUGGING")) {
21✔
27
        if (std::string(env_p) == "1") {
×
28
            LogDebug() << "Callback debugging is on.";
×
29
            _callback_debugging = true;
×
30
        }
31
    }
32

33
    if (const char* env_p = std::getenv("MAVSDK_MESSAGE_DEBUGGING")) {
21✔
34
        if (std::string(env_p) == "1") {
×
35
            LogDebug() << "Message debugging is on.";
×
36
            _message_logging_on = true;
×
37
        }
38
    }
39

40
    _work_thread = new std::thread(&MavsdkImpl::work_thread, this);
21✔
41

42
    _process_user_callbacks_thread =
42✔
43
        new std::thread(&MavsdkImpl::process_user_callbacks_thread, this);
21✔
44
}
21✔
45

46
MavsdkImpl::~MavsdkImpl()
21✔
47
{
48
    call_every_handler.remove(_heartbeat_send_cookie);
21✔
49

50
    _should_exit = true;
21✔
51

52
    if (_process_user_callbacks_thread != nullptr) {
21✔
53
        _user_callback_queue.stop();
21✔
54
        _process_user_callbacks_thread->join();
21✔
55
        delete _process_user_callbacks_thread;
21✔
56
        _process_user_callbacks_thread = nullptr;
21✔
57
    }
58

59
    if (_work_thread != nullptr) {
21✔
60
        _work_thread->join();
21✔
61
        delete _work_thread;
21✔
62
        _work_thread = nullptr;
21✔
63
    }
64

65
    {
66
        std::lock_guard<std::recursive_mutex> lock(_systems_mutex);
42✔
67
        _systems.clear();
21✔
68
    }
69

70
    {
71
        std::lock_guard<std::mutex> lock(_connections_mutex);
42✔
72
        _connections.clear();
21✔
73
    }
74
}
21✔
75

76
std::string MavsdkImpl::version()
1✔
77
{
78
    static unsigned version_counter = 0;
79

80
    ++version_counter;
1✔
81

82
    switch (version_counter) {
1✔
83
        case 10:
×
84
            return "You were wondering about the name of this library?";
×
85
        case 11:
×
86
            return "Let's look at the history:";
×
87
        case 12:
×
88
            return "DroneLink";
×
89
        case 13:
×
90
            return "DroneCore";
×
91
        case 14:
×
92
            return "DronecodeSDK";
×
93
        case 15:
×
94
            return "MAVSDK";
×
95
        case 16:
×
96
            return "And that's it...";
×
97
        case 17:
×
98
            return "At least for now ¯\\_(ツ)_/¯.";
×
99
        default:
1✔
100
            return mavsdk_version;
1✔
101
    }
102
}
103

104
std::vector<std::shared_ptr<System>> MavsdkImpl::systems() const
20✔
105
{
106
    std::vector<std::shared_ptr<System>> systems_result{};
20✔
107

108
    std::lock_guard<std::recursive_mutex> lock(_systems_mutex);
40✔
109
    for (auto& system : _systems) {
31✔
110
        // We ignore the 0 entry because it's just a null system.
111
        // It's only created because the older, deprecated API needs a
112
        // reference.
113
        if (system.first == 0) {
11✔
114
            continue;
×
115
        }
116
        systems_result.push_back(system.second);
11✔
117
    }
118

119
    return systems_result;
20✔
120
}
121

122
std::optional<std::shared_ptr<System>> MavsdkImpl::first_autopilot(double timeout_s)
9✔
123
{
124
    {
125
        std::lock_guard<std::recursive_mutex> lock(_systems_mutex);
9✔
126
        for (auto system : _systems) {
10✔
127
            if (system.second->is_connected() && system.second->has_autopilot()) {
1✔
128
                return system.second;
×
129
            }
130
        }
131
    }
132

133
    if (timeout_s == 0.0) {
9✔
134
        // Don't wait at all.
135
        return {};
×
136
    }
137

138
    auto prom = std::promise<std::shared_ptr<System>>();
18✔
139

140
    std::once_flag flag;
9✔
141
    auto handle = subscribe_on_new_system([this, &prom, &flag]() {
9✔
142
        const auto system = systems().at(0);
27✔
143
        if (system->is_connected() && system->has_autopilot()) {
9✔
144
            std::call_once(flag, [&prom, &system]() { prom.set_value(system); });
18✔
145
        }
146
    });
9✔
147

148
    auto fut = prom.get_future();
18✔
149

150
    if (timeout_s > 0.0) {
9✔
151
        if (fut.wait_for(std::chrono::milliseconds(int64_t(timeout_s * 1e3))) ==
9✔
152
            std::future_status::ready) {
153
            unsubscribe_on_new_system(handle);
9✔
154
            return fut.get();
9✔
155

156
        } else {
157
            unsubscribe_on_new_system(handle);
×
158
            return std::nullopt;
×
159
        }
160
    } else {
161
        fut.wait();
×
162
        unsubscribe_on_new_system(handle);
×
163
        return std::optional(fut.get());
×
164
    }
165
}
166

167
std::shared_ptr<ServerComponent> MavsdkImpl::server_component_by_type(
10✔
168
    Mavsdk::ServerComponentType server_component_type, unsigned instance)
169
{
170
    switch (server_component_type) {
10✔
171
        case Mavsdk::ServerComponentType::Autopilot:
9✔
172
            if (instance == 0) {
9✔
173
                return server_component_by_id(MAV_COMP_ID_AUTOPILOT1);
9✔
174
            } else {
175
                LogErr() << "Only autopilot instance 0 is valid";
×
176
                return {};
×
177
            }
178

179
        case Mavsdk::ServerComponentType::GroundStation:
×
180
            if (instance == 0) {
×
181
                return server_component_by_id(MAV_COMP_ID_MISSIONPLANNER);
×
182
            } else {
183
                LogErr() << "Only one ground station supported at this time";
×
184
                return {};
×
185
            }
186

187
        case Mavsdk::ServerComponentType::CompanionComputer:
×
188
            if (instance == 0) {
×
189
                return server_component_by_id(MAV_COMP_ID_ONBOARD_COMPUTER);
×
190
            } else if (instance == 1) {
×
191
                return server_component_by_id(MAV_COMP_ID_ONBOARD_COMPUTER2);
×
192
            } else if (instance == 2) {
×
193
                return server_component_by_id(MAV_COMP_ID_ONBOARD_COMPUTER3);
×
194
            } else if (instance == 3) {
×
195
                return server_component_by_id(MAV_COMP_ID_ONBOARD_COMPUTER4);
×
196
            } else {
197
                LogErr() << "Only companion computer 0..3 are supported";
×
198
                return {};
×
199
            }
200

201
        case Mavsdk::ServerComponentType::Camera:
1✔
202
            if (instance == 0) {
1✔
203
                return server_component_by_id(MAV_COMP_ID_CAMERA);
1✔
204
            } else if (instance == 1) {
×
205
                return server_component_by_id(MAV_COMP_ID_CAMERA2);
×
206
            } else if (instance == 2) {
×
207
                return server_component_by_id(MAV_COMP_ID_CAMERA3);
×
208
            } else if (instance == 3) {
×
209
                return server_component_by_id(MAV_COMP_ID_CAMERA4);
×
210
            } else if (instance == 4) {
×
211
                return server_component_by_id(MAV_COMP_ID_CAMERA5);
×
212
            } else if (instance == 5) {
×
213
                return server_component_by_id(MAV_COMP_ID_CAMERA6);
×
214
            } else {
215
                LogErr() << "Only camera 0..5 are supported";
×
216
                return {};
×
217
            }
218

219
        default:
×
220
            LogErr() << "Unknown server component type";
×
221
            return {};
×
222
    }
223
}
224

225
std::shared_ptr<ServerComponent> MavsdkImpl::server_component_by_id(uint8_t component_id)
40✔
226
{
227
    if (component_id == 0) {
40✔
228
        LogErr() << "Server component with component ID 0 not allowed";
×
229
        return nullptr;
×
230
    }
231

232
    std::lock_guard<std::mutex> lock(_server_components_mutex);
80✔
233

234
    for (auto& it : _server_components) {
40✔
235
        if (it.first == component_id) {
20✔
236
            if (it.second != nullptr) {
20✔
237
                return it.second;
20✔
238
            } else {
239
                it.second = std::make_shared<ServerComponent>(*this, component_id);
×
240
            }
241
        }
242
    }
243

244
    _server_components.emplace_back(std::pair<uint8_t, std::shared_ptr<ServerComponent>>(
60✔
245
        component_id, std::make_shared<ServerComponent>(*this, component_id)));
80✔
246

247
    return _server_components.back().second;
20✔
248
}
249

250
void MavsdkImpl::forward_message(mavlink_message_t& message, Connection* connection)
×
251
{
252
    // Forward_message Function implementing Mavlink routing rules.
253
    // See https://mavlink.io/en/guide/routing.html
254

255
    bool forward_heartbeats_enabled = true;
×
256
    const uint8_t target_system_id = get_target_system_id(message);
×
257
    const uint8_t target_component_id = get_target_component_id(message);
×
258

259
    // If it's a message only for us, we keep it, otherwise, we forward it.
260
    const bool targeted_only_at_us =
261
        (target_system_id == get_own_system_id() && target_component_id == get_own_component_id());
×
262

263
    // We don't forward heartbeats unless it's specifically enabled.
264
    const bool heartbeat_check_ok =
×
265
        (message.msgid != MAVLINK_MSG_ID_HEARTBEAT || forward_heartbeats_enabled);
×
266

267
    if (!targeted_only_at_us && heartbeat_check_ok) {
×
268
        std::lock_guard<std::mutex> lock(_connections_mutex);
×
269

270
        unsigned successful_emissions = 0;
×
271
        for (auto& entry : _connections) {
×
272
            // Check whether the connection is not the one from which we received the message.
273
            // And also check if the connection was set to forward messages.
274
            if (entry.connection.get() == connection ||
×
275
                !entry.connection->should_forward_messages()) {
×
276
                continue;
×
277
            }
278
            if ((*entry.connection).send_message(message)) {
×
279
                successful_emissions++;
×
280
            }
281
        }
282
        if (successful_emissions == 0) {
×
283
            LogErr() << "Message forwarding failed";
×
284
        }
285
    }
286
}
×
287

288
void MavsdkImpl::receive_message(mavlink_message_t& message, Connection* connection)
184✔
289
{
290
    if (_message_logging_on) {
184✔
291
        LogDebug() << "Processing message " << message.msgid << " from "
×
292
                   << static_cast<int>(message.sysid) << "/" << static_cast<int>(message.compid);
×
293
    }
294

295
    // This is a low level interface where incoming messages can be tampered
296
    // with or even dropped.
297
    {
298
        std::lock_guard<std::mutex> lock(_intercept_callback_mutex);
184✔
299
        if (_intercept_incoming_messages_callback != nullptr) {
184✔
300
            bool keep = _intercept_incoming_messages_callback(message);
49✔
301
            if (!keep) {
49✔
302
                LogDebug() << "Dropped incoming message: " << int(message.msgid);
14✔
303
                return;
14✔
304
            }
305
        }
306
    }
307

308
    /** @note: Forward message if option is enabled and multiple interfaces are connected.
309
     *  Performs message forwarding checks for every messages if message forwarding
310
     *  is enabled on at least one connection, and in case of a single forwarding connection,
311
     *  we check that it is not the one which received the current message.
312
     *
313
     * Conditions:
314
     * 1. At least 2 connections.
315
     * 2. At least 1 forwarding connection.
316
     * 3. At least 2 forwarding connections or current connection is not forwarding.
317
     */
318
    if (_connections.size() > 1 && mavsdk::Connection::forwarding_connections_count() > 0 &&
170✔
319
        (mavsdk::Connection::forwarding_connections_count() > 1 ||
×
320
         !connection->should_forward_messages())) {
×
321
        if (_message_logging_on) {
×
322
            LogDebug() << "Forwarding message " << message.msgid << " from "
×
323
                       << static_cast<int>(message.sysid) << "/"
×
324
                       << static_cast<int>(message.compid);
×
325
        }
326
        forward_message(message, connection);
×
327
    }
328

329
    // Don't ever create a system with sysid 0.
330
    if (message.sysid == 0) {
170✔
331
        if (_message_logging_on) {
×
332
            LogDebug() << "Ignoring message with sysid == 0";
×
333
        }
334
        return;
×
335
    }
336

337
    // Filter out messages by QGroundControl, however, only do that if MAVSDK
338
    // is also implementing a ground station and not if it is used in another
339
    // configuration, e.g. on a companion.
340
    //
341
    // This is a workaround because PX4 started forwarding messages between
342
    // mavlink instances which leads to existing implementations (including
343
    // examples and integration tests) to connect to QGroundControl by accident
344
    // instead of PX4 because the check `has_autopilot()` is not used.
345
    if (_configuration.get_usage_type() == Mavsdk::Configuration::UsageType::GroundStation &&
170✔
346
        message.sysid == 255 && message.compid == MAV_COMP_ID_MISSIONPLANNER) {
170✔
347
        if (_message_logging_on) {
×
348
            LogDebug() << "Ignoring messages from QGC as we are also a ground station";
×
349
        }
350
        return;
×
351
    }
352

353
    std::lock_guard<std::recursive_mutex> lock(_systems_mutex);
170✔
354

355
    // The only situation where we create a system with sysid 0 is when we initialize the connection
356
    // to the remote.
357
    if (_systems.size() == 1 && _systems[0].first == 0) {
170✔
358
        LogDebug() << "New: System ID: " << static_cast<int>(message.sysid)
30✔
359
                   << " Comp ID: " << static_cast<int>(message.compid);
30✔
360
        _systems[0].first = message.sysid;
10✔
361
        _systems[0].second->system_impl()->set_system_id(message.sysid);
10✔
362

363
        // Even though the fake system was already discovered, we can now
364
        // send a notification, now that it seems to really actually exist.
365
        notify_on_discover();
10✔
366
    }
367

368
    bool found_system = false;
170✔
369
    for (auto& system : _systems) {
170✔
370
        if (system.first == message.sysid) {
160✔
371
            system.second->system_impl()->add_new_component(message.compid);
160✔
372
            found_system = true;
160✔
373
            break;
160✔
374
        }
375
    }
376

377
    if (!found_system && message.compid == MAV_COMP_ID_TELEMETRY_RADIO) {
170✔
378
        if (_message_logging_on) {
×
379
            LogDebug() << "Don't create new system just for telemetry radio";
×
380
        }
381
        return;
×
382
    }
383

384
    if (!found_system) {
170✔
385
        make_system_with_component(message.sysid, message.compid);
10✔
386
    }
387

388
    if (_should_exit) {
170✔
389
        // Don't try to call at() if systems have already been destroyed
390
        // in destructor.
391
        return;
2✔
392
    }
393

394
    for (auto& system : _systems) {
168✔
395
        if (system.first == message.sysid) {
168✔
396
            // system.second->system_impl()->process_mavlink_message(message);
397
            mavlink_message_handler.process_message(message);
168✔
398
            break;
168✔
399
        }
400
    }
401
}
402

403
bool MavsdkImpl::send_message(mavlink_message_t& message)
185✔
404
{
405
    if (_message_logging_on) {
185✔
406
        LogDebug() << "Sending message " << message.msgid << " from "
×
407
                   << static_cast<int>(message.sysid) << "/" << static_cast<int>(message.compid);
×
408
    }
409

410
    // This is a low level interface where outgoing messages can be tampered
411
    // with or even dropped.
412
    if (_intercept_outgoing_messages_callback != nullptr) {
185✔
413
        const bool keep = _intercept_outgoing_messages_callback(message);
×
414
        if (!keep) {
×
415
            // We fake that everything was sent as instructed because
416
            // a potential loss would happen later, and we would not be informed
417
            // about it.
418
            LogDebug() << "Dropped outgoing message: " << int(message.msgid);
×
419
            return true;
×
420
        }
421
    }
422

423
    std::lock_guard<std::mutex> lock(_connections_mutex);
370✔
424

425
    if (_connections.empty()) {
185✔
426
        // We obviously can't send any messages without a connection added, so
427
        // we silently ignore this.
428
        return true;
×
429
    }
430

431
    uint8_t successful_emissions = 0;
185✔
432
    for (auto& _connection : _connections) {
370✔
433
        const uint8_t target_system_id = get_target_system_id(message);
185✔
434

435
        if (target_system_id != 0 && !(*_connection.connection).has_system_id(target_system_id)) {
185✔
436
            continue;
×
437
        }
438

439
        if ((*_connection.connection).send_message(message)) {
185✔
440
            successful_emissions++;
185✔
441
        }
442
    }
443

444
    if (successful_emissions == 0) {
185✔
445
        LogErr() << "Sending message failed";
×
446
        return false;
×
447
    }
448

449
    return true;
185✔
450
}
451

452
std::pair<ConnectionResult, Mavsdk::ConnectionHandle> MavsdkImpl::add_any_connection(
20✔
453
    const std::string& connection_url, ForwardingOption forwarding_option)
454
{
455
    CliArg cli_arg;
40✔
456
    if (!cli_arg.parse(connection_url)) {
20✔
457
        return {ConnectionResult::ConnectionUrlInvalid, Mavsdk::ConnectionHandle{}};
×
458
    }
459

460
    switch (cli_arg.get_protocol()) {
20✔
461
        case CliArg::Protocol::Udp: {
20✔
462
            int port = cli_arg.get_port() ? cli_arg.get_port() : Mavsdk::DEFAULT_UDP_PORT;
20✔
463

464
            if (cli_arg.get_path().empty() || cli_arg.get_path() == Mavsdk::DEFAULT_UDP_BIND_IP) {
20✔
465
                std::string path = Mavsdk::DEFAULT_UDP_BIND_IP;
30✔
466
                return add_udp_connection(path, port, forwarding_option);
10✔
467
            } else {
468
                std::string path = cli_arg.get_path();
20✔
469
                return setup_udp_remote(path, port, forwarding_option);
10✔
470
            }
471
        }
472

473
        case CliArg::Protocol::Tcp: {
×
474
            std::string path = Mavsdk::DEFAULT_TCP_REMOTE_IP;
×
475
            int port = Mavsdk::DEFAULT_TCP_REMOTE_PORT;
×
476
            if (!cli_arg.get_path().empty()) {
×
477
                path = cli_arg.get_path();
×
478
            }
479
            if (cli_arg.get_port()) {
×
480
                port = cli_arg.get_port();
×
481
            }
482
            return add_tcp_connection(path, port, forwarding_option);
×
483
        }
484

485
        case CliArg::Protocol::Serial: {
×
486
            int baudrate = Mavsdk::DEFAULT_SERIAL_BAUDRATE;
×
487
            if (cli_arg.get_baudrate()) {
×
488
                baudrate = cli_arg.get_baudrate();
×
489
            }
490
            bool flow_control = cli_arg.get_flow_control();
×
491
            return add_serial_connection(
492
                cli_arg.get_path(), baudrate, flow_control, forwarding_option);
×
493
        }
494

495
        default:
×
496
            return {ConnectionResult::ConnectionError, Mavsdk::ConnectionHandle{}};
×
497
    }
498
}
499

500
std::pair<ConnectionResult, Mavsdk::ConnectionHandle> MavsdkImpl::add_udp_connection(
10✔
501
    const std::string& local_ip, const int local_port, ForwardingOption forwarding_option)
502
{
503
    auto new_conn = std::make_shared<UdpConnection>(
10✔
504
        [this](mavlink_message_t& message, Connection* connection) {
108✔
505
            receive_message(message, connection);
108✔
506
        },
108✔
507
        local_ip,
508
        local_port,
509
        forwarding_option);
20✔
510
    if (!new_conn) {
10✔
511
        return {ConnectionResult::ConnectionError, Mavsdk::ConnectionHandle{}};
×
512
    }
513
    ConnectionResult ret = new_conn->start();
10✔
514
    if (ret == ConnectionResult::Success) {
10✔
515
        return {ret, add_connection(new_conn)};
10✔
516
    } else {
517
        return {ret, Mavsdk::ConnectionHandle{}};
×
518
    }
519
}
520

521
std::pair<ConnectionResult, Mavsdk::ConnectionHandle> MavsdkImpl::setup_udp_remote(
10✔
522
    const std::string& remote_ip, int remote_port, ForwardingOption forwarding_option)
523
{
524
    auto new_conn = std::make_shared<UdpConnection>(
10✔
525
        [this](mavlink_message_t& message, Connection* connection) {
76✔
526
            receive_message(message, connection);
76✔
527
        },
76✔
528
        "0.0.0.0",
529
        0,
10✔
530
        forwarding_option);
20✔
531
    if (!new_conn) {
10✔
532
        return {ConnectionResult::ConnectionError, Mavsdk::ConnectionHandle{}};
×
533
    }
534
    ConnectionResult ret = new_conn->start();
10✔
535
    if (ret == ConnectionResult::Success) {
10✔
536
        new_conn->add_remote(remote_ip, remote_port);
10✔
537
        auto handle = add_connection(new_conn);
10✔
538
        std::lock_guard<std::recursive_mutex> lock(_systems_mutex);
20✔
539
        if (_systems.empty()) {
10✔
540
            make_system_with_component(0, 0);
10✔
541
        }
542

543
        // With a UDP remote, we need to initiate the connection by sending
544
        // heartbeats.
545
        auto new_configuration = get_configuration();
10✔
546
        new_configuration.set_always_send_heartbeats(true);
10✔
547
        set_configuration(new_configuration);
10✔
548

549
        return {ret, handle};
10✔
550
    } else {
551
        return {ret, Mavsdk::ConnectionHandle{}};
×
552
    }
553
}
554

555
std::pair<ConnectionResult, Mavsdk::ConnectionHandle> MavsdkImpl::add_tcp_connection(
×
556
    const std::string& remote_ip, int remote_port, ForwardingOption forwarding_option)
557
{
558
    auto new_conn = std::make_shared<TcpConnection>(
×
559
        [this](mavlink_message_t& message, Connection* connection) {
×
560
            receive_message(message, connection);
×
561
        },
×
562
        remote_ip,
563
        remote_port,
564
        forwarding_option);
×
565
    if (!new_conn) {
×
566
        return {ConnectionResult::ConnectionError, Mavsdk::ConnectionHandle{}};
×
567
    }
568
    ConnectionResult ret = new_conn->start();
×
569
    if (ret == ConnectionResult::Success) {
×
570
        return {ret, add_connection(new_conn)};
×
571
    } else {
572
        return {ret, Mavsdk::ConnectionHandle{}};
×
573
    }
574
}
575

576
std::pair<ConnectionResult, Mavsdk::ConnectionHandle> MavsdkImpl::add_serial_connection(
×
577
    const std::string& dev_path,
578
    int baudrate,
579
    bool flow_control,
580
    ForwardingOption forwarding_option)
581
{
582
    auto new_conn = std::make_shared<SerialConnection>(
×
583
        [this](mavlink_message_t& message, Connection* connection) {
×
584
            receive_message(message, connection);
×
585
        },
×
586
        dev_path,
587
        baudrate,
588
        flow_control,
589
        forwarding_option);
×
590
    if (!new_conn) {
×
591
        return {ConnectionResult::ConnectionError, Mavsdk::ConnectionHandle{}};
×
592
    }
593
    ConnectionResult ret = new_conn->start();
×
594
    if (ret == ConnectionResult::Success) {
×
595
        auto handle = add_connection(new_conn);
×
596

597
        auto new_configuration = get_configuration();
×
598

599
        // PX4 starting with v1.13 does not send heartbeats by default, so we need
600
        // to initiate the MAVLink connection by sending heartbeats.
601
        // Therefore, we override the default here and enable sending heartbeats.
602
        new_configuration.set_always_send_heartbeats(true);
×
603
        set_configuration(new_configuration);
×
604

605
        return {ret, handle};
×
606

607
    } else {
608
        return {ret, Mavsdk::ConnectionHandle{}};
×
609
    }
610
}
611

612
Mavsdk::ConnectionHandle
613
MavsdkImpl::add_connection(const std::shared_ptr<Connection>& new_connection)
20✔
614
{
615
    std::lock_guard<std::mutex> lock(_connections_mutex);
20✔
616
    auto handle = Mavsdk::ConnectionHandle{_connections_handle_id++};
20✔
617
    _connections.emplace_back(ConnectionEntry{new_connection, handle});
20✔
618

619
    return handle;
20✔
620
}
621

622
void MavsdkImpl::remove_connection(Mavsdk::ConnectionHandle handle)
×
623
{
624
    std::lock_guard<std::mutex> lock(_connections_mutex);
×
625

626
    _connections.erase(std::remove_if(_connections.begin(), _connections.end(), [&](auto&& entry) {
×
627
        return (entry.handle == handle);
×
628
    }));
×
629
}
×
630

631
Mavsdk::Configuration MavsdkImpl::get_configuration() const
10✔
632
{
633
    return _configuration;
10✔
634
}
635

636
void MavsdkImpl::set_configuration(Mavsdk::Configuration new_configuration)
30✔
637
{
638
    // We just point the default to the newly created component. This means
639
    // that the previous default component will be deleted if it is not
640
    // used/referenced anywhere.
641
    _default_server_component = server_component_by_id(new_configuration.get_component_id());
30✔
642

643
    if (new_configuration.get_always_send_heartbeats() &&
50✔
644
        !_configuration.get_always_send_heartbeats()) {
20✔
645
        start_sending_heartbeats();
10✔
646
    } else if (
20✔
647
        !new_configuration.get_always_send_heartbeats() &&
30✔
648
        _configuration.get_always_send_heartbeats() && !is_any_system_connected()) {
30✔
649
        stop_sending_heartbeats();
×
650
    }
651

652
    _configuration = new_configuration;
30✔
653
}
30✔
654

655
uint8_t MavsdkImpl::get_own_system_id() const
265✔
656
{
657
    return _configuration.get_system_id();
265✔
658
}
659

660
uint8_t MavsdkImpl::get_own_component_id() const
12✔
661
{
662
    return _configuration.get_component_id();
12✔
663
}
664

665
uint8_t MavsdkImpl::channel() const
×
666
{
667
    // TODO
668
    return 0;
×
669
}
670

671
Autopilot MavsdkImpl::autopilot() const
×
672
{
673
    // TODO
674
    return Autopilot::Px4;
×
675
}
676

677
// FIXME: this should be per component
678
uint8_t MavsdkImpl::get_mav_type() const
25✔
679
{
680
    switch (_configuration.get_usage_type()) {
25✔
681
        case Mavsdk::Configuration::UsageType::Autopilot:
13✔
682
            return MAV_TYPE_GENERIC;
13✔
683

684
        case Mavsdk::Configuration::UsageType::GroundStation:
11✔
685
            return MAV_TYPE_GCS;
11✔
686

687
        case Mavsdk::Configuration::UsageType::CompanionComputer:
×
688
            return MAV_TYPE_ONBOARD_CONTROLLER;
×
689

690
        case Mavsdk::Configuration::UsageType::Camera:
1✔
691
            return MAV_TYPE_CAMERA;
1✔
692

693
        case Mavsdk::Configuration::UsageType::Custom:
×
694
            return MAV_TYPE_GENERIC;
×
695

696
        default:
×
697
            LogErr() << "Unknown configuration";
×
698
            return 0;
×
699
    }
700
}
701

702
void MavsdkImpl::make_system_with_component(uint8_t system_id, uint8_t comp_id)
20✔
703
{
704
    // Needs _systems_lock
705

706
    if (_should_exit) {
20✔
707
        // When the system got destroyed in the destructor, we have to give up.
708
        return;
×
709
    }
710

711
    if (static_cast<int>(system_id) == 0 && static_cast<int>(comp_id) == 0) {
20✔
712
        LogDebug() << "Initializing connection to remote system...";
10✔
713
    } else {
714
        LogDebug() << "New system ID: " << static_cast<int>(system_id)
30✔
715
                   << " Comp ID: " << static_cast<int>(comp_id);
30✔
716
    }
717

718
    // Make a system with its first component
719
    auto new_system = std::make_shared<System>(*this);
40✔
720
    new_system->init(system_id, comp_id);
20✔
721

722
    _systems.emplace_back(system_id, new_system);
20✔
723
}
724

725
void MavsdkImpl::notify_on_discover()
28✔
726
{
727
    std::lock_guard<std::recursive_mutex> lock(_systems_mutex);
56✔
728
    _new_system_callbacks.queue([this](const auto& func) { call_user_callback(func); });
38✔
729
}
28✔
730

731
void MavsdkImpl::notify_on_timeout()
×
732
{
733
    std::lock_guard<std::recursive_mutex> lock(_systems_mutex);
×
734
    _new_system_callbacks.queue([this](const auto& func) { call_user_callback(func); });
×
735
}
×
736

737
Mavsdk::NewSystemHandle
738
MavsdkImpl::subscribe_on_new_system(const Mavsdk::NewSystemCallback& callback)
10✔
739
{
740
    std::lock_guard<std::recursive_mutex> lock(_systems_mutex);
10✔
741

742
    const auto handle = _new_system_callbacks.subscribe(callback);
10✔
743

744
    if (is_any_system_connected()) {
10✔
745
        _new_system_callbacks.queue([this](const auto& func) { call_user_callback(func); });
×
746
    }
747

748
    return handle;
10✔
749
}
750

751
void MavsdkImpl::unsubscribe_on_new_system(Mavsdk::NewSystemHandle handle)
10✔
752
{
753
    _new_system_callbacks.unsubscribe(handle);
10✔
754
}
10✔
755

756
bool MavsdkImpl::is_any_system_connected() const
10✔
757
{
758
    std::vector<std::shared_ptr<System>> connected_systems = systems();
20✔
759
    return std::any_of(connected_systems.cbegin(), connected_systems.cend(), [](auto& system) {
10✔
760
        return system->is_connected();
1✔
761
    });
10✔
762
}
763

764
void MavsdkImpl::work_thread()
1,361✔
765
{
766
    while (!_should_exit) {
1,361✔
767
        timeout_handler.run_once();
1,339✔
768
        call_every_handler.run_once();
1,340✔
769

770
        {
771
            std::lock_guard<std::mutex> lock(_server_components_mutex);
2,676✔
772
            for (auto& it : _server_components) {
2,657✔
773
                if (it.second != nullptr) {
1,318✔
774
                    it.second->_impl->do_work();
1,318✔
775
                }
776
            }
777
        }
778

779
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
1,340✔
780
    }
781
}
21✔
782

783
void MavsdkImpl::call_user_callback_located(
42✔
784
    const std::string& filename, const int linenumber, const std::function<void()>& func)
785
{
786
    auto callback_size = _user_callback_queue.size();
42✔
787
    if (callback_size == 10) {
42✔
788
        LogWarn()
×
789
            << "User callback queue too slow.\n"
×
790
               "See: https://mavsdk.mavlink.io/main/en/cpp/troubleshooting.html#user_callbacks";
×
791

792
    } else if (callback_size == 99) {
42✔
793
        LogErr()
×
794
            << "User callback queue overflown\n"
×
795
               "See: https://mavsdk.mavlink.io/main/en/cpp/troubleshooting.html#user_callbacks";
×
796

797
    } else if (callback_size == 100) {
42✔
798
        return;
×
799
    }
800

801
    // We only need to keep track of filename and linenumber if we're actually debugging this.
802
    UserCallback user_callback =
42✔
803
        _callback_debugging ? UserCallback{func, filename, linenumber} : UserCallback{func};
126✔
804

805
    _user_callback_queue.enqueue(user_callback);
42✔
806
}
807

808
void MavsdkImpl::process_user_callbacks_thread()
84✔
809
{
810
    while (!_should_exit) {
84✔
811
        auto callback = _user_callback_queue.dequeue();
63✔
812
        if (!callback) {
63✔
813
            continue;
21✔
814
        }
815

816
        void* cookie{nullptr};
42✔
817

818
        const double timeout_s = 1.0;
42✔
819
        timeout_handler.add(
42✔
820
            [&]() {
×
821
                if (_callback_debugging) {
×
822
                    LogWarn() << "Callback called from " << callback.value().filename << ":"
×
823
                              << callback.value().linenumber << " took more than " << timeout_s
×
824
                              << " second to run.";
×
825
                    fflush(stdout);
×
826
                    fflush(stderr);
×
827
                    abort();
×
828
                } else {
829
                    LogWarn()
×
830
                        << "Callback took more than " << timeout_s << " second to run.\n"
×
831
                        << "See: https://mavsdk.mavlink.io/main/en/cpp/troubleshooting.html#user_callbacks";
×
832
                }
833
            },
×
834
            timeout_s,
835
            &cookie);
836
        callback.value().func();
42✔
837
        timeout_handler.remove(cookie);
42✔
838
    }
839
}
21✔
840

841
void MavsdkImpl::start_sending_heartbeats()
28✔
842
{
843
    // Before sending out first heartbeats we need to make sure we have a
844
    // default server component.
845
    default_server_component_impl();
28✔
846

847
    if (_heartbeat_send_cookie == nullptr) {
28✔
848
        call_every_handler.add(
20✔
849
            [this]() { send_heartbeat(); }, HEARTBEAT_SEND_INTERVAL_S, &_heartbeat_send_cookie);
25✔
850
    }
851
}
28✔
852

853
void MavsdkImpl::stop_sending_heartbeats()
×
854
{
855
    if (!_configuration.get_always_send_heartbeats()) {
×
856
        call_every_handler.remove(_heartbeat_send_cookie);
×
857
        _heartbeat_send_cookie = nullptr;
×
858
    }
859
}
×
860

861
ServerComponentImpl& MavsdkImpl::default_server_component_impl()
72✔
862
{
863
    if (_default_server_component == nullptr) {
72✔
864
        _default_server_component = server_component_by_id(_configuration.get_component_id());
×
865
    }
866
    return *_default_server_component->_impl;
72✔
867
}
868

869
void MavsdkImpl::send_heartbeat()
25✔
870
{
871
    std::lock_guard<std::mutex> lock(_server_components_mutex);
50✔
872

873
    for (auto& it : _server_components) {
50✔
874
        if (it.second != nullptr) {
25✔
875
            it.second->_impl->send_heartbeat();
25✔
876
        }
877
    }
878
}
25✔
879

880
void MavsdkImpl::intercept_incoming_messages_async(std::function<bool(mavlink_message_t&)> callback)
12✔
881
{
882
    std::lock_guard<std::mutex> lock(_intercept_callback_mutex);
24✔
883
    _intercept_incoming_messages_callback = callback;
12✔
884
}
12✔
885

886
void MavsdkImpl::intercept_outgoing_messages_async(std::function<bool(mavlink_message_t&)> callback)
×
887
{
888
    std::lock_guard<std::mutex> lock(_intercept_callback_mutex);
×
889
    _intercept_outgoing_messages_callback = callback;
×
890
}
×
891

892
uint8_t MavsdkImpl::get_target_system_id(const mavlink_message_t& message)
185✔
893
{
894
    // Checks whether connection knows target system ID by extracting target system if set.
895
    const mavlink_msg_entry_t* meta = mavlink_get_msg_entry(message.msgid);
185✔
896

897
    if (meta == nullptr || !(meta->flags & MAV_MSG_ENTRY_FLAG_HAVE_TARGET_SYSTEM)) {
185✔
898
        return 0;
98✔
899
    }
900

901
    // Don't look at the target system offset if it is outside the payload length.
902
    // This can happen if the fields are trimmed.
903
    if (meta->target_system_ofs >= message.len) {
87✔
904
        return 0;
×
905
    }
906

907
    return (_MAV_PAYLOAD(&message))[meta->target_system_ofs];
87✔
908
}
909

910
uint8_t MavsdkImpl::get_target_component_id(const mavlink_message_t& message)
×
911
{
912
    // Checks whether connection knows target system ID by extracting target system if set.
913
    const mavlink_msg_entry_t* meta = mavlink_get_msg_entry(message.msgid);
×
914

915
    if (meta == nullptr || !(meta->flags & MAV_MSG_ENTRY_FLAG_HAVE_TARGET_COMPONENT)) {
×
916
        return 0;
×
917
    }
918

919
    // Don't look at the target component offset if it is outside the payload length.
920
    // This can happen if the fields are trimmed.
921
    if (meta->target_component_ofs >= message.len) {
×
922
        return 0;
×
923
    }
924

925
    return (_MAV_PAYLOAD(&message))[meta->target_system_ofs];
×
926
}
927

928
Sender& MavsdkImpl::sender()
×
929
{
930
    return default_server_component_impl().sender();
×
931
}
932

933
} // 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