标签:
#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
#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";
}
}
#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();
}
标签:
原文地址:http://blog.csdn.net/lifan1314521/article/details/51353518