QBluetoothSocket Class

The QBluetoothSocket class enables connection to a Bluetooth device running a bluetooth server. More...

Header: #include <QBluetoothSocket>
qmake: QT += bluetooth
Since: Qt 5.2
Inherits: QIODevice

Public Types

enum SocketError { UnknownSocketError, NoSocketError, HostNotFoundError, ServiceNotFoundError, ..., OperationError }
enum SocketState { UnconnectedState, ServiceLookupState, ConnectingState, ConnectedState, ..., ListeningState }

Public Functions

QBluetoothSocket(QBluetoothServiceInfo::Protocol socketType, QObject *parent = Q_NULLPTR)
QBluetoothSocket(QObject *parent = Q_NULLPTR)
virtual ~QBluetoothSocket()
void abort()
void connectToService(const QBluetoothServiceInfo &service, OpenMode openMode = ReadWrite)
void connectToService(const QBluetoothAddress &address, const QBluetoothUuid &uuid, OpenMode openMode = ReadWrite)
void connectToService(const QBluetoothAddress &address, quint16 port, OpenMode openMode = ReadWrite)
void disconnectFromService()
SocketError error() const
QString errorString() const
QBluetoothAddress localAddress() const
QString localName() const
quint16 localPort() const
QBluetoothAddress peerAddress() const
QString peerName() const
quint16 peerPort() const
QBluetooth::SecurityFlags preferredSecurityFlags() const
void setPreferredSecurityFlags(QBluetooth::SecurityFlags flags)
bool setSocketDescriptor(int socketDescriptor, QBluetoothServiceInfo::Protocol socketType, SocketState socketState = ConnectedState, OpenMode openMode = ReadWrite)
int socketDescriptor() const
QBluetoothServiceInfo::Protocol socketType() const
SocketState state() const

Reimplemented Public Functions

virtual qint64 bytesAvailable() const
virtual qint64 bytesToWrite() const
virtual bool canReadLine() const
virtual void close()
virtual bool isSequential() const
  • 43 public functions inherited from QIODevice
  • 31 public functions inherited from QObject

Signals

void connected()
void disconnected()
void error(QBluetoothSocket::SocketError error)
void stateChanged(QBluetoothSocket::SocketState state)

Protected Functions

void doDeviceDiscovery(const QBluetoothServiceInfo &service, OpenMode openMode)
void setSocketError(SocketError error_)
void setSocketState(SocketState state)

Reimplemented Protected Functions

virtual qint64 readData(char *data, qint64 maxSize)
virtual qint64 writeData(const char *data, qint64 maxSize)
  • 5 protected functions inherited from QIODevice
  • 9 protected functions inherited from QObject

Additional Inherited Members

  • 1 property inherited from QObject
  • 1 public slot inherited from QObject
  • 1 public variable inherited from QObject
  • 10 static public members inherited from QObject
  • 2 protected variables inherited from QObject

Detailed Description

The QBluetoothSocket class enables connection to a Bluetooth device running a bluetooth server.

QBluetoothSocket supports two socket types, L2CAP and RFCOMM.

L2CAP is a low level datagram-oriented Bluetooth socket. Android does not support L2CAP for socket connections.

RFCOMM is a reliable, stream-oriented socket. RFCOMM sockets emulate an RS-232 serial port.

To create a connection to a Bluetooth service, create a socket of the appropriate type and call connectToService() passing the Bluetooth address and port number. QBluetoothSocket will emit the connected() signal when the connection is established.

If the Protocol is not supported on a platform, calling connectToService() will emit a UnsupportedProtocolError error.

Note: QBluetoothSocket does not support synchronous read and write operations. Functions such as waitForReadyRead() and waitForBytesWritten() are not implemented. I/O operations should be performed using readyRead(), read() and write().

Member Type Documentation

enum QBluetoothSocket::SocketError

This enum describes Bluetooth socket error types.

ConstantValueDescription
QBluetoothSocket::UnknownSocketErrorQAbstractSocket::UnknownSocketErrorAn unknown error has occurred.
QBluetoothSocket::NoSocketError-2No error. Used for testing.
QBluetoothSocket::HostNotFoundErrorQAbstractSocket::HostNotFoundErrorCould not find the remote host.
QBluetoothSocket::ServiceNotFoundErrorQAbstractSocket::SocketAddressNotAvailableErrorCould not find the service UUID on remote host.
QBluetoothSocket::NetworkErrorQAbstractSocket::NetworkErrorAttempt to read or write from socket returned an error
QBluetoothSocket::UnsupportedProtocolError8The Protocol is not supported on this platform.
QBluetoothSocket::OperationErrorQAbstractSocket::OperationErrorAn operation was attempted while the socket was in a state that did not permit it.

enum QBluetoothSocket::SocketState

This enum describes the state of the Bluetooth socket.

ConstantValueDescription
QBluetoothSocket::UnconnectedStateQAbstractSocket::UnconnectedStateSocket is not connected.
QBluetoothSocket::ServiceLookupStateQAbstractSocket::HostLookupStateSocket is querying connection parameters.
QBluetoothSocket::ConnectingStateQAbstractSocket::ConnectingStateSocket is attempting to connect to a device.
QBluetoothSocket::ConnectedStateQAbstractSocket::ConnectedStateSocket is connected to a device.
QBluetoothSocket::BoundStateQAbstractSocket::BoundStateSocket is bound to a local address and port.
QBluetoothSocket::ClosingStateQAbstractSocket::ClosingStateSocket is connected and will be closed once all pending data is written to the socket.
QBluetoothSocket::ListeningStateQAbstractSocket::ListeningStateSocket is listening for incoming connections.

Member Function Documentation

QBluetoothSocket::QBluetoothSocket(QBluetoothServiceInfo::Protocol socketType, QObject *parent = Q_NULLPTR)

Constructs a Bluetooth socket of socketType type, with parent.

QBluetoothSocket::QBluetoothSocket(QObject *parent = Q_NULLPTR)

Constructs a Bluetooth socket with parent.

[virtual] QBluetoothSocket::~QBluetoothSocket()

Destroys the Bluetooth socket.

void QBluetoothSocket::abort()

Aborts the current connection and resets the socket. Unlike disconnectFromService(), this function immediately closes the socket, discarding any pending data in the write buffer.

Note: On Android, aborting the socket requires asynchronous interaction with Android threads. Therefore the associated disconnected() and stateChanged() signals are delayed until the threads have finished the closure.

See also disconnectFromService() and close().

[virtual] qint64 QBluetoothSocket::bytesAvailable() const

Reimplemented from QIODevice::bytesAvailable().

Returns the number of incoming bytes that are waiting to be read.

See also bytesToWrite() and read().

[virtual] qint64 QBluetoothSocket::bytesToWrite() const

Reimplemented from QIODevice::bytesToWrite().

Returns the number of bytes that are waiting to be written. The bytes are written when control goes back to the event loop.

[virtual] bool QBluetoothSocket::canReadLine() const

Reimplemented from QIODevice::canReadLine().

Returns true if you can read at least one line from the device

[virtual] void QBluetoothSocket::close()

Reimplemented from QIODevice::close().

Disconnects the socket's connection with the device.

Note: On Android, closing the socket requires asynchronous interaction with Android threads. Therefore the associated disconnected() and stateChanged() signals are delayed until the threads have finished the closure.

void QBluetoothSocket::connectToService(const QBluetoothServiceInfo &service, OpenMode openMode = ReadWrite)

Attempts to connect to the service described by service.

The socket is opened in the given openMode. The socketType() may change depending on the protocol required by service.

The socket first enters ConnectingState and attempts to connect to the device providing service. If a connection is established, QBluetoothSocket enters ConnectedState and emits connected().

At any point, the socket can emit error() to signal that an error occurred.

Note that most platforms require a pairing prior to connecting to the remote device. Otherwise the connection process may fail.

See also state() and disconnectFromService().

void QBluetoothSocket::connectToService(const QBluetoothAddress &address, const QBluetoothUuid &uuid, OpenMode openMode = ReadWrite)

Attempts to make a connection to the service identified by uuid on the device with address address.

The socket is opened in the given openMode.

For BlueZ, the socket first enters the ServiceLookupState and queries the connection parameters for uuid. If the service parameters are successfully retrieved the socket enters ConnectingState, and attempts to connect to address. If a connection is established, QBluetoothSocket enters Connected State and emits connected().

On Android, the service connection can directly be established using the UUID of the remote service. Therefore the platforms does not require the ServiceLookupState and socketType() is always set to QBluetoothServiceInfo::RfcommProtocol.

At any point, the socket can emit error() to signal that an error occurred.

Note that most platforms require a pairing prior to connecting to the remote device. Otherwise the connection process may fail.

See also state() and disconnectFromService().

void QBluetoothSocket::connectToService(const QBluetoothAddress &address, quint16 port, OpenMode openMode = ReadWrite)

Attempts to make a connection with address on the given port.

The socket is opened in the given openMode.

The socket first enters ConnectingState, and attempts to connect to address. If a connection is established, QBluetoothSocket enters ConnectedState and emits connected().

At any point, the socket can emit error() to signal that an error occurred.

On Android, a connection to a service can not be established using a port. Calling this function will emit a ServiceNotFoundError

Note that most platforms require a pairing prior to connecting to the remote device. Otherwise the connection process may fail.

See also state() and disconnectFromService().

[signal] void QBluetoothSocket::connected()

This signal is emitted when a connection is established.

See also QBluetoothSocket::ConnectedState and stateChanged().

void QBluetoothSocket::disconnectFromService()

Attempts to close the socket. If there is pending data waiting to be written QBluetoothSocket will enter ClosingState and wait until all data has been written. Eventually, it will enter UnconnectedState and emit the disconnected() signal.

See also connectToService().

[signal] void QBluetoothSocket::disconnected()

This signal is emitted when the socket is disconnected.

See also QBluetoothSocket::UnconnectedState and stateChanged().

[protected] void QBluetoothSocket::doDeviceDiscovery(const QBluetoothServiceInfo &service, OpenMode openMode)

Start device discovery for service and open the socket with openMode. If the socket is created with a service uuid device address, use service discovery to find the port number to connect to.

SocketError QBluetoothSocket::error() const

Returns the last error.

[signal] void QBluetoothSocket::error(QBluetoothSocket::SocketError error)

This signal is emitted when an error occurs.

Note: Signal error is overloaded in this class. To connect to this one using the function pointer syntax, you must specify the signal type in a static cast, as shown in this example:


  connect(bluetoothSocket, static_cast<void(QBluetoothSocket::*)(QBluetoothSocket::SocketError)>(&QBluetoothSocket::error),
      [=](QBluetoothSocket::SocketError error){ /* ... */ });

See also error().

QString QBluetoothSocket::errorString() const

Returns a user displayable text string for the error.

[virtual] bool QBluetoothSocket::isSequential() const

Reimplemented from QIODevice::isSequential().

QBluetoothAddress QBluetoothSocket::localAddress() const

Returns the address of the local device.

Although some platforms may differ the socket must generally be connected to guarantee the return of a valid address. In particular, this is true when dealing with platforms that support multiple local Bluetooth adapters.

QString QBluetoothSocket::localName() const

Returns the name of the local device.

Although some platforms may differ the socket must generally be connected to guarantee the return of a valid name. In particular, this is true when dealing with platforms that support multiple local Bluetooth adapters.

quint16 QBluetoothSocket::localPort() const

Returns the port number of the local socket if available, otherwise returns 0. Although some platforms may differ the socket must generally be connected to guarantee the return of a valid port number.

On Android and macOS, this feature is not supported and returns 0.

QBluetoothAddress QBluetoothSocket::peerAddress() const

Returns the address of the peer device.

QString QBluetoothSocket::peerName() const

Returns the name of the peer device.

quint16 QBluetoothSocket::peerPort() const

Return the port number of the peer socket if available, otherwise returns 0. On Android, this feature is not supported.

QBluetooth::SecurityFlags QBluetoothSocket::preferredSecurityFlags() const

Returns the security parameters used for the initial connection attempt.

The security parameters may be renegotiated between the two parties during or after the connection has been established. If such a change happens it is not reflected in the value of this flag.

On macOS, this flag is always set to QBluetooth::Secure.

This function was introduced in Qt 5.6.

See also setPreferredSecurityFlags().

[virtual protected] qint64 QBluetoothSocket::readData(char *data, qint64 maxSize)

Reimplemented from QIODevice::readData().

void QBluetoothSocket::setPreferredSecurityFlags(QBluetooth::SecurityFlags flags)

Sets the preferred security parameter for the connection attempt to flags. This value is incorporated when calling connectToService(). Therefore it is required to reconnect to change this parameter for an existing connection.

On Bluez this property is set to QBluetooth::Authorization by default.

On macOS, this value is ignored as the platform does not permit access to the security parameter of the socket. By default the platform prefers secure/encrypted connections though and therefore this function always returns QBluetooth::Secure.

Android only supports two levels of security (secure and non-secure). If this flag is set to QBluetooth::NoSecurity the socket object will not employ any authentication or encryption. Any other security flag combination will trigger a secure Bluetooth connection. This flag is set to QBluetooth::Secure by default.

Note: A secure connection requires a pairing between the two devices. On some platforms, the pairing is automatically initiated during the establishment of the connection. Other platforms require the application to manually trigger the pairing before attempting to connect.

This function was introduced in Qt 5.6.

See also preferredSecurityFlags().

bool QBluetoothSocket::setSocketDescriptor(int socketDescriptor, QBluetoothServiceInfo::Protocol socketType, SocketState socketState = ConnectedState, OpenMode openMode = ReadWrite)

Set the socket to use socketDescriptor with a type of socketType, which is in state, socketState, and mode, openMode.

Returns true on success

See also socketDescriptor().

[protected] void QBluetoothSocket::setSocketError(SocketError error_)

Sets the type of error that last occurred to error_.

[protected] void QBluetoothSocket::setSocketState(SocketState state)

Sets the socket state to state.

int QBluetoothSocket::socketDescriptor() const

Returns the platform-specific socket descriptor, if available. This function returns -1 if the descriptor is not available or an error has occurred.

See also setSocketDescriptor().

QBluetoothServiceInfo::Protocol QBluetoothSocket::socketType() const

Returns the socket type. The socket automatically adjusts to the protocol offered by the remote service.

Android only support RFCOMM based sockets.

SocketState QBluetoothSocket::state() const

Returns the current state of the socket.

[signal] void QBluetoothSocket::stateChanged(QBluetoothSocket::SocketState state)

This signal is emitted when the socket state changes to state.

See also connected(), disconnected(), state(), and QBluetoothSocket::SocketState.

[virtual protected] qint64 QBluetoothSocket::writeData(const char *data, qint64 maxSize)

Reimplemented from QIODevice::writeData().