MQTTClient.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #ifndef Mqtt_H
  2. #define Mqtt_H
  3. #pragma once
  4. // #include "qmqtt.h"
  5. #include <qmqtt_client.h>
  6. #include <QObject>
  7. #include <functional>
  8. //回调函数,注意:为了防止复制(深拷贝),多处使用了右值引用&&
  9. // typedef void (mqttCallbackFn)(QString &&topic, QByteArray &&payload);
  10. using MQTTCallbackFn = std::function<void(const QString& topic, const QByteArray&payload)>;
  11. //调用例子
  12. //void subCbFunc(QString &&topic, QByteArray &&payload)
  13. //{
  14. // qDebug()<< "sub cb func" << topic << payload;
  15. //}
  16. //mqtt->subscribe(topic, subCbFunc);
  17. class MQTTClient : public QObject
  18. {
  19. Q_OBJECT
  20. public:
  21. explicit MQTTClient(QObject *parent = 0);
  22. ~MQTTClient();
  23. //void regCallback(mqttCallbackFn *func); //通配符订阅公共回调
  24. void subscribe(const QString& topic, MQTTCallbackFn&func); //单一主题分开回调,通配符为公共回调
  25. void publish(const QString &topic, const QByteArray &payload); //发布主题
  26. void connect2Host(const QString& host, const uint16_t port, const QString& usr, const QString& passwd, const QString& clientID);
  27. public slots:
  28. void onReceived(const QMQTT::Message& message); //收到数据后发送到回调
  29. private:
  30. QMQTT::Client *mqtt;
  31. const QString host = "192.168.9.6";
  32. const quint16 port = 1883;
  33. const QString userName = "admin";
  34. const QString password = "N6pNXbZjspDRqNGnxMmc";
  35. MQTTCallbackFn shareCbFunc; //共享回调
  36. QHash<QString, MQTTCallbackFn> hCbFuncs; //独立回调集
  37. };
  38. #endif // Mqtt_H