#include #include #include // For std::this_thread::sleep_for #include // For std::chrono::seconds // Define the address of the MQTT broker, the client ID, and the topic to subscribe to. const std::string ADDRESS("mqtt://localhost:1883"); // Broker address (Raspberry Pi) const std::string CLIENT_ID("raspberry_pi_client"); const std::string TOPIC("home/commands"); // Define a callback class that handles incoming messages and connection events. class callback : public virtual mqtt::callback { // Called when a message arrives on a subscribed topic. void message_arrived(mqtt::const_message_ptr msg) override { std::cout << "Received message: '" << msg->get_topic()<< "' : " << msg->to_string() << std::endl; } // Called when the connection to the broker is lost. void connection_lost(const std::string& cause) override { std::cerr << "Connection lost. Reason: " << cause << std::endl; } // Called when a message delivery is complete. void delivery_complete(mqtt::delivery_token_ptr token) override { std::cout << "Message delivered!" << std::endl; } }; int main() { // Create an MQTT async client and set up the callback class. mqtt::async_client client(ADDRESS, CLIENT_ID); callback cb; client.set_callback(cb); // Set up the connection options (such as username and password). 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); try { // Try to connect to the broker and wait until successful. std::cout << "Connecting to broker..." << std::endl; client.connect(connOpts)->wait(); // Connect with the provided options std::cout << "Connected!" << std::endl; // Subscribe to the specified topic and wait for confirmation. std::cout << "Subscribing to topic: " << TOPIC << std::endl; client.subscribe(TOPIC, 1)->wait(); // Subscribe with QoS level 1 // Keep the program running to continue receiving messages from the broker. while (true) { std::this_thread::sleep_for(std::chrono::seconds(1)); // Sleep to reduce CPU usage } } catch (const mqtt::exception &exc) { // Catch any MQTT exceptions and display the error message. std::cerr << "Error: " << exc.what() << std::endl; return 1; } return 0; // Return 0 to indicate successful execution }