This commit is contained in:
cxh 2025-06-05 09:42:09 +08:00
parent 5233c4e9af
commit 64a92ac418
3 changed files with 32 additions and 6 deletions

View File

@ -7,7 +7,10 @@ class MqttClient
{ {
public: public:
MqttClient(const std::string &configPath); MqttClient(const std::string &configPath);
bool start(); ~MqttClient();
bool start(); // 连接并订阅
void disconnect(); // 断开连接
private: private:
std::string broker; std::string broker;

View File

@ -49,6 +49,11 @@ MqttClient::MqttClient(const std::string &configPath)
} }
} }
MqttClient::~MqttClient()
{
delete client;
}
bool MqttClient::start() bool MqttClient::start()
{ {
try try
@ -65,6 +70,19 @@ bool MqttClient::start()
} }
} }
void MqttClient::disconnect()
{
try
{
std::cout << "断开 MQTT 连接..." << std::endl;
client->disconnect()->wait();
}
catch (const mqtt::exception &e)
{
std::cerr << "MQTT 断开失败: " << e.what() << std::endl;
}
}
void MqttClient::Callback::message_arrived(mqtt::const_message_ptr msg) void MqttClient::Callback::message_arrived(mqtt::const_message_ptr msg)
{ {
std::cout << "接收到消息: " << msg->to_string() << std::endl; std::cout << "接收到消息: " << msg->to_string() << std::endl;

View File

@ -88,16 +88,21 @@ int main()
std::cout << "串口号: " << port << "\n波特率: " << baudrate << std::endl; std::cout << "串口号: " << port << "\n波特率: " << baudrate << std::endl;
// ===== MQTT 测试连接 ===== // ===== MQTT 测试连接 =====
MqttClient mqtt("config.toml"); // 构造时自动读取配置并初始化 MqttClient mqtt("config.toml");
if (mqtt.connect()) if (mqtt.start())
{ {
std::cout << "MQTT 连接成功" << std::endl; std::cout << "MQTT 启动成功,等待消息..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2)); std::this_thread::sleep_for(std::chrono::seconds(5));
mqtt.disconnect(); mqtt.disconnect();
} }
else else
{ {
std::cerr << "MQTT 连接失败" << std::endl; std::cerr << "MQTT 启动失败" << std::endl;
}
while (1)
{
/* code */
} }
SerialPort serial; SerialPort serial;