MQTTBase.h 3.6 KB

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