1. 程式人生 > 實用技巧 >qt 低功耗(BLE)藍芽demo外圍裝置程式碼示例Periphral

qt 低功耗(BLE)藍芽demo外圍裝置程式碼示例Periphral

qt藍芽網上找到的大部分是central的程式碼,我這裡分享一個外圍的程式碼驅動(之前發過一版,有bug)

bledevicetool.h

#ifndef BLEDEVICETOOL_H
#define BLEDEVICETOOL_H

#include <QObject>

#include<QBluetoothDeviceDiscoveryAgent>
#include<QBluetoothDeviceInfo>
#include<QBluetoothUuid>
#include<QBluetoothServiceInfo>

#include
<QLowEnergyController> #include<QLowEnergyService> #include<QLowEnergyDescriptor> #include <QLowEnergyServiceData> #include <QLowEnergyCharacteristicData> //廣播要用的兩個類 #include <QLowEnergyAdvertisingParameters> #include <QLowEnergyDescriptorData> #include <QLowEnergyAdvertisingData> class
BleDeviceTool : public QObject { Q_OBJECT public: explicit BleDeviceTool(QObject *parent = nullptr); void send(QString &msg); signals: void sigStatueChanged(QString msg = ""); //private slots: // void on_pushButton_clicked(); // void on_pushButton_2_clicked(); // void on_pushButton_3_clicked();
// void on_pushButton_4_clicked(); // void on_pushButton_5_clicked(); // void on_pushButton_7_clicked(); // void on_pushButton_6_clicked(); // void on_pushButton_8_clicked(); private: QLowEnergyController *m_controlerPeripheral; //單個藍芽裝置控制器 QLowEnergyService *m_service; //服務物件例項 QLowEnergyCharacteristicData *character;//全域性物件 QLowEnergyCharacteristic sendInfoLoad; QLowEnergyAdvertisingData advertisingData; QLowEnergyServiceData service; }; #endif // BLEDEVICETOOL_H

bledevicetool.cpp

#include "bledevicetool.h"

#include <QDebug>


#include <QtBluetooth/qlowenergyadvertisingdata.h>
#include <QtBluetooth/qlowenergyadvertisingparameters.h>
#include <QtBluetooth/qlowenergycharacteristic.h>
#include <QtBluetooth/qlowenergycharacteristicdata.h>
#include <QtBluetooth/qlowenergydescriptordata.h>
#include <QtBluetooth/qlowenergycontroller.h>
#include <QtBluetooth/qlowenergyservice.h>
#include <QtBluetooth/qlowenergyservicedata.h>
#include <QtCore/qbytearray.h>
#ifndef Q_OS_ANDROID
#include <QtCore/qcoreapplication.h>
#else
#include <QtGui/qguiapplication.h>
#endif
#include <QtCore/qlist.h>
#include <QtCore/qloggingcategory.h>
#include <QtCore/qscopedpointer.h>
#include <QtCore/qtimer.h>


BleDeviceTool::BleDeviceTool(QObject *parent) : QObject(parent)
{
    m_controlerPeripheral = QLowEnergyController::createPeripheral(this);





    character = new QLowEnergyCharacteristicData();
    character->setUuid(QBluetoothUuid(quint16(0xFF10)));
    character->setValue(QString("Peripheral chat test\n").toUtf8());
    //這個character設定為可讀可寫
    //character->setProperties(QLowEnergyCharacteristic::PropertyType::Read|QLowEnergyCharacteristic::PropertyType::Write|QLowEnergyCharacteristic::Notify);
    character->setProperties(QLowEnergyCharacteristic::Notify);


    QLowEnergyDescriptorData clientConfig;
    clientConfig.setUuid(QBluetoothUuid::ClientCharacteristicConfiguration);
    character->addDescriptor(clientConfig);

    service.setUuid(QBluetoothUuid(quint16(0xFF00)));
    //設定為這個模式不新增其他的service
    service.setType(QLowEnergyServiceData::ServiceType::ServiceTypePrimary);
    service.addCharacteristic(*character);
    m_service = m_controlerPeripheral->addService(service);
    //m_service->setProperty()

    //傳送訊息的載體
    sendInfoLoad = m_service->characteristic(QBluetoothUuid(quint16(0xFF10)));

    connect(m_service,&QLowEnergyService::characteristicChanged,this,[this](const QLowEnergyCharacteristic &c,const QByteArray &value){
        //sendInfoLoad = info;

        qDebug() << "Peripheral characteristicChanged::" <<c.uuid();
        qDebug() << "Peripheral value length::" << value.length();
        qDebug() << "Peripheral value length::" << value;
        //ui->dataShow->insertPlainText("\ncharacteristicChanged->"+QString(value));

        //QLowEnergyService *s = m_controlerPeripheral->createServiceObject(QBluetoothUuid(quint16(0xFF00)));
        //QLowEnergyCharacteristic characteristic = s->characteristic(QBluetoothUuid(quint16(0xFF10)));
        //Q_ASSERT(characteristic.isValid());
        //s->writeCharacteristic(characteristic,QString(value).toLatin1(),QLowEnergyService::WriteWithoutResponse);

        //m_service->writeCharacteristic(c,QString("\ncharacteristicChanged Peripheral receiveed: "+QString(value)).toUtf8());
        //qDebug()<<"properties"<<m_service->error()<<endl;

    });

    connect(m_service,&QLowEnergyService::characteristicWritten, this,
            [this](QLowEnergyCharacteristic c,QByteArray value) {
            qDebug() << "Peripheral characteristicWritten::";
        //m_service->writeCharacteristic(c,QString("\ncharacteristicWritten Peripheral receiveed: "+QString(value)).toUtf8());
    });

    connect(m_service,&QLowEnergyService::characteristicRead, this,
            [this](QLowEnergyCharacteristic c,QByteArray value) {
        //sendInfoLoad = c;
        qDebug() << "Peripheral characteristicRead::" <<c.uuid();
    });

    connect(m_controlerPeripheral,&QLowEnergyController::stateChanged,this,[this](){
         //sendInfoLoad = m_controlerPeripheral->
        qDebug()<<"QLowEnergyController::stateChanged------------------------------------"<<endl;
        //ui->dataShow->insertPlainText(QString("QLowEnergyController::stateChanged"));
         //on_pushButton_clicked();
    });

    connect(m_controlerPeripheral,&QLowEnergyController::connectionUpdated,this,[this](){
         //sendInfoLoad = m_controlerPeripheral->
        qDebug()<<"QLowEnergyController::connectionUpdated------------------------------------"<<endl;
        //ui->dataShow->insertPlainText(QString("QLowEnergyController::connectionUpdated"));
         //on_pushButton_clicked();
    });

//    connect(m_controlerPeripheral,&QLowEnergyController::,this,[this](){
//         //sendInfoLoad = m_controlerPeripheral->
//        qDebug()<<"QLowEnergyController::connectionUpdated------------------------------------"<<endl;
//        ui->dataShow->insertPlainText(QString("QLowEnergyController::connectionUpdated"));
//         //on_pushButton_clicked();
//    });

    connect(m_controlerPeripheral,&QLowEnergyController::disconnected,this,[this](){
         //sendInfoLoad = m_controlerPeripheral->
        qDebug()<<"QLowEnergyController::disconnected------------------------------------"<<endl;
        emit sigStatueChanged("Controller::disconnected");
        //ui->dataShow->insertPlainText(QString("\nQLowEnergyController::disconnected"));
         //on_pushButton_clicked();
    });

    connect(m_controlerPeripheral,&QLowEnergyController::connected,this,[this](){
         //sendInfoLoad = m_controlerPeripheral->
        qDebug()<<"QLowEnergyController::connected------------------------------------"<<endl;
        emit sigStatueChanged("Controller::connected");
        //ui->dataShow->insertPlainText(QString("\nQLowEnergyController::connected___"));
         //on_pushButton_clicked();
    });

    //嘗試開啟廣播

    advertisingData.setDiscoverability(QLowEnergyAdvertisingData::DiscoverabilityGeneral);
    advertisingData.setIncludePowerLevel(true);
    advertisingData.setLocalName("BLEPeriphralServer");
    advertisingData.setServices(QList<QBluetoothUuid>() << QBluetoothUuid::HeartRate);

    m_controlerPeripheral->startAdvertising(QLowEnergyAdvertisingParameters(), advertisingData,
                                   advertisingData);

    /////////////////////////////////////////////////////////////////
}

void BleDeviceTool::send(QString &msg)
{
    qDebug()<<"interface,,,,,send:"+msg<<endl;

    int packSize = 100;
    int lenStr = msg.length();
    if(lenStr<=packSize){
        qDebug()<<"interface,,,,,send package =: "<<0<<"--------------------->"<<msg<<endl;
        //QLowEnergyService *s = m_controlerPeripheral->createServiceObject(QBluetoothUuid(quint16(0xFF00)));
        QLowEnergyCharacteristic characteristic = m_service->characteristic(QBluetoothUuid(quint16(0xFF10)));
        Q_ASSERT(characteristic.isValid());
        m_service->writeCharacteristic(characteristic,msg.toLatin1());
    }
    else{
        //計算共有多少包資料
        int packageCount = lenStr%packSize==0?lenStr/packSize:lenStr/packSize+1;
        for(int i=0;i<packageCount;i++){
            QString temstr = msg.mid(i*packSize,i==(packageCount-1)?(lenStr-i*packSize):packSize);
            qDebug()<<"interface,,,,,send package : "<<i<<"--------------------->"<<temstr<<endl;
            //QLowEnergyService *s = m_controlerPeripheral->createServiceObject(QBluetoothUuid(quint16(0xFF00)));
            QLowEnergyCharacteristic characteristic = m_service->characteristic(QBluetoothUuid(quint16(0xFF10)));
            Q_ASSERT(characteristic.isValid());
            m_service->writeCharacteristic(characteristic,temstr.toLatin1());
        }


    }

}

注意點:  

character->setProperties(QLowEnergyCharacteristic::Notify);