初始化:
void Widget::init()
{
discoveryAgent = new QBluetoothDeviceDiscoveryAgent();
localDevice = new QBluetoothLocalDevice();
socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
}
绑定信号 :
void Widget::setConnect()
{
connect(discoveryAgent,
SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),
this,
SLOT(addBlueToothDevicesToList(QBluetoothDeviceInfo))
);
connect(ui->list,
SIGNAL(itemClicked(QListWidgetItem*)),
this,
SLOT(itemActivated(QListWidgetItem*))
);
connect(socket,
SIGNAL(readyRead()),
this,
SLOT(readBluetoothDataEvent())
);
connect(socket,
SIGNAL(connected()),
this,
SLOT(bluetoothConnectedEvent())
);
connect(socket, QOverload<QBluetoothSocket::SocketError>::of(&QBluetoothSocket::error),
[=](QBluetoothSocket::SocketError error){ qDebug() << "134error" << error ; });
connect(socket,
SIGNAL(disconnected()),
this,
SLOT(bluetoothDisconnectedEvent())
);
扫描蓝牙:
void Widget::on_pushButton_scan_clicked()
{
discoveryAgent->start();
ui->pushButton_scan->setEnabled(false);
}
打开蓝牙:
void Widget::on_pushButton_openBluetooth_clicked()
{
localDevice->powerOn();
ui->pushButton_closeDevice->setEnabled(true);
ui->pushButton_openBluetooth->setEnabled(false);
ui->pushButton_scan->setEnabled(true);
}
关闭蓝牙:
void Widget::on_pushButton_closeDevice_clicked()
{
localDevice->setHostMode(QBluetoothLocalDevice::HostPoweredOff);
ui->pushButton_closeDevice->setEnabled(false);
ui->pushButton_openBluetooth->setEnabled(true);
ui->pushButton_scan->setEnabled(false);
}
连接蓝牙 : address 为 蓝牙的 mac 地址 字符串
socket->connectToService(address, QBluetoothUuid(serviceUuid),QIODevice::ReadWrite);
serviceUuid 为 串口 Uuid
static const QLatin1String serviceUuid("00001101-0000-1000-8000-00805F9B34FB");
发送数据:
void Widget::sendMsg(const QString & str)
{
QByteArray arrayData;
arrayData = str.toUtf8();
socket->write(arrayData);
}
接收数据:
void Widget::readBluetoothDataEvent()
{
QByteArray line = socket->readAll();
qDebug() << "aaaaaa";
QString comStr = QString::fromStdString(line.toStdString());
ui->textBrowser_info->append(comStr);
}
}