#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QBluetoothDeviceDiscoveryAgent *discoveryAgent;
discoveryAgent = new QBluetoothDeviceDiscoveryAgent;
connect(discoveryAgent, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)), this, SLOT(discoverBlueTooth(QBluetoothDeviceInfo)));
connect(discoveryAgent, SIGNAL(finished()), this, SLOT(discoveryFinished()));
discoveryAgent->start();
}
void MainWindow::discoveryFinished()
{
qDebug()<<"discoveryFinished";
static QString serviceUuid("00001101-0000-1000-8000-00805F9B34FB");
socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
socket->connectToService(QBluetoothAddress(BTaddress), QBluetoothUuid(serviceUuid),QIODevice::ReadWrite);
connect(socket,SIGNAL(readyRead()), this, SLOT(readBluetoothDataEvent()));
connect(socket,SIGNAL(connected()), this, SLOT(bluetoothConnectedEvent()));
}
void MainWindow::discoverBlueTooth(QBluetoothDeviceInfo info)
{
QString label = QString("%1 %2").arg(info.address().toString()).arg(info.name());
if(info.name()=="HC-06")
{
BTaddress = info.address().toString();
}
qDebug()<<label;
}
void MainWindow::readBluetoothDataEvent()
{
char data[100];
qint64 len = socket->read((char *)data, 100);
QByteArray qa2((char*)data,len);
QString qstr(qa2.toHex());//
qDebug()<<"----"<<qstr.toUpper();
}
void MainWindow::bluetoothConnectedEvent()
{
qDebug()<<"bluetoothConnectedEvent";
bluetoothDataSend("hellow bluetooth");
}
void MainWindow::bluetoothDataSend(QString str)
{
QByteArray arrayData;
arrayData = str.toUtf8();
socket->write(arrayData);
}
MainWindow::~MainWindow()
{
delete ui;
}