如何在C++中使用Qt Bluetooth创建蓝牙连接

rwqw0loc  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(153)

我写的C++应用程序的蓝牙客户端,这应该能够发现,配对和连接到另一个蓝牙设备,具有特定的MAC地址,使用蓝牙经典(不是BLE).主要问题是,如何创建连接?发现和配对过程中描述的Qt Bluetooth Overview和预期的工作:

//  To switch bluetooth on, code inside MyClass constructor
    QBluetoothLocalDevice localDevice;
    //  Check if Bluetooth is available on this device
    if (localDevice.isValid())
    {
        //  Turn Bluetooth on
        localDevice.powerOn();
        //  Other code
    }

    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();
        //  Other code
    }

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

字符串
我还检查了this answer,它包含了打开蓝牙,发现和配对的完整代码实现。然而,在配对完成后,我找不到一种方法来实现与发现和配对的蓝牙设备的连接。Qt文档中的Bluetooth Chat示例提供了此任务的某种解决方案,但其中出现了几个问题。此示例建议创建对象

RemoteSelector remoteSelector(adapter);


其中RemoteSelector是类,由Qt Mobility Components提供。该类的示例将允许创建特定的服务

QBluetoothServiceInfo service = remoteSelector.service();


然后可以使用该服务与远程设备建立连接:

client->startClient(service);


该示例还提供了一段代码

m_discoveryAgent = new QBluetoothServiceDiscoveryAgent(localAdapter);

    connect(m_discoveryAgent, &QBluetoothServiceDiscoveryAgent::serviceDiscovered,
        this, &RemoteSelector::serviceDiscovered);
    connect(m_discoveryAgent, &QBluetoothServiceDiscoveryAgent::finished,
        this, &RemoteSelector::discoveryFinished);
    connect(m_discoveryAgent, &QBluetoothServiceDiscoveryAgent::canceled,
        this, &RemoteSelector::discoveryFinished);


这与RemoteSelector类的实现内部的代码类似,但不完全相同。
因此,几个问题由此产生:
1.我是否理解正确,为了能够在Qt 6.5中实现与配对设备的蓝牙连接,有必要安装单独的组件,称为Qt Mobility Components,并从那里使用RemoteSelector类?
1.为什么聊天蓝牙示例提供了RemoteSelector类构造函数实现的部分代码,与本实现部分不同,是否需要根据提供的代码修改RemoteSelector的实现?
1.蓝牙聊天示例中描述的连接方式是否是在Qt中实现蓝牙连接的最佳方式,从良好的编码实践,编写干净的代码,良好的代码风格和组织的Angular 来看?
1.一般来说,所描述的连接方式似乎很奇怪,因为虽然Qt蓝牙提供了直接的方式来打开蓝牙,发现和配对设备,但连接过程似乎要复杂得多,它需要额外的操作和额外的组件,Qt Mobility Components。对此有什么解释吗?
请注意,我的程序中没有图形界面,也没有使用QT Creator,因为任务只是使用Qt库编写用于蓝牙连接的C++应用程序。

goucqfw6

goucqfw61#

不需要安装Qt Mobility Components。示例中使用的RemoteSelector类的实现是不同的,可以找到here我想这回答了前两个问题,希望对您有帮助。

相关问题