Skip to content

Conversation

@bastianhjaeger
Copy link
Contributor

In case one needs to broadcast and receive messages, this solution is what I came up with so far.

#include <thread>
#include <chrono>
#include <string>

#include <mav/UDPServer.h>

using namespace std::chrono;

mav::MessageSet message_set_{"mavlink/common.xml"};

void receive_thread_function(mav::MessageSet& message_set,  mav::NetworkInterface& network_interface) {
    mav::StreamParser parser(message_set, network_interface);
    while (1) {
        mav::Message message = parser.next();
        std::cout << "received " << message.name() << " (" << message.id() << ") from" << std::endl
                  << " IP " << message.source().toString() << std::endl
                  << " systemId " << (int)message.header().systemId() << std::endl
                  << " componentId " << (int)message.header().componentId() << std::endl << std::endl;
    }
}

int main() {
    const char* broadcast_ip = std::getenv("BROADCAST_IP");
    const uint16_t broadcast_port = static_cast<uint16_t>(std::stoi(std::getenv("BROADCAST_PORT")));

    const uint16_t sys_id = static_cast<uint16_t>(std::getenv("SYS_ID") ? std::stoi(std::getenv("SYS_ID")) : 1);
    const uint16_t comp_id = static_cast<uint16_t>(message_set_.e("MAV_COMP_ID_USER1"));

    const mav::Identifier identifier{sys_id, comp_id};

    struct in_addr addr{};
    if (inet_pton(AF_INET, broadcast_ip, &addr) != 1) {
        perror("inet_pton failed");
        return 1;
    }
    mav::ConnectionPartner broadcast_target(addr.s_addr, htons(broadcast_port), false);

    mav::UDPServer network_interface = mav::UDPServer(broadcast_port, broadcast_ip);
  
    std::thread receive_thread = std::thread{[&network_interface]() {
        receive_thread_function(message_set_, network_interface);
    }};

    while(1) {
        std::cout << "Send HEARTBEAT" << std::endl;
        auto message = message_set_.create("HEARTBEAT") ({});

        const int wire_length = static_cast<int>(message.finalize(0, identifier));
        network_interface.send(message.data(), wire_length, broadcast_target);

        std::this_thread::sleep_for(1000ms);
    }

    return 0;
}

Co-authored-by: Tobias Büchli <tobias@auterion.com>
Copy link
Contributor

@tobias-auterion tobias-auterion left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, thanks. Looks good to me.

@bastianhjaeger bastianhjaeger merged this pull request into main Nov 20, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants