mirror of
https://gitlab.fdmci.hva.nl/technische-informatica-sm3/ti-projectten/rooziinuubii79.git
synced 2025-08-04 04:14:58 +00:00
57 lines
1.7 KiB
C++
57 lines
1.7 KiB
C++
#include <iostream>
|
|
#include <mqtt/async_client.h>
|
|
#include <thread> // Voor std::this_thread::sleep_for
|
|
#include <chrono> // Voor std::chrono::seconds
|
|
|
|
const std::string ADDRESS("mqtt://ishakpi.ddns.net:1883"); // Aanpassen indien nodig
|
|
const std::string CLIENT_ID("raspberry_pi_client");
|
|
const std::string TOPIC("home/commands");
|
|
|
|
class callback : public virtual mqtt::callback {
|
|
void message_arrived(mqtt::const_message_ptr msg) override {
|
|
std::cout << "Ontvangen bericht: '" << msg->get_topic()
|
|
<< "' : " << msg->to_string() << std::endl;
|
|
// Doe iets met het bericht, bijvoorbeeld een GP.IO-activering
|
|
}
|
|
|
|
void connection_lost(const std::string& cause) override {
|
|
std::cerr << "Verbinding verloren. Oorzaak: " << cause << std::endl;
|
|
}
|
|
|
|
void delivery_complete(mqtt::delivery_token_ptr token) override {
|
|
std::cout << "Bericht afgeleverd!" << std::endl;
|
|
}
|
|
};
|
|
|
|
int main() {
|
|
mqtt::async_client client(ADDRESS, CLIENT_ID);
|
|
callback cb;
|
|
client.set_callback(cb);
|
|
|
|
mqtt::connect_options connOpts;
|
|
connOpts.set_clean_session(true);
|
|
connOpts.set_user_name("ishak");
|
|
connOpts.set_password("kobuki");
|
|
connOpts.set_mqtt_version(MQTTVERSION_3_1_1); // Voor MQTT 3.1.1
|
|
|
|
try {
|
|
std::cout << "Verbinden met broker..." << std::endl;
|
|
client.connect(connOpts)->wait();
|
|
std::cout << "Verbonden!" << std::endl;
|
|
|
|
std::cout << "Abonneren op topic: " << TOPIC << std::endl;
|
|
client.subscribe(TOPIC, 1)->wait();
|
|
|
|
// Houd de client draaiende om berichten te blijven ontvangen
|
|
while (true) {
|
|
std::this_thread::sleep_for(std::chrono::seconds(1)); // Wacht om CPU-gebruik te verminderen
|
|
}
|
|
|
|
} catch (const mqtt::exception &exc) {
|
|
std::cerr << "Fout: " << exc.what() << std::endl;
|
|
return 1;
|
|
}
|
|
|
|
return 0;
|
|
}
|