Qt windows 蓝牙4.0开发

小王子🤴 2020-08-23 21:54:03 11487
Qt windows 蓝牙4.0开发

本篇文章记录学习使用Qt在windows下开发蓝牙4.0的过程。

在介绍Qt windows蓝牙4.0开发之前,先说一些关于qt蓝牙在windows中的一些限制:

只可以在win10 1607版本以上使用(Qt5.14以上官方说已经可以支持win7、win8)

标准蓝牙(2.0)只有手动搜索配对后才可以使用Qt蓝牙搜索到

应用程序使用蓝牙库需要在.pro文件中添加配置“QT += bluetooth”

蓝牙搜索
//蓝牙扫描类
QBluetoothDeviceDiscoveryAgent *discoveryAgent = nullptr;
discoveryAgent = new QBluetoothDeviceDiscoveryAgent();
//设置扫描时间
discoveryAgent->setLowEnergyDiscoveryTimeout(5000);
//扫描设备信号
connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered,
this, &QBLEDeviceManagement::addBLEDevice);
//扫描错误信号
connect(discoveryAgent,QOverload<QBluetoothDeviceDiscoveryAgent::Error>::of(&QBluetoothDeviceDiscoveryAgent::error),this, &QBLEDeviceManagement::bleError);
//扫描完成
connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::finished, this, &QBLEDeviceManagement::bleDeviceScanFinished);
void QBLEDeviceManagement::startScan()
{
    if(discoveryAgent->isActive())
    {
        return;
}
//开始扫描 只扫描BLE设备
discoveryAgent->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod);
}

void QBLEDeviceManagement::addBLEDevice(const QBluetoothDeviceInfo &info)
{
//扫描到的设备,可以根据蓝牙名过滤设备
    if(!info.name().contains(QRegExp(BTNAME_MATCHING1)) &&  \
       !info.name().contains(QRegExp(BTNAME_MATCHING2)) &&  \
       !info.name().contains(QRegExp(BTNAME_MATCHING3))
{
    qDebug() << info.name();
QBluetoothDeviceInfo bleInfo = info;
}
}
连接蓝牙
//创建低功耗蓝牙控制对象
bleController = QLowEnergyController::createCentral(bleInfo);

//绑定服务扫描信号
    connect(bleController, SIGNAL(serviceDiscovered(QBluetoothUuid)),
            this, SLOT(onServiceDiscovered(QBluetoothUuid)));
//服务扫描完成信号
    connect(bleController, SIGNAL(discoveryFinished()),
            this, SLOT(onServiceScanDone()),Qt::QueuedConnection);
//低功耗蓝牙控制错误信号
    connect(bleController, SIGNAL(error(QLowEnergyController::Error)),
            this, SLOT(onControllerError(QLowEnergyController::Error)));
//蓝牙连接信号
    connect(bleController, SIGNAL(connected()),
            this, SLOT(onDeviceConnected()));
//断开连接信号
    connect(bleController, SIGNAL(disconnected()),
            this, SLOT(onDeviceDisconnected()));
//连接设备
 bleController->connectToDevice();
扫描服务
QList<QBluetoothUuid> m_servicesUuid;
m_servicesUuid.clear();
bleController->discoverServices();
QLowEnergyService* bleServer = nullptr;
//服务扫描完成
void QBLECommunication::onServiceScanDone()
{
//获取所有服务UUID
    m_servicesUuid = bleController->services();
    if(m_servicesUuid.isEmpty())
    {
    }else{
//循环所有服务
        foreach (auto i, m_servicesUuid) {
            if(i == QBluetoothUuid(QString(SERVICE_UUID)) || i == QBluetoothUuid(QString(BLE_SERVICE_UUID)))//判断是否有所连接设备的读写服务的UUID
            {
                if(bleServer)
                {
                    delete bleServer;
                    bleServer = nullptr;
                }
       //创建服务对象
                bleServer = bleController->createServiceObject(i);

                if (!bleServer) {
                    return;
                }
//服务状态
                if(bleServer->state() == QLowEnergyService::DiscoveryRequired) {

                    connect(bleServer, SIGNAL(stateChanged(QLowEnergyService::ServiceState)),
                            this, SLOT(onServiceStateChanged(QLowEnergyService::ServiceState)));
                    connect(bleServer, SIGNAL(characteristicChanged(QLowEnergyCharacteristic,QByteArray)),
                            this, SLOT(onCharacteristicChanged(QLowEnergyCharacteristic,QByteArray)));
                    connect(bleServer, SIGNAL(error(QLowEnergyService::ServiceError)),
                            this, SLOT(serviceError(QLowEnergyService::ServiceError)));
//查询服务特征值
                    bleServer->discoverDetails();
                }else
                {
                    searchCharacteristic();
                }

            }
        }

    }
}
void QBLECommunication::searchCharacteristic()
{
    if(bleServer)
    {
        bool ok = false;
//循环特征值
        foreach (QLowEnergyCharacteristic c, bleServer->characteristics())
        {
//判断特征UUID是否是写特征
            if(c.isValid() && ( c.uuid() == QBluetoothUuid(QString(UUIDSTR_ISSC_TRANS_Write)) || c.uuid() == QBluetoothUuid(QString(UUIDSTR_BLE_TRANS_Write)) ))
            {
              bleWriteCharacteristic = c;
              qDebug() << "bleWriteCharacteristic:" << bleWriteCharacteristic.isValid();
            }
//判断特征UUID是否是读特征
            if(c.isValid() && ( c.uuid() == QBluetoothUuid(QString(UUIDSTR_ISSC_TRANS_Read)) || c.uuid() == QBluetoothUuid(QString(UUIDSTR_BLE_TRANS_Read)) ))
           {

                m_notificationDesc = c.descriptor(\
                        QBluetoothUuid::ClientCharacteristicConfiguration);
                qDebug() << "m_notificationDesc:" << m_notificationDesc.isValid();
                if (m_notificationDesc.isValid()) {
                    bleServer->writeDescriptor(m_notificationDesc, QByteArray::fromHex("0100"));//使能通知
                    ok = true;
                }
            }
        }
    }
}
数据接收发送
数据发送:
通过服务将数据写到对应发特征值中
void QBLECommunication::bthWrite(const char* dat,const qint64 len)
{
    if(bleServer && bleWriteCharacteristic.isValid()){
        QByteArray sbuf(dat,static_cast<int>(len));
        bleServer->writeCharacteristic(bleWriteCharacteristic,sbuf);
        qDebug() << sbuf.toHex().data();
    }
}
数据接收:
特征值改变信号(说明有数据)
void QBLECommunication::onCharacteristicChanged(const QLowEnergyCharacteristic &c, const QByteArray &value)
{
    if(c.uuid() == QBluetoothUuid(QString(UUIDSTR_ISSC_TRANS_Read)) || c.uuid() == QBluetoothUuid(QString(UUIDSTR_BLE_TRANS_Read)))
{
qDebug() << value;
}
}
关闭蓝牙设备
void QBLECommunication::bleDisConnect()
{
    //disable notifications 禁用通知
    if (m_notificationDesc.isValid() && bleServer) {
        bleServer->writeDescriptor(m_notificationDesc, QByteArray::fromHex("0000"));
    }
//关闭设备
        bleController->disconnectFromDevice();
//删除服务对象
        if(bleServer)
        {
            delete bleServer;
            bleServer = nullptr;
        }

}
声明:本文内容由易百纳平台入驻作者撰写,文章观点仅代表作者本人,不代表易百纳立场。如有内容侵权或者其他问题,请联系本站进行删除。
红包 点赞 收藏 评论 打赏
评论
0个
内容存在敏感词
手气红包
    易百纳技术社区暂无数据
相关专栏
置顶时间设置
结束时间
删除原因
  • 广告/SPAM
  • 恶意灌水
  • 违规内容
  • 文不对题
  • 重复发帖
打赏作者
易百纳技术社区
小王子🤴
您的支持将鼓励我继续创作!
打赏金额:
¥1易百纳技术社区
¥5易百纳技术社区
¥10易百纳技术社区
¥50易百纳技术社区
¥100易百纳技术社区
支付方式:
微信支付
支付宝支付
易百纳技术社区微信支付
易百纳技术社区
打赏成功!

感谢您的打赏,如若您也想被打赏,可前往 发表专栏 哦~

举报反馈

举报类型

  • 内容涉黄/赌/毒
  • 内容侵权/抄袭
  • 政治相关
  • 涉嫌广告
  • 侮辱谩骂
  • 其他

详细说明

审核成功

发布时间设置
发布时间:
是否关联周任务-专栏模块

审核失败

失败原因
备注
拼手气红包 红包规则
祝福语
恭喜发财,大吉大利!
红包金额
红包最小金额不能低于5元
红包数量
红包数量范围10~50个
余额支付
当前余额:
可前往问答、专栏板块获取收益 去获取
取 消 确 定

小包子的红包

恭喜发财,大吉大利

已领取20/40,共1.6元 红包规则

    易百纳技术社区