Bluetooth QML Ping Pong example

The Bluetooth QML Ping Pong example presents the socket communication between two Bluetooth devices. The basic concept is the ping pong game where two players communicate via sockets.

Image non disponible

Running the Example

To run the example from Qt Creator, open the Welcome mode and select the example from Examples. For more information, visit Building and Running an Example.

At the beginning, the user selects the role. One device acts as a server and the second one as a client. After selecting the role, adjustments to the screen size are done (two devices might have different screen sizes). The server side starts a service named "PingPong server".

 
Sélectionnez
m_serverInfo = new QBluetoothServer(QBluetoothServiceInfo::RfcommProtocol, this);
connect(m_serverInfo, &QBluetoothServer::newConnection,
        this, &PingPong::clientConnected);
connect(m_serverInfo, QOverload<QBluetoothServer::Error>::of(&QBluetoothServer::error),
        this, &PingPong::serverError);
const QBluetoothUuid uuid(serviceUuid);

m_serverInfo->listen(uuid, QStringLiteral("PingPong server"));

On the client side, the full service discovery on the nearby Bluetooth devices is done.

 
Sélectionnez
discoveryAgent = new QBluetoothServiceDiscoveryAgent(QBluetoothAddress());

connect(discoveryAgent, &QBluetoothServiceDiscoveryAgent::serviceDiscovered,
        this, &PingPong::addService);
connect(discoveryAgent, &QBluetoothServiceDiscoveryAgent::finished,
        this, &PingPong::done);
connect(discoveryAgent, QOverload<QBluetoothServiceDiscoveryAgent::Error>::of(&QBluetoothServiceDiscoveryAgent::error),
        this, &PingPong::serviceScanError);
#ifdef Q_OS_ANDROID //see QTBUG-61392
if (QtAndroid::androidSdkVersion() >= 23)
    discoveryAgent->setUuidFilter(QBluetoothUuid(androidUuid));
else
    discoveryAgent->setUuidFilter(QBluetoothUuid(serviceUuid));
#else
discoveryAgent->setUuidFilter(QBluetoothUuid(serviceUuid));
#endif
discoveryAgent->start(QBluetoothServiceDiscoveryAgent::FullDiscovery);

When the ping pong service is discovered, the client connects to the server using the socket.

 
Sélectionnez
socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
socket->connectToService(service);

connect(socket, &QBluetoothSocket::readyRead, this, &PingPong::readSocket);
connect(socket, &QBluetoothSocket::connected, this, &PingPong::serverConnected);
connect(socket, &QBluetoothSocket::disconnected, this, &PingPong::serverDisconnected);

On the server side, the connected signal is emitted initiating that the client is connected. The necessary signals and slots on the server side are connected.

 
Sélectionnez
if (!m_serverInfo->hasPendingConnections()) {
    setMessage("FAIL: expected pending server connection");
    return;
}
socket = m_serverInfo->nextPendingConnection();
if (!socket)
    return;
socket->setParent(this);
connect(socket, &QBluetoothSocket::readyRead,
        this, &PingPong::readSocket);
connect(socket,