如何设置Qt使用blueZ蓝牙堆栈

时间:2015-10-14 14:32:14

标签: c++ linux qt bluetooth qt-creator

我在Windows 7机器上开发,但最终产品将是linux,我也在使用Ubuntu虚拟机。

我需要搜索并连接到蓝牙设备并运行this示例但是从研究看来Qt蓝牙API并不真正支持Windows - 这没关系,我还是需要它用于Linux。蓝牙设备发现代码供参考:

void MyClass::startDeviceDiscovery()
{

    // Create a discovery agent and connect to its signals
    QBluetoothDeviceDiscoveryAgent *discoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
    connect(discoveryAgent, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),
            this, SLOT(deviceDiscovered(QBluetoothDeviceInfo)));

    // Start a discovery
    discoveryAgent->start();

    //...
}

// In your local slot, read information about the found devices
void MyClass::deviceDiscovered(const QBluetoothDeviceInfo &device)
{
    qDebug() << "Found new device:" << device.name() << '(' << device.address().toString() << ')';
}

现在我使用的是blue Qx 4.x,Qt确实支持,但我的应用程序也没有在linux中发现任何内容。我在我的虚拟机中安装了blueZ bluetooth:

  

sudo apt-get install libbluetooth-dev

但是我怎么告诉Qt / Qt-Creator使用blueZ蓝牙堆栈? Qt如何针对blueZ库构建?

更新

我差不多3年前发布了这个问题,我相信版本是Qt 5.4,但如果有人想发布解决方案,请将其发布到Qt的最新版本,这样可以让其他人受益。据我所知,我相信我发现Qt仅在Linux上支持蓝牙而不支持Windows。它在Windows上的实现只是一个存根。

1 个答案:

答案 0 :(得分:0)

发布的代码是实际使用的代码吗? (下一次提供MCVE)。您正在运行哪个版本的QT?

如果是,则问题在于discoveryAgentnull的末尾变成startDeviceDiscovery。对于编译器来说,这是合法的,但实际上这是一个逻辑错误。

可能的解决方案可能是:

  1. 实现一个包装所有设置和内容的类以执行发现
  2. discoveryAgent设为班级成员

一种更快的尝试方法是 Qt控制台应用程序

btdiscover.pro

QT -= gui
QT += bluetooth # Add it in your .pro file

CONFIG += c++11 console
CONFIG -= app_bundle

DEFINES += QT_DEPRECATED_WARNINGS

SOURCES += main.cpp

main.cpp

#include <QCoreApplication>
#include <QBluetoothServiceDiscoveryAgent>
#include <QBluetoothDeviceInfo>
#include <QDebug>
#include <QObject>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QBluetoothDeviceDiscoveryAgent *discoveryAgent = new QBluetoothDeviceDiscoveryAgent();

    // Connect the signal to a lambda function
    // The 3rd param is a dummy one, in real life application it will be an instance that point to the slot (4th param) owner
    QObject::connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, new QObject(),
            [](const QBluetoothDeviceInfo &device){
        qInfo() << QString("Device found!! Its name is %1 and its MAC is %2").arg(device.name(), device.address().toString());
    });

    // Stop after 5000 mS
    discoveryAgent->setLowEnergyDiscoveryTimeout(5000);
    // Start the discovery process
    discoveryAgent->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod);

    return a.exec();
}

就我而言,程序输出以下行:

"Device found!! Its name is IO_EXP and its MAC is 00:XX:XX:XX:XX:A1"
"Device found!! Its name is IO_EXP and its MAC is 00:XX:XX:XX:XX:57"

我使用 Qt 5.11.1

编译了代码

Here由QT提供了入门指南。

此外,如引述here所示,在Linux上,QT使用Bluez。