diff --git a/src/C++/Socket/main.cpp b/src/C++/Socket/main.cpp index 1449e3a..6098121 100644 --- a/src/C++/Socket/main.cpp +++ b/src/C++/Socket/main.cpp @@ -1,53 +1,40 @@ #include -#include -#include +#include "mqtt/async_client.h" -using boost::asio::ip::tcp; +const std::string SERVER_ADDRESS("tcp://localhost:1883"); +const std::string CLIENT_ID("pi_client"); +const std::string TOPIC("button/pressed"); + +class callback : public virtual mqtt::callback +{ +public: + void message_arrived(mqtt::const_message_ptr msg) override { + std::cout << "Message arrived: " << msg->get_payload_str() << std::endl; + } +}; int main() { + mqtt::async_client client(SERVER_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 { - // Create an io_context object - boost::asio::io_context io_context; + client.connect(connOpts)->wait(); + client.subscribe(TOPIC, 1)->wait(); + } + catch (const mqtt::exception& exc) { + std::cerr << "Error: " << exc.what() << std::endl; + return 1; + } - // Resolve the server address and port - tcp::resolver resolver(io_context); - tcp::resolver::results_type endpoints = resolver.resolve("127.0.0.1", "4024"); - - // Create and connect the socket - tcp::socket socket(io_context); - boost::asio::connect(socket, endpoints); - - std::cout << "Connected to the server." << std::endl; - - // Receive initial message from the server - boost::asio::streambuf buffer; - boost::asio::read_until(socket, buffer, "\n"); - std::istream is(&buffer); - std::string initial_message; - std::getline(is, initial_message); - std::cout << "Initial message from server: " << initial_message << std::endl; - - // Send and receive messages - while (true) { - // Send a message to the server - std::string message; - std::cout << "Enter message: "; - std::getline(std::cin, message); - message += "\n"; // Add newline to mark the end of the message - boost::asio::write(socket, boost::asio::buffer(message)); - - // Receive a response from the server - boost::asio::streambuf response_buffer; - boost::asio::read_until(socket, response_buffer, "\n"); - std::istream response_stream(&response_buffer); - std::string reply; - std::getline(response_stream, reply); - std::cout << "Reply from server: " << reply << std::endl; - } - - } catch (std::exception& e) { - std::cerr << "Exception: " << e.what() << std::endl; + // Houd de verbinding actief + while (true) { + std::this_thread::sleep_for(std::chrono::seconds(1)); } return 0; -} \ No newline at end of file +}