2025-06-05 09:24:58 +08:00
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
|
|
|
|
#include <string>
|
|
|
|
|
|
#include <mqtt/async_client.h>
|
2025-06-05 10:08:38 +08:00
|
|
|
|
#include <chrono>
|
|
|
|
|
|
#include <mutex>
|
2025-06-05 09:24:58 +08:00
|
|
|
|
|
|
|
|
|
|
class MqttClient
|
|
|
|
|
|
{
|
|
|
|
|
|
public:
|
|
|
|
|
|
MqttClient(const std::string &configPath);
|
2025-06-05 09:42:09 +08:00
|
|
|
|
~MqttClient();
|
|
|
|
|
|
|
|
|
|
|
|
bool start(); // 连接并订阅
|
|
|
|
|
|
void disconnect(); // 断开连接
|
2025-06-05 09:24:58 +08:00
|
|
|
|
|
2025-06-05 10:08:38 +08:00
|
|
|
|
// 让外部可以访问最新的 gear 和 speed
|
2025-06-05 10:15:00 +08:00
|
|
|
|
int getGear();
|
|
|
|
|
|
double getSpeed();
|
2025-06-05 10:08:38 +08:00
|
|
|
|
void checkTimeout(std::chrono::seconds timeout);
|
|
|
|
|
|
|
2025-06-05 09:24:58 +08:00
|
|
|
|
private:
|
|
|
|
|
|
std::string broker;
|
|
|
|
|
|
std::string clientId;
|
|
|
|
|
|
std::string username;
|
|
|
|
|
|
std::string password;
|
|
|
|
|
|
std::string topic;
|
|
|
|
|
|
int qos;
|
|
|
|
|
|
|
2025-06-05 10:08:38 +08:00
|
|
|
|
// 让回调持有指向MqttClient的指针,方便修改成员变量
|
2025-06-05 09:24:58 +08:00
|
|
|
|
class Callback : public virtual mqtt::callback
|
|
|
|
|
|
{
|
|
|
|
|
|
public:
|
2025-06-05 10:08:38 +08:00
|
|
|
|
explicit Callback(MqttClient *parent) : parent(parent) {}
|
2025-06-05 09:24:58 +08:00
|
|
|
|
void message_arrived(mqtt::const_message_ptr msg) override;
|
2025-06-05 10:08:38 +08:00
|
|
|
|
|
|
|
|
|
|
private:
|
|
|
|
|
|
MqttClient *parent;
|
2025-06-05 09:24:58 +08:00
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
mqtt::async_client *client = nullptr;
|
|
|
|
|
|
mqtt::connect_options connOpts;
|
2025-06-05 10:08:38 +08:00
|
|
|
|
Callback callback{this}; // 初始化时传入 this 指针
|
|
|
|
|
|
|
|
|
|
|
|
// 存储解析结果
|
|
|
|
|
|
int gear = 0;
|
|
|
|
|
|
double speed = 0.0;
|
|
|
|
|
|
std::chrono::steady_clock::time_point lastMessageTime = std::chrono::steady_clock::now();
|
|
|
|
|
|
std::mutex dataMutex;
|
2025-06-05 09:24:58 +08:00
|
|
|
|
};
|