QBluetoothServer Class
A classe QBluetoothServer utiliza o protocolo RFCOMM ou L2cap para se comunicar com um dispositivo Bluetooth. Saiba mais...
| Cabeçalho: | #include <QBluetoothServer> |
| CMake: | find_package(Qt6 REQUIRED COMPONENTS Bluetooth) target_link_libraries(mytarget PRIVATE Qt6::Bluetooth) |
| qmake: | QT += bluetooth |
| Herdado de: | QObject |
Tipos públicos
| enum | Error { NoError, UnknownError, PoweredOffError, InputOutputError, ServiceAlreadyRegisteredError, …, MissingPermissionsError } |
Funções públicas
| QBluetoothServer(QBluetoothServiceInfo::Protocol serverType, QObject *parent = nullptr) | |
| virtual | ~QBluetoothServer() |
| void | close() |
| QBluetoothServer::Error | error() const |
| bool | hasPendingConnections() const |
| bool | isListening() const |
| bool | listen(const QBluetoothAddress &address = QBluetoothAddress(), quint16 port = 0) |
| QBluetoothServiceInfo | listen(const QBluetoothUuid &uuid, const QString &serviceName = QString()) |
| int | maxPendingConnections() const |
| QBluetoothSocket * | nextPendingConnection() |
| QBluetooth::SecurityFlags | securityFlags() const |
| QBluetoothAddress | serverAddress() const |
| quint16 | serverPort() const |
| QBluetoothServiceInfo::Protocol | serverType() const |
| void | setMaxPendingConnections(int numConnections) |
| void | setSecurityFlags(QBluetooth::SecurityFlags security) |
Sinais
(since 6.2) void | errorOccurred(QBluetoothServer::Error error) |
| void | newConnection() |
Descrição detalhada
O QBluetoothServer é usado para implementar serviços Bluetooth via RFCOMM ou L2cap.
Comece a escutar conexões de entrada com ` listen()`. Aguarde até que o sinal ` newConnection()` seja emitido quando uma nova conexão for estabelecida e chame ` nextPendingConnection()` para obter um ` QBluetoothSocket ` para a nova conexão.
Para permitir que outros dispositivos encontrem seu serviço, crie um QBluetoothServiceInfo com os atributos aplicáveis ao seu serviço e registre-o usando QBluetoothServiceInfo::registerService(). Chame serverPort() para obter o número do canal que está sendo usado.
Se o QBluetoothServiceInfo::Protocol não for compatível com uma plataforma, listen() retornará false. O Android e o WinRT, por exemplo, suportam apenas RFCOMM.
No iOS, essa classe não pode ser utilizada porque a plataforma não expõe uma API que permita o acesso a recursos relacionados ao QBluetoothServer.
Veja também QBluetoothServiceInfo e QBluetoothSocket.
Documentação sobre tipos de membros
enum QBluetoothServer::Error
Esta enumeração descreve os tipos de erros do servidor Bluetooth.
| Constante | Valor | Descrição |
|---|---|---|
QBluetoothServer::NoError | 0 | Sem erro. |
QBluetoothServer::UnknownError | 1 | Ocorreu um erro desconhecido. |
QBluetoothServer::PoweredOffError | 2 | O adaptador Bluetooth está desligado. |
QBluetoothServer::InputOutputError | 3 | Ocorreu um erro de entrada/saída. |
QBluetoothServer::ServiceAlreadyRegisteredError | 4 | O serviço ou a porta já estava registrado |
QBluetoothServer::UnsupportedProtocolError | 5 | O “ Protocol ” não é compatível com esta plataforma. |
QBluetoothServer::MissingPermissionsError (since Qt 6.4) | 6 | O sistema operacional solicita permissões que não foram concedidas pelo usuário. |
Documentação da função de membro
[explicit] QBluetoothServer::QBluetoothServer(QBluetoothServiceInfo::Protocol serverType, QObject *parent = nullptr)
Cria um servidor Bluetooth com parent e serverType.
[virtual noexcept] QBluetoothServer::~QBluetoothServer()
Encerra o servidor Bluetooth.
void QBluetoothServer::close()
Fech QBluetoothSocket e reinicia o soquete de escuta. Qualquer conexão já estabelecida continua em funcionamento e deve ser closed ada separadamente.
QBluetoothServer::Error QBluetoothServer::error() const
Retorna o último erro do ` QBluetoothServer`.
[signal, since 6.2] void QBluetoothServer::errorOccurred(QBluetoothServer::Error error)
Esse sinal é emitido quando ocorre um erro de " error ".
Essa função foi introduzida no Qt 6.2.
Veja também error() e QBluetoothServer::Error.
bool QBluetoothServer::hasPendingConnections() const
Retorna `true` se houver uma conexão pendente; caso contrário, retorna `false`.
bool QBluetoothServer::isListening() const
Retorna “true” se o servidor estiver à espera de conexões de entrada; caso contrário, retorna “false”.
bool QBluetoothServer::listen(const QBluetoothAddress &address = QBluetoothAddress(), quint16 port = 0)
Comece a escutar conexões de entrada para address no endereço port. address deve ser o endereço de um adaptador Bluetooth local e port deve ser maior que zero e não estar já ocupado por outro objeto servidor Bluetooth. Recomenda-se evitar definir um número de porta para permitir que o sistema escolha automaticamente uma porta.
Retorna ` true ` se a operação for bem-sucedida e o servidor estiver à escuta de conexões de entrada; caso contrário, retorna ` false`.
Se o objeto servidor já estiver à escuta de conexões de entrada, esta função sempre retorna ` false`. A função ` close()` deve ser chamada antes de chamar esta função.
Veja também isListening() e newConnection().
QBluetoothServiceInfo QBluetoothServer::listen(const QBluetoothUuid &uuid, const QString &serviceName = QString())
Função de conveniência para registrar um serviço SPP com uuid e serviceName. Como essa função já registra o serviço, o objeto QBluetoothServiceInfo retornado não pode mais ser alterado. Para desligar o servidor posteriormente, é necessário chamar QBluetoothServiceInfo::unregisterService() e close() nesse objeto de servidor.
Retorna uma instância registrada de ` QBluetoothServiceInfo ` em caso de sucesso; caso contrário, retorna um ` QBluetoothServiceInfo` inválido. Esta função sempre pressupõe que o adaptador Bluetooth padrão deve ser utilizado.
Se o objeto servidor já estiver à escuta de conexões de entrada, esta função retorna um QBluetoothServiceInfo inválido.
Para um servidor RFCOMM, esta função é equivalente ao trecho de código a seguir.
QBluetoothServiceInfo serviceInfo;
serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceName, serviceName);
QBluetoothServiceInfo::Sequence browseSequence;
browseSequence << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::ServiceClassUuid::PublicBrowseGroup));
serviceInfo.setAttribute(QBluetoothServiceInfo::BrowseGroupList,
browseSequence);
QBluetoothServiceInfo::Sequence profileSequence;
QBluetoothServiceInfo::Sequence classId;
classId << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::ServiceClassUuid::SerialPort));
classId << QVariant::fromValue(quint16(0x100));
profileSequence.append(QVariant::fromValue(classId));
serviceInfo.setAttribute(QBluetoothServiceInfo::BluetoothProfileDescriptorList,
profileSequence);
classId.clear();
//Android requires custom uuid to be set as service class
classId << QVariant::fromValue(uuid);
classId << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::ServiceClassUuid::SerialPort));
serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceClassIds, classId);
serviceInfo.setServiceUuid(uuid);
QBluetoothServiceInfo::Sequence protocolDescriptorList;
QBluetoothServiceInfo::Sequence protocol;
protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::ProtocolUuid::L2cap));
if (d->serverType == QBluetoothServiceInfo::L2capProtocol)
protocol << QVariant::fromValue(serverPort());
protocolDescriptorList.append(QVariant::fromValue(protocol));
protocol.clear();
protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::ProtocolUuid::Rfcomm))
<< QVariant::fromValue(quint8(serverPort()));
protocolDescriptorList.append(QVariant::fromValue(protocol));
serviceInfo.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList,
protocolDescriptorList);
bool result = serviceInfo.registerService();Veja também isListening(), newConnection() e listen().
int QBluetoothServer::maxPendingConnections() const
Retorna o número máximo de conexões pendentes.
Veja também setMaxPendingConnections().
[signal] void QBluetoothServer::newConnection()
Esse sinal é emitido quando uma nova conexão fica disponível.
O slot conectado deve chamar nextPendingConnection() para obter um objeto QBluetoothSocket, a fim de enviar e receber dados pela conexão.
Veja também nextPendingConnection() e hasPendingConnections().
QBluetoothSocket *QBluetoothServer::nextPendingConnection()
Retorna um ponteiro para o objeto ` QBluetoothSocket ` da próxima conexão pendente. É de responsabilidade do chamador excluir o ponteiro.
QBluetooth::SecurityFlags QBluetoothServer::securityFlags() const
Retorna os sinalizadores de segurança do Bluetooth.
Veja também ` setSecurityFlags()`.
QBluetoothAddress QBluetoothServer::serverAddress() const
Retorna o endereço do servidor.
quint16 QBluetoothServer::serverPort() const
Retorna o número da porta do servidor.
QBluetoothServiceInfo::Protocol QBluetoothServer::serverType() const
Retorna o tipo da ` QBluetoothServer`.
void QBluetoothServer::setMaxPendingConnections(int numConnections)
Define o número máximo de conexões pendentes em numConnections. Se o número de soquetes pendentes exceder esse limite, novos soquetes serão rejeitados.
Veja também maxPendingConnections().
void QBluetoothServer::setSecurityFlags(QBluetooth::SecurityFlags security)
Define os sinalizadores de segurança do Bluetooth como ` security`. Essa função deve ser chamada antes de chamar ` listen()`. A conexão Bluetooth estará sempre criptografada ao usar dispositivos Bluetooth 2.1, pois a criptografia é obrigatória.
No backend BlueZ do Linux, os sinalizadores são mapeados para os níveis de segurança do kernel:
- QBluetooth::Security::Authorization mapeia para
BT_SECURITY_LOW; - QBluetooth::Security::Encryption corresponde a
BT_SECURITY_MEDIUM; - QBluetooth::Security::Secure corresponde a
BT_SECURITY_HIGH; - QBluetooth::Security::Authentication não é usado pelo kernel e é ignorado.
O valor padrão é ` QBluetooth::Security::Authorization`.
O Android suporta apenas dois níveis de segurança (seguro e não seguro). Se esse sinalizador for definido como ` QBluetooth::Security::NoSecurity `, o objeto servidor não utilizará nenhuma autenticação ou criptografia. Qualquer outra combinação de sinalizadores de segurança acionará uma conexão Bluetooth segura.
No macOS e no Windows, os sinalizadores de segurança não são suportados e serão ignorados.
Veja também ` securityFlags()`.
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.