测试环境:
mqtt_client(Publish) QT 5.6.0 win10
mqtt_client(Subscribe) ubuntu 12.04
mqtt_broker mosquitto ubuntu 12.0.4
开发QT程序使用了QMQTT library 下载地址
效果:
QT Client代码:
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "qmqtt.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QMQTT::Client *_client;
private slots:
void onConnect();
void onDisconnect();
void ledonSlot();
void ledoffSlot();
void adjustLightNess();
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->luxHorizontalSlider->setMinimum(0);
ui->luxHorizontalSlider->setMaximum(100);
_client = new QMQTT::Client();
QObject::connect(ui->connectBtn,SIGNAL(clicked(bool)),this,SLOT(onConnect()));
QObject::connect(ui->disconnectBtn,SIGNAL(clicked(bool)),this,SLOT(onDisconnect()));
QObject::connect(ui->ledOnBtn,SIGNAL(clicked(bool)),this,SLOT(ledonSlot()));
QObject::connect(ui->ledOffBtn,SIGNAL(clicked(bool)),this,SLOT(ledoffSlot()));
QObject::connect(ui->luxHorizontalSlider,SIGNAL(valueChanged(int)),this,SLOT(adjustLightNess()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::onConnect()
{
QHostAddress host("127.0.0.1");
quint16 port = 1883;
_client->setHost(host);
_client->setPort(port);
_client->setClientId("client_id_1");
_client->setUsername("sagarfan");
_client->setPassword("password");
_client->connectToHost();
if(_client->isConnectedToHost())
{
ui->statusTextEdit->setText("connected");
}
}
void MainWindow::onDisconnect()
{
if(_client->isConnectedToHost())
{
_client->disconnectFromHost();
ui->statusTextEdit->setText("disconnected");
}
}
void MainWindow::ledonSlot()
{
QString payload = "{\"cmd\":1}";
qDebug() << payload;
QMQTT::Message msg(0,"cmd",payload.toLatin1());
if(_client->isConnectedToHost())
{
_client->publish(msg);
}
else
{
qDebug() << "not connected";
}
}
void MainWindow::ledoffSlot()
{
QString payload("{\"cmd\":0}");
qDebug() << payload;
QMQTT::Message msg(0,"cmd",payload.toLatin1());
if(_client->isConnectedToHost())
{
_client->publish(msg);
}
else
{
qDebug() << "not connected";
}
}
void MainWindow::adjustLightNess()
{
QString tmp = "\"lux\":";
QString postfix;
postfix = QString::number(ui->luxHorizontalSlider->value());
qDebug() << ui->luxHorizontalSlider->value();
tmp += postfix;
tmp += "}";
QString prefix("{\"cmd\":3,");
QString payload(prefix+tmp);
qDebug() << payload;
QMQTT::Message msg(0,"cmd",payload.toLatin1());
if(_client->isConnectedToHost())
{
_client->publish(msg);
}
else
{
qDebug() << "not connected";
}
}
main.cpp
#include <QApplication>
#include "mainwindow.h"
#include "qmqtt.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
时间: 2024-11-08 20:42:06