123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170 |
- #include "widget.h"
- #include "./ui_widget.h"
- #include <QNetworkReply>
- #include <QNetworkAccessManager>
- #include <QNetworkRequest>
- #include <QTimer>
- #include <QNetworkProxy>
- #include <QJsonDocument>
- #include <QJsonParseError>
- #include "spdlog/spdlog.h"
- Widget::Widget(QWidget *parent)
- : QWidget(parent)
- , ui(new Ui::Widget)
- {
- ui->setupUi(this);
- SPDLOG_INFO("***** Qt Library *****");
-
- QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy);
- m_client = new QMQTT::Client;
- QHostAddress addr("192.1.2.61");
- m_client->setHost(addr);
- m_client->setPort(1883);
- m_client->setClientId("qt_client");
- m_client->setKeepAlive(60);
- m_client->setWillQos(0);
- connect(m_client,SIGNAL(received(const QMQTT::Message)),this,SLOT(do_receiveFromMqtt(const QMQTT::Message)));
- connect(m_client,&QMQTT::Client::connected,this,[&](){
- SPDLOG_INFO("连接成功!");
-
- m_client->subscribe(ui->lineEdit_subscribe->text());
- });
- connect(m_client,&QMQTT::Client::error,this,[&](const QMQTT::ClientError error){
- SPDLOG_ERROR("MQTT Error: {}", (int)error);
- });
- connect(m_client,&QMQTT::Client::subscribed,this,[&](const QString& topic, const quint8 qos){
- SPDLOG_INFO("Subscribed to: {}", topic.toStdString());
- });
-
- auto timer = new QTimer(this);
- timer->setTimerType(Qt::PreciseTimer);
- connect(timer,&QTimer::timeout,this,[&](){
- SPDLOG_INFO("Publishing to MQTT broker");
- m_client->publish(QMQTT::Message(0,"test/one","Hello from Qt"));
- });
-
- ui->lineEdit_IP->setText("192.1.2.61");
- ui->lineEdit_subscribe->setText("LH_ENERGY_FILE/ME24052101-hzlh-com");
- }
- Widget::~Widget()
- {
- delete m_client;
- delete ui;
- }
- void Widget::do_receiveFromMqtt(const QMQTT::Message& msg)
- {
- SPDLOG_INFO("Received: {}", msg.payload().toStdString());
- QJsonParseError error;
- QJsonDocument doc = QJsonDocument::fromJson(msg.payload(),&error);
-
-
-
-
- SPDLOG_INFO("JSON : {}", doc.toJson().toStdString());
- SPDLOG_INFO("原始数据 : {}", msg.payload().toHex().toStdString());
- }
- void Widget::on_pBtn_connectMQTT_clicked()
- {
- SPDLOG_INFO("点击了“连接按钮”");
- m_client->setHost(QHostAddress(ui->lineEdit_IP->text()));
- m_client->connectToHost();
- }
- void Widget::on_pBtn_publishMSG_clicked()
- {
- SPDLOG_INFO("点击了“发布按钮”");
- m_client->publish(QMQTT::Message(0,"test/one","Hello from Qt"));
- }
-
-
-
|