void ppsSendOpp(const char *msg, const QByteArray &url, const QBluetoothAddress &address, QObject *sender)
{
    pps_encoder_t *encoder = beginCtrlMessage(msg, sender);

    pps_encoder_start_object(encoder, "dat");
    pps_encoder_add_string(encoder, "address", address.toString().toUtf8().constData());
    pps_encoder_start_array(encoder, "urls");
    pps_encoder_add_string(encoder, 0, url.constData());
    pps_encoder_end_array(encoder);
    pps_encoder_end_object(encoder);

    endCtrlMessage(encoder);
}
Exemple #2
0
void ChatServer::startServer(const QBluetoothAddress& localAdapter)
{
    if (rfcommServer)
        return;

    rfcommServer = new QBluetoothServer(QBluetoothServiceInfo::RfcommProtocol, this);
    connect(rfcommServer, SIGNAL(newConnection()), this, SLOT(clientConnected()));
    bool result = rfcommServer->listen(localAdapter);
    if (!result) {
        qWarning() << "Cannot bind chat server to" << localAdapter.toString();
        return;
    }

    //serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceRecordHandle, (uint)0x00010010);

    QBluetoothServiceInfo::Sequence classId;

    classId << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::SerialPort));
    serviceInfo.setAttribute(QBluetoothServiceInfo::BluetoothProfileDescriptorList,
                             classId);

    classId.prepend(QVariant::fromValue(QBluetoothUuid(serviceUuid)));

    serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceClassIds, classId);
    serviceInfo.setAttribute(QBluetoothServiceInfo::BluetoothProfileDescriptorList,classId);

    serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceName, tr("Bt Chat Server"));
    serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceDescription,
                             tr("Example bluetooth chat server"));
    serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceProvider, tr("qt-project.org"));

    serviceInfo.setServiceUuid(QBluetoothUuid(serviceUuid));

    QBluetoothServiceInfo::Sequence publicBrowse;
    publicBrowse << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::PublicBrowseGroup));
    serviceInfo.setAttribute(QBluetoothServiceInfo::BrowseGroupList,
                             publicBrowse);

    QBluetoothServiceInfo::Sequence protocolDescriptorList;
    QBluetoothServiceInfo::Sequence protocol;
    protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::L2cap));
    protocolDescriptorList.append(QVariant::fromValue(protocol));
    protocol.clear();
    protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::Rfcomm))
             << QVariant::fromValue(quint8(rfcommServer->serverPort()));
    protocolDescriptorList.append(QVariant::fromValue(protocol));
    serviceInfo.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList,
                             protocolDescriptorList);

    serviceInfo.registerService(localAdapter);
}
bool RemoteDeviceData::updateLabel(QBluetoothRemoteDeviceSelector::DisplayFlags flags)
{
    QString newLabel;
    if (flags & QBluetoothRemoteDeviceSelector::Alias && !m_alias.isEmpty())
        newLabel = m_alias;
    else if (flags & QBluetoothRemoteDeviceSelector::Name && !m_name.isEmpty() && m_canDisplayName)
        newLabel = m_name;
    else
        newLabel = m_address.toString();

    if (newLabel != m_label) {
        m_label = newLabel;
        return true;
    }
    return false;
}
Exemple #4
0
void DeviceDiscoveryDialog::pairingDone(const QBluetoothAddress &address, QBluetoothLocalDevice::Pairing pairing)
{
    QList<QListWidgetItem *> items = ui->list->findItems(address.toString(), Qt::MatchContains);

    if (pairing == QBluetoothLocalDevice::Paired || pairing == QBluetoothLocalDevice::AuthorizedPaired ) {
        for (int var = 0; var < items.count(); ++var) {
            QListWidgetItem *item = items.at(var);
            item->setTextColor(QColor(Qt::green));
        }
    } else {
        for (int var = 0; var < items.count(); ++var) {
            QListWidgetItem *item = items.at(var);
            item->setTextColor(QColor(Qt::red));
        }
    }
}
QBluetoothLocalDevice::Pairing QBluetoothLocalDevice::pairingStatus(
    const QBluetoothAddress &address) const
{
    if (!isValid())
        return Unpaired;
    bool paired = false;
    bool btle = false; // Bluetooth Low Energy devices
    QByteArray qnxPath("/pps/services/bluetooth/remote_devices/");
    qnxPath.append(address.toString().toUtf8());
    int m_rdfd;
    if ((m_rdfd = qt_safe_open(qnxPath.constData(), O_RDONLY)) == -1) {
        btle = true;
        qnxPath.append("-00");
        if ((m_rdfd = qt_safe_open(qnxPath.constData(), O_RDONLY)) == -1) {
            qnxPath.replace((qnxPath.length()-3), 3, "-01");
            if ((m_rdfd = qt_safe_open(qnxPath.constData(), O_RDONLY)) == -1)
                return Unpaired;
        }
    }

    pps_decoder_t ppsDecoder;
    pps_decoder_initialize(&ppsDecoder, NULL);

    QBluetoothAddress deviceAddr;
    QString deviceName;

    if (!ppsReadRemoteDevice(m_rdfd, &ppsDecoder, &deviceAddr, &deviceName))
        return Unpaired;
    bool known = false;
    // Paired BTLE devices have only known field set to true.
    if (btle)
        pps_decoder_get_bool(&ppsDecoder, "known", &known);
    pps_decoder_get_bool(&ppsDecoder, "paired", &paired);
    pps_decoder_cleanup(&ppsDecoder);

    if (paired)
        return Paired;
    else if (btle && known)
        return Paired;
    else
        return Unpaired;
}
void QBluetoothLocalDevicePrivate::controlEvent(ppsResult result)
{
    qCDebug(QT_BT_QNX) << Q_FUNC_INFO << "Control Event" << result.msg;
    if (result.msg == QStringLiteral("access_changed")) {
        if (__newHostMode == -1 && result.dat.size() > 1
            && result.dat.first() == QStringLiteral("level")) {
            QBluetoothLocalDevice::HostMode newHostMode = hostMode();
            qCDebug(QT_BT_QNX) << "New Host mode" << newHostMode;
            connectedDevices();
            emit q_ptr->hostModeStateChanged(newHostMode);
        }
    } else if (result.msg == QStringLiteral("pairing_complete")) {
        qCDebug(QT_BT_QNX) << "pairing completed";
        if (result.dat.contains(QStringLiteral("addr"))) {
            const QBluetoothAddress address = QBluetoothAddress(
                result.dat.at(result.dat.indexOf(QStringLiteral("addr")) + 1));

            QBluetoothLocalDevice::Pairing pairingStatus = QBluetoothLocalDevice::Paired;

            if (result.dat.contains(QStringLiteral("trusted"))
                && result.dat.at(result.dat.indexOf(QStringLiteral("trusted")) + 1)
                == QStringLiteral("true")) {
                pairingStatus = QBluetoothLocalDevice::AuthorizedPaired;
            }
            qCDebug(QT_BT_QNX) << "pairing completed" << address.toString();
            emit q_ptr->pairingFinished(address, pairingStatus);
        }
    } else if (result.msg == QStringLiteral("device_deleted")) {
        qCDebug(QT_BT_QNX) << "device deleted";
        if (result.dat.contains(QStringLiteral("addr"))) {
            const QBluetoothAddress address = QBluetoothAddress(
                result.dat.at(result.dat.indexOf(QStringLiteral("addr")) + 1));
            emit q_ptr->pairingFinished(address, QBluetoothLocalDevice::Unpaired);
        }
    } else if (result.msg == QStringLiteral("radio_shutdown")) {
        qCDebug(QT_BT_QNX) << "radio shutdown";
        emit q_ptr->hostModeStateChanged(QBluetoothLocalDevice::HostPoweredOff);
    }
}
void QBluetoothSocketPrivate::connectToService(const QBluetoothAddress &address, QBluetoothUuid uuid, QIODevice::OpenMode openMode)
{
    Q_UNUSED(openMode);
    qBBBluetoothDebug() << "Connecting socket";
    if (isServerSocket) {
        m_peerAddress = address;
        m_uuid = uuid;
        return;
    }

    if (state != QBluetoothSocket::UnconnectedState) {
        qBBBluetoothDebug() << "Socket already connected";
        return;
    }
    state = QBluetoothSocket::ConnectingState;

    m_uuid = uuid;
    m_peerAddress = address;

    ppsSendControlMessage("connect_service", 0x1101, uuid, address.toString(), this, BT_SPP_CLIENT_SUBTYPE);
    ppsRegisterForEvent(QStringLiteral("service_connected"),this);
    ppsRegisterForEvent(QStringLiteral("get_mount_point_path"),this);
    socketType = QBluetoothSocket::RfcommSocket;
}
Exemple #8
0
void BtLocalDevice::disconnected(const QBluetoothAddress &addr)
{
    qDebug() << "Newly disconnected device" << addr.toString();
}
Exemple #9
0
void BtLocalDevice::pairingFinished(const QBluetoothAddress &address, QBluetoothLocalDevice::Pairing pairing)
{
    qDebug() << "(Un)Pairing finished" << address.toString() << pairing;
}
void QBluetoothSocketPrivate::connectToServiceConc(const QBluetoothAddress &address,
                                                   const QBluetoothUuid &uuid, QIODevice::OpenMode openMode, int fallbackServiceChannel)
{
    Q_Q(QBluetoothSocket);
    Q_UNUSED(openMode);

    qCDebug(QT_BT_ANDROID) << "connectToServiceConc()" << address.toString() << uuid.toString();

    if (!adapter.isValid()) {
        qCWarning(QT_BT_ANDROID) << "Device does not support Bluetooth";
        errorString = QBluetoothSocket::tr("Device does not support Bluetooth");
        q->setSocketError(QBluetoothSocket::NetworkError);
        q->setSocketState(QBluetoothSocket::UnconnectedState);
        return;
    }

    const int state = adapter.callMethod<jint>("getState");
    if (state != 12 ) { //BluetoothAdapter.STATE_ON
        qCWarning(QT_BT_ANDROID) << "Bt device offline";
        errorString = QBluetoothSocket::tr("Device is powered off");
        q->setSocketError(QBluetoothSocket::NetworkError);
        q->setSocketState(QBluetoothSocket::UnconnectedState);
        return;
    }

    QAndroidJniEnvironment env;
    QAndroidJniObject inputString = QAndroidJniObject::fromString(address.toString());
    remoteDevice = adapter.callObjectMethod("getRemoteDevice",
                                            "(Ljava/lang/String;)Landroid/bluetooth/BluetoothDevice;",
                                            inputString.object<jstring>());
    if (env->ExceptionCheck()) {
        env->ExceptionDescribe();
        env->ExceptionClear();

        errorString = QBluetoothSocket::tr("Cannot access address %1", "%1 = Bt address e.g. 11:22:33:44:55:66").arg(address.toString());
        q->setSocketError(QBluetoothSocket::HostNotFoundError);
        q->setSocketState(QBluetoothSocket::UnconnectedState);
        return;
    }

    //cut leading { and trailing } {xxx-xxx}
    QString tempUuid = uuid.toString();
    tempUuid.chop(1); //remove trailing '}'
    tempUuid.remove(0, 1); //remove first '{'

    inputString = QAndroidJniObject::fromString(tempUuid);
    QAndroidJniObject uuidObject = QAndroidJniObject::callStaticObjectMethod("java/util/UUID", "fromString",
                                                                       "(Ljava/lang/String;)Ljava/util/UUID;",
                                                                       inputString.object<jstring>());

    socketObject = remoteDevice.callObjectMethod("createRfcommSocketToServiceRecord",
                                                 "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothSocket;",
                                                 uuidObject.object<jobject>());

    if (env->ExceptionCheck()) {
        env->ExceptionDescribe();
        env->ExceptionClear();

        socketObject = remoteDevice = QAndroidJniObject();
        errorString = QBluetoothSocket::tr("Cannot connect to %1 on %2",
                                           "%1 = uuid, %2 = Bt address").arg(uuid.toString()).arg(address.toString());
        q->setSocketError(QBluetoothSocket::ServiceNotFoundError);
        q->setSocketState(QBluetoothSocket::UnconnectedState);
        return;
    }

    socketObject.callMethod<void>("connect");
    if (env->ExceptionCheck()) {
        env->ExceptionDescribe();
        env->ExceptionClear();

        bool success = fallBackConnect(uuidObject, fallbackServiceChannel);
        if (!success) {
            errorString = QBluetoothSocket::tr("Connection to service failed");
            socketObject = remoteDevice = QAndroidJniObject();
            q->setSocketError(QBluetoothSocket::ServiceNotFoundError);
            q->setSocketState(QBluetoothSocket::UnconnectedState);

            env->ExceptionClear(); //just in case
            return;
        }
    }

    if (inputThread) {
        inputThread->deleteLater();
        inputThread = 0;
    }

    inputStream = socketObject.callObjectMethod("getInputStream", "()Ljava/io/InputStream;");
    outputStream = socketObject.callObjectMethod("getOutputStream", "()Ljava/io/OutputStream;");

    if (env->ExceptionCheck() || !inputStream.isValid() || !outputStream.isValid()) {
        env->ExceptionDescribe();
        env->ExceptionClear();

        //close socket again
        socketObject.callMethod<void>("close");
        if (env->ExceptionCheck()) {
            env->ExceptionDescribe();
            env->ExceptionClear();
        }

        socketObject = inputStream = outputStream = remoteDevice = QAndroidJniObject();


        errorString = QBluetoothSocket::tr("Obtaining streams for service failed");
        q->setSocketError(QBluetoothSocket::NetworkError);
        q->setSocketState(QBluetoothSocket::UnconnectedState);
        return;
    }

    inputThread = new InputStreamThread(this);
    QObject::connect(inputThread, SIGNAL(dataAvailable()),
                     q, SIGNAL(readyRead()), Qt::QueuedConnection);
    QObject::connect(inputThread, SIGNAL(error(int)),
                     this, SLOT(inputThreadError(int)), Qt::QueuedConnection);

    if (!inputThread->run()) {
        //close socket again
        socketObject.callMethod<void>("close");
        if (env->ExceptionCheck()) {
            env->ExceptionDescribe();
            env->ExceptionClear();
        }

        socketObject = inputStream = outputStream = remoteDevice = QAndroidJniObject();

        delete inputThread;
        inputThread = 0;

        errorString = QBluetoothSocket::tr("Input stream thread cannot be started");
        q->setSocketError(QBluetoothSocket::NetworkError);
        q->setSocketState(QBluetoothSocket::UnconnectedState);
        return;
    }

    // only unbuffered behavior supported at this stage
    q->setOpenMode(QIODevice::ReadWrite|QIODevice::Unbuffered);

    q->setSocketState(QBluetoothSocket::ConnectedState);
    emit q->connected();
}
bool QBluetoothServer::listen(const QBluetoothAddress &address, quint16 port)
{
    Q_UNUSED(address)
    Q_D(QBluetoothServer);
    if (serverType() != QBluetoothServiceInfo::RfcommProtocol) {
        d->m_lastError = UnsupportedProtocolError;
        emit error(d->m_lastError);
        return false;
    }

    QBluetoothLocalDevice device(address);
    if (!device.isValid()) {
        qCWarning(QT_BT_QNX) << "Device does not support Bluetooth or"
                                 << address.toString() << "is not a valid local adapter";
        d->m_lastError = QBluetoothServer::UnknownError;
        emit error(d->m_lastError);
        return false;
    }

    QBluetoothLocalDevice::HostMode hostMode= device.hostMode();
    if (hostMode == QBluetoothLocalDevice::HostPoweredOff) {
        d->m_lastError = QBluetoothServer::PoweredOffError;
        emit error(d->m_lastError);
        qCWarning(QT_BT_QNX) << "Bluetooth device is powered off";
        return false;
    }

    // listen has already been called before
    if (!d->socket)
        d->socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
    else if (d->socket->state() == QBluetoothSocket::ListeningState)
        return false;

    //We can not register an actual Rfcomm port, because the platform does not allow it
    //but we need a way to associate a server with a service

    if (port == 0) { //Try to assign a non taken port id
        for (int i=1; ; i++){
            if (__fakeServerPorts.key(i) == 0) {
                port = i;
                break;
            }
        }
    }

    if (__fakeServerPorts.key(port) == 0) {
        __fakeServerPorts[d] = port;
        qCDebug(QT_BT_QNX) << "Port" << port << "registered";
    } else {
        qCWarning(QT_BT_QNX) << "server with port" << port << "already registered or port invalid";
        d->m_lastError = ServiceAlreadyRegisteredError;
        emit error(d->m_lastError);
        return false;
    }

#ifndef QT_QNX_BT_BLUETOOTH
    ppsRegisterForEvent(QStringLiteral("service_connected"),d);
#endif
    d->socket->setSocketState(QBluetoothSocket::ListeningState);
    return true;
}
QDebug operator<<(QDebug debug, const QBluetoothAddress &address)
{
    debug << address.toString();
    return debug;
}
void QBluetoothServiceDiscoveryAgentPrivate::start(const QBluetoothAddress &address)
{
    Q_Q(QBluetoothServiceDiscoveryAgent);

    if (!btAdapter.isValid()) {
        error = QBluetoothServiceDiscoveryAgent::UnknownError;
        errorString = QBluetoothServiceDiscoveryAgent::tr("Platform does not support Bluetooth");

        //abort any outstanding discoveries
        discoveredDevices.clear();
        emit q->error(error);
        _q_serviceDiscoveryFinished();

        return;
    }

    /* SDP discovery was officially added by Android API v15
     * BluetoothDevice.getUuids() existed in earlier APIs already and in the future we may use
     * reflection to support earlier Android versions than 15. Unfortunately
     * BluetoothDevice.fetchUuidsWithSdp() and related APIs had some structure changes
     * over time. Therefore we won't attempt this with reflection.
     *
     * TODO: Use reflection to support getUuuids() where possible.
     * */
    if (QtAndroidPrivate::androidSdkVersion() < 15) {
        qCWarning(QT_BT_ANDROID) << "Aborting SDP enquiry due to too low Android API version (requires v15+)";

        error = QBluetoothServiceDiscoveryAgent::UnknownError;
        errorString = QBluetoothServiceDiscoveryAgent::tr("Android API below v15 does not support SDP discovery");

        //abort any outstanding discoveries
        sdpCache.clear();
        discoveredDevices.clear();
        emit q->error(error);
        _q_serviceDiscoveryFinished();

        return;
    }

    QAndroidJniObject inputString = QAndroidJniObject::fromString(address.toString());
    QAndroidJniObject remoteDevice =
            btAdapter.callObjectMethod("getRemoteDevice",
                                               "(Ljava/lang/String;)Landroid/bluetooth/BluetoothDevice;",
                                               inputString.object<jstring>());
    QAndroidJniEnvironment env;
    if (env->ExceptionCheck()) {
        env->ExceptionClear();
        env->ExceptionDescribe();

        //if it was only device then its error -> otherwise go to next device
        if (singleDevice) {
            error = QBluetoothServiceDiscoveryAgent::InputOutputError;
            errorString = QBluetoothServiceDiscoveryAgent::tr("Cannot create Android BluetoothDevice");

            qCWarning(QT_BT_ANDROID) << "Cannot start SDP for" << discoveredDevices.at(0).name()
                                     << "(" << address.toString() << ")";
            emit q->error(error);
        }
        _q_serviceDiscoveryFinished();
        return;
    }


    if (mode == QBluetoothServiceDiscoveryAgent::MinimalDiscovery) {
        qCDebug(QT_BT_ANDROID) << "Minimal discovery on (" << discoveredDevices.at(0).name()
                               << ")" << address.toString() ;

        //Minimal discovery uses BluetoothDevice.getUuids()
        QAndroidJniObject parcelUuidArray = remoteDevice.callObjectMethod(
                    "getUuids", "()[Landroid/os/ParcelUuid;");

        if (!parcelUuidArray.isValid()) {
            if (singleDevice) {
                error = QBluetoothServiceDiscoveryAgent::InputOutputError;
                errorString = QBluetoothServiceDiscoveryAgent::tr("Cannot obtain service uuids");
                emit q->error(error);
            }
            qCWarning(QT_BT_ANDROID) << "Cannot retrieve SDP UUIDs for" << discoveredDevices.at(0).name()
                                     << "(" << address.toString() << ")";
            _q_serviceDiscoveryFinished();
            return;
        }

        const QList<QBluetoothUuid> results = ServiceDiscoveryBroadcastReceiver::convertParcelableArray(parcelUuidArray);
        populateDiscoveredServices(discoveredDevices.at(0), results);

        _q_serviceDiscoveryFinished();
    } else {
        qCDebug(QT_BT_ANDROID) << "Full discovery on (" << discoveredDevices.at(0).name()
                               << ")" << address.toString();

        //Full discovery uses BluetoothDevice.fetchUuidsWithSdp()
        if (!receiver) {
            receiver = new ServiceDiscoveryBroadcastReceiver();
            QObject::connect(receiver, SIGNAL(uuidFetchFinished(QBluetoothAddress,QList<QBluetoothUuid>)),
                    q, SLOT(_q_processFetchedUuids(QBluetoothAddress,QList<QBluetoothUuid>)));
        }

        if (!localDeviceReceiver) {
            localDeviceReceiver = new LocalDeviceBroadcastReceiver();
            QObject::connect(localDeviceReceiver, SIGNAL(hostModeStateChanged(QBluetoothLocalDevice::HostMode)),
                             q, SLOT(_q_hostModeStateChanged(QBluetoothLocalDevice::HostMode)));
        }

        jboolean result = remoteDevice.callMethod<jboolean>("fetchUuidsWithSdp");
        if (!result) {
            //kill receiver to limit load of signals
            receiver->unregisterReceiver();
            receiver->deleteLater();
            receiver = 0;
            qCWarning(QT_BT_ANDROID) << "Cannot start dynamic fetch.";
            _q_serviceDiscoveryFinished();
        }
    }
}
Exemple #14
0
int Main::buttonClicked() {
    QList<QBluetoothHostInfo> localAdapters = QBluetoothLocalDevice::allDevices();
    printf("%s - localAdapters.count=%d\n", __func__, localAdapters.count());
    for(int i = 0; i < localAdapters.size(); i++) {
        qDebug() <<  __func__ << " - adapter: " <<  i <<
            " " << localAdapters[i].name().toUtf8().constData() <<
            " " << localAdapters[i].address().toString();
    }

    if (localAdapters.size() < 1) {
        qDebug() << __func__ << " no bluetooth found";
        return -1;
    }


    QBluetoothLocalDevice adapter(localAdapters.at(0).address());
    adapter.setHostMode(QBluetoothLocalDevice::HostDiscoverable);

    QBluetoothServer *rfcommServer = new QBluetoothServer(QBluetoothServiceInfo::RfcommProtocol, NULL);
    connect(rfcommServer, SIGNAL(newConnection()), this, SLOT(clientConnected()));

    QBluetoothAddress actualAddress = localAdapters[0].address();
    printf("%s - QBluetoothServer - starting to listen at %s\n", __func__,
           actualAddress.toString().toUtf8().constData());
    bool result = rfcommServer->listen(actualAddress);
    if (!result) {
        qDebug() <<  __func__ << "-" << result;
        return -1;
    }

    //! [Get local device name]
    QString localName = QBluetoothLocalDevice().name();
    qDebug() << "local device name" << localName;

    //result = serviceInfo.registerService(/*actualAddress*/);

#pragma region Attributes
    serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceRecordHandle, (uint)0x00010010);

    //! [Class Uuuid must contain at least 1 entry]
    QBluetoothServiceInfo::Sequence classId;

    classId << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::SerialPort));
    serviceInfo.setAttribute(QBluetoothServiceInfo::BluetoothProfileDescriptorList,
                             classId);

    printf("%s - done %d\n", __func__, 1);

    classId.prepend(QVariant::fromValue(QBluetoothUuid(serviceUuid)));

    serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceClassIds, classId);
    serviceInfo.setAttribute(QBluetoothServiceInfo::BluetoothProfileDescriptorList,classId);
    //! [Class Uuuid must contain at least 1 entry]


    printf("%s - done %d\n", __func__, 2);
    //! [Service name, description and provider]
    serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceName, tr("Bt Chat Server"));
    serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceDescription,
                             tr("Example bluetooth chat server"));
    serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceProvider, tr("qt-project.org"));
    //! [Service name, description and provider]

    //! [Service UUID set]
    serviceInfo.setServiceUuid(QBluetoothUuid(serviceUuid));
    //! [Service UUID set]


    printf("%s - done %d\n", __func__, 3);
    //! [Service Discoverability]
    QBluetoothServiceInfo::Sequence publicBrowse;
    publicBrowse << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::PublicBrowseGroup));
    serviceInfo.setAttribute(QBluetoothServiceInfo::BrowseGroupList,
                             publicBrowse);
    //! [Service Discoverability]

    printf("%s - done %d\n", __func__, 4);
    //! [Protocol descriptor list]
    QBluetoothServiceInfo::Sequence protocolDescriptorList;
    QBluetoothServiceInfo::Sequence protocol;
    protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::L2cap));
    protocolDescriptorList.append(QVariant::fromValue(protocol));
    protocol.clear();
    protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::Rfcomm))
             << QVariant::fromValue(quint8(rfcommServer->serverPort()));
    protocolDescriptorList.append(QVariant::fromValue(protocol));
    serviceInfo.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList,
                             protocolDescriptorList);
    //! [Protocol descriptor list]

    printf("%s - done %d\n", __func__, 5);
    //! [Register service]
    result = serviceInfo.registerService(actualAddress);
    if (!result) {
        printf("%s - registering with SDP failed\n", __func__);
        return -1;
    }
    //! [Register service]
#pragma endregion

    printf("%s - done\n", __func__);
    return 0;


}
Exemple #15
0
static QString bluetoothAddressToString(const QBluetoothAddress &addr)
{
    return addr.toString();
}
Exemple #16
0
int BtSettings::audioProfileChannel(const QBluetoothAddress &addr, QBluetooth::SDPProfile profile)
{
    QSettings settings("Trolltech", "BluetoothKnownHeadsets");
    return settings.value(addr.toString() + "/" + QString::number(int(profile)), -1).toInt();
}
Exemple #17
0
void BtSettings::setAudioProfileChannel(const QBluetoothAddress &addr, QBluetooth::SDPProfile profile, int channel)
{
    QSettings settings("Trolltech", "BluetoothKnownHeadsets");
    settings.setValue(addr.toString() + "/" + QString::number(int(profile)),
                      channel);
}
void QBluetoothLocalDevice::requestPairing(const QBluetoothAddress &address, Pairing pairing)
{
    Q_UNUSED(pairing);
    ppsSendControlMessage("initiate_pairing", QStringLiteral("{\"addr\":\"%1\"}").arg(address.toString()), this);
}
void QBluetoothServiceDiscoveryAgentPrivate::_q_processFetchedUuids(
    const QBluetoothAddress &address, const QList<QBluetoothUuid> &uuids)
{
    //don't leave more data through if we are not interested anymore
    if (discoveredDevices.count() == 0)
        return;

    //could not find any service for the current address/device -> go to next one
    if (address.isNull() || uuids.isEmpty()) {
        _q_serviceDiscoveryFinished();
        return;
    }

    if (QT_BT_ANDROID().isDebugEnabled()) {
        qCDebug(QT_BT_ANDROID) << "Found UUID for" << address.toString()
                               << "\ncount: " << uuids.count();

        QString result;
        for (int i = 0; i<uuids.count(); i++)
            result += uuids.at(i).toString() + QStringLiteral("**");
        qCDebug(QT_BT_ANDROID) << result;
    }

    /* In general there are two uuid events per device.
     * We'll wait for the second event to arrive before we process the UUIDs.
     * We utilize a timeout to catch cases when the second
     * event doesn't arrive at all.
     * Generally we assume that the second uuid event carries the most up-to-date
     * set of uuids and discard the first events results.
    */

    if (sdpCache.contains(address)) {
        //second event
        QPair<QBluetoothDeviceInfo,QList<QBluetoothUuid> > pair = sdpCache.take(address);

        //prefer second uuid set over first
        populateDiscoveredServices(pair.first, uuids);

        if (discoveredDevices.count() == 1 && sdpCache.isEmpty()) {
            //last regular uuid data set from OS -> we finish here
            _q_serviceDiscoveryFinished();
        }
    } else {
        //first event
        QPair<QBluetoothDeviceInfo,QList<QBluetoothUuid> > pair;
        pair.first = discoveredDevices.at(0);
        pair.second = uuids;

        if (pair.first.address() != address)
            return;

        sdpCache.insert(address, pair);

        //the discovery on the last device cannot immediately finish
        //we have to grant the 2 seconds timeout delay
        if (discoveredDevices.count() == 1) {
            Q_Q(QBluetoothServiceDiscoveryAgent);
            QTimer::singleShot(4000, q, SLOT(_q_fetchUuidsTimeout()));
            return;
        }

        _q_serviceDiscoveryFinished();
    }
}
Exemple #20
0
void QBluetoothLocalDevice::requestPairing(const QBluetoothAddress &address, Pairing pairing)
{

    if(pairing == Paired || pairing == AuthorizedPaired) {

        d_ptr->address = address;
        d_ptr->pairing = pairing;

        if(!d_ptr->agent){
            d_ptr->agent = new OrgBluezAgentAdaptor(d_ptr);
            bool res = QDBusConnection::systemBus().registerObject(d_ptr->agent_path, d_ptr);
            if(!res){
                qDebug() << "Failed to register agent";
                return;
            }
        }

        Pairing current_pairing = pairingStatus(address);
        if(current_pairing == Paired && pairing == AuthorizedPaired){
            OrgBluezDeviceInterface *device = getDevice(address, d_ptr);
            if(!device)
                return;
            QDBusPendingReply<> deviceReply = device->SetProperty(QLatin1String("Trusted"), QDBusVariant(true));
            deviceReply.waitForFinished();
            if(deviceReply.isError()){
                qDebug() << Q_FUNC_INFO << "reply failed" << deviceReply.error();
                return;
            }
            delete device;
            QMetaObject::invokeMethod(this, "pairingFinished", Qt::QueuedConnection, Q_ARG(QBluetoothAddress, address),
                                      Q_ARG(QBluetoothLocalDevice::Pairing, QBluetoothLocalDevice::AuthorizedPaired));
        }
        else if(current_pairing == AuthorizedPaired && pairing == Paired){
            OrgBluezDeviceInterface *device = getDevice(address, d_ptr);
            if(!device)
                return;
            QDBusPendingReply<> deviceReply = device->SetProperty(QLatin1String("Trusted"), QDBusVariant(false));
            deviceReply.waitForFinished();
            if(deviceReply.isError()){
                qDebug() << Q_FUNC_INFO << "reply failed" << deviceReply.error();
                return;
            }
            delete device;
            QMetaObject::invokeMethod(this, "pairingFinished", Qt::QueuedConnection, Q_ARG(QBluetoothAddress, address),
                                      Q_ARG(QBluetoothLocalDevice::Pairing, QBluetoothLocalDevice::Paired));
        }
        else {
            QDBusPendingReply<QDBusObjectPath> reply =
                    d_ptr->adapter->CreatePairedDevice(address.toString(),
                                                       QDBusObjectPath(d_ptr->agent_path),
                                                       QLatin1String("NoInputNoOutput"));

            QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
            connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), d_ptr, SLOT(pairingCompleted(QDBusPendingCallWatcher*)));

            if(reply.isError())
                qDebug() << Q_FUNC_INFO << reply.error() << d_ptr->agent_path;
        }
    }
    else if(pairing == Unpaired) {
        QDBusPendingReply<QDBusObjectPath> reply = this->d_ptr->adapter->FindDevice(address.toString());
        reply.waitForFinished();
        if(reply.isError()) {
            qDebug() << Q_FUNC_INFO << "failed to find device" << reply.error();
            return;
        }
        QDBusPendingReply<> removeReply = this->d_ptr->adapter->RemoveDevice(reply.value());
        removeReply.waitForFinished();
        if(removeReply.isError()){
            qDebug() << Q_FUNC_INFO << "failed to remove device" << removeReply.error();
        }
        return;
    }
    return;
}