Integrate Paho MQTT C library into project. Updated CMakeLists.txt to find PahoMqttC package and added fallback for manual linking. Refactored mqtt.hpp and mqtt.cpp to utilize Paho MQTT C API, replacing previous async client implementation. Added Windows setup guide for MQTT library installation.

This commit is contained in:
2025-09-08 19:53:39 +08:00
parent c655cd8c91
commit 7a9a31afd4
4 changed files with 254 additions and 156 deletions

View File

@@ -9,7 +9,7 @@
#include <mutex>
#include <condition_variable>
#include <nlohmann/json.hpp>
#include <mqtt/async_client.h>
#include <MQTTClient.h> // Paho MQTT C library
namespace custom {
@@ -39,34 +39,22 @@ public:
void stopMessageProcessor();
private:
class Callback : public virtual mqtt::callback,
public virtual mqtt::iaction_listener {
public:
Callback(MqttClient* client) : client_(client) {}
void connected(const std::string& cause) override;
void connection_lost(const std::string& cause) override;
void message_arrived(mqtt::const_message_ptr msg) override;
void delivery_complete(mqtt::delivery_token_ptr token) override;
void on_failure(const mqtt::token& tok) override;
void on_success(const mqtt::token& tok) override;
private:
MqttClient* client_;
};
struct QueuedMessage {
std::string topic;
std::string payload;
};
// C callback functions (static)
static int messageArrivedCallback(void* context, char* topicName, int topicLen, MQTTClient_message* message);
static void connectionLostCallback(void* context, char* cause);
static void deliveryCompleteCallback(void* context, MQTTClient_deliveryToken dt);
void processMessageQueue();
void handleConnectionLost();
void handleConnectionEstablished();
void reconnectWorker();
std::unique_ptr<mqtt::async_client> client_;
std::unique_ptr<Callback> callback_;
MQTTClient client_;
MessageCallback messageCallback_;
ConnectionCallback connectionCallback_;
@@ -82,8 +70,7 @@ private:
std::atomic<bool> processorRunning_;
// Connection parameters
std::string broker_;
int port_;
std::string serverURI_;
std::string clientId_;
std::string username_;
std::string password_;
@@ -92,6 +79,9 @@ private:
std::thread reconnectThread_;
std::atomic<bool> shouldReconnect_;
int reconnectDelay_ = 5; // seconds
// Connection options
MQTTClient_connectOptions connOpts_;
};
} // namespace custom