| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- #ifndef MQTTBase_H
- #define MQTTBase_H
- #include <QObject>
- #include <QMap>
- #include <QChar>
- #include <QTimer>
- #include "qmqtt.h"
- /**
- 使用说明:
- 1. 子类可以继承这个类,重新实现 recvMessage 函数,这个函数是接收到消息的回调函数
- 2. 使用SPDLOG日志库,不需要设置日志记录器
-
- 在C++线程池中使用注意事项:
- 1、这个库依赖的是Qt的网络库,所以需要依赖Qt的事件循环
- 2、如果线程是由C++创建的,需要将这个线程交给Qt的事件循环来管理,在线程中创建一个QEventLoop,然后执行
- exec()函数,这样才能正常接收、发送消息
- 3、线程归属权问题,QObject及子类有线程归属权问题,在哪个线程中创建的就归属于哪个线程,除非使用moveToThread()修改线程,
- 但是C++线程无法被move,所以推荐这个子线程使用一个壳函数作为线程功能函数,在线程函数中创建功能类,这样整个类的归属权都是子线程
- class A;
- void thread_task() { new A; }
- CPPTP.add_task(thread_task);
- 4、如果功能类是单例或者全局变量,无法在线程创建之后new出来,在线程中连接信号和槽的时候设置为Qt::DirectConnection,
- 这样才能在子线程中调用槽函数
- 5、MQTTBase及其子类,连接服务器的时候依赖信号和槽的返回,因此连接服务器最好在运行exec()之后进行。
- */
- class MQTTBase : public QObject
- {
- Q_OBJECT
- public:
- MQTTBase(QObject* parent = nullptr);
- /* 设置地址 */
- void setIPAndPort(const QString& IP, int port = 1883);
- /* 设置订阅 */
- void addSubcribe(const QString& topic,int qos = 0);
- /* 设置自动重连 */
- void setAutoReconnect(bool isAuto = true);
- /* 连接到服务器 */
- void connectToServer();
- /* 断开连接 */
- void disconnectFromServer() {m_client.disconnectFromHost();}
- /* 获取连接状态 */
- QMQTT::ConnectionState connectState();
- /* 发送消息 */
- bool sendMessage(const QString& topic, const QByteArray& message, int qos = 0);
- /* 发送消息,设置消息保留 */
- bool sendMessage(const QString& topic, const QByteArray& message, int qos = 0, bool retain = false);
-
-
- signals:
- /* 原地转发消息 */
- void signal_recvMessage(const QMQTT::Message& message);
- /* 断开连接的信号 */
- void signal_disconnected();
- protected:
- /* 接收到消息,子类继承这个解析消息数据 */
- virtual void recvMessage(const QMQTT::Message& message) = 0;
- protected slots:
- void do_connected(); /* 连接成功 */
- void do_disconnect(); /* 断开连接 */
- void do_error(const QMQTT::ClientError error); /* 错误 */
- void do_subscribed(const QString& topic, const quint8 qos); /* 订阅成功 */
- void do_received(const QMQTT::Message& message);/* 接收到消息,子类继承这个解析消息数据 */
- /* 超时重连 */
- void do_timeoutReconnect();
-
- protected:
- bool m_isAutoReconnect = true; /* 是否自动重连 */
- QString m_mqttIP; /* MQTT服务器IP */
- int m_mqttPort; /* MQTT服务器端口 */
- QMap<QString, int> m_mapTopic; /* 订阅的主题和QOS */
- QMQTT::Client m_client; /* MQTT客户端 */
- QTimer m_reconnectTimer; /* 重连定时器 */
- };
- #endif /* MQTTBase_H */
|