From 2dadabba1868113a2adb33b54bb942a7ddacb068 Mon Sep 17 00:00:00 2001 From: "ishak jmilou.ishak" Date: Mon, 21 Oct 2024 09:56:07 +0200 Subject: [PATCH] Refactor MQTT connection and message receiving in C++ Socket code --- src/C++/Socket/main.cpp | 45 ++++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/src/C++/Socket/main.cpp b/src/C++/Socket/main.cpp index 6098121..f44e437 100644 --- a/src/C++/Socket/main.cpp +++ b/src/C++/Socket/main.cpp @@ -1,39 +1,38 @@ #include -#include "mqtt/async_client.h" +#include -const std::string SERVER_ADDRESS("tcp://localhost:1883"); -const std::string CLIENT_ID("pi_client"); -const std::string TOPIC("button/pressed"); +const std::string ADDRESS("tcp://localhost:1883"); // Brokeradres (Raspberry Pi) +const std::string CLIENT_ID("cpp_subscriber"); +const std::string TOPIC("website/knop"); -class callback : public virtual mqtt::callback -{ -public: + +class callback : public virtual mqtt::callback { void message_arrived(mqtt::const_message_ptr msg) override { - std::cout << "Message arrived: " << msg->get_payload_str() << std::endl; + std::cout << "Ontvangen bericht: '" << msg->get_topic() << "' : " << msg->to_string() << std::endl; + // Doe iets met het bericht, bijvoorbeeld een GPIO-activering } }; int main() { - mqtt::async_client client(SERVER_ADDRESS, CLIENT_ID); + + mqtt::async_client client(ADDRESS, CLIENT_ID); callback cb; client.set_callback(cb); - mqtt::connect_options connOpts; - connOpts.set_keep_alive_interval(20); - connOpts.set_clean_session(true); - try { - client.connect(connOpts)->wait(); - client.subscribe(TOPIC, 1)->wait(); - } - catch (const mqtt::exception& exc) { - std::cerr << "Error: " << exc.what() << std::endl; - return 1; - } + std::cout << "Verbinden met broker..." << std::endl; + client.connect()->wait(); + std::cout << "Verbonden!" << std::endl; - // Houd de verbinding actief - while (true) { - std::this_thread::sleep_for(std::chrono::seconds(1)); + std::cout << "Abonneren op topic: " << TOPIC << std::endl; + client.subscribe(TOPIC, 1)->wait(); + + while (true) { + // Houd de client draaiende om berichten te blijven ontvangen + } + } catch (const mqtt::exception& exc) { + std::cerr << exc.what() << std::endl; + return 1; } return 0;