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

mavlink / MAVSDK / 7231729416

16 Dec 2023 11:54AM UTC coverage: 36.997% (-0.08%) from 37.074%
7231729416

push

github

web-flow
Merge pull request #2193 from mavlink/pr-fix-target-check

core: fix component ID check

0 of 4 new or added lines in 1 file covered. (0.0%)

20 existing lines in 4 files now uncovered.

9970 of 26948 relevant lines covered (37.0%)

111.98 hits per line

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

55.35
/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)
69✔
23
{
24
    LogInfo() << "MAVSDK version: " << mavsdk_version;
69✔
25

26
    if (const char* env_p = std::getenv("MAVSDK_CALLBACK_DEBUGGING")) {
69✔
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")) {
69✔
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);
69✔
41

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

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

50
    _should_exit = true;
69✔
51

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

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

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

70
    {
71
        std::lock_guard<std::mutex> lock(_connections_mutex);
138✔
72
        _connections.clear();
69✔
73
    }
74
}
69✔
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
68✔
105
{
106
    std::vector<std::shared_ptr<System>> systems_result{};
68✔
107

108
    std::lock_guard<std::recursive_mutex> lock(_systems_mutex);
136✔
109
    for (auto& system : _systems) {
102✔
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) {
34✔
114
            continue;
×
115
        }
116
        systems_result.push_back(system.second);
34✔
117
    }
118

119
    return systems_result;
68✔
120
}
121

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

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

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

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

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

150
    if (timeout_s > 0.0) {
33✔
151
        if (fut.wait_for(std::chrono::milliseconds(int64_t(timeout_s * 1e3))) ==
33✔
152
            std::future_status::ready) {
153
            unsubscribe_on_new_system(handle);
33✔
154
            return fut.get();
33✔
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(
34✔
168
    Mavsdk::ServerComponentType server_component_type, unsigned instance)
169
{
170
    switch (server_component_type) {
34✔
171
        case Mavsdk::ServerComponentType::Autopilot:
33✔
172
            if (instance == 0) {
33✔
173
                return server_component_by_id(MAV_COMP_ID_AUTOPILOT1);
33✔
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)
136✔
226
{
227
    if (component_id == 0) {
136✔
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);
272✔
233

234
    for (auto& it : _server_components) {
136✔
235
        if (it.first == component_id) {
68✔
236
            if (it.second != nullptr) {
68✔
237
                return it.second;
68✔
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>>(
204✔
245
        component_id, std::make_shared<ServerComponent>(*this, component_id)));
272✔
246

247
    return _server_components.back().second;
68✔
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)
1,446✔
289
{
290
    if (_message_logging_on) {
1,446✔
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);
1,446✔
299
        if (_intercept_incoming_messages_callback != nullptr) {
1,446✔
300
            bool keep = _intercept_incoming_messages_callback(message);
241✔
301
            if (!keep) {
241✔
302
                LogDebug() << "Dropped incoming message: " << int(message.msgid);
39✔
303
                return;
39✔
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 &&
1,407✔
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) {
1,406✔
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 &&
1,406✔
346
        message.sysid == 255 && message.compid == MAV_COMP_ID_MISSIONPLANNER) {
1,407✔
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);
1,407✔
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) {
1,406✔
358
        LogDebug() << "New: System ID: " << static_cast<int>(message.sysid)
102✔
359
                   << " Comp ID: " << static_cast<int>(message.compid);
102✔
360
        _systems[0].first = message.sysid;
34✔
361
        _systems[0].second->system_impl()->set_system_id(message.sysid);
34✔
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();
34✔
366
    }
367

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

377
    if (!found_system && message.compid == MAV_COMP_ID_TELEMETRY_RADIO) {
1,405✔
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) {
1,405✔
385
        make_system_with_component(message.sysid, message.compid);
34✔
386
    }
387

388
    if (_should_exit) {
1,405✔
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) {
1,404✔
395
        if (system.first == message.sysid) {
1,404✔
396
            // system.second->system_impl()->process_mavlink_message(message);
397
            mavlink_message_handler.process_message(message);
1,404✔
398
            break;
1,405✔
399
        }
400
    }
401
}
402

403
bool MavsdkImpl::send_message(mavlink_message_t& message)
1,527✔
404
{
405
    if (_message_logging_on) {
1,527✔
406
        LogDebug() << "Sending message " << message.msgid << " from "
×
NEW
407
                   << static_cast<int>(message.sysid) << "/" << static_cast<int>(message.compid)
×
NEW
408
                   << " to " << static_cast<int>(get_target_system_id(message)) << "/"
×
NEW
409
                   << static_cast<int>(get_target_component_id(message));
×
410
    }
411

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

425
    std::lock_guard<std::mutex> lock(_connections_mutex);
2,894✔
426

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

433
    uint8_t successful_emissions = 0;
1,447✔
434
    for (auto& _connection : _connections) {
2,894✔
435
        const uint8_t target_system_id = get_target_system_id(message);
1,447✔
436

437
        if (target_system_id != 0 && !(*_connection.connection).has_system_id(target_system_id)) {
1,447✔
438
            continue;
×
439
        }
440

441
        if ((*_connection.connection).send_message(message)) {
1,447✔
442
            successful_emissions++;
1,447✔
443
        }
444
    }
445

446
    if (successful_emissions == 0) {
1,447✔
447
        LogErr() << "Sending message failed";
×
448
        return false;
×
449
    }
450

451
    return true;
1,447✔
452
}
453

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

462
    switch (cli_arg.get_protocol()) {
68✔
463
        case CliArg::Protocol::Udp: {
68✔
464
            int port = cli_arg.get_port() ? cli_arg.get_port() : Mavsdk::DEFAULT_UDP_PORT;
68✔
465

466
            if (cli_arg.get_path().empty() || cli_arg.get_path() == Mavsdk::DEFAULT_UDP_BIND_IP) {
68✔
467
                std::string path = Mavsdk::DEFAULT_UDP_BIND_IP;
102✔
468
                return add_udp_connection(path, port, forwarding_option);
34✔
469
            } else {
470
                std::string path = cli_arg.get_path();
68✔
471
                return setup_udp_remote(path, port, forwarding_option);
34✔
472
            }
473
        }
474

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

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

497
        default:
×
498
            return {ConnectionResult::ConnectionError, Mavsdk::ConnectionHandle{}};
×
499
    }
500
}
501

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

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

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

551
        return {ret, handle};
34✔
552
    } else {
553
        return {ret, Mavsdk::ConnectionHandle{}};
×
554
    }
555
}
556

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

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

599
        auto new_configuration = get_configuration();
×
600

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

607
        return {ret, handle};
×
608

609
    } else {
610
        return {ret, Mavsdk::ConnectionHandle{}};
×
611
    }
612
}
613

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

621
    return handle;
68✔
622
}
623

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

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

633
Mavsdk::Configuration MavsdkImpl::get_configuration() const
34✔
634
{
635
    return _configuration;
34✔
636
}
637

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

645
    if (new_configuration.get_always_send_heartbeats() &&
170✔
646
        !_configuration.get_always_send_heartbeats()) {
68✔
647
        start_sending_heartbeats();
34✔
648
    } else if (
68✔
649
        !new_configuration.get_always_send_heartbeats() &&
102✔
650
        _configuration.get_always_send_heartbeats() && !is_any_system_connected()) {
102✔
651
        stop_sending_heartbeats();
×
652
    }
653

654
    _configuration = new_configuration;
102✔
655
}
102✔
656

657
uint8_t MavsdkImpl::get_own_system_id() const
3,899✔
658
{
659
    return _configuration.get_system_id();
3,899✔
660
}
661

662
uint8_t MavsdkImpl::get_own_component_id() const
1,135✔
663
{
664
    return _configuration.get_component_id();
1,135✔
665
}
666

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

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

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

686
        case Mavsdk::Configuration::UsageType::GroundStation:
45✔
687
            return MAV_TYPE_GCS;
45✔
688

689
        case Mavsdk::Configuration::UsageType::CompanionComputer:
×
690
            return MAV_TYPE_ONBOARD_CONTROLLER;
×
691

692
        case Mavsdk::Configuration::UsageType::Camera:
1✔
693
            return MAV_TYPE_CAMERA;
1✔
694

695
        case Mavsdk::Configuration::UsageType::Custom:
×
696
            return MAV_TYPE_GENERIC;
×
697

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

704
void MavsdkImpl::make_system_with_component(uint8_t system_id, uint8_t comp_id)
68✔
705
{
706
    // Needs _systems_lock
707

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

713
    if (static_cast<int>(system_id) == 0 && static_cast<int>(comp_id) == 0) {
68✔
714
        LogDebug() << "Initializing connection to remote system...";
34✔
715
    } else {
716
        LogDebug() << "New system ID: " << static_cast<int>(system_id)
102✔
717
                   << " Comp ID: " << static_cast<int>(comp_id);
102✔
718
    }
719

720
    // Make a system with its first component
721
    auto new_system = std::make_shared<System>(*this);
136✔
722
    new_system->init(system_id, comp_id);
68✔
723

724
    _systems.emplace_back(system_id, new_system);
68✔
725
}
726

727
void MavsdkImpl::notify_on_discover()
100✔
728
{
729
    std::lock_guard<std::recursive_mutex> lock(_systems_mutex);
200✔
730
    _new_system_callbacks.queue([this](const auto& func) { call_user_callback(func); });
134✔
731
}
100✔
732

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

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

744
    const auto handle = _new_system_callbacks.subscribe(callback);
34✔
745

746
    if (is_any_system_connected()) {
34✔
747
        _new_system_callbacks.queue([this](const auto& func) { call_user_callback(func); });
×
748
    }
749

750
    return handle;
34✔
751
}
752

753
void MavsdkImpl::unsubscribe_on_new_system(Mavsdk::NewSystemHandle handle)
34✔
754
{
755
    _new_system_callbacks.unsubscribe(handle);
34✔
756
}
34✔
757

758
bool MavsdkImpl::is_any_system_connected() const
34✔
759
{
760
    std::vector<std::shared_ptr<System>> connected_systems = systems();
68✔
761
    return std::any_of(connected_systems.cbegin(), connected_systems.cend(), [](auto& system) {
34✔
762
        return system->is_connected();
×
763
    });
34✔
764
}
765

766
void MavsdkImpl::work_thread()
4,721✔
767
{
768
    while (!_should_exit) {
4,721✔
769
        timeout_handler.run_once();
4,587✔
770
        call_every_handler.run_once();
4,667✔
771

772
        {
773
            std::lock_guard<std::mutex> lock(_server_components_mutex);
9,290✔
774
            for (auto& it : _server_components) {
9,257✔
775
                if (it.second != nullptr) {
4,594✔
776
                    it.second->_impl->do_work();
4,609✔
777
                }
778
            }
779
        }
780

781
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
4,617✔
782
    }
783
}
68✔
784

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

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

799
    } else if (callback_size == 100) {
116✔
800
        return;
×
801
    }
802

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

807
    _user_callback_queue.enqueue(user_callback);
116✔
808
}
809

810
void MavsdkImpl::process_user_callbacks_thread()
254✔
811
{
812
    while (!_should_exit) {
254✔
813
        auto callback = _user_callback_queue.dequeue();
185✔
814
        if (!callback) {
185✔
815
            continue;
69✔
816
        }
817

818
        void* cookie{nullptr};
116✔
819

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

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

849
    if (_heartbeat_send_cookie == nullptr) {
100✔
850
        call_every_handler.add(
68✔
851
            [this]() { send_heartbeat(); }, HEARTBEAT_SEND_INTERVAL_S, &_heartbeat_send_cookie);
96✔
852
    }
853
}
100✔
854

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

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

871
void MavsdkImpl::send_heartbeat()
96✔
872
{
873
    std::lock_guard<std::mutex> lock(_server_components_mutex);
192✔
874

875
    for (auto& it : _server_components) {
192✔
876
        if (it.second != nullptr) {
96✔
877
            it.second->_impl->send_heartbeat();
96✔
878
        }
879
    }
880
}
96✔
881

882
void MavsdkImpl::intercept_incoming_messages_async(std::function<bool(mavlink_message_t&)> callback)
22✔
883
{
884
    std::lock_guard<std::mutex> lock(_intercept_callback_mutex);
44✔
885
    _intercept_incoming_messages_callback = callback;
22✔
886
}
22✔
887

888
void MavsdkImpl::intercept_outgoing_messages_async(std::function<bool(mavlink_message_t&)> callback)
14✔
889
{
890
    std::lock_guard<std::mutex> lock(_intercept_callback_mutex);
28✔
891
    _intercept_outgoing_messages_callback = callback;
14✔
892
}
14✔
893

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

899
    if (meta == nullptr || !(meta->flags & MAV_MSG_ENTRY_FLAG_HAVE_TARGET_SYSTEM)) {
1,447✔
900
        return 0;
193✔
901
    }
902

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

909
    return (_MAV_PAYLOAD(&message))[meta->target_system_ofs];
1,254✔
910
}
911

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

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

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

NEW
927
    return (_MAV_PAYLOAD(&message))[meta->target_component_ofs];
×
928
}
929

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

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