一、描述
QBluetoothServer 用于通过 RFCOMM 或 L2cap 协议实现蓝牙服务。
使用时:
- listen() 开始监听传入连接。
- 等到新连接建立时发出 newConnection() 信号。
- 调用 nextPendingConnection() 来获取新连接的 QBluetoothSocket。
要使其他设备能够找用户建立的的服务:
- 为服务创建一个具有适用属性的 QBluetoothServiceInfo。
- 并使用 QBluetoothServiceInfo::registerService() 注册它。
- 调用 serverPort() 以获取服务正在使用的通道号。
在 iOS 上,不能使用此类,因为平台没有公开可能允许访问 QBluetoothServer 相关功能的 API。
二、类型成员
1、enum QBluetoothServer::Error:此枚举描述蓝牙服务错误类型。
- NoError:没有错误。
- UnknownError:发生未知错误。
- PoweredOffError:蓝牙适配器断电。
- InputOutputError:发生输入输出错误。
- ServiceAlreadyRegisteredError:服务或端口已经注册
- UnsupportedProtocolError:该平台不支持该协议。
三、成员函数
1、QBluetoothServer(QBluetoothServiceInfo::Protocol serverType, QObject *parent = nullptr)
构造一个带有 parent 和 serverType 的蓝牙服务。
2、【信号】void errorOccurred(QBluetoothServer::Error error)
发生错误时发出此信号。
3、【信号】void newConnection()
当有新连接可用时会发出此信号。
已连接的槽应调用 nextPendingConnection() 以获取 QBluetoothSocket 对象以通过连接发送和接收数据。
4、void close()
关闭并重置监听套接字。
5、QBluetoothServer::Error error()
返回最后一个错误。
6、bool hasPendingConnections()
连接是否处于挂起状态。
7、bool isListening()
是否正在侦听传入连接。
8、bool listen(const QBluetoothAddress &address = QBluetoothAddress(), quint16 port = 0)
开始监听传入连接到端口 port 上的地址 address。address 必须是本地蓝牙适配器地址,端口 port 必须大于零且尚未被另一个蓝牙服务器对象占用。使用默认参数可以使系统自动选择端口。
如果操作成功并且服务器正在侦听传入连接,则返回 true,否则返回 false。
9、QBluetoothServiceInfo listen(const QBluetoothUuid &uuid, const QString &serviceName = QString())
使用 uuid 和 serviceName 注册 SPP 服务的便捷功能。 因为这个函数已经注册了服务,所以返回的 QBluetoothServiceInfo 对象不能再改变了。要稍后关闭服务,需要在此服务对象上调用 QBluetoothServiceInfo::unregisterService() 和 close()。
如果成功则返回一个注册的 QBluetoothServiceInfo 实例,否则返回一个无效的 QBluetoothServiceInfo。
10、int maxPendingConnections() / void setMaxPendingConnections(int numConnections)
返回最大挂起连接数。
11、QBluetoothSocket * nextPendingConnection()
返回指向下一个挂起连接的 QBluetoothSocket 的指针。删除指针是调用者的责任。
12、QBluetooth::SecurityFlags securityFlags()
返回蓝牙安全标志。
enum class QBluetooth::Security:此枚举描述了蓝牙服务的安全要求。
- QBluetooth::Security::NoSecurity:服务不需要任何安全性。
- QBluetooth::Security::Authorization:服务需要用户授权,除非设备是授权配对的。
- QBluetooth::Security::Authentication:服务需要身份验证。设备必须配对,除非设备是授权配对的,否则会提示用户连接。
- QBluetooth::Security::Encryption:服务要求对通信链路进行加密。这需要对设备进行配对。
- QBluetooth::Security::Secure:服务要求通信链路是安全的。需要从蓝牙 2.1 或更高版本进行简单配对。
void setSecurityFlags(QBluetooth::SecurityFlags security)
设置蓝牙安全标志。此函数必须在调用 listen() 之前调用。
在 macOS 上,不支持安全标志并将被忽略。
13、QBluetoothAddress serverAddress()
返回服务地址。
14、quint16 serverPort()
返回服务器口号。
15、QBluetoothServiceInfo::Protocol serverType()
返回 QBluetoothServer 的类型。
enum QBluetoothServiceInfo::Protocol:此枚举描述了服务使用的套接字协议。
- UnknownProtocol:使用未知的套接字协议。
- L2capProtocol:使用 L2CAP 套接字协议。
- RfcommProtocol:使用 RFCOMM 套接字协议。