Refactor MQTT connection and message receiving in C++ Socket code

This commit is contained in:
ishak jmilou.ishak
2024-10-21 09:56:07 +02:00
parent 9aec5eaaa4
commit 2dadabba18

View File

@@ -1,39 +1,38 @@
#include <iostream> #include <iostream>
#include "mqtt/async_client.h" #include <mqtt/async_client.h>
const std::string SERVER_ADDRESS("tcp://localhost:1883"); const std::string ADDRESS("tcp://localhost:1883"); // Brokeradres (Raspberry Pi)
const std::string CLIENT_ID("pi_client"); const std::string CLIENT_ID("cpp_subscriber");
const std::string TOPIC("button/pressed"); const std::string TOPIC("website/knop");
class callback : public virtual mqtt::callback
{ class callback : public virtual mqtt::callback {
public:
void message_arrived(mqtt::const_message_ptr msg) override { 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() { int main() {
mqtt::async_client client(SERVER_ADDRESS, CLIENT_ID);
mqtt::async_client client(ADDRESS, CLIENT_ID);
callback cb; callback cb;
client.set_callback(cb); client.set_callback(cb);
mqtt::connect_options connOpts;
connOpts.set_keep_alive_interval(20);
connOpts.set_clean_session(true);
try { try {
client.connect(connOpts)->wait(); std::cout << "Verbinden met broker..." << std::endl;
client.subscribe(TOPIC, 1)->wait(); client.connect()->wait();
} std::cout << "Verbonden!" << std::endl;
catch (const mqtt::exception& exc) {
std::cerr << "Error: " << exc.what() << std::endl;
return 1;
}
// Houd de verbinding actief std::cout << "Abonneren op topic: " << TOPIC << std::endl;
while (true) { client.subscribe(TOPIC, 1)->wait();
std::this_thread::sleep_for(std::chrono::seconds(1));
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; return 0;