12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- #ifndef Mqtt_H
- #define Mqtt_H
- #pragma once
- // #include "qmqtt.h"
- #include <qmqtt_client.h>
- #include <QObject>
- #include <functional>
- //回调函数,注意:为了防止复制(深拷贝),多处使用了右值引用&&
- // typedef void (mqttCallbackFn)(QString &&topic, QByteArray &&payload);
- using MQTTCallbackFn = std::function<void(const QString& topic, const QByteArray&payload)>;
- //调用例子
- //void subCbFunc(QString &&topic, QByteArray &&payload)
- //{
- // qDebug()<< "sub cb func" << topic << payload;
- //}
- //mqtt->subscribe(topic, subCbFunc);
- class MQTTClient : public QObject
- {
- Q_OBJECT
- public:
- explicit MQTTClient(QObject *parent = 0);
- ~MQTTClient();
- //void regCallback(mqttCallbackFn *func); //通配符订阅公共回调
- void subscribe(const QString& topic, MQTTCallbackFn&func); //单一主题分开回调,通配符为公共回调
- void publish(const QString &topic, const QByteArray &payload); //发布主题
- void connect2Host(const QString& host, const uint16_t port, const QString& usr, const QString& passwd, const QString& clientID);
- public slots:
- void onReceived(const QMQTT::Message& message); //收到数据后发送到回调
- private:
- QMQTT::Client *mqtt;
- // QString host = "192.168.9.6";
- // quint16 port = 1883;
- // QString userName = "admin";
- // QString password = "N6pNXbZjspDRqNGnxMmc";
- MQTTCallbackFn shareCbFunc; //共享回调
- QHash<QString, MQTTCallbackFn> hCbFuncs; //独立回调集
- };
- #endif // Mqtt_H
|