Qt 藍牙通訊

pro文件加上QT += bluetooth

頭文件:

#ifndef BLUETOOTHPROXY_H
#define BLUETOOTHPROXY_H

#include <QObject>

#include <QtBluetooth/qbluetoothlocaldevice.h>
#include <qbluetoothaddress.h>
#include <qbluetoothdevicediscoveryagent.h>
#include <qbluetoothlocaldevice.h>
#include <qbluetoothsocket.h>


class BluetoothProxy : public QObject
{
    Q_OBJECT
public:
    explicit BluetoothProxy(QObject *parent = nullptr);
    ~BluetoothProxy();
public slots:
    void addBlueToothDevicesToList(const QBluetoothDeviceInfo&);
    void readBluetoothDataEvent();
    void bluetoothConnectedEvent();
    void bluetoothDisconnectedEvent();
    void onError(QBluetoothSocket::SocketError error);

private:
    QBluetoothDeviceDiscoveryAgent *discoveryAgent;
    QBluetoothLocalDevice *localDevice;
    QBluetoothSocket *socket;
    QByteArray blueArray;

};

#endif // BLUETOOTHPROXY_H

源文件:

#include "bluetoothproxy.h"


//這個UUID要根據自己的使用情況來確定,我使用的是串口類的UUID,具體可https://www.jianshu.com/p/eb85cb690e86
static const QLatin1String serviceUuid("00001101-0000-1000-8000-00805F9B34FB");
BluetoothProxy::BluetoothProxy(QObject *parent) : QObject(parent)
{
    discoveryAgent = new QBluetoothDeviceDiscoveryAgent();
    localDevice = new QBluetoothLocalDevice();
    socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);

    discoveryAgent->start();

    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,SIGNAL(error(QBluetoothSocket::SocketError)),this,SLOT(onError(QBluetoothSocket::SocketError)));

}

BluetoothProxy::~BluetoothProxy()
{
    
}


void BluetoothProxy::onError(QBluetoothSocket::SocketError error)
{
    QString str;
    if(QBluetoothSocket::UnknownSocketError == error){
        str = "UnknownSocketError";
    }else if(QBluetoothSocket::NoSocketError == error){
        str = "NoSocketError";
    }else if(QBluetoothSocket::HostNotFoundError == error){
        str = "HostNotFoundError";
    }else if(QBluetoothSocket::ServiceNotFoundError == error){
        str = "ServiceNotFoundError";
    }else if(QBluetoothSocket::NetworkError == error){
        str = "NetworkError";
    }else if(QBluetoothSocket::UnsupportedProtocolError == error){
        str = "UnsupportedProtocolError";
    }else if(QBluetoothSocket::OperationError == error){
        str = "OperationError";
    }else if(QBluetoothSocket::RemoteHostClosedError == error){
        str = "RemoteHostClosedError";
    }
    qDebug()<<error;
    emit backendRunMesgPost(str);
    emit backendRunMesgPost("SocketError");
}


void BluetoothProxy::addBlueToothDevicesToList( const QBluetoothDeviceInfo &info )
{
    QString label = QString("%1 %2").arg(info.address().toString()).arg(info.name());

    qDebug()<<label;
    if(label.contains("TableSoccer")){
    //找到需要連接的藍牙名字
        int index = label.indexOf(' ');
        if(index == -1){
            qDebug()<<"index";
            return;
        }
        QBluetoothAddress address(label.left(index));
        QString name(label.mid(index + 1));
        qDebug() << "You has choice the bluetooth address is " << address<<name;
        qDebug() << "The device is connneting.... ";
        emit backendRunMesgPost("The device is connneting");
        socket->connectToService(address, QBluetoothUuid(serviceUuid) ,QIODevice::ReadWrite);
    }
}



void BluetoothProxy::readBluetoothDataEvent()
{
    QByteArray line = socket->readAll();
    if(line.size() > 4)return;
    blueArray.append(line);
    if(blueArray.size() < 4 && blueArray.size()%4 != 0)return;
    //qDebug()<<blueArray.size();
    for(int i = 0; i< blueArray.size();i++){
        if(blueArray.at(i) == 0x01 && blueArray.at(i+1) == 0x01 && blueArray.at(i+2) == 0x01 && blueArray.at(i+3) == 0x03){
            emit redTeam();
        }else if(blueArray.at(i) == 0x01 && blueArray.at(i+1) == 0x02 && blueArray.at(i+2) == 0x01 && blueArray.at(i+3) == 0x04){
            emit blueTeam();
        }/*else if(blueArray.at(i) == 3 && blueArray.at(i+1) == 4 && blueArray.at(i+2) == 5 && blueArray.at(i+3) == 0x0f){
            count = 0;
            qDebug()<<"------------------------------------------>";
        }*/
    }
    if(blueArray.size() >= 4){
        blueArray.clear();
    }
}

void BluetoothProxy::bluetoothConnectedEvent()
{
    qDebug() << "The android device has been connected successfully!";
    emit backendRunMesgPost("connected successfully");
}

void BluetoothProxy::bluetoothDisconnectedEvent()
{
    qDebug() << "The android device has been disconnected successfully!";
    emit backendRunMesgPost("disconnected");
    emit speakString("藍牙已斷開連接");
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章