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 "mqtt/async_client.h"
#include <mqtt/async_client.h>
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;
std::cout << "Abonneren op topic: " << TOPIC << std::endl;
client.subscribe(TOPIC, 1)->wait();
// Houd de verbinding actief
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
// Houd de client draaiende om berichten te blijven ontvangen
}
} catch (const mqtt::exception& exc) {
std::cerr << exc.what() << std::endl;
return 1;
}
return 0;