MQTTBase.h 3.5 KB

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