void tst_QBluetoothHostInfo::tst_construction()
{
    QFETCH(QString, btAddress);
    QFETCH(QString, name);
    QFETCH(bool, validBtAddress);

    QBluetoothAddress empty;
    QVERIFY(empty.isNull());

    QBluetoothHostInfo setter;
    QBluetoothAddress addr(btAddress);
    setter.setName(name);
    setter.setAddress(addr);
    QCOMPARE(setter.name(), name);
    QCOMPARE(setter.address().toString(), btAddress);
    QCOMPARE(setter.address().isNull(), !validBtAddress);

    setter.setAddress(empty);
    QCOMPARE(setter.name(), name);
    QCOMPARE(setter.address().toString(), QString("00:00:00:00:00:00"));
    QCOMPARE(setter.address().isNull(), true);

    setter.setName(QString());
    QCOMPARE(setter.name(), QString());
    QCOMPARE(setter.address().toString(), QString("00:00:00:00:00:00"));
    QCOMPARE(setter.address().isNull(), true);

    setter.setAddress(addr);
    QCOMPARE(setter.name(), QString());
    QCOMPARE(setter.address().toString(), btAddress);
    QCOMPARE(setter.address().isNull(), !validBtAddress);
}
/*!
  Initializes the client and connects to \a remoteService.
*/
void BluetoothClient::startClient(const QBluetoothServiceInfo &remoteService)
{
    if (mSocket || mRetries) {
        qDebug() << "BluetoothClient::startClient(): Already running!";
        return;
    }

    mService = remoteService;
    mRetries = NumberOfRetries;
    mLastErrorString = "";

    Common::resetBuffer();

    QBluetoothAddress address = mService.device().address();
    qDebug() << "BluetoothClient::startClient(): Bluetooth address: " << address.toString();

    mSocket = new QBluetoothSocket(QBluetoothSocket::RfcommSocket);
    connect(mSocket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    connect(mSocket, SIGNAL(connected()), this, SLOT(onConnected()));
    connect(mSocket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));
    connect(mSocket, SIGNAL(error(QBluetoothSocket::SocketError)),
            this, SLOT(onSocketError(QBluetoothSocket::SocketError)));

    // mSocket->connectToService() call may block the UI thread. Thus, use the
    // the timer to delay the call in case we want to show some note for the
    // user.
    QTimer::singleShot(RetryInterval, this, SLOT(connectToService()));
}
void tst_QBluetoothAddress::tst_construction()
{
    QFETCH(quint64, addressUInt);
    QFETCH(QString, addressS12);
    QFETCH(QString, addressS17);

    {
        QBluetoothAddress address;

        QVERIFY(address.isNull());
    }

    {
        /* construct from quint64 */
        QBluetoothAddress address(addressUInt);

        QVERIFY(!address.isNull());

        QVERIFY(address.toUInt64() == addressUInt);

        QCOMPARE(address.toString(), addressS17);
    }

    {
        /* construct from string without colons */
        QBluetoothAddress address(addressS12);

        QVERIFY(!address.isNull());

        QVERIFY(address.toUInt64() == addressUInt);

        QCOMPARE(address.toString(), addressS17);
    }

    {
        /* construct from string with colons */
        QBluetoothAddress address(addressS17);

        QVERIFY(!address.isNull());

        QVERIFY(address.toUInt64() == addressUInt);

        QCOMPARE(address.toString(), addressS17);
    }

    {
        QString empty;
        QBluetoothAddress address(empty);

        QVERIFY(address.isNull());
    }

    {
        QBluetoothAddress address(addressUInt);

        QBluetoothAddress copy(address);

        QVERIFY(address.toUInt64() == copy.toUInt64());
    }
}
Exemple #4
0
void QBluetoothSocketPrivate::connectToService(const QBluetoothAddress &address, quint16 port, QIODevice::OpenMode openMode)
{
    Q_Q(QBluetoothSocket);
    Q_UNUSED(openMode);
    
    TBTSockAddr a;

    if(address.isNull())
        {
        socketError = QBluetoothSocket::UnknownSocketError;
        emit q->error(socketError);
        return;
        }
    TInt err = KErrNone;
    a.SetPort(port);
    // Trap TBTDevAddr constructor which may panic
    TRAP(err, a.SetBTAddr(TBTDevAddr(address.toUInt64())));
    if(err == KErrNone)
        err = iSocket->Connect(a);
    if (err == KErrNone) {
        q->setSocketState(QBluetoothSocket::ConnectingState);
    } else {
        socketError = QBluetoothSocket::UnknownSocketError;
        emit q->error(socketError);
    }
}
void tst_QBluetoothAddress::tst_assignment()
{
    QBluetoothAddress address(Q_UINT64_C(0x112233445566));

    {
        QBluetoothAddress copy = address;

        QCOMPARE(address.toUInt64(), copy.toUInt64());
    }

    {
        QBluetoothAddress copy1;
        QBluetoothAddress copy2;

        QVERIFY(copy1.isNull());
        QVERIFY(copy2.isNull());

        copy1 = copy2 = address;

        QVERIFY(!copy1.isNull());
        QVERIFY(!copy2.isNull());

        QVERIFY(address.toUInt64() == copy1.toUInt64());
        QVERIFY(address.toUInt64() == copy2.toUInt64());

        copy1.clear();
        QVERIFY(copy1.isNull());
        QVERIFY2(copy1 != address, "Verify that copy1 is a copy of address, the d_ptr are being copied");
    }
}
QString QBluetoothSocketPrivate::localName() const
{
    const QBluetoothAddress address = localAddress();
    if (address.isNull())
        return QString();

    QBluetoothLocalDevice device(address);
    return device.name();
}
Exemple #7
0
void HciManager::handleHciEventPacket(const quint8 *data, int size)
{
    if (size < HCI_EVENT_HDR_SIZE) {
        qCWarning(QT_BT_BLUEZ) << "Unexpected HCI event packet size:" << size;
        return;
    }

    hci_event_hdr *header = (hci_event_hdr *) data;

    size -= HCI_EVENT_HDR_SIZE;
    data += HCI_EVENT_HDR_SIZE;

    if (header->plen != size) {
        qCWarning(QT_BT_BLUEZ) << "Invalid HCI event packet size";
        return;
    }

    qCDebug(QT_BT_BLUEZ) << "HCI event triggered, type:" << hex << header->evt;

    switch (header->evt) {
    case EVT_ENCRYPT_CHANGE:
    {
        const evt_encrypt_change *event = (evt_encrypt_change *) data;
        qCDebug(QT_BT_BLUEZ) << "HCI Encrypt change, status:"
                             << (event->status == 0 ? "Success" : "Failed")
                             << "handle:" << hex << event->handle
                             << "encrypt:" << event->encrypt;

        QBluetoothAddress remoteDevice = addressForConnectionHandle(event->handle);
        if (!remoteDevice.isNull())
            emit encryptionChangedEvent(remoteDevice, event->status == 0);
    }
        break;
    case EVT_CMD_COMPLETE: {
        auto * const event = reinterpret_cast<const evt_cmd_complete *>(data);
        static_assert(sizeof *event == 3, "unexpected struct size");

        // There is always a status byte right after the generic structure.
        Q_ASSERT(size > static_cast<int>(sizeof *event));
        const quint8 status = data[sizeof *event];
        const auto additionalData = QByteArray(reinterpret_cast<const char *>(data)
                                               + sizeof *event + 1, size - sizeof *event - 1);
        emit commandCompleted(event->opcode, status, additionalData);
    }
        break;
    case LeMetaEvent:
        handleLeMetaEvent(data);
        break;
    default:
        break;
    }

}
void RemoteSelector::pairingFinished(const QBluetoothAddress &address, QBluetoothLocalDevice::Pairing status)
{
    QBluetoothServiceInfo service;
    int row = 0;

    ui->pairingBusy->hide();
    ui->pairingBusy->movie()->stop();

    ui->remoteDevices->blockSignals(true);

    for(int i = 0; i < m_discoveredServices.count(); i++){
        if(m_discoveredServices.value(i).device().address() == address){
            service = m_discoveredServices.value(i);
            row = i;
            break;
        }
    }

    if(m_pindisplay)
        delete m_pindisplay;

    QMessageBox msgBox;
    if(status == QBluetoothLocalDevice::Paired ||
       status == QBluetoothLocalDevice::AuthorizedPaired){
        msgBox.setText("Paired successfully with" + address.toString());
    }
    else {
        msgBox.setText("Pairing failed with " + address.toString());
    }

    if(service.isValid()){
        if(status == QBluetoothLocalDevice::AuthorizedPaired){
            ui->remoteDevices->item(row, 3)->setCheckState(Qt::Checked);
            ui->remoteDevices->item(row, 4)->setCheckState(Qt::Checked);
        }
        else if(status == QBluetoothLocalDevice::Paired){
            ui->remoteDevices->item(row, 3)->setCheckState(Qt::Checked);
            ui->remoteDevices->item(row, 4)->setCheckState(Qt::Unchecked);
        }
        else {
            ui->remoteDevices->item(row, 3)->setCheckState(Qt::Unchecked);
            ui->remoteDevices->item(row, 4)->setCheckState(Qt::Unchecked);
        }
    }

    msgBox.exec();

    ui->remoteDevices->blockSignals(false);


}
Exemple #9
0
/*!
 * Process all incoming HCI events. Function cannot process anything else but events.
 */
void HciManager::_q_readNotify()
{

    unsigned char buffer[HCI_MAX_EVENT_SIZE];
    int size;

    size = ::read(hciSocket, buffer, sizeof(buffer));
    if (size < 0) {
        if (errno != EAGAIN && errno != EINTR)
            qCWarning(QT_BT_BLUEZ) << "Failed reading HCI events:" << qt_error_string(errno);

        return;
    }

    const unsigned char *data = buffer;

    // Not interested in anything but valid HCI events
    if ((size < HCI_EVENT_HDR_SIZE + 1) || buffer[0] != HCI_EVENT_PKT)
        return;

    hci_event_hdr *header = (hci_event_hdr *)(&buffer[1]);

    size = size - HCI_EVENT_HDR_SIZE - 1;
    data = data + HCI_EVENT_HDR_SIZE + 1;

    if (header->plen != size) {
        qCWarning(QT_BT_BLUEZ) << "Invalid HCI event packet size";
        return;
    }

    qCDebug(QT_BT_BLUEZ) << "HCI event triggered, type:" << hex << header->evt;

    switch (header->evt) {
    case EVT_ENCRYPT_CHANGE:
    {
        const evt_encrypt_change *event = (evt_encrypt_change *) data;
        qCDebug(QT_BT_BLUEZ) << "HCI Encrypt change, status:"
                             << (event->status == 0 ? "Success" : "Failed")
                             << "handle:" << hex << event->handle
                             << "encrypt:" << event->encrypt;

        QBluetoothAddress remoteDevice = addressForConnectionHandle(event->handle);
        if (!remoteDevice.isNull())
            emit encryptionChangedEvent(remoteDevice, event->status == 0);
    }
        break;
    default:
        break;
    }
}
void QBluetoothLocalDevicePrivate::requestPairing(const QBluetoothAddress &address,
                                                  QBluetoothLocalDevice::Pairing pairing)
{
    if (pairing == QBluetoothLocalDevice::Paired
        || pairing == QBluetoothLocalDevice::AuthorizedPaired) {
        ppsSendControlMessage("initiate_pairing",
                              QStringLiteral("{\"addr\":\"%1\"}").arg(address.toString()),
                              this);
    } else {
        ppsSendControlMessage("remove_device",
                              QStringLiteral("{\"addr\":\"%1\"}").arg(address.toString()),
                              this);
    }
}
void tst_QBluetoothHostInfo::tst_address()
{
    QFETCH(QString, addressString);

    QBluetoothAddress address(addressString);
    QVERIFY(!address.isNull());
    QCOMPARE(address.toString(), addressString);

    QBluetoothHostInfo info;
    QBluetoothAddress result = info.address();
    QVERIFY(result.isNull());
    info.setAddress(address);
    QCOMPARE(info.address().toString(), addressString);

}
QBluetoothLocalDevice::Pairing QBluetoothLocalDevice::pairingStatus(const QBluetoothAddress &address) const
{
    QVariant status = ppsRemoteDeviceStatus(address.toString().toLocal8Bit(), "paired");
    if (status.toBool())
        return Paired;
    return Unpaired;
}
Exemple #13
0
HciManager::HciManager(const QBluetoothAddress& deviceAdapter, QObject *parent) :
    QObject(parent), hciSocket(-1), hciDev(-1), notifier(0)
{
    hciSocket = ::socket(AF_BLUETOOTH, SOCK_RAW | SOCK_CLOEXEC, BTPROTO_HCI);
    if (hciSocket < 0) {
        qCWarning(QT_BT_BLUEZ) << "Cannot open HCI socket";
        return; //TODO error report
    }

    hciDev = hciForAddress(deviceAdapter);
    if (hciDev < 0) {
        qCWarning(QT_BT_BLUEZ) << "Cannot find hci dev for" << deviceAdapter.toString();
        close(hciSocket);
        hciSocket = -1;
        return;
    }

    struct sockaddr_hci addr;

    memset(&addr, 0, sizeof(struct sockaddr_hci));
    addr.hci_dev = hciDev;
    addr.hci_family = AF_BLUETOOTH;

    if (::bind(hciSocket, (struct sockaddr *) (&addr), sizeof(addr)) < 0) {
        qCWarning(QT_BT_BLUEZ) << "HCI bind failed:" << strerror(errno);
        close(hciSocket);
        hciSocket = hciDev = -1;
        return;
    }

    notifier = new QSocketNotifier(hciSocket, QSocketNotifier::Read, this);
    connect(notifier, SIGNAL(activated(int)), this, SLOT(_q_readNotify()));

}
void QBluetoothSocketPrivate::connectToService(const QBluetoothAddress &address,
                                               const QBluetoothUuid &uuid,
                                               QIODevice::OpenMode openMode)
{
    Q_Q(QBluetoothSocket);
    Q_UNUSED(openMode);
    qCDebug(QT_BT_QNX) << "Connecting socket";

    m_peerAddress = address;
#ifdef QT_QNX_BT_BLUETOOTH
    QByteArray b_uuid = uuid.toByteArray();
    b_uuid = b_uuid.mid(1, b_uuid.length() - 2);
    socket = bt_spp_open(address.toString().toUtf8().data(), b_uuid.data(), false);
    if (socket == -1) {
        qCWarning(QT_BT_QNX) << "Could not connect to" << address.toString() << b_uuid <<  qt_error_string(errno);
        errorString = qt_error_string(errno);
        q->setSocketError(QBluetoothSocket::NetworkError);
        return;
    }

    delete readNotifier;
    delete connectWriteNotifier;

    readNotifier = new QSocketNotifier(socket, QSocketNotifier::Read);
    QObject::connect(readNotifier, SIGNAL(activated(int)), this, SLOT(_q_readNotify()));
    connectWriteNotifier = new QSocketNotifier(socket, QSocketNotifier::Write, q);
    QObject::connect(connectWriteNotifier, SIGNAL(activated(int)), this, SLOT(_q_writeNotify()));

    connecting = true;
    q->setOpenMode(openMode);
#else
    m_uuid = uuid;
    if (isServerSocket)
        return;

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

    ppsSendControlMessage("connect_service", 0x1101, uuid, address.toString(), QString(), this, BT_SPP_CLIENT_SUBTYPE);
    ppsRegisterForEvent(QStringLiteral("service_connected"),this);
    ppsRegisterForEvent(QStringLiteral("get_mount_point_path"),this);
#endif
    q->setSocketState(QBluetoothSocket::ConnectingState);
}
Exemple #15
0
void RfcommClient::connectSocket()
{
    QBluetoothAddress addr = QBluetoothRemoteDeviceDialog::getRemoteDevice(this);

    if (!addr.isValid()) {
        return;
    }

    connectAction->setVisible(false);
    waiter->setText(tr("Connecting..."));
    waiter->setCancelEnabled(true);

    connect(socket, SIGNAL(error(QBluetoothAbstractSocket::SocketError)),
            this, SLOT(connectFailed()));
    socket->connect(QBluetoothAddress::any, addr, 14);
    waiter->show();
}
Exemple #16
0
QString RemoteSelector::addressToName(const QBluetoothAddress &address) {
    QMapIterator<int, QBluetoothServiceInfo> i(discoveredServices_);
    while (i.hasNext()){
        i.next();
        if (i.value().device().address() == address)
            return i.value().device().name();
    }
    return address.toString();
}
/*!
    Sets the remote device address to \a address. If \a address is default constructed,
    services will be discovered on all contactable Bluetooth devices. A new remote
    address can only be set while there is no service discovery in progress; otherwise
    this function returns false.

    On some platforms such as Blackberry the service discovery might lead to pairing requests.
    Therefore it is not recommended to do service discoveries on all devices.

    \sa remoteAddress()
*/
bool QBluetoothServiceDiscoveryAgent::setRemoteAddress(const QBluetoothAddress &address)
{
    if (isActive())
        return false;
    if (!address.isNull())
        d_ptr->singleDevice = true;
    d_ptr->deviceAddress = address;
    return true;
}
Exemple #18
0
/*!
    Finds the path for the local adapter with \a wantedAddress or an empty string
    if no local adapter with the given address can be found.
    If \a wantedAddress is \c null it returns the first/default adapter or an empty
    string if none is available.

    If \a ok is false the lookup was aborted due to a dbus error and this function
    returns an empty string.
 */
QString findAdapterForAddress(const QBluetoothAddress &wantedAddress, bool *ok = 0)
{
    OrgFreedesktopDBusObjectManagerInterface manager(QStringLiteral("org.bluez"),
                                                     QStringLiteral("/"),
                                                     QDBusConnection::systemBus());

    QDBusPendingReply<ManagedObjectList> reply = manager.GetManagedObjects();
    reply.waitForFinished();
    if (reply.isError()) {
        if (ok)
            *ok = false;

        return QString();
    }

    typedef QPair<QString, QBluetoothAddress> AddressForPathType;
    QList<AddressForPathType> localAdapters;

    ManagedObjectList managedObjectList = reply.value();
    for (ManagedObjectList::const_iterator it = managedObjectList.constBegin(); it != managedObjectList.constEnd(); ++it) {
        const QDBusObjectPath &path = it.key();
        const InterfaceList &ifaceList = it.value();

        for (InterfaceList::const_iterator jt = ifaceList.constBegin(); jt != ifaceList.constEnd(); ++jt) {
            const QString &iface = jt.key();

            if (iface == QStringLiteral("org.bluez.Adapter1")) {
                AddressForPathType pair;
                pair.first = path.path();
                pair.second = QBluetoothAddress(ifaceList.value(iface).value(
                                          QStringLiteral("Address")).toString());
                if (!pair.second.isNull())
                    localAdapters.append(pair);
                break;
            }
        }
    }

    if (ok)
        *ok = true;

    if (localAdapters.isEmpty())
        return QString(); // -> no local adapter found

    if (wantedAddress.isNull())
        return localAdapters.front().first; // -> return first found adapter

    foreach (const AddressForPathType &pair, localAdapters) {
        if (pair.second == wantedAddress)
            return pair.first; // -> found local adapter with wanted address
    }

    return QString(); // nothing matching found
}
void QBluetoothServiceDiscoveryAgentPrivate::initL(const QBluetoothAddress &address)
{
    TBTDevAddr btAddress(address.toUInt64());
    stop();

    //Trapped in Start
    m_sdpAgent = q_check_ptr(CSdpAgent::NewL(*this, btAddress));
    m_filter = q_check_ptr(CSdpSearchPattern::NewL());
    m_attributes = q_check_ptr(CSdpAttrIdMatchList::NewL());
    m_attributes->AddL(KAttrRangeAll);

}
static PyObject *meth_QBluetoothAddress_clear(PyObject *sipSelf, PyObject *sipArgs)
{
    PyObject *sipParseErr = NULL;

    {
        QBluetoothAddress *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "B", &sipSelf, sipType_QBluetoothAddress, &sipCpp))
        {
            sipCpp->clear();

            Py_INCREF(Py_None);
            return Py_None;
        }
    }

    /* Raise an exception if the arguments couldn't be parsed. */
    sipNoMethod(sipParseErr, sipName_QBluetoothAddress, sipName_clear, doc_QBluetoothAddress_clear);

    return NULL;
}
Exemple #21
0
int HciManager::hciForAddress(const QBluetoothAddress &deviceAdapter)
{
    if (hciSocket < 0)
        return -1;

    bdaddr_t adapter;
    convertAddress(deviceAdapter.toUInt64(), adapter.b);

    struct hci_dev_req *devRequest = 0;
    struct hci_dev_list_req *devRequestList = 0;
    struct hci_dev_info devInfo;
    const int devListSize = sizeof(struct hci_dev_list_req)
                        + HCI_MAX_DEV * sizeof(struct hci_dev_req);

    devRequestList = (hci_dev_list_req *) malloc(devListSize);
    if (!devRequestList)
        return -1;

    QScopedPointer<hci_dev_list_req, QScopedPointerPodDeleter> p(devRequestList);

    memset(p.data(), 0, devListSize);
    p->dev_num = HCI_MAX_DEV;
    devRequest = p->dev_req;

    if (ioctl(hciSocket, HCIGETDEVLIST, devRequestList) < 0)
        return -1;

    for (int i = 0; i < devRequestList->dev_num; i++) {
        devInfo.dev_id = (devRequest+i)->dev_id;
        if (ioctl(hciSocket, HCIGETDEVINFO, &devInfo) < 0) {
            continue;
        }

        int result = memcmp(&adapter, &devInfo.bdaddr, sizeof(bdaddr_t));
        if (result == 0 || deviceAdapter.isNull()) // addresses match
            return devInfo.dev_id;
    }

    return -1;
}
Exemple #22
0
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);
}
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);
    }
}
Exemple #24
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);
}
/*!
    Constructs a new QBluetoothServiceDiscoveryAgent for \a deviceAdapter and with \a parent.

    It uses \a deviceAdapter for the service search. If \a deviceAdapter is default constructed
    the resulting QBluetoothServiceDiscoveryAgent object will use the local default Bluetooth adapter.

    If a \a deviceAdapter is specified that is not a local adapter \l error() will be set to
    \l InvalidBluetoothAdapterError. Therefore it is recommended to test the error flag immediately after
    using this constructor.

    \sa error()
*/
QBluetoothServiceDiscoveryAgent::QBluetoothServiceDiscoveryAgent(const QBluetoothAddress &deviceAdapter, QObject *parent)
: QObject(parent), d_ptr(new QBluetoothServiceDiscoveryAgentPrivate(deviceAdapter))
{
    d_ptr->q_ptr = this;
    if (!deviceAdapter.isNull()) {
        const QList<QBluetoothHostInfo> localDevices = QBluetoothLocalDevice::allDevices();
        foreach (const QBluetoothHostInfo &hostInfo, localDevices) {
            if (hostInfo.address() == deviceAdapter)
                return;
        }
        d_ptr->error = InvalidBluetoothAdapterError;
        d_ptr->errorString = tr("Invalid Bluetooth adapter address");
    }
}
Exemple #26
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));
        }
    }
}
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;
}
void QBluetoothLocalDevice::requestPairing(const QBluetoothAddress &address, Pairing pairing)
{
    if (address.isNull()) {
        QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
                                  Q_ARG(QBluetoothLocalDevice::Error,
                                        QBluetoothLocalDevice::PairingError));
        return;
    }

    const Pairing current_pairing = pairingStatus(address);
    if (current_pairing == pairing) {
        QMetaObject::invokeMethod(this, "pairingFinished", Qt::QueuedConnection,
                                  Q_ARG(QBluetoothAddress, address),
                                  Q_ARG(QBluetoothLocalDevice::Pairing, pairing));
        return;
    }
    d_ptr->requestPairing(address, pairing);
}
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;
}
QBluetoothLocalDevice::Pairing QBluetoothLocalDevice::pairingStatus(const QBluetoothAddress &address) const
{
    if (address.isNull())
        return Unpaired;

    OrgBluezDeviceInterface *device = getDevice(address, d_ptr);

    if(!device)
        return Unpaired;

    QDBusPendingReply<QVariantMap> deviceReply = device->GetProperties();
    deviceReply.waitForFinished();
    if (deviceReply.isError())
        return Unpaired;

    QVariantMap map = deviceReply.value();

    if (map.value(QLatin1String("Trusted")).toBool() && map.value(QLatin1String("Paired")).toBool())
        return AuthorizedPaired;
    else if (map.value(QLatin1String("Paired")).toBool())
        return Paired;
    else
        return Unpaired;
}