天天看點

QT應用程式設計: 編寫HC05序列槽藍牙調試助手(Android系統APP)

一、環境介紹

QT版本: 5.12.6

編譯環境: win10 64位

目标系統: Android

完整工程源碼下載下傳位址(包含APK檔案):  

https://download.csdn.net/download/xiaolong1126626497/19051787 想學習QT的Android環境搭建看這裡(win10版本): https://blog.csdn.net/xiaolong1126626497/article/details/117254453                                                          (ubuntu版本): https://blog.csdn.net/xiaolong1126626497/article/details/117256660 想學習QT入門到精通程式設計的看這裡: https://blog.csdn.net/xiaolong1126626497/article/details/116485145

二、功能介紹

設計本軟體的目的是作為HC05/06系列藍牙序列槽的調試助手,友善嵌入式工程師、電子工程師調試藍牙序列槽子產品,HC05/06是經典的2.0序列槽藍牙子產品。

QT應用程式設計: 編寫HC05序列槽藍牙調試助手(Android系統APP)
QT應用程式設計: 編寫HC05序列槽藍牙調試助手(Android系統APP)
QT應用程式設計: 編寫HC05序列槽藍牙調試助手(Android系統APP)
三、軟體核心源碼

#include "mainwindow.h"
#include "ui_mainwindow.h"
 
 
/*
 * 設定QT界面的樣式
*/
void MainWindow::SetStyle(const QString &qssFile) {
    QFile file(qssFile);
    if (file.open(QFile::ReadOnly)) {
        QString qss = QLatin1String(file.readAll());
        qApp->setStyleSheet(qss);
        QString PaletteColor = qss.mid(20,7);
        qApp->setPalette(QPalette(QColor(PaletteColor)));
        file.close();
    }
    else
    {
        qApp->setStyleSheet("");
    }
}
 
 
static const QLatin1String serviceUuid("00001101-0000-1000-8000-00805F9B34FB");
//這個字元串裡面的内容就是序列槽模式的Uuid
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
 
    this->SetStyle(":/qss/blue.css");     //設定樣式表
    this->setWindowTitle("HC05藍牙調試助手"); //設定标題
    this->setWindowIcon(QIcon(":/wbyq.ico")); //設定圖示
 
    /*1. 執行個體化藍牙相關的對象*/
    discoveryAgent = new QBluetoothDeviceDiscoveryAgent();
    localDevice = new QBluetoothLocalDevice();
    socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
    //RfcommProtocol表示該服務使用RFCOMM套接字協定。RfcommProtocol屬于模拟RS232模式,就叫序列槽模式
 
    /*2. 關聯藍牙裝置相關的信号*/
    /*2.1 關聯發現裝置的槽函數,當掃描發現周圍的藍牙裝置時,會發出deviceDiscovered信号*/
    connect(discoveryAgent,
            SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),
            this,
            SLOT(addBlueToothDevicesToList(QBluetoothDeviceInfo))
            );
 
    //藍牙有資料可讀
    connect(socket,
            SIGNAL(readyRead()),
            this,
            SLOT(readBluetoothDataEvent())
            );
 
    //藍牙連接配接建立成功
    connect(socket,
            SIGNAL(connected()),
            this,
            SLOT(bluetoothConnectedEvent())
            );
 
    //藍牙斷開連接配接
    connect(socket,
            SIGNAL(disconnected()),
            this,
            SLOT(bluetoothDisconnectedEvent())
            );
    //藍牙連接配接錯誤
    connect(socket, static_cast<void(QBluetoothSocket::*)(QBluetoothSocket::SocketError)>(&QBluetoothSocket::error),
          [=](QBluetoothSocket::SocketError error)
    {
            ui->plainTextEdit_BluetoothInfiShow->insertPlainText(socket->errorString()); //顯示錯誤資訊
 
            if(QBluetoothSocket::UnknownSocketError ==error)
            {
               ui->plainTextEdit_BluetoothInfiShow->insertPlainText("位置錯誤\n"); //顯示錯誤資訊
            }
 
            if(QBluetoothSocket::NoSocketError ==error)
            {
                ui->plainTextEdit_BluetoothInfiShow->insertPlainText(" 沒有錯誤 用于測試\n"); //顯示錯誤資訊
            }
 
            if(QBluetoothSocket::HostNotFoundError ==error)
            {
                  ui->plainTextEdit_BluetoothInfiShow->insertPlainText("找不到遠端主機\n"); //顯示錯誤資訊
            }
 
            if(QBluetoothSocket::ServiceNotFoundError ==error)
            {
                     ui->plainTextEdit_BluetoothInfiShow->insertPlainText(" 無法在遠端主機上找到服務UUID\n"); //顯示錯誤資訊
            }
 
            if(QBluetoothSocket::NetworkError ==error)
            {
                 ui->plainTextEdit_BluetoothInfiShow->insertPlainText("嘗試從套接字讀取或寫入傳回錯誤\n"); //顯示錯誤資訊
            }
 
            if(QBluetoothSocket::UnsupportedProtocolError ==error)
            {
                 ui->plainTextEdit_BluetoothInfiShow->insertPlainText(" 該平台不支援該協定\n"); //顯示錯誤資訊
            }
 
            if(QBluetoothSocket::OperationError ==error)
            {
                 ui->plainTextEdit_BluetoothInfiShow->insertPlainText("當套接字處于不允許的狀态時嘗試進行操作\n"); //顯示錯誤資訊
            }
    });
 
    /*3. 檢查藍牙的狀态,用于設定按鈕的初始狀态*/
    /*3.1 檢查藍牙是否開啟*/
    if(localDevice->hostMode() == QBluetoothLocalDevice::HostPoweredOff)
    {
            //如果藍牙處于關閉狀态
            ui->pushButton_OpenBluetooth->setEnabled(true);   //打開按鈕
            ui->pushButton_CloseBluetooth->setEnabled(false); //關閉按鈕
            ui->pushButton_BluetoothScan->setEnabled(false);
 
    }
    else    //如果藍牙處于開啟狀态
    {
            ui->pushButton_OpenBluetooth->setEnabled(false);//打開按鈕
            ui->pushButton_CloseBluetooth->setEnabled(true);//關閉按鈕
             ui->pushButton_BluetoothScan->setEnabled(true); //設定掃描按鈕可用
    }
 
    /*3.2 設定标簽顯示本地藍牙的名稱*/
    QString name_info("本機藍牙:");
    name_info+=localDevice->name();
    ui->label_BluetoothName->setText(name_info);
 
     ui->pushButton_StopScan->setEnabled(false);      //設定停止掃描藍牙的按鈕不可用
 
     ui->plainTextEdit_BluetoothInfiShow->setEnabled(false); //設定不可編輯
}
 
 
MainWindow::~MainWindow()
{
    delete ui;
    delete discoveryAgent;
    delete localDevice;
    delete socket;
}
 
void MainWindow::on_pushButton_OpenBluetooth_clicked()
{
    /*請求打開藍牙裝置*/
    localDevice->powerOn();
    ui->pushButton_OpenBluetooth->setEnabled(false);//打開按鈕
    ui->pushButton_CloseBluetooth->setEnabled(true);//關閉按鈕
    ui->pushButton_BluetoothScan->setEnabled(true); //設定掃描按鈕可用
    ui->pushButton_StopScan->setEnabled(true);
}
 
void MainWindow::on_pushButton_CloseBluetooth_clicked()
{
    /*關閉藍牙裝置*/
    localDevice->setHostMode(QBluetoothLocalDevice::HostPoweredOff);
    ui->pushButton_OpenBluetooth->setEnabled(true);//打開按鈕
    ui->pushButton_CloseBluetooth->setEnabled(false);//關閉按鈕
    ui->pushButton_BluetoothScan->setEnabled(false); //設定掃描按鈕不可用
    ui->pushButton_StopScan->setEnabled(false);
 
}
 
 
void MainWindow::on_pushButton_BluetoothScan_clicked()
{
     /*開始掃描周圍的藍牙裝置*/
    discoveryAgent->start();
    ui->comboBox_BluetoothDevice->clear(); //清除條目
    ui->pushButton_BluetoothScan->setEnabled(false); //設定掃描按鈕不可用
    ui->pushButton_StopScan->setEnabled(true);     //設定停止掃描按鈕可用
}
 
 
void MainWindow::on_pushButton_StopScan_clicked()
{
    /*停止掃描周圍的藍牙裝置*/
    discoveryAgent->stop();
    ui->pushButton_StopScan->setEnabled(false);     //設定停止掃描按鈕不可用
    ui->pushButton_BluetoothScan->setEnabled(true); //設定掃描按鈕可用
 
}
 
 
/*當掃描到周圍的裝置時會調用目前的槽函數*/
void MainWindow::addBlueToothDevicesToList(const QBluetoothDeviceInfo &info)
{
   // QString label = QString("%1 %2").arg(info.name()).arg(info.address().toString());
    QString label = QString("%1 %2").arg(info.address().toString()).arg(info.name());
    ui->comboBox_BluetoothDevice->addItem(label); //添加字元串到comboBox上
}
 
 
//有資料可讀
void MainWindow::readBluetoothDataEvent()
{
    QByteArray all = socket->readAll();
    ui->plainTextEdit_BluetoothInfiShow->insertPlainText(QString::fromLocal8Bit(all));
}
 
 
//建立連接配接
void MainWindow::bluetoothConnectedEvent()
{
    QMessageBox::information(this,tr("連接配接提示"),"藍牙連接配接成功!");
 
    /*停止掃描周圍的藍牙裝置*/
    discoveryAgent->stop();
    ui->pushButton_StopScan->setEnabled(false);     //設定停止掃描按鈕不可用
    ui->pushButton_BluetoothScan->setEnabled(false); //設定掃描按鈕不可用
}
 
 
//斷開連接配接
void MainWindow::bluetoothDisconnectedEvent()
{
    QMessageBox::information(this,tr("連接配接提示"),"藍牙斷開連接配接!");
    ui->pushButton_BluetoothScan->setEnabled(true); //設定掃描按鈕可用
}
 
 
/*
在說藍牙裝置連接配接之前,不得不提一個非常重要的概念,就是藍牙的Uuid,引用一下百度的:
在藍牙中,每個服務和服務屬性都唯一地由"全球唯一辨別符" (UUID)來校驗。
正如它的名字所暗示的,每一個這樣的辨別符都要在時空上保證唯一。
UUID類可表現為短整形(16或32位)和長整形(128位)UUID。
他提供了分别利用String和16位或32位數值來建立類的構造函數,提供了一個可以比較兩個UUID(如果兩個都是128位)的方法,還有一個可以轉換一個UUID為一個字元串的方法。
UUID執行個體是不可改變的(immutable),隻有被UUID标示的服務可以被發現。
在Linux下你用一個指令uuidgen -t可以生成一個UUID值;
在Windows下則執行指令uuidgen 。UUID看起來就像如下的這個形式:2d266186-01fb-47c2-8d9f-10b8ec891363。當使用生成的UUID去建立一個UUID對象,你可以去掉連字元。
*/
 
//發送資料
void MainWindow::on_pushButton_SendData_clicked()
{
    QString text=ui->lineEdit_SendData->text();
    QByteArray send_data=text.toLocal8Bit();
    socket->write(send_data); //發送資料
}
 
//清空收到的資料
void MainWindow::on_pushButton_Clear_clicked()
{
    ui->plainTextEdit_BluetoothInfiShow->setPlainText("");
}
 
//連接配接藍牙
void MainWindow::on_pushButton_ConnectDev_clicked()
{
    QString text = ui->comboBox_BluetoothDevice->currentText();
    int index = text.indexOf(' ');
    if(index == -1) return;
 
    QBluetoothAddress address(text.left(index));
 
    QString connect_device="開始連接配接藍牙裝置:\n";
    connect_device+=ui->comboBox_BluetoothDevice->currentText();
    QMessageBox::information(this,tr("連接配接提示"),connect_device);
 
    //開始連接配接藍牙裝置
    socket->connectToService(address, QBluetoothUuid(serviceUuid) ,QIODevice::ReadWrite);
}
 
 
//幫助提示
void MainWindow::on_pushButton_help_clicked()
{
    QMessageBox::information(this,tr("幫助提示"),"本軟體用于HC-05/06系列序列槽藍牙調試!\n"
                                             "不支援BLE4.0版本藍牙調試!\n"
                                             "軟體作者:DS小龍哥\n"
                                             "BUG回報:[email protected]");
}
       

繼續閱讀