diff --git a/autotests/adaptertest.cpp b/autotests/adaptertest.cpp index ff066ef..447f492 100644 --- a/autotests/adaptertest.cpp +++ b/autotests/adaptertest.cpp @@ -1,382 +1,382 @@ /* * Copyright (C) 2014-2015 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "adaptertest.h" #include "autotests.h" #include "device.h" #include "pendingcall.h" #include "initmanagerjob.h" #include #include namespace BluezQt { extern void bluezqt_initFakeBluezTestRun(); } using namespace BluezQt; AdapterTest::AdapterTest() : m_manager(nullptr) { Autotests::registerMetatypes(); } void AdapterTest::initTestCase() { QDBusConnection connection = QDBusConnection::sessionBus(); QString service = QStringLiteral("org.kde.bluezqt.fakebluez"); bluezqt_initFakeBluezTestRun(); FakeBluez::start(); FakeBluez::runTest(QStringLiteral("bluez-standard")); // Create adapters QDBusObjectPath adapter1path = QDBusObjectPath(QStringLiteral("/org/bluez/hci0")); QVariantMap adapterProps; adapterProps[QStringLiteral("Path")] = QVariant::fromValue(adapter1path); adapterProps[QStringLiteral("Address")] = QStringLiteral("1C:E5:C3:BC:94:7E"); adapterProps[QStringLiteral("Name")] = QStringLiteral("TestAdapter"); adapterProps[QStringLiteral("Alias")] = QStringLiteral("TestAlias"); adapterProps[QStringLiteral("Class")] = QVariant::fromValue(quint32(101)); adapterProps[QStringLiteral("Powered")] = false; adapterProps[QStringLiteral("Discoverable")] = false; adapterProps[QStringLiteral("Pairable")] = false; adapterProps[QStringLiteral("PairableTimeout")] = QVariant::fromValue(quint32(0)); adapterProps[QStringLiteral("DiscoverableTimeout")] = QVariant::fromValue(quint32(0)); adapterProps[QStringLiteral("Discovering")] = false; adapterProps[QStringLiteral("UUIDs")] = QStringList(QStringLiteral("00001200-0000-1000-8000-00805f9b34fb")); adapterProps[QStringLiteral("Modalias")] = QStringLiteral("usb:v2D6Bp1236d0215"); FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-adapter"), adapterProps); QDBusObjectPath adapter2path = QDBusObjectPath(QStringLiteral("/org/bluez/hci1")); adapterProps[QStringLiteral("Path")] = QVariant::fromValue(adapter2path); adapterProps[QStringLiteral("Address")] = QStringLiteral("2E:3A:C3:BC:85:7C"); adapterProps[QStringLiteral("Name")] = QStringLiteral("TestAdapter2"); adapterProps[QStringLiteral("Alias")] = QStringLiteral("TestAlias2"); adapterProps[QStringLiteral("Class")] = QVariant::fromValue(quint32(201)); adapterProps[QStringLiteral("Powered")] = true; adapterProps[QStringLiteral("Discoverable")] = true; adapterProps[QStringLiteral("Pairable")] = true; adapterProps[QStringLiteral("PairableTimeout")] = QVariant::fromValue(quint32(150)); adapterProps[QStringLiteral("DiscoverableTimeout")] = QVariant::fromValue(quint32(120)); adapterProps[QStringLiteral("Discovering")] = false; adapterProps[QStringLiteral("UUIDs")] = QStringList(QStringLiteral("0000110c-0000-1000-8000-00805f9b34fb")); adapterProps[QStringLiteral("Modalias")] = QStringLiteral("usb:v1D3Bp1134d0214"); FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-adapter"), adapterProps); // Create devices QVariantMap deviceProps; deviceProps[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath("/org/bluez/hci0/dev_40_79_6A_0C_39_75")); deviceProps[QStringLiteral("Adapter")] = QVariant::fromValue(adapter1path); deviceProps[QStringLiteral("Address")] = QStringLiteral("40:79:6A:0C:39:75"); deviceProps[QStringLiteral("Name")] = QStringLiteral("TestDevice"); FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-device"), deviceProps); deviceProps[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath("/org/bluez/hci1/dev_50_79_6A_0C_39_75")); deviceProps[QStringLiteral("Adapter")] = QVariant::fromValue(adapter2path); deviceProps[QStringLiteral("Address")] = QStringLiteral("50:79:6A:0C:39:75"); deviceProps[QStringLiteral("Name")] = QStringLiteral("TestDevice2"); FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-device"), deviceProps); m_manager = new Manager(); InitManagerJob *initJob = m_manager->init(); initJob->exec(); QVERIFY(!initJob->error()); - Q_FOREACH (AdapterPtr adapter, m_manager->adapters()) { + for (AdapterPtr adapter : m_manager->adapters()) { QVERIFY(!adapter->ubi().isEmpty()); AdapterUnit u; u.adapter = adapter; u.dbusAdapter = new org::bluez::Adapter1(service, adapter->ubi(), connection, this); u.dbusProperties = new org::freedesktop::DBus::Properties(service, adapter->ubi(), connection, this); m_units.append(u); } QCOMPARE(m_manager->adapters().count(), 2); } void AdapterTest::cleanupTestCase() { - Q_FOREACH (const AdapterUnit &unit, m_units) { + for (const AdapterUnit &unit : m_units) { delete unit.dbusAdapter; delete unit.dbusProperties; } delete m_manager; FakeBluez::stop(); } static void compareUuids(const QStringList &actual, const QStringList &expected) { QCOMPARE(actual.size(), expected.size()); for (int i = 0; i < actual.size(); ++i) { QCOMPARE(actual.at(i).toUpper(), expected.at(i).toUpper()); } } void AdapterTest::getPropertiesTest() { - Q_FOREACH (const AdapterUnit &unit, m_units) { + for (const AdapterUnit &unit : m_units) { QCOMPARE(unit.adapter->ubi(), unit.dbusAdapter->path()); QCOMPARE(unit.adapter->address(), unit.dbusAdapter->address()); QCOMPARE(unit.adapter->name(), unit.dbusAdapter->alias()); QCOMPARE(unit.adapter->systemName(), unit.dbusAdapter->name()); QCOMPARE(unit.adapter->adapterClass(), unit.dbusAdapter->adapterClass()); QCOMPARE(unit.adapter->isPowered(), unit.dbusAdapter->powered()); QCOMPARE(unit.adapter->isDiscoverable(), unit.dbusAdapter->discoverable()); QCOMPARE(unit.adapter->discoverableTimeout(), unit.dbusAdapter->discoverableTimeout()); QCOMPARE(unit.adapter->isPairable(), unit.dbusAdapter->pairable()); QCOMPARE(unit.adapter->pairableTimeout(), unit.dbusAdapter->pairableTimeout()); QCOMPARE(unit.adapter->isDiscovering(), unit.dbusAdapter->discovering()); QCOMPARE(unit.adapter->modalias(), unit.dbusAdapter->modalias()); compareUuids(unit.adapter->uuids(), unit.dbusAdapter->uUIDs()); } } void AdapterTest::setAliasTest() { - Q_FOREACH (const AdapterUnit &unit, m_units) { + for (const AdapterUnit &unit : m_units) { QSignalSpy adapterSpy(unit.adapter.data(), SIGNAL(nameChanged(QString))); QSignalSpy dbusSpy(unit.dbusProperties, SIGNAL(PropertiesChanged(QString,QVariantMap,QStringList))); QString value = unit.adapter->name() + QLatin1String("_tst_alias"); unit.adapter->setName(value); QTRY_COMPARE(adapterSpy.count(), 1); QList adapterArguments = adapterSpy.takeFirst(); QCOMPARE(adapterArguments.at(0).toString(), value); Autotests::verifyPropertiesChangedSignal(dbusSpy, QStringLiteral("Alias"), value); QCOMPARE(unit.adapter->name(), value); QCOMPARE(unit.dbusAdapter->alias(), value); } } void AdapterTest::setPoweredTest() { - Q_FOREACH (const AdapterUnit &unit, m_units) { + for (const AdapterUnit &unit : m_units) { QSignalSpy adapterSpy(unit.adapter.data(), SIGNAL(poweredChanged(bool))); QSignalSpy dbusSpy(unit.dbusProperties, SIGNAL(PropertiesChanged(QString,QVariantMap,QStringList))); bool value = !unit.adapter->isPowered(); unit.adapter->setPowered(value); QTRY_COMPARE(adapterSpy.count(), 1); QVERIFY(dbusSpy.count() >= 1); Autotests::verifyPropertiesChangedSignal(dbusSpy, QStringLiteral("Powered"), value); QList adapterArguments = adapterSpy.takeFirst(); QCOMPARE(adapterArguments.at(0).toBool(), value); QCOMPARE(unit.adapter->isPowered(), value); QCOMPARE(unit.dbusAdapter->powered(), value); } } void AdapterTest::setDiscoverableTest() { // Discoverable cannot be changed when Adapter is off - Q_FOREACH (const AdapterUnit &unit, m_units) { + for (const AdapterUnit &unit : m_units) { unit.adapter->setPowered(true)->waitForFinished(); QSignalSpy adapterSpy(unit.adapter.data(), SIGNAL(discoverableChanged(bool))); QSignalSpy dbusSpy(unit.dbusProperties, SIGNAL(PropertiesChanged(QString,QVariantMap,QStringList))); bool value = !unit.adapter->isDiscoverable(); unit.adapter->setDiscoverable(value); QTRY_COMPARE(adapterSpy.count(), 1); QList adapterArguments = adapterSpy.takeFirst(); QCOMPARE(adapterArguments.at(0).toBool(), value); Autotests::verifyPropertiesChangedSignal(dbusSpy, QStringLiteral("Discoverable"), value); QCOMPARE(unit.adapter->isDiscoverable(), value); QCOMPARE(unit.dbusAdapter->discoverable(), value); } } void AdapterTest::setDiscoverableTimeoutTest() { - Q_FOREACH (const AdapterUnit &unit, m_units) { + for (const AdapterUnit &unit : m_units) { QSignalSpy adapterSpy(unit.adapter.data(), SIGNAL(discoverableTimeoutChanged(quint32))); QSignalSpy dbusSpy(unit.dbusProperties, SIGNAL(PropertiesChanged(QString,QVariantMap,QStringList))); quint32 value = unit.adapter->discoverableTimeout() + 1; unit.adapter->setDiscoverableTimeout(value); QTRY_COMPARE(adapterSpy.count(), 1); QVERIFY(dbusSpy.count() >= 1); Autotests::verifyPropertiesChangedSignal(dbusSpy, QStringLiteral("DiscoverableTimeout"), value); QList adapterArguments = adapterSpy.takeFirst(); QCOMPARE(adapterArguments.at(0).toUInt(), value); QCOMPARE(unit.adapter->discoverableTimeout(), value); QCOMPARE(unit.dbusAdapter->discoverableTimeout(), value); } } void AdapterTest::setPairableTest() { - Q_FOREACH (const AdapterUnit &unit, m_units) { + for (const AdapterUnit &unit : m_units) { QSignalSpy adapterSpy(unit.adapter.data(), SIGNAL(pairableChanged(bool))); QSignalSpy dbusSpy(unit.dbusProperties, SIGNAL(PropertiesChanged(QString,QVariantMap,QStringList))); bool value = !unit.adapter->isPairable(); unit.adapter->setPairable(value); QTRY_COMPARE(adapterSpy.count(), 1); QList adapterArguments = adapterSpy.takeFirst(); QCOMPARE(adapterArguments.at(0).toBool(), value); Autotests::verifyPropertiesChangedSignal(dbusSpy, QStringLiteral("Pairable"), value); QCOMPARE(unit.adapter->isPairable(), value); QCOMPARE(unit.dbusAdapter->pairable(), value); } } void AdapterTest::setPairableTimeoutTest() { - Q_FOREACH (const AdapterUnit &unit, m_units) { + for (const AdapterUnit &unit : m_units) { QSignalSpy adapterSpy(unit.adapter.data(), SIGNAL(pairableTimeoutChanged(quint32))); QSignalSpy dbusSpy(unit.dbusProperties, SIGNAL(PropertiesChanged(QString,QVariantMap,QStringList))); quint32 value = unit.adapter->pairableTimeout() + 1; unit.adapter->setPairableTimeout(value); QTRY_COMPARE(adapterSpy.count(), 1); QVERIFY(dbusSpy.count() >= 1); Autotests::verifyPropertiesChangedSignal(dbusSpy, QStringLiteral("PairableTimeout"), value); QList adapterArguments = adapterSpy.takeFirst(); QCOMPARE(adapterArguments.at(0).toUInt(), value); QCOMPARE(unit.adapter->pairableTimeout(), value); QCOMPARE(unit.dbusAdapter->pairableTimeout(), value); } } void AdapterTest::discoveryTest() { // Discovery needs Adapter powered on - Q_FOREACH (const AdapterUnit &unit, m_units) { + for (const AdapterUnit &unit : m_units) { // Make sure the Adapter is powered on and not discovering unit.adapter->setPowered(true)->waitForFinished(); if (unit.adapter->isDiscovering()) { unit.adapter->stopDiscovery()->waitForFinished(); } QSignalSpy adapterSpy(unit.adapter.data(), SIGNAL(discoveringChanged(bool))); QSignalSpy dbusSpy(unit.dbusProperties, SIGNAL(PropertiesChanged(QString,QVariantMap,QStringList))); // Start Discovery unit.adapter->startDiscovery(); QTRY_COMPARE(adapterSpy.count(), 1); QVERIFY(dbusSpy.count() >= 1); Autotests::verifyPropertiesChangedSignal(dbusSpy, QStringLiteral("Discovering"), true); QList adapterArguments = adapterSpy.takeFirst(); QCOMPARE(adapterArguments.at(0).toBool(), true); QCOMPARE(unit.adapter->isDiscovering(), true); QCOMPARE(unit.dbusAdapter->discovering(), true); adapterSpy.clear(); dbusSpy.clear(); // Stop Discovery unit.adapter->stopDiscovery(); QTRY_COMPARE(adapterSpy.count(), 1); QVERIFY(dbusSpy.count() >= 1); Autotests::verifyPropertiesChangedSignal(dbusSpy, QStringLiteral("Discovering"), false); adapterArguments = adapterSpy.takeFirst(); QCOMPARE(adapterArguments.at(0).toBool(), false); QCOMPARE(unit.adapter->isDiscovering(), false); QCOMPARE(unit.dbusAdapter->discovering(), false); } } void AdapterTest::removeDeviceTest() { - Q_FOREACH (const AdapterUnit &unit, m_units) { + for (const AdapterUnit &unit : m_units) { while (!unit.adapter->devices().isEmpty()) { DevicePtr device = unit.adapter->devices().first(); QSignalSpy managerSpy(m_manager, SIGNAL(deviceRemoved(DevicePtr))); QSignalSpy adapterSpy(unit.adapter.data(), SIGNAL(deviceRemoved(DevicePtr))); QSignalSpy deviceSpy(device.data(), SIGNAL(deviceRemoved(DevicePtr))); unit.adapter->removeDevice(device); QTRY_COMPARE(managerSpy.count(), 1); QTRY_COMPARE(adapterSpy.count(), 1); QTRY_COMPARE(deviceSpy.count(), 1); QCOMPARE(managerSpy.at(0).at(0).value(), device); QCOMPARE(adapterSpy.at(0).at(0).value(), device); QCOMPARE(deviceSpy.at(0).at(0).value(), device); } } } void AdapterTest::adapterRemovedTest() { - Q_FOREACH (const AdapterUnit &unit, m_units) { + for (const AdapterUnit &unit : m_units) { QSignalSpy managerSpy(m_manager, SIGNAL(adapterRemoved(AdapterPtr))); QSignalSpy adapterSpy(unit.adapter.data(), SIGNAL(adapterRemoved(AdapterPtr))); QVariantMap properties; properties[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath(unit.adapter->ubi())); FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("remove-adapter"), properties); QTRY_COMPARE(managerSpy.count(), 1); QTRY_COMPARE(adapterSpy.count(), 1); QCOMPARE(managerSpy.at(0).at(0).value(), unit.adapter); QCOMPARE(adapterSpy.at(0).at(0).value(), unit.adapter); } } QTEST_MAIN(AdapterTest) diff --git a/autotests/devicetest.cpp b/autotests/devicetest.cpp index b1767fc..59e43e0 100644 --- a/autotests/devicetest.cpp +++ b/autotests/devicetest.cpp @@ -1,283 +1,283 @@ /* * Copyright (C) 2014-2015 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "devicetest.h" #include "autotests.h" #include "pendingcall.h" #include "initmanagerjob.h" #include #include namespace BluezQt { extern void bluezqt_initFakeBluezTestRun(); } using namespace BluezQt; DeviceTest::DeviceTest() : m_manager(nullptr) { Autotests::registerMetatypes(); } void DeviceTest::initTestCase() { QDBusConnection connection = QDBusConnection::sessionBus(); QString service = QStringLiteral("org.kde.bluezqt.fakebluez"); bluezqt_initFakeBluezTestRun(); FakeBluez::start(); FakeBluez::runTest(QStringLiteral("bluez-standard")); // Create adapters QDBusObjectPath adapter1 = QDBusObjectPath(QStringLiteral("/org/bluez/hci0")); QVariantMap adapterProps; adapterProps[QStringLiteral("Path")] = QVariant::fromValue(adapter1); adapterProps[QStringLiteral("Address")] = QStringLiteral("1C:E5:C3:BC:94:7E"); adapterProps[QStringLiteral("Name")] = QStringLiteral("TestAdapter"); FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-adapter"), adapterProps); QDBusObjectPath adapter2 = QDBusObjectPath(QStringLiteral("/org/bluez/hci1")); adapterProps[QStringLiteral("Path")] = QVariant::fromValue(adapter2); adapterProps[QStringLiteral("Address")] = QStringLiteral("2E:3A:C3:BC:85:7C"); adapterProps[QStringLiteral("Name")] = QStringLiteral("TestAdapter2"); FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-adapter"), adapterProps); // Create devices QVariantMap deviceProps; deviceProps[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath("/org/bluez/hci0/dev_40_79_6A_0C_39_75")); deviceProps[QStringLiteral("Adapter")] = QVariant::fromValue(QDBusObjectPath("/org/bluez/hci0")); deviceProps[QStringLiteral("Address")] = QStringLiteral("40:79:6A:0C:39:75"); deviceProps[QStringLiteral("Name")] = QStringLiteral("TestDevice"); deviceProps[QStringLiteral("Alias")] = QStringLiteral("TestAlias"); deviceProps[QStringLiteral("Icon")] = QStringLiteral("phone"); deviceProps[QStringLiteral("Class")] = QVariant::fromValue(quint32(101)); deviceProps[QStringLiteral("Appearance")] = QVariant::fromValue(quint16(25)); deviceProps[QStringLiteral("UUIDs")] = QStringList(); deviceProps[QStringLiteral("Paired")] = false; deviceProps[QStringLiteral("Connected")] = false; deviceProps[QStringLiteral("Trusted")] = false; deviceProps[QStringLiteral("Blocked")] = false; deviceProps[QStringLiteral("LegacyPairing")] = false; deviceProps[QStringLiteral("RSSI")] = QVariant::fromValue(qint16(20)); deviceProps[QStringLiteral("Modalias")] = QStringLiteral("bluetooth:v001Dp1200d1236"); FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-device"), deviceProps); deviceProps[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath("/org/bluez/hci1/dev_50_79_6A_0C_39_75")); deviceProps[QStringLiteral("Adapter")] = QVariant::fromValue(QDBusObjectPath("/org/bluez/hci1")); deviceProps[QStringLiteral("Address")] = QStringLiteral("50:79:6A:0C:39:75"); deviceProps[QStringLiteral("Name")] = QStringLiteral("TestDevice2"); deviceProps[QStringLiteral("Alias")] = QStringLiteral("TestAlias2"); deviceProps[QStringLiteral("Icon")] = QStringLiteral("joypad"); deviceProps[QStringLiteral("Class")] = QVariant::fromValue(quint32(201)); deviceProps[QStringLiteral("Appearance")] = QVariant::fromValue(quint16(32)); deviceProps[QStringLiteral("UUIDs")] = QStringList(); deviceProps[QStringLiteral("Paired")] = true; deviceProps[QStringLiteral("Connected")] = false; deviceProps[QStringLiteral("Trusted")] = true; deviceProps[QStringLiteral("Blocked")] = false; deviceProps[QStringLiteral("LegacyPairing")] = false; deviceProps[QStringLiteral("RSSI")] = QVariant::fromValue(qint16(-15)); deviceProps[QStringLiteral("Modalias")] = QStringLiteral("bluetooth:v001Dp1100d1236"); FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-device"), deviceProps); m_manager = new Manager(); InitManagerJob *initJob = m_manager->init(); initJob->exec(); QVERIFY(!initJob->error()); - Q_FOREACH (const AdapterPtr &adapter, m_manager->adapters()) { + for (const AdapterPtr &adapter : m_manager->adapters()) { QVERIFY(!adapter->ubi().isEmpty()); - Q_FOREACH (const DevicePtr &device, adapter->devices()) { + for (const DevicePtr &device : adapter->devices()) { QVERIFY(!device->ubi().isEmpty()); DeviceUnit u; u.device = device; u.dbusDevice = new org::bluez::Device1(service, device->ubi(), connection, this); u.dbusProperties = new org::freedesktop::DBus::Properties(service, device->ubi(), connection, this); m_units.append(u); } } QCOMPARE(m_manager->adapters().count(), 2); QCOMPARE(m_manager->devices().count(), 2); } void DeviceTest::cleanupTestCase() { - Q_FOREACH (const DeviceUnit &unit, m_units) { + for (const DeviceUnit &unit : m_units) { delete unit.dbusDevice; delete unit.dbusProperties; } delete m_manager; FakeBluez::stop(); } static void compareUuids(const QStringList &actual, const QStringList &expected) { QCOMPARE(actual.size(), expected.size()); for (int i = 0; i < actual.size(); ++i) { QCOMPARE(actual.at(i).toUpper(), expected.at(i).toUpper()); } } void DeviceTest::getPropertiesTest() { - Q_FOREACH (const DeviceUnit &unit, m_units) { + for (const DeviceUnit &unit : m_units) { QCOMPARE(unit.device->ubi(), unit.dbusDevice->path()); QCOMPARE(unit.device->address(), unit.dbusDevice->address()); QCOMPARE(unit.device->name(), unit.dbusDevice->alias()); QCOMPARE(unit.device->remoteName(), unit.dbusDevice->name()); QCOMPARE(unit.device->deviceClass(), unit.dbusDevice->deviceClass()); QCOMPARE(unit.device->appearance(), unit.dbusDevice->appearance()); QCOMPARE(unit.device->icon(), deviceIcon(unit.dbusDevice)); QCOMPARE(unit.device->isPaired(), unit.dbusDevice->paired()); QCOMPARE(unit.device->isTrusted(), unit.dbusDevice->trusted()); QCOMPARE(unit.device->isBlocked(), unit.dbusDevice->blocked()); QCOMPARE(unit.device->hasLegacyPairing(), unit.dbusDevice->legacyPairing()); QCOMPARE(unit.device->rssi(), deviceRssi(unit.dbusDevice)); QCOMPARE(unit.device->isConnected(), unit.dbusDevice->connected()); QCOMPARE(unit.device->modalias(), unit.dbusDevice->modalias()); QCOMPARE(unit.device->adapter()->ubi(), unit.dbusDevice->adapter().path()); compareUuids(unit.device->uuids(), unit.dbusDevice->uUIDs()); } } void DeviceTest::setAliasTest() { - Q_FOREACH (const DeviceUnit &unit, m_units) { + for (const DeviceUnit &unit : m_units) { QSignalSpy deviceSpy(unit.device.data(), SIGNAL(nameChanged(QString))); QSignalSpy dbusSpy(unit.dbusProperties, SIGNAL(PropertiesChanged(QString,QVariantMap,QStringList))); QString value = unit.device->name() + QLatin1String("_tst_alias"); unit.device->setName(value); QTRY_COMPARE(deviceSpy.count(), 1); QList arguments = deviceSpy.takeFirst(); QCOMPARE(arguments.at(0).toString(), value); Autotests::verifyPropertiesChangedSignal(dbusSpy, QStringLiteral("Alias"), value); QCOMPARE(unit.device->name(), value); QCOMPARE(unit.dbusDevice->alias(), value); } } void DeviceTest::setTrustedTest() { - Q_FOREACH (const DeviceUnit &unit, m_units) { + for (const DeviceUnit &unit : m_units) { QSignalSpy deviceSpy(unit.device.data(), SIGNAL(trustedChanged(bool))); QSignalSpy dbusSpy(unit.dbusProperties, SIGNAL(PropertiesChanged(QString,QVariantMap,QStringList))); bool value = !unit.device->isTrusted(); unit.device->setTrusted(value); QTRY_COMPARE(deviceSpy.count(), 1); QList arguments = deviceSpy.takeFirst(); QCOMPARE(arguments.at(0).toBool(), value); Autotests::verifyPropertiesChangedSignal(dbusSpy, QStringLiteral("Trusted"), value); QCOMPARE(unit.device->isTrusted(), value); QCOMPARE(unit.dbusDevice->trusted(), value); } } void DeviceTest::setBlockedTest() { - Q_FOREACH (const DeviceUnit &unit, m_units) { + for (const DeviceUnit &unit : m_units) { QSignalSpy deviceSpy(unit.device.data(), SIGNAL(blockedChanged(bool))); QSignalSpy dbusSpy(unit.dbusProperties, SIGNAL(PropertiesChanged(QString,QVariantMap,QStringList))); bool value = !unit.device->isBlocked(); unit.device->setBlocked(value); QTRY_COMPARE(deviceSpy.count(), 1); QList arguments = deviceSpy.takeFirst(); QCOMPARE(arguments.at(0).toBool(), value); Autotests::verifyPropertiesChangedSignal(dbusSpy, QStringLiteral("Blocked"), value); QCOMPARE(unit.device->isBlocked(), value); QCOMPARE(unit.dbusDevice->blocked(), value); } } void DeviceTest::deviceRemovedTest() { - Q_FOREACH (const DeviceUnit &unit, m_units) { + for (const DeviceUnit &unit : m_units) { QSignalSpy managerSpy(m_manager, SIGNAL(deviceRemoved(DevicePtr))); QSignalSpy adapterSpy(unit.device->adapter().data(), SIGNAL(deviceRemoved(DevicePtr))); QSignalSpy deviceSpy(unit.device.data(), SIGNAL(deviceRemoved(DevicePtr))); QVariantMap properties; properties[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath(unit.device->ubi())); FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("remove-device"), properties); QTRY_COMPARE(managerSpy.count(), 1); QTRY_COMPARE(adapterSpy.count(), 1); QTRY_COMPARE(deviceSpy.count(), 1); QCOMPARE(managerSpy.at(0).at(0).value(), unit.device); QCOMPARE(adapterSpy.at(0).at(0).value(), unit.device); QCOMPARE(deviceSpy.at(0).at(0).value(), unit.device); } } QString DeviceTest::deviceIcon(org::bluez::Device1 *device) const { quint32 classNum = device->deviceClass(); switch ((classNum & 0x1f00) >> 8) { case 0x04: switch ((classNum & 0xfc) >> 2) { case 0x01: case 0x02: return QStringLiteral("audio-headset"); case 0x06: return QStringLiteral("audio-headphones"); } } return device->icon(); } qint16 DeviceTest::deviceRssi(org::bluez::Device1 *device) const { qint16 rssi = device->rSSI(); if (!rssi) { rssi = -32768; } return rssi; } QTEST_MAIN(DeviceTest) diff --git a/autotests/fakebluez/objectmanager.cpp b/autotests/fakebluez/objectmanager.cpp index 6621e7b..15938ff 100644 --- a/autotests/fakebluez/objectmanager.cpp +++ b/autotests/fakebluez/objectmanager.cpp @@ -1,95 +1,95 @@ /* * Copyright (C) 2014-2015 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "objectmanager.h" #include "object.h" #include #include ObjectManager *s_instance = nullptr; ObjectManager::ObjectManager(QObject *parent) : QDBusAbstractAdaptor(parent) { s_instance = this; qDBusRegisterMetaType(); qDBusRegisterMetaType(); QDBusConnection::sessionBus().registerObject(QStringLiteral("/org/bluez"), this); } ObjectManager::~ObjectManager() { s_instance = nullptr; qDeleteAll(m_autoDeleteObjects); } void ObjectManager::addObject(Object *object) { m_objects.insert(object->path().path(), object); QVariantMapMap interfaces; interfaces.insert(object->name(), object->properties()); Q_EMIT InterfacesAdded(object->path(), interfaces); } void ObjectManager::removeObject(Object *object) { m_objects.remove(object->path().path()); m_autoDeleteObjects.removeOne(object->objectParent()); Q_EMIT InterfacesRemoved(object->path(), QStringList(object->name())); delete object->objectParent(); } void ObjectManager::addAutoDeleteObject(QObject *object) { m_autoDeleteObjects.append(object); } Object *ObjectManager::objectByPath(const QDBusObjectPath &path) const { return m_objects.value(path.path()); } ObjectManager *ObjectManager::self() { return s_instance; } DBusManagerStruct ObjectManager::GetManagedObjects() { DBusManagerStruct objects; - Q_FOREACH (Object *object, m_objects.values()) { + for (Object *object : m_objects.values()) { if (objects.value(object->path()).isEmpty()) { objects[object->path()].insert(QStringLiteral("org.freedesktop.DBus.Introspectable"), QVariantMap()); if (object->haveProperties()) { objects[object->path()].insert(QStringLiteral("org.freedesktop.DBus.Properties"), QVariantMap()); } } objects[object->path()].insert(object->name(), object->properties()); } return objects; } diff --git a/autotests/inputtest.cpp b/autotests/inputtest.cpp index ba0918b..c770398 100644 --- a/autotests/inputtest.cpp +++ b/autotests/inputtest.cpp @@ -1,161 +1,161 @@ /* * Copyright (C) 2014-2015 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "inputtest.h" #include "autotests.h" #include "pendingcall.h" #include "initmanagerjob.h" #include #include namespace BluezQt { extern void bluezqt_initFakeBluezTestRun(); } using namespace BluezQt; Q_DECLARE_METATYPE(Input::ReconnectMode) InputTest::InputTest() : m_manager(nullptr) { Autotests::registerMetatypes(); qRegisterMetaType("ReconnectMode"); } void InputTest::initTestCase() { QDBusConnection connection = QDBusConnection::sessionBus(); QString service = QStringLiteral("org.kde.bluezqt.fakebluez"); bluezqt_initFakeBluezTestRun(); FakeBluez::start(); FakeBluez::runTest(QStringLiteral("bluez-standard")); // Create adapter QString adapter = QStringLiteral("/org/bluez/hci0"); QVariantMap adapterProps; adapterProps[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath(adapter)); adapterProps[QStringLiteral("Address")] = QStringLiteral("1C:E5:C3:BC:94:7E"); adapterProps[QStringLiteral("Name")] = QStringLiteral("TestAdapter"); FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-adapter"), adapterProps); // Create devices QVariantMap deviceProps; QVariantMap inputProps; QString device1 = adapter + QLatin1String("/dev_40_79_6A_0C_39_75"); deviceProps[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath(device1)); deviceProps[QStringLiteral("Adapter")] = QVariant::fromValue(QDBusObjectPath(adapter)); deviceProps[QStringLiteral("Address")] = QStringLiteral("40:79:6A:0C:39:75"); deviceProps[QStringLiteral("Name")] = QStringLiteral("TestDevice"); deviceProps[QStringLiteral("UUIDs")] = QStringList(QStringLiteral("00001124-0000-1000-8000-00805F9B34FB")); inputProps[QStringLiteral("ReconnectMode")] = QStringLiteral("none"); deviceProps[QStringLiteral("Input")] = inputProps; FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-device"), deviceProps); QString device2 = adapter + QLatin1String("/dev_50_79_6A_0C_39_75"); deviceProps[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath(device2)); deviceProps[QStringLiteral("Adapter")] = QVariant::fromValue(QDBusObjectPath(adapter)); deviceProps[QStringLiteral("Address")] = QStringLiteral("50:79:6A:0C:39:75"); deviceProps[QStringLiteral("Name")] = QStringLiteral("TestDevice2"); deviceProps[QStringLiteral("UUIDs")] = QStringList(QStringLiteral("00001124-0000-1000-8000-00805F9B34FB")); inputProps[QStringLiteral("ReconnectMode")] = QStringLiteral("host"); deviceProps[QStringLiteral("Input")] = inputProps; FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-device"), deviceProps); QString device3 = adapter + QLatin1String("/dev_60_79_6B_0C_39_55"); deviceProps[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath(device3)); deviceProps[QStringLiteral("Adapter")] = QVariant::fromValue(QDBusObjectPath(adapter)); deviceProps[QStringLiteral("Address")] = QStringLiteral("60:79:6B:0C:39:55"); deviceProps[QStringLiteral("Name")] = QStringLiteral("TestDevice3"); deviceProps[QStringLiteral("UUIDs")] = QStringList(QStringLiteral("00001124-0000-1000-8000-00805F9B34FB")); inputProps[QStringLiteral("ReconnectMode")] = QStringLiteral("device"); deviceProps[QStringLiteral("Input")] = inputProps; FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-device"), deviceProps); QString device4 = adapter + QLatin1String("/dev_70_79_6B_0C_39_55"); deviceProps[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath(device4)); deviceProps[QStringLiteral("Adapter")] = QVariant::fromValue(QDBusObjectPath(adapter)); deviceProps[QStringLiteral("Address")] = QStringLiteral("70:79:6B:0C:39:55"); deviceProps[QStringLiteral("Name")] = QStringLiteral("TestDevice4"); deviceProps[QStringLiteral("UUIDs")] = QStringList(QStringLiteral("00001124-0000-1000-8000-00805F9B34FB")); inputProps[QStringLiteral("ReconnectMode")] = QStringLiteral("any"); deviceProps[QStringLiteral("Input")] = inputProps; FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-device"), deviceProps); m_manager = new Manager(); InitManagerJob *initJob = m_manager->init(); initJob->exec(); QVERIFY(!initJob->error()); - Q_FOREACH (DevicePtr device, m_manager->devices()) { + for (DevicePtr device : m_manager->devices()) { QVERIFY(device->input()); InputUnit u; u.device = device; u.dbusInput = new org::bluez::Input1(service, device->ubi(), connection, this); m_units.append(u); } QCOMPARE(m_manager->adapters().count(), 1); QCOMPARE(m_manager->devices().count(), 4); } void InputTest::cleanupTestCase() { - Q_FOREACH (const InputUnit &unit, m_units) { + for (const InputUnit &unit : m_units) { delete unit.dbusInput; } delete m_manager; FakeBluez::stop(); } void InputTest::getPropertiesTest() { - Q_FOREACH (const InputUnit &unit, m_units) { + for (const InputUnit &unit : m_units) { QCOMPARE(reconnectModeString(unit.device->input()), unit.dbusInput->reconnectMode()); } } QString InputTest::reconnectModeString(const InputPtr &input) const { switch (input->reconnectMode()) { case Input::NoReconnect: return QStringLiteral("none"); case Input::HostReconnect: return QStringLiteral("host"); case Input::DeviceReconnect: return QStringLiteral("device"); default: return QStringLiteral("any"); } } QTEST_MAIN(InputTest) diff --git a/autotests/mediaplayertest.cpp b/autotests/mediaplayertest.cpp index 35bf633..e5a31f3 100644 --- a/autotests/mediaplayertest.cpp +++ b/autotests/mediaplayertest.cpp @@ -1,436 +1,436 @@ /* * Copyright (C) 2014-2015 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "mediaplayertest.h" #include "autotests.h" #include "pendingcall.h" #include "initmanagerjob.h" #include "services.h" #include #include namespace BluezQt { extern void bluezqt_initFakeBluezTestRun(); } using namespace BluezQt; Q_DECLARE_METATYPE(MediaPlayer::Equalizer) Q_DECLARE_METATYPE(MediaPlayer::Repeat) Q_DECLARE_METATYPE(MediaPlayer::Shuffle) Q_DECLARE_METATYPE(MediaPlayer::Status) MediaPlayerTest::MediaPlayerTest() : m_manager(nullptr) { Autotests::registerMetatypes(); qRegisterMetaType("Equalizer"); qRegisterMetaType("Repeat"); qRegisterMetaType("Shuffle"); qRegisterMetaType("Status"); qRegisterMetaType("MediaPlayerTrack"); } void MediaPlayerTest::initTestCase() { bluezqt_initFakeBluezTestRun(); FakeBluez::start(); FakeBluez::runTest(QStringLiteral("bluez-standard")); // Create adapter QString adapter = QStringLiteral("/org/bluez/hci0"); QVariantMap adapterProps; adapterProps[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath(adapter)); adapterProps[QStringLiteral("Address")] = QStringLiteral("1C:E5:C3:BC:94:7E"); adapterProps[QStringLiteral("Name")] = QStringLiteral("TestAdapter"); FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-adapter"), adapterProps); // Create devices QVariantMap deviceProps; QVariantMap mediaPlayerProps; QVariantMap trackProps; QString device1 = adapter + QLatin1String("/dev_40_79_6A_0C_39_75"); deviceProps[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath(device1)); deviceProps[QStringLiteral("Adapter")] = QVariant::fromValue(QDBusObjectPath(adapter)); deviceProps[QStringLiteral("Address")] = QStringLiteral("40:79:6A:0C:39:75"); deviceProps[QStringLiteral("Name")] = QStringLiteral("TestDevice"); deviceProps[QStringLiteral("UUIDs")] = QStringList(QStringLiteral("0000110E-0000-1000-8000-00805F9B34FB")); mediaPlayerProps[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath(device1 + QLatin1String("/player0"))); mediaPlayerProps[QStringLiteral("Name")] = QStringLiteral("Player1"); mediaPlayerProps[QStringLiteral("Equalizer")] = QStringLiteral("on"); mediaPlayerProps[QStringLiteral("Repeat")] = QStringLiteral("singletrack"); mediaPlayerProps[QStringLiteral("Shuffle")] = QStringLiteral("group"); mediaPlayerProps[QStringLiteral("Status")] = QStringLiteral("stopped"); mediaPlayerProps[QStringLiteral("Position")] = QVariant::fromValue(quint32(150)); mediaPlayerProps[QStringLiteral("Device")] = QVariant::fromValue(QDBusObjectPath(device1)); trackProps[QStringLiteral("Title")] = QStringLiteral("Song1"); trackProps[QStringLiteral("Artist")] = QStringLiteral("Band1"); trackProps[QStringLiteral("Album")] = QStringLiteral("First Album"); trackProps[QStringLiteral("Genre")] = QStringLiteral("Rock"); trackProps[QStringLiteral("NumberOfTracks")] = 24; trackProps[QStringLiteral("TrackNumber")] = 4; trackProps[QStringLiteral("Duration")] = 12403; mediaPlayerProps[QStringLiteral("Track")] = trackProps; deviceProps[QStringLiteral("MediaPlayer")] = mediaPlayerProps; FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-device"), deviceProps); QString device2 = adapter + QLatin1String("/dev_50_79_6A_0C_39_75"); deviceProps[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath(device2)); deviceProps[QStringLiteral("Adapter")] = QVariant::fromValue(QDBusObjectPath(adapter)); deviceProps[QStringLiteral("Address")] = QStringLiteral("50:79:6A:0C:39:75"); deviceProps[QStringLiteral("Name")] = QStringLiteral("TestDevice2"); deviceProps[QStringLiteral("UUIDs")] = QStringList(QStringLiteral("0000110E-0000-1000-8000-00805F9B34FB")); mediaPlayerProps[QStringLiteral("Path")] = QVariant::fromValue(QDBusObjectPath(device2 + QLatin1String("/player0"))); mediaPlayerProps[QStringLiteral("Name")] = QStringLiteral("Player2"); mediaPlayerProps[QStringLiteral("Equalizer")] = QStringLiteral("off"); mediaPlayerProps[QStringLiteral("Repeat")] = QStringLiteral("alltracks"); mediaPlayerProps[QStringLiteral("Shuffle")] = QStringLiteral("off"); mediaPlayerProps[QStringLiteral("Status")] = QStringLiteral("paused"); mediaPlayerProps[QStringLiteral("Position")] = QVariant::fromValue(quint32(2500)); mediaPlayerProps[QStringLiteral("Device")] = QVariant::fromValue(QDBusObjectPath(device2)); trackProps[QStringLiteral("Title")] = QStringLiteral("Song2"); trackProps[QStringLiteral("Artist")] = QStringLiteral("Band2"); trackProps[QStringLiteral("Album")] = QStringLiteral("Second Album"); trackProps[QStringLiteral("Genre")] = QStringLiteral("Heavy Metal"); trackProps[QStringLiteral("NumberOfTracks")] = 666; trackProps[QStringLiteral("TrackNumber")] = 22; trackProps[QStringLiteral("Duration")] = 22403; mediaPlayerProps[QStringLiteral("Track")] = trackProps; deviceProps[QStringLiteral("MediaPlayer")] = mediaPlayerProps; FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("create-device"), deviceProps); m_manager = new Manager(); InitManagerJob *initJob = m_manager->init(); initJob->exec(); QVERIFY(!initJob->error()); QCOMPARE(m_manager->adapters().count(), 1); QCOMPARE(m_manager->devices().count(), 2); } void MediaPlayerTest::cleanupTestCase() { - Q_FOREACH (const MediaPlayerUnit &unit, m_units) { + for (const MediaPlayerUnit &unit : m_units) { delete unit.dbusMediaPlayer; delete unit.dbusProperties; } delete m_manager; FakeBluez::stop(); } void MediaPlayerTest::connectTest() { - Q_FOREACH (DevicePtr device, m_manager->devices()) { + for (DevicePtr device : m_manager->devices()) { QVERIFY(!device->ubi().isEmpty()); QVERIFY(!device->mediaPlayer()); QSignalSpy deviceSpy(device.data(), SIGNAL(mediaPlayerChanged(MediaPlayerPtr))); device->connectToDevice(); QTRY_COMPARE(deviceSpy.count(), 1); QVERIFY(device->mediaPlayer()); } } void MediaPlayerTest::disconnectTest() { - Q_FOREACH (DevicePtr device, m_manager->devices()) { + for (DevicePtr device : m_manager->devices()) { QVERIFY(device->mediaPlayer()); QSignalSpy deviceSpy(device.data(), SIGNAL(mediaPlayerChanged(MediaPlayerPtr))); device->disconnectFromDevice(); QTRY_COMPARE(deviceSpy.count(), 1); QVERIFY(!device->mediaPlayer()); } } void MediaPlayerTest::connectProfileTest() { QDBusConnection connection = QDBusConnection::sessionBus(); QString service = QStringLiteral("org.kde.bluezqt.fakebluez"); - Q_FOREACH (DevicePtr device, m_manager->devices()) { + for (DevicePtr device : m_manager->devices()) { QVERIFY(!device->ubi().isEmpty()); QVERIFY(!device->mediaPlayer()); QSignalSpy deviceSpy(device.data(), SIGNAL(mediaPlayerChanged(MediaPlayerPtr))); device->connectProfile(Services::AudioVideoRemoteControl); QTRY_COMPARE(deviceSpy.count(), 1); QVERIFY(device->mediaPlayer()); QString path = device->ubi() + QLatin1String("/player0"); MediaPlayerUnit u; u.device = device; u.dbusMediaPlayer = new org::bluez::MediaPlayer1(service, path, connection, this); u.dbusProperties = new org::freedesktop::DBus::Properties(service, path, connection, this); m_units.append(u); } } void MediaPlayerTest::getPropertiesTest() { - Q_FOREACH (const MediaPlayerUnit &unit, m_units) { + for (const MediaPlayerUnit &unit : m_units) { QCOMPARE(unit.device->mediaPlayer()->name(), unit.dbusMediaPlayer->name()); QCOMPARE(equalizerString(unit.device->mediaPlayer()), unit.dbusMediaPlayer->equalizer()); QCOMPARE(repeatString(unit.device->mediaPlayer()), unit.dbusMediaPlayer->repeat()); QCOMPARE(shuffleString(unit.device->mediaPlayer()), unit.dbusMediaPlayer->shuffle()); QCOMPARE(statusString(unit.device->mediaPlayer()), unit.dbusMediaPlayer->status()); QCOMPARE(trackMap(unit.device->mediaPlayer()), unit.dbusMediaPlayer->track()); QCOMPARE(unit.device->mediaPlayer()->position(), unit.dbusMediaPlayer->position()); } } void MediaPlayerTest::setEqualizerTest() { - Q_FOREACH (const MediaPlayerUnit &unit, m_units) { + for (const MediaPlayerUnit &unit : m_units) { MediaPlayerPtr mediaPlayer = unit.device->mediaPlayer(); MediaPlayer::Equalizer value = mediaPlayer->equalizer() == MediaPlayer::EqualizerOff ? MediaPlayer::EqualizerOn : MediaPlayer::EqualizerOff; QSignalSpy equalizerSpy(mediaPlayer.data(), SIGNAL(equalizerChanged(Equalizer))); mediaPlayer->setEqualizer(value); QTRY_COMPARE(equalizerSpy.count(), 1); QCOMPARE(equalizerSpy.at(0).at(0).value(), value); QCOMPARE(mediaPlayer->equalizer(), value); } } void MediaPlayerTest::setRepeatTest() { - Q_FOREACH (const MediaPlayerUnit &unit, m_units) { + for (const MediaPlayerUnit &unit : m_units) { MediaPlayerPtr mediaPlayer = unit.device->mediaPlayer(); MediaPlayer::Repeat value = mediaPlayer->repeat() == MediaPlayer::RepeatGroup ? MediaPlayer::RepeatSingleTrack : MediaPlayer::RepeatGroup; QSignalSpy equalizerSpy(mediaPlayer.data(), SIGNAL(repeatChanged(Repeat))); mediaPlayer->setRepeat(value); QTRY_COMPARE(equalizerSpy.count(), 1); QCOMPARE(equalizerSpy.at(0).at(0).value(), value); QCOMPARE(mediaPlayer->repeat(), value); } } void MediaPlayerTest::setShuffleTest() { - Q_FOREACH (const MediaPlayerUnit &unit, m_units) { + for (const MediaPlayerUnit &unit : m_units) { MediaPlayerPtr mediaPlayer = unit.device->mediaPlayer(); MediaPlayer::Shuffle value = mediaPlayer->shuffle() == MediaPlayer::ShuffleAllTracks ? MediaPlayer::ShuffleOff : MediaPlayer::ShuffleAllTracks; QSignalSpy equalizerSpy(mediaPlayer.data(), SIGNAL(shuffleChanged(Shuffle))); mediaPlayer->setShuffle(value); QTRY_COMPARE(equalizerSpy.count(), 1); QCOMPARE(equalizerSpy.at(0).at(0).value(), value); QCOMPARE(mediaPlayer->shuffle(), value); } } void MediaPlayerTest::changeStatusTest() { - Q_FOREACH (const MediaPlayerUnit &unit, m_units) { + for (const MediaPlayerUnit &unit : m_units) { MediaPlayerPtr mediaPlayer = unit.device->mediaPlayer(); QSignalSpy statusSpy(mediaPlayer.data(), SIGNAL(statusChanged(Status))); if (mediaPlayer->status() != MediaPlayer::Stopped) { mediaPlayer->stop(); QTRY_COMPARE(statusSpy.count(), 1); QCOMPARE(statusSpy.at(0).at(0).value(), MediaPlayer::Stopped); QCOMPARE(mediaPlayer->status(), MediaPlayer::Stopped); } statusSpy.clear(); mediaPlayer->play(); QTRY_COMPARE(statusSpy.count(), 1); QCOMPARE(statusSpy.at(0).at(0).value(), MediaPlayer::Playing); QCOMPARE(mediaPlayer->status(), MediaPlayer::Playing); statusSpy.clear(); mediaPlayer->pause(); QTRY_COMPARE(statusSpy.count(), 1); QCOMPARE(statusSpy.at(0).at(0).value(), MediaPlayer::Paused); QCOMPARE(mediaPlayer->status(), MediaPlayer::Paused); statusSpy.clear(); mediaPlayer->fastForward(); QTRY_COMPARE(statusSpy.count(), 1); QCOMPARE(statusSpy.at(0).at(0).value(), MediaPlayer::ForwardSeek); QCOMPARE(mediaPlayer->status(), MediaPlayer::ForwardSeek); statusSpy.clear(); mediaPlayer->rewind(); QTRY_COMPARE(statusSpy.count(), 1); QCOMPARE(statusSpy.at(0).at(0).value(), MediaPlayer::ReverseSeek); QCOMPARE(mediaPlayer->status(), MediaPlayer::ReverseSeek); statusSpy.clear(); mediaPlayer->stop(); QTRY_COMPARE(statusSpy.count(), 1); QCOMPARE(statusSpy.at(0).at(0).value(), MediaPlayer::Stopped); QCOMPARE(mediaPlayer->status(), MediaPlayer::Stopped); } } void MediaPlayerTest::changeTrackTest() { - Q_FOREACH (const MediaPlayerUnit &unit, m_units) { + for (const MediaPlayerUnit &unit : m_units) { MediaPlayerPtr mediaPlayer = unit.device->mediaPlayer(); QSignalSpy trackSpy(mediaPlayer.data(), SIGNAL(trackChanged(MediaPlayerTrack))); trackSpy.clear(); mediaPlayer->next(); QTRY_COMPARE(trackSpy.count(), 1); QCOMPARE(mediaPlayer->track().isValid(), true); trackSpy.clear(); mediaPlayer->previous(); QTRY_COMPARE(trackSpy.count(), 1); QCOMPARE(mediaPlayer->track().isValid(), true); } } void MediaPlayerTest::disconnectProfileTest() { - Q_FOREACH (const MediaPlayerUnit &unit, m_units) { + for (const MediaPlayerUnit &unit : m_units) { QVERIFY(unit.device->mediaPlayer()); QSignalSpy deviceSpy(unit.device.data(), SIGNAL(mediaPlayerChanged(MediaPlayerPtr))); unit.device->disconnectProfile(Services::AudioVideoRemoteControl); QTRY_COMPARE(deviceSpy.count(), 1); QVERIFY(!unit.device->mediaPlayer()); } } void MediaPlayerTest::bug403289() { // Bug 403289: MediaPlayer interface path is not checked in InterfacesRemoved signal QDBusConnection connection = QDBusConnection::sessionBus(); QString service = QStringLiteral("org.kde.bluezqt.fakebluez"); - Q_FOREACH (DevicePtr device, m_manager->devices()) { + for (DevicePtr device : m_manager->devices()) { QVERIFY(!device->mediaPlayer()); QSignalSpy deviceSpy(device.data(), SIGNAL(mediaPlayerChanged(MediaPlayerPtr))); const QVariantMap props = { { QStringLiteral("DevicePath"), QVariant::fromValue(QDBusObjectPath(device->ubi())) } }; FakeBluez::runAction(QStringLiteral("devicemanager"), QStringLiteral("bug403289"), props); QTRY_COMPARE(deviceSpy.count(), 1); QVERIFY(deviceSpy.at(0).at(0).value()); QTest::qWait(100); QCOMPARE(deviceSpy.count(), 1); device->disconnectProfile(Services::AudioVideoRemoteControl); QTRY_COMPARE(deviceSpy.count(), 2); QVERIFY(!deviceSpy.at(1).at(0).value()); } } QString MediaPlayerTest::equalizerString(const MediaPlayerPtr &mediaPlayer) const { switch (mediaPlayer->equalizer()) { case MediaPlayer::EqualizerOn: return QStringLiteral("on"); default: return QStringLiteral("off"); } } QString MediaPlayerTest::repeatString(const MediaPlayerPtr &mediaPlayer) const { switch (mediaPlayer->repeat()) { case MediaPlayer::RepeatSingleTrack: return QStringLiteral("singletrack"); case MediaPlayer::RepeatAllTracks: return QStringLiteral("alltracks"); case MediaPlayer::RepeatGroup: return QStringLiteral("group"); default: return QStringLiteral("off"); } } QString MediaPlayerTest::shuffleString(const MediaPlayerPtr &mediaPlayer) const { switch (mediaPlayer->shuffle()) { case MediaPlayer::ShuffleAllTracks: return QStringLiteral("alltracks"); case MediaPlayer::ShuffleGroup: return QStringLiteral("group"); default: return QStringLiteral("off"); } } QString MediaPlayerTest::statusString(const MediaPlayerPtr &mediaPlayer) const { switch (mediaPlayer->status()) { case MediaPlayer::Playing: return QStringLiteral("playing"); case MediaPlayer::Stopped: return QStringLiteral("stopped"); case MediaPlayer::Paused: return QStringLiteral("paused"); case MediaPlayer::ForwardSeek: return QStringLiteral("forward-seek"); case MediaPlayer::ReverseSeek: return QStringLiteral("reverse-seek"); default: return QStringLiteral("error"); } } QVariantMap MediaPlayerTest::trackMap(const MediaPlayerPtr &mediaPlayer) const { QVariantMap out; if (!mediaPlayer->track().isValid()) { return out; } out[QStringLiteral("Title")] = mediaPlayer->track().title(); out[QStringLiteral("Artist")] = mediaPlayer->track().artist(); out[QStringLiteral("Album")] = mediaPlayer->track().album(); out[QStringLiteral("Genre")] = mediaPlayer->track().genre(); out[QStringLiteral("NumberOfTracks")] = mediaPlayer->track().numberOfTracks(); out[QStringLiteral("TrackNumber")] = mediaPlayer->track().trackNumber(); out[QStringLiteral("Duration")] = mediaPlayer->track().duration(); return out; } QTEST_MAIN(MediaPlayerTest) diff --git a/autotests/qmltests.cpp b/autotests/qmltests.cpp index 9b75d5f..60efc7e 100644 --- a/autotests/qmltests.cpp +++ b/autotests/qmltests.cpp @@ -1,108 +1,108 @@ /* * Copyright (C) 2015 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "autotests.h" #include #include #include // krazy:exclude=includes #include // krazy:exclude=includes class FakeBluezObject : public QObject { Q_OBJECT public Q_SLOTS: void start() { FakeBluez::start(); } void stop() { FakeBluez::stop(); } bool isRunning() { return FakeBluez::isRunning(); } void runTest(const QString &testName) { FakeBluez::runTest(testName); } static void processProperties(QVariantMap &properties) { const QStringList &toDBusObjectPath = properties.value(QStringLiteral("_toDBusObjectPath")).toStringList(); - Q_FOREACH (const QString &name, toDBusObjectPath) { + for (const QString &name : toDBusObjectPath) { const QString &val = properties.value(name).toString(); properties[name] = QVariant::fromValue(QDBusObjectPath(val)); } properties.remove(QStringLiteral("_toDBusObjectPath")); QMapIterator it(properties); while (it.hasNext()) { it.next(); if (it.key() == QLatin1String("UUIDs")) { properties[it.key()] = it.value().toStringList(); } else if (it.value().type() == QVariant::Map) { QVariantMap props = it.value().toMap(); processProperties(props); properties[it.key()] = props; } } } void runAction(const QString &object, const QString &actionName, QVariantMap properties = QVariantMap()) { processProperties(properties); FakeBluez::runAction(object, actionName, properties); } }; static QObject *fakebluez_singleton(QQmlEngine *engine, QJSEngine *scriptEngine) { Q_UNUSED(engine) Q_UNUSED(scriptEngine) return new FakeBluezObject; } namespace BluezQt { extern void bluezqt_initFakeBluezTestRun(); } int main(int argc, char *argv[]) { qmlRegisterSingletonType("org.kde.bluezqt.fakebluez", 1, 0, "FakeBluez", fakebluez_singleton); BluezQt::bluezqt_initFakeBluezTestRun(); qputenv("QML2_IMPORT_PATH", QByteArrayLiteral(BLUEZQT_QML_IMPORT_PATH)); const QString &testsDir = QFileInfo(QFINDTESTDATA("qml/tst_device.qml")).absolutePath(); return quick_test_main(argc, argv, "qmltests", testsDir.toUtf8().constData()); } #include "qmltests.moc" diff --git a/src/adapter.cpp b/src/adapter.cpp index 1feb0ed..c6b63bf 100644 --- a/src/adapter.cpp +++ b/src/adapter.cpp @@ -1,187 +1,187 @@ /* * BluezQt - Asynchronous Bluez wrapper library * * Copyright (C) 2014 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "adapter.h" #include "adapter_p.h" #include "device.h" #include "device_p.h" #include "pendingcall.h" namespace BluezQt { Adapter::Adapter(const QString &path, const QVariantMap &properties) : QObject() , d(new AdapterPrivate(path, properties)) { } Adapter::~Adapter() { delete d; } AdapterPtr Adapter::toSharedPtr() const { return d->q.toStrongRef(); } QString Adapter::ubi() const { return d->m_bluezAdapter->path(); } QString Adapter::address() const { return d->m_address; } QString Adapter::name() const { return d->m_alias; } PendingCall *Adapter::setName(const QString &name) { return new PendingCall(d->setDBusProperty(QStringLiteral("Alias"), name), PendingCall::ReturnVoid, this); } QString Adapter::systemName() const { return d->m_name; } quint32 Adapter::adapterClass() const { return d->m_adapterClass; } bool Adapter::isPowered() const { return d->m_powered; } PendingCall *Adapter::setPowered(bool powered) { return new PendingCall(d->setDBusProperty(QStringLiteral("Powered"), powered), PendingCall::ReturnVoid, this); } bool Adapter::isDiscoverable() const { return d->m_discoverable; } PendingCall *Adapter::setDiscoverable(bool discoverable) { return new PendingCall(d->setDBusProperty(QStringLiteral("Discoverable"), discoverable), PendingCall::ReturnVoid, this); } quint32 Adapter::discoverableTimeout() const { return d->m_discoverableTimeout; } PendingCall *Adapter::setDiscoverableTimeout(quint32 timeout) { return new PendingCall(d->setDBusProperty(QStringLiteral("DiscoverableTimeout"), timeout), PendingCall::ReturnVoid, this); } bool Adapter::isPairable() const { return d->m_pairable; } PendingCall *Adapter::setPairable(bool pairable) { return new PendingCall(d->setDBusProperty(QStringLiteral("Pairable"), pairable), PendingCall::ReturnVoid, this); } quint32 Adapter::pairableTimeout() const { return d->m_pairableTimeout; } PendingCall *Adapter::setPairableTimeout(quint32 timeout) { return new PendingCall(d->setDBusProperty(QStringLiteral("PairableTimeout"), timeout), PendingCall::ReturnVoid, this); } bool Adapter::isDiscovering() { return d->m_discovering; } QStringList Adapter::uuids() const { return d->m_uuids; } QString Adapter::modalias() const { return d->m_modalias; } MediaPtr Adapter::media() const { return d->m_media; } QList Adapter::devices() const { return d->m_devices; } DevicePtr Adapter::deviceForAddress(const QString &address) const { - Q_FOREACH (DevicePtr device, d->m_devices) { + for (DevicePtr device : qAsConst(d->m_devices)) { if (device->address() == address) { return device; } } return DevicePtr(); } PendingCall *Adapter::startDiscovery() { return new PendingCall(d->m_bluezAdapter->StartDiscovery(), PendingCall::ReturnVoid, this); } PendingCall *Adapter::stopDiscovery() { return new PendingCall(d->m_bluezAdapter->StopDiscovery(), PendingCall::ReturnVoid, this); } PendingCall *Adapter::removeDevice(DevicePtr device) { return new PendingCall(d->m_bluezAdapter->RemoveDevice(QDBusObjectPath(device->ubi())), PendingCall::ReturnVoid, this); } } // namespace BluezQt diff --git a/src/adapter_p.cpp b/src/adapter_p.cpp index 1ae4f94..73048b3 100644 --- a/src/adapter_p.cpp +++ b/src/adapter_p.cpp @@ -1,169 +1,169 @@ /* * BluezQt - Asynchronous Bluez wrapper library * * Copyright (C) 2014 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "adapter_p.h" #include "adapter.h" #include "utils.h" #include "macros.h" #include "media.h" #include "media_p.h" namespace BluezQt { AdapterPrivate::AdapterPrivate(const QString &path, const QVariantMap &properties) : QObject() , m_dbusProperties(nullptr) , m_adapterClass(0) , m_powered(0) , m_discoverable(false) , m_discoverableTimeout(0) , m_pairable(false) , m_pairableTimeout(0) { m_bluezAdapter = new BluezAdapter(Strings::orgBluez(), path, DBusConnection::orgBluez(), this); init(properties); } void AdapterPrivate::init(const QVariantMap &properties) { m_dbusProperties = new DBusProperties(Strings::orgBluez(), m_bluezAdapter->path(), DBusConnection::orgBluez(), this); // Init properties m_address = properties.value(QStringLiteral("Address")).toString(); m_name = properties.value(QStringLiteral("Name")).toString(); m_alias = properties.value(QStringLiteral("Alias")).toString(); m_adapterClass = properties.value(QStringLiteral("Class")).toUInt(); m_powered = properties.value(QStringLiteral("Powered")).toBool(); m_discoverable = properties.value(QStringLiteral("Discoverable")).toBool(); m_discoverableTimeout = properties.value(QStringLiteral("DiscoverableTimeout")).toUInt(); m_pairable = properties.value(QStringLiteral("Pairable")).toBool(); m_pairableTimeout = properties.value(QStringLiteral("PairableTimeout")).toUInt(); m_discovering = properties.value(QStringLiteral("Discovering")).toBool(); m_uuids = stringListToUpper(properties.value(QStringLiteral("UUIDs")).toStringList()); m_modalias = properties.value(QStringLiteral("Modalias")).toString(); } void AdapterPrivate::interfacesAdded(const QString &path, const QVariantMapMap &interfaces) { bool changed = false; for (auto it = interfaces.cbegin(); it != interfaces.cend(); ++it) { if (it.key() == Strings::orgBluezMedia1()) { m_media = MediaPtr(new Media(path)); Q_EMIT q.data()->mediaChanged(m_media); changed = true; } } if (changed) { Q_EMIT q.data()->adapterChanged(q.toStrongRef()); } } void AdapterPrivate::interfacesRemoved(const QString &path, const QStringList &interfaces) { bool changed = false; for (const QString &interface : interfaces) { if (interface == Strings::orgBluezMedia1() && m_media && m_media->d->m_path == path) { m_media.clear(); Q_EMIT q.data()->mediaChanged(m_media); changed = true; } } if (changed) { Q_EMIT q.data()->adapterChanged(q.toStrongRef()); } } void AdapterPrivate::addDevice(const DevicePtr &device) { m_devices.append(device); Q_EMIT q.data()->deviceAdded(device); connect(device.data(), &Device::deviceChanged, q.data(), &Adapter::deviceChanged); } void AdapterPrivate::removeDevice(const DevicePtr &device) { m_devices.removeOne(device); Q_EMIT device->deviceRemoved(device); Q_EMIT q.data()->deviceRemoved(device); disconnect(device.data(), &Device::deviceChanged, q.data(), &Adapter::deviceChanged); } QDBusPendingReply<> AdapterPrivate::setDBusProperty(const QString &name, const QVariant &value) { return m_dbusProperties->Set(Strings::orgBluezAdapter1(), name, QDBusVariant(value)); } void AdapterPrivate::propertiesChanged(const QString &interface, const QVariantMap &changed, const QStringList &invalidated) { if (interface != Strings::orgBluezAdapter1()) { return; } QVariantMap::const_iterator i; for (i = changed.constBegin(); i != changed.constEnd(); ++i) { const QVariant &value = i.value(); const QString &property = i.key(); if (property == QLatin1String("Name")) { PROPERTY_CHANGED(m_name, toString, systemNameChanged); } else if (property == QLatin1String("Alias")) { PROPERTY_CHANGED(m_alias, toString, nameChanged); } else if (property == QLatin1String("Class")) { PROPERTY_CHANGED(m_adapterClass, toUInt, adapterClassChanged); } else if (property == QLatin1String("Powered")) { PROPERTY_CHANGED(m_powered, toBool, poweredChanged); } else if (property == QLatin1String("Discoverable")) { PROPERTY_CHANGED(m_discoverable, toBool, discoverableChanged); } else if (property == QLatin1String("DiscoverableTimeout")) { PROPERTY_CHANGED(m_discoverableTimeout, toUInt, discoverableTimeoutChanged); } else if (property == QLatin1String("Pairable")) { PROPERTY_CHANGED(m_pairable, toBool, pairableChanged); } else if (property == QLatin1String("PairableTimeout")) { PROPERTY_CHANGED(m_pairableTimeout, toUInt, pairableTimeoutChanged); } else if (property == QLatin1String("Discovering")) { PROPERTY_CHANGED(m_discovering, toBool, discoveringChanged); } else if (property == QLatin1String("Modalias")) { PROPERTY_CHANGED(m_modalias, toString, modaliasChanged); } else if (property == QLatin1String("UUIDs")) { PROPERTY_CHANGED2(m_uuids, stringListToUpper(value.toStringList()), uuidsChanged); } } - Q_FOREACH (const QString &property, invalidated) { + for (const QString &property : invalidated) { if (property == QLatin1String("Modalias")) { PROPERTY_INVALIDATED(m_modalias, QString(), modaliasChanged); } } Q_EMIT q.data()->adapterChanged(q.toStrongRef()); } } // namespace BluezQt diff --git a/src/device_p.cpp b/src/device_p.cpp index 58327d1..87c82fd 100644 --- a/src/device_p.cpp +++ b/src/device_p.cpp @@ -1,234 +1,234 @@ /* * BluezQt - Asynchronous Bluez wrapper library * * Copyright (C) 2014 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "device_p.h" #include "device.h" #include "adapter.h" #include "input.h" #include "input_p.h" #include "mediaplayer.h" #include "mediaplayer_p.h" #include "utils.h" #include "macros.h" namespace BluezQt { static const qint16 INVALID_RSSI = -32768; // qint16 minimum DevicePrivate::DevicePrivate(const QString &path, const QVariantMap &properties, const AdapterPtr &adapter) : QObject() , m_dbusProperties(nullptr) , m_deviceClass(0) , m_appearance(0) , m_paired(false) , m_trusted(false) , m_blocked(false) , m_legacyPairing(false) , m_rssi(INVALID_RSSI) , m_connected(false) , m_adapter(adapter) { m_bluezDevice = new BluezDevice(Strings::orgBluez(), path, DBusConnection::orgBluez(), this); init(properties); } void DevicePrivate::init(const QVariantMap &properties) { m_dbusProperties = new DBusProperties(Strings::orgBluez(), m_bluezDevice->path(), DBusConnection::orgBluez(), this); // Init properties m_address = properties.value(QStringLiteral("Address")).toString(); m_name = properties.value(QStringLiteral("Name")).toString(); m_alias = properties.value(QStringLiteral("Alias")).toString(); m_deviceClass = properties.value(QStringLiteral("Class")).toUInt(); m_appearance = properties.value(QStringLiteral("Appearance")).toUInt(); m_icon = properties.value(QStringLiteral("Icon")).toString(); m_paired = properties.value(QStringLiteral("Paired")).toBool(); m_trusted = properties.value(QStringLiteral("Trusted")).toBool(); m_blocked = properties.value(QStringLiteral("Blocked")).toBool(); m_legacyPairing = properties.value(QStringLiteral("LegacyPairing")).toBool(); m_rssi = properties.value(QStringLiteral("RSSI")).toInt(); m_connected = properties.value(QStringLiteral("Connected")).toBool(); m_uuids = stringListToUpper(properties.value(QStringLiteral("UUIDs")).toStringList()); m_modalias = properties.value(QStringLiteral("Modalias")).toString(); if (!m_rssi) { m_rssi = INVALID_RSSI; } } void DevicePrivate::interfacesAdded(const QString &path, const QVariantMapMap &interfaces) { bool changed = false; QVariantMapMap::const_iterator it; for (it = interfaces.constBegin(); it != interfaces.constEnd(); ++it) { if (it.key() == Strings::orgBluezInput1()) { m_input = InputPtr(new Input(path, it.value())); m_input->d->q = m_input.toWeakRef(); Q_EMIT q.data()->inputChanged(m_input); changed = true; } else if (it.key() == Strings::orgBluezMediaPlayer1()) { m_mediaPlayer = MediaPlayerPtr(new MediaPlayer(path, it.value())); m_mediaPlayer->d->q = m_mediaPlayer.toWeakRef(); Q_EMIT q.data()->mediaPlayerChanged(m_mediaPlayer); changed = true; } } if (changed) { Q_EMIT q.data()->deviceChanged(q.toStrongRef()); } } void DevicePrivate::interfacesRemoved(const QString &path, const QStringList &interfaces) { bool changed = false; - Q_FOREACH (const QString &interface, interfaces) { + for (const QString &interface : interfaces) { if (interface == Strings::orgBluezInput1() && m_input && m_input->d->m_path == path) { m_input.clear(); Q_EMIT q.data()->inputChanged(m_input); changed = true; } else if (interface == Strings::orgBluezMediaPlayer1() && m_mediaPlayer && m_mediaPlayer->d->m_path == path) { m_mediaPlayer.clear(); Q_EMIT q.data()->mediaPlayerChanged(m_mediaPlayer); changed = true; } } if (changed) { Q_EMIT q.data()->deviceChanged(q.toStrongRef()); } } QDBusPendingReply<> DevicePrivate::setDBusProperty(const QString &name, const QVariant &value) { return m_dbusProperties->Set(Strings::orgBluezDevice1(), name, QDBusVariant(value)); } void DevicePrivate::propertiesChanged(const QString &interface, const QVariantMap &changed, const QStringList &invalidated) { if (interface == Strings::orgBluezInput1() && m_input) { m_input->d->propertiesChanged(interface, changed, invalidated); } else if (interface == Strings::orgBluezMediaPlayer1() && m_mediaPlayer) { m_mediaPlayer->d->propertiesChanged(interface, changed, invalidated); } else if (interface != Strings::orgBluezDevice1()) { return; } QVariantMap::const_iterator i; for (i = changed.constBegin(); i != changed.constEnd(); ++i) { const QVariant &value = i.value(); const QString &property = i.key(); if (property == QLatin1String("Name")) { namePropertyChanged(value.toString()); } else if (property == QLatin1String("Address")) { addressPropertyChanged(value.toString()); } else if (property == QLatin1String("Alias")) { aliasPropertyChanged(value.toString()); } else if (property == QLatin1String("Class")) { classPropertyChanged(value.toUInt()); } else if (property == QLatin1String("Appearance")) { PROPERTY_CHANGED(m_appearance, toUInt, appearanceChanged); } else if (property == QLatin1String("Icon")) { PROPERTY_CHANGED(m_icon, toString, iconChanged); } else if (property == QLatin1String("Paired")) { PROPERTY_CHANGED(m_paired, toBool, pairedChanged); } else if (property == QLatin1String("Trusted")) { PROPERTY_CHANGED(m_trusted, toBool, trustedChanged); } else if (property == QLatin1String("Blocked")) { PROPERTY_CHANGED(m_blocked, toBool, blockedChanged); } else if (property == QLatin1String("LegacyPairing")) { PROPERTY_CHANGED(m_legacyPairing, toBool, legacyPairingChanged); } else if (property == QLatin1String("RSSI")) { PROPERTY_CHANGED(m_rssi, toInt, rssiChanged); } else if (property == QLatin1String("Connected")) { PROPERTY_CHANGED(m_connected, toBool, connectedChanged); } else if (property == QLatin1String("Modalias")) { PROPERTY_CHANGED(m_modalias, toString, modaliasChanged); } else if (property == QLatin1String("UUIDs")) { PROPERTY_CHANGED2(m_uuids, stringListToUpper(value.toStringList()), uuidsChanged); } } - Q_FOREACH (const QString &property, invalidated) { + for (const QString &property : invalidated) { if (property == QLatin1String("Name")) { namePropertyChanged(QString()); } else if (property == QLatin1String("Class")) { classPropertyChanged(0); } else if (property == QLatin1String("Appearance")) { PROPERTY_INVALIDATED(m_appearance, 0, appearanceChanged); } else if (property == QLatin1String("Icon")) { PROPERTY_INVALIDATED(m_icon, QString(), iconChanged); } else if (property == QLatin1String("RSSI")) { PROPERTY_INVALIDATED(m_rssi, INVALID_RSSI, rssiChanged); } else if (property == QLatin1String("Modalias")) { PROPERTY_INVALIDATED(m_modalias, QString(), modaliasChanged); } else if (property == QLatin1String("UUIDs")) { PROPERTY_INVALIDATED(m_uuids, QStringList(), uuidsChanged); } } Q_EMIT q.data()->deviceChanged(q.toStrongRef()); } void DevicePrivate::namePropertyChanged(const QString &value) { if (m_name != value) { m_name = value; Q_EMIT q.data()->remoteNameChanged(m_name); Q_EMIT q.data()->friendlyNameChanged(q.data()->friendlyName()); } } void DevicePrivate::addressPropertyChanged(const QString &value) { if (m_address != value) { m_address = value; Q_EMIT q.data()->addressChanged(m_address); } } void DevicePrivate::aliasPropertyChanged(const QString &value) { if (m_alias != value) { m_alias = value; Q_EMIT q.data()->nameChanged(m_alias); Q_EMIT q.data()->friendlyNameChanged(q.data()->friendlyName()); } } void DevicePrivate::classPropertyChanged(quint32 value) { if (m_deviceClass != value) { m_deviceClass = value; Q_EMIT q.data()->deviceClassChanged(m_deviceClass); Q_EMIT q.data()->typeChanged(q.data()->type()); } } } // namespace BluezQt diff --git a/src/devicesmodel.cpp b/src/devicesmodel.cpp index fbf1bda..451d729 100644 --- a/src/devicesmodel.cpp +++ b/src/devicesmodel.cpp @@ -1,230 +1,231 @@ /* * BluezQt - Asynchronous Bluez wrapper library * * Copyright (C) 2014 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "devicesmodel.h" #include "manager.h" #include "adapter.h" #include "device.h" namespace BluezQt { class DevicesModelPrivate : public QObject { public: explicit DevicesModelPrivate(DevicesModel *q); void init(); void deviceAdded(DevicePtr device); void deviceRemoved(DevicePtr device); void deviceChanged(DevicePtr device); void adapterChanged(AdapterPtr adapter); DevicesModel *q; Manager *m_manager; QList m_devices; }; DevicesModelPrivate::DevicesModelPrivate(DevicesModel *q) : QObject(q) , q(q) , m_manager(nullptr) { } void DevicesModelPrivate::init() { m_devices = m_manager->devices(); connect(m_manager, &Manager::deviceAdded, this, &DevicesModelPrivate::deviceAdded); connect(m_manager, &Manager::deviceRemoved, this, &DevicesModelPrivate::deviceRemoved); connect(m_manager, &Manager::deviceChanged, this, &DevicesModelPrivate::deviceChanged); connect(m_manager, &Manager::adapterChanged, this, &DevicesModelPrivate::adapterChanged); } void DevicesModelPrivate::deviceAdded(DevicePtr device) { q->beginInsertRows(QModelIndex(), m_devices.size(), m_devices.size()); m_devices.append(device); q->endInsertRows(); } void DevicesModelPrivate::deviceRemoved(DevicePtr device) { int offset = m_devices.indexOf(device); Q_ASSERT(offset >= 0); q->beginRemoveRows(QModelIndex(), offset, offset); m_devices.removeAt(offset); q->endRemoveRows(); } void DevicesModelPrivate::deviceChanged(DevicePtr device) { int offset = m_devices.indexOf(device); Q_ASSERT(offset >= 0); QModelIndex idx = q->createIndex(offset, 0); Q_EMIT q->dataChanged(idx, idx); } void DevicesModelPrivate::adapterChanged(AdapterPtr adapter) { - Q_FOREACH (const DevicePtr &device, adapter->devices()) { + const auto devices = adapter->devices(); + for (const DevicePtr &device : devices) { deviceChanged(device); } } DevicesModel::DevicesModel(Manager *manager, QObject *parent) : QAbstractListModel(parent) , d(new DevicesModelPrivate(this)) { d->m_manager = manager; d->init(); } DevicesModel::~DevicesModel() { delete d; } QHash DevicesModel::roleNames() const { QHash roles = QAbstractListModel::roleNames(); roles[UbiRole] = QByteArrayLiteral("Ubi"); roles[AddressRole] = QByteArrayLiteral("Address"); roles[NameRole] = QByteArrayLiteral("Name"); roles[FriendlyNameRole] = QByteArrayLiteral("FriendlyName"); roles[RemoteNameRole] = QByteArrayLiteral("RemoteName"); roles[ClassRole] = QByteArrayLiteral("Class"); roles[TypeRole] = QByteArrayLiteral("Type"); roles[AppearanceRole] = QByteArrayLiteral("Appearance"); roles[IconRole] = QByteArrayLiteral("Icon"); roles[PairedRole] = QByteArrayLiteral("Paired"); roles[TrustedRole] = QByteArrayLiteral("Trusted"); roles[BlockedRole] = QByteArrayLiteral("Blocked"); roles[LegacyPairingRole] = QByteArrayLiteral("LegacyPairing"); roles[RssiRole] = QByteArrayLiteral("Rssi"); roles[ConnectedRole] = QByteArrayLiteral("Connected"); roles[UuidsRole] = QByteArrayLiteral("Uuids"); roles[ModaliasRole] = QByteArrayLiteral("Modalias"); roles[AdapterNameRole] = QByteArrayLiteral("AdapterName"); roles[AdapterAddressRole] = QByteArrayLiteral("AdapterAddress"); roles[AdapterPoweredRole] = QByteArrayLiteral("AdapterPowered"); roles[AdapterDiscoverableRole] = QByteArrayLiteral("AdapterDiscoverable"); roles[AdapterPairableRole] = QByteArrayLiteral("AdapterPairable"); roles[AdapterDiscoveringRole] = QByteArrayLiteral("AdapterDiscovering"); roles[AdapterUuidsRole] = QByteArrayLiteral("AdapterUuids"); return roles; } int DevicesModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) { return 0; } return d->m_devices.size(); } QVariant DevicesModel::data(const QModelIndex &index, int role) const { DevicePtr dev = device(index); if (!dev) { return QVariant(); } switch (role) { case Qt::DisplayRole: return dev->name(); case UbiRole: return dev->ubi(); case AddressRole: return dev->address(); case NameRole: return dev->name(); case FriendlyNameRole: return dev->friendlyName(); case RemoteNameRole: return dev->remoteName(); case ClassRole: return dev->deviceClass(); case TypeRole: return dev->type(); case AppearanceRole: return dev->appearance(); case IconRole: return dev->icon(); case PairedRole: return dev->isPaired(); case TrustedRole: return dev->isTrusted(); case BlockedRole: return dev->isBlocked(); case LegacyPairingRole: return dev->hasLegacyPairing(); case RssiRole: return dev->rssi(); case ConnectedRole: return dev->isConnected(); case UuidsRole: return dev->uuids(); case ModaliasRole: return dev->modalias(); case AdapterNameRole: return dev->adapter()->name(); case AdapterAddressRole: return dev->adapter()->address(); case AdapterPoweredRole: return dev->adapter()->isPowered(); case AdapterDiscoverableRole: return dev->adapter()->isDiscoverable(); case AdapterPairableRole: return dev->adapter()->isPairable(); case AdapterDiscoveringRole: return dev->adapter()->isDiscovering(); case AdapterUuidsRole: return dev->adapter()->uuids(); default: return QVariant(); } } QModelIndex DevicesModel::index(int row, int column, const QModelIndex &parent) const { if (!hasIndex(row, column, parent)) { return QModelIndex(); } return createIndex(row, 0); } DevicePtr DevicesModel::device(const QModelIndex &index) const { if (!index.isValid()) { return DevicePtr(); } return d->m_devices.at(index.row()); } } // namespace BluezQt diff --git a/src/manager.cpp b/src/manager.cpp index 8316da8..e0849c9 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -1,254 +1,254 @@ /* * BluezQt - Asynchronous Bluez wrapper library * * Copyright (C) 2014 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "manager.h" #include "manager_p.h" #include "adapter.h" #include "agent.h" #include "agentadaptor.h" #include "profile.h" #include "profile_p.h" #include "profileadaptor.h" #include "pendingcall.h" #include "initmanagerjob.h" #include "utils.h" #include "debug.h" namespace BluezQt { Manager::Manager(QObject *parent) : QObject(parent) , d(new ManagerPrivate(this)) { Instance::setManager(this); } Manager::~Manager() { delete d; } InitManagerJob *Manager::init() { return new InitManagerJob(this); } bool Manager::isInitialized() const { return d->m_initialized; } bool Manager::isOperational() const { return d->m_initialized && d->m_bluezRunning && d->m_loaded; } bool Manager::isBluetoothOperational() const { return !d->m_bluetoothBlocked && d->m_bluezRunning && d->m_loaded && d->m_usableAdapter; } bool Manager::isBluetoothBlocked() const { return d->m_bluetoothBlocked; } bool Manager::setBluetoothBlocked(bool blocked) { if (blocked) { return d->m_rfkill->block(); } else { return d->m_rfkill->unblock(); } } AdapterPtr Manager::usableAdapter() const { return d->m_usableAdapter; } QList Manager::adapters() const { return d->m_adapters.values(); } QList Manager::devices() const { return d->m_devices.values(); } PendingCall *Manager::startService() { QDBusMessage msg = QDBusMessage::createMethodCall(Strings::orgFreedesktopDBus(), QStringLiteral("/org/freedesktop/DBus"), Strings::orgFreedesktopDBus(), QStringLiteral("StartServiceByName")); msg << Strings::orgBluez(); msg << quint32(0); return new PendingCall(DBusConnection::orgBluez().asyncCall(msg), PendingCall::ReturnUint32); } AdapterPtr Manager::adapterForAddress(const QString &address) const { - Q_FOREACH (AdapterPtr adapter, d->m_adapters) { + for (AdapterPtr adapter : qAsConst(d->m_adapters)) { if (adapter->address() == address) { return adapter; } } return AdapterPtr(); } AdapterPtr Manager::adapterForUbi(const QString &ubi) const { return d->m_adapters.value(ubi); } DevicePtr Manager::deviceForAddress(const QString &address) const { DevicePtr device; - Q_FOREACH (AdapterPtr adapter, d->m_adapters) { + for (AdapterPtr adapter : qAsConst(d->m_adapters)) { DevicePtr d = adapter->deviceForAddress(address); if (!d) { continue; } // Prefer powered adapter if (!device) { device = d; } else if (adapter->isPowered()) { device = d; } } return device; } DevicePtr Manager::deviceForUbi(const QString &ubi) const { return d->m_devices.value(ubi); } PendingCall *Manager::registerAgent(Agent *agent) { Q_ASSERT(agent); if (!d->m_bluezAgentManager) { return new PendingCall(PendingCall::InternalError, QStringLiteral("Manager not operational!")); } QString capability; switch (agent->capability()) { case Agent::DisplayOnly: capability = QStringLiteral("DisplayOnly"); break; case Agent::DisplayYesNo: capability = QStringLiteral("DisplayYesNo"); break; case Agent::KeyboardOnly: capability = QStringLiteral("KeyboardOnly"); break; case Agent::NoInputNoOutput: capability = QStringLiteral("NoInputNoOutput"); break; default: capability = QStringLiteral("DisplayYesNo"); break; } new AgentAdaptor(agent, this); if (!DBusConnection::orgBluez().registerObject(agent->objectPath().path(), agent)) { qCDebug(BLUEZQT) << "Cannot register object" << agent->objectPath().path(); } return new PendingCall(d->m_bluezAgentManager->RegisterAgent(agent->objectPath(), capability), PendingCall::ReturnVoid, this); } PendingCall *Manager::unregisterAgent(Agent *agent) { Q_ASSERT(agent); if (!d->m_bluezAgentManager) { return new PendingCall(PendingCall::InternalError, QStringLiteral("Manager not operational!")); } DBusConnection::orgBluez().unregisterObject(agent->objectPath().path()); return new PendingCall(d->m_bluezAgentManager->UnregisterAgent(agent->objectPath()), PendingCall::ReturnVoid, this); } PendingCall *Manager::requestDefaultAgent(Agent *agent) { Q_ASSERT(agent); if (!d->m_bluezAgentManager) { return new PendingCall(PendingCall::InternalError, QStringLiteral("Manager not operational!")); } return new PendingCall(d->m_bluezAgentManager->RequestDefaultAgent(agent->objectPath()), PendingCall::ReturnVoid, this); } PendingCall *Manager::registerProfile(Profile *profile) { Q_ASSERT(profile); if (!d->m_bluezProfileManager) { return new PendingCall(PendingCall::InternalError, QStringLiteral("Manager not operational!")); } new ProfileAdaptor(profile, this); if (!DBusConnection::orgBluez().registerObject(profile->objectPath().path(), profile)) { qCDebug(BLUEZQT) << "Cannot register object" << profile->objectPath().path(); } return new PendingCall(d->m_bluezProfileManager->RegisterProfile(profile->objectPath(), profile->uuid(), profile->d->options), PendingCall::ReturnVoid, this); } PendingCall *Manager::unregisterProfile(Profile *profile) { Q_ASSERT(profile); if (!d->m_bluezProfileManager) { return new PendingCall(PendingCall::InternalError, QStringLiteral("Manager not operational!")); } DBusConnection::orgBluez().unregisterObject(profile->objectPath().path()); return new PendingCall(d->m_bluezProfileManager->UnregisterProfile(profile->objectPath()), PendingCall::ReturnVoid, this); } MediaPtr Manager::media() const { return usableAdapter() ? usableAdapter()->media() : nullptr; } } // namespace BluezQt diff --git a/src/manager_p.cpp b/src/manager_p.cpp index 354052c..29b39a1 100644 --- a/src/manager_p.cpp +++ b/src/manager_p.cpp @@ -1,471 +1,472 @@ /* * BluezQt - Asynchronous Bluez wrapper library * * Copyright (C) 2014-2015 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "manager_p.h" #include "manager.h" #include "device.h" #include "device_p.h" #include "adapter.h" #include "adapter_p.h" #include "debug.h" #include "utils.h" #include #include #include namespace BluezQt { ManagerPrivate::ManagerPrivate(Manager *parent) : QObject(parent) , q(parent) , m_dbusObjectManager(nullptr) , m_bluezAgentManager(nullptr) , m_bluezProfileManager(nullptr) , m_initialized(false) , m_bluezRunning(false) , m_loaded(false) , m_adaptersLoaded(false) { qDBusRegisterMetaType(); qDBusRegisterMetaType(); m_rfkill = new Rfkill(this); m_bluetoothBlocked = rfkillBlocked(); connect(m_rfkill, &Rfkill::stateChanged, this, &ManagerPrivate::rfkillStateChanged); connect(q, &Manager::adapterRemoved, this, &ManagerPrivate::adapterRemoved); } void ManagerPrivate::init() { // Keep an eye on org.bluez service QDBusServiceWatcher *serviceWatcher = new QDBusServiceWatcher(Strings::orgBluez(), DBusConnection::orgBluez(), QDBusServiceWatcher::WatchForRegistration | QDBusServiceWatcher::WatchForUnregistration, this); connect(serviceWatcher, &QDBusServiceWatcher::serviceRegistered, this, &ManagerPrivate::serviceRegistered); connect(serviceWatcher, &QDBusServiceWatcher::serviceUnregistered, this, &ManagerPrivate::serviceUnregistered); // Update the current state of org.bluez service if (!DBusConnection::orgBluez().isConnected()) { Q_EMIT initError(QStringLiteral("DBus system bus is not connected!")); return; } QDBusMessage call = QDBusMessage::createMethodCall(Strings::orgFreedesktopDBus(), QStringLiteral("/"), Strings::orgFreedesktopDBus(), QStringLiteral("NameHasOwner")); call << Strings::orgBluez(); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(DBusConnection::orgBluez().asyncCall(call)); connect(watcher, &QDBusPendingCallWatcher::finished, this, &ManagerPrivate::nameHasOwnerFinished); DBusConnection::orgBluez().connect(Strings::orgBluez(), QString(), Strings::orgFreedesktopDBusProperties(), QStringLiteral("PropertiesChanged"), this, SLOT(propertiesChanged(QString,QVariantMap,QStringList))); } void ManagerPrivate::nameHasOwnerFinished(QDBusPendingCallWatcher *watcher) { const QDBusPendingReply &reply = *watcher; watcher->deleteLater(); if (reply.isError()) { Q_EMIT initError(reply.error().message()); return; } m_bluezRunning = reply.value(); if (m_bluezRunning) { load(); } else { m_initialized = true; Q_EMIT initFinished(); } } void ManagerPrivate::load() { if (!m_bluezRunning || m_loaded) { return; } // Force QDBus to cache owner of org.bluez - this will be the only blocking call on system connection DBusConnection::orgBluez().connect(Strings::orgBluez(), QStringLiteral("/"), Strings::orgFreedesktopDBus(), QStringLiteral("Dummy"), this, SLOT(dummy())); m_dbusObjectManager = new DBusObjectManager(Strings::orgBluez(), QStringLiteral("/"), DBusConnection::orgBluez(), this); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(m_dbusObjectManager->GetManagedObjects(), this); connect(watcher, &QDBusPendingCallWatcher::finished, this, &ManagerPrivate::getManagedObjectsFinished); } void ManagerPrivate::getManagedObjectsFinished(QDBusPendingCallWatcher *watcher) { const QDBusPendingReply &reply = *watcher; watcher->deleteLater(); if (reply.isError()) { Q_EMIT initError(reply.error().message()); return; } DBusManagerStruct::const_iterator it; const DBusManagerStruct &managedObjects = reply.value(); for (it = managedObjects.constBegin(); it != managedObjects.constEnd(); ++it) { const QString &path = it.key().path(); const QVariantMapMap &interfaces = it.value(); interfacesAdded(it.key(), interfaces); if (interfaces.contains(Strings::orgBluezAgentManager1())) { m_bluezAgentManager = new BluezAgentManager(Strings::orgBluez(), path, DBusConnection::orgBluez(), this); } if (interfaces.contains(Strings::orgBluezProfileManager1())) { m_bluezProfileManager = new BluezProfileManager(Strings::orgBluez(), path, DBusConnection::orgBluez(), this); } } if (!m_bluezAgentManager) { Q_EMIT initError(QStringLiteral("Cannot find org.bluez.AgentManager1 object!")); return; } if (!m_bluezProfileManager) { Q_EMIT initError(QStringLiteral("Cannot find org.bluez.ProfileManager1 object!")); return; } connect(m_dbusObjectManager, &DBusObjectManager::InterfacesAdded, this, &ManagerPrivate::interfacesAdded); connect(m_dbusObjectManager, &DBusObjectManager::InterfacesRemoved, this, &ManagerPrivate::interfacesRemoved); m_loaded = true; m_initialized = true; Q_EMIT q->operationalChanged(true); if (q->isBluetoothOperational()) { Q_EMIT q->bluetoothOperationalChanged(true); } Q_EMIT initFinished(); } void ManagerPrivate::clear() { m_loaded = false; // Delete all devices first while (!m_devices.isEmpty()) { DevicePtr device = m_devices.begin().value(); m_devices.remove(m_devices.begin().key()); device->adapter()->d->removeDevice(device); } // Delete all adapters while (!m_adapters.isEmpty()) { AdapterPtr adapter = m_adapters.begin().value(); m_adapters.remove(m_adapters.begin().key()); Q_EMIT adapter->adapterRemoved(adapter); if (m_adapters.isEmpty()) { Q_EMIT q->allAdaptersRemoved(); } } // Delete all other objects m_usableAdapter.clear(); if (m_dbusObjectManager) { m_dbusObjectManager->deleteLater(); m_dbusObjectManager = nullptr; } if (m_bluezAgentManager) { m_bluezAgentManager->deleteLater(); m_bluezAgentManager = nullptr; } } AdapterPtr ManagerPrivate::findUsableAdapter() const { - Q_FOREACH (AdapterPtr adapter, m_adapters) { + for (AdapterPtr adapter : qAsConst(m_adapters)) { if (adapter->isPowered()) { return adapter; } } return AdapterPtr(); } void ManagerPrivate::serviceRegistered() { qCDebug(BLUEZQT) << "BlueZ service registered"; m_bluezRunning = true; load(); } void ManagerPrivate::serviceUnregistered() { qCDebug(BLUEZQT) << "BlueZ service unregistered"; bool wasBtOperational = q->isBluetoothOperational(); m_bluezRunning = false; if (wasBtOperational) { Q_EMIT q->bluetoothOperationalChanged(false); } clear(); Q_EMIT q->operationalChanged(false); } void ManagerPrivate::interfacesAdded(const QDBusObjectPath &objectPath, const QVariantMapMap &interfaces) { const QString &path = objectPath.path(); QVariantMapMap::const_iterator it; for (it = interfaces.constBegin(); it != interfaces.constEnd(); ++it) { if (it.key() == Strings::orgBluezAdapter1()) { addAdapter(path, it.value()); } else if (it.key() == Strings::orgBluezDevice1()) { addDevice(path, it.value()); } } for (auto it = m_adapters.cbegin(); it != m_adapters.cend(); ++it) { if (path.startsWith(it.value()->ubi())) { it.value()->d->interfacesAdded(path, interfaces); break; } } for (auto it = m_devices.cbegin(); it != m_devices.cend(); ++it) { if (path.startsWith(it.value()->ubi())) { it.value()->d->interfacesAdded(path, interfaces); break; } } } void ManagerPrivate::interfacesRemoved(const QDBusObjectPath &objectPath, const QStringList &interfaces) { const QString &path = objectPath.path(); - Q_FOREACH (const QString &interface, interfaces) { + for (const QString &interface : interfaces) { if (interface == Strings::orgBluezAdapter1()) { removeAdapter(path); } else if (interface == Strings::orgBluezDevice1()) { removeDevice(path); } } for (auto it = m_adapters.cbegin(); it != m_adapters.cend(); ++it) { if (path.startsWith(it.value()->ubi())) { it.value()->d->interfacesRemoved(path, interfaces); break; } } for (auto it = m_devices.cbegin(); it != m_devices.cend(); ++it) { if (path.startsWith(it.value()->ubi())) { it.value()->d->interfacesRemoved(path, interfaces); break; } } } void ManagerPrivate::adapterRemoved(const AdapterPtr &adapter) { disconnect(adapter.data(), &Adapter::poweredChanged, this, &ManagerPrivate::adapterPoweredChanged); // Current usable adapter was removed if (adapter == m_usableAdapter) { setUsableAdapter(findUsableAdapter()); } } void ManagerPrivate::adapterPoweredChanged(bool powered) { Q_ASSERT(qobject_cast(sender())); AdapterPtr adapter = static_cast(sender())->toSharedPtr(); // Current usable adapter was powered off if (m_usableAdapter == adapter && !powered) { setUsableAdapter(findUsableAdapter()); } // Adapter was powered on, set it as usable if (!m_usableAdapter && powered) { setUsableAdapter(adapter); } } void ManagerPrivate::rfkillStateChanged(Rfkill::State state) { Q_UNUSED(state) bool blocked = rfkillBlocked(); bool wasBtOperational = q->isBluetoothOperational(); if (m_bluetoothBlocked != blocked) { m_bluetoothBlocked = blocked; Q_EMIT q->bluetoothBlockedChanged(m_bluetoothBlocked); if (wasBtOperational != q->isBluetoothOperational()) { Q_EMIT q->bluetoothOperationalChanged(q->isBluetoothOperational()); } } } void ManagerPrivate::addAdapter(const QString &adapterPath, const QVariantMap &properties) { AdapterPtr adapter = AdapterPtr(new Adapter(adapterPath, properties)); adapter->d->q = adapter.toWeakRef(); m_adapters.insert(adapterPath, adapter); Q_EMIT q->adapterAdded(adapter); // Powered adapter was added, set it as usable if (!m_usableAdapter && adapter->isPowered()) { setUsableAdapter(adapter); } connect(adapter.data(), &Adapter::deviceAdded, q, &Manager::deviceAdded); connect(adapter.data(), &Adapter::adapterRemoved, q, &Manager::adapterRemoved); connect(adapter.data(), &Adapter::adapterChanged, q, &Manager::adapterChanged); connect(adapter.data(), &Adapter::poweredChanged, this, &ManagerPrivate::adapterPoweredChanged); } void ManagerPrivate::addDevice(const QString &devicePath, const QVariantMap &properties) { AdapterPtr adapter = m_adapters.value(properties.value(QStringLiteral("Adapter")).value().path()); if (!adapter) { return; } DevicePtr device = DevicePtr(new Device(devicePath, properties, adapter)); device->d->q = device.toWeakRef(); m_devices.insert(devicePath, device); adapter->d->addDevice(device); connect(device.data(), &Device::deviceRemoved, q, &Manager::deviceRemoved); connect(device.data(), &Device::deviceChanged, q, &Manager::deviceChanged); } void ManagerPrivate::removeAdapter(const QString &adapterPath) { AdapterPtr adapter = m_adapters.value(adapterPath); if (!adapter) { return; } // Make sure we always remove all devices before removing the adapter - Q_FOREACH (const DevicePtr &device, adapter->devices()) { + const auto devices = adapter->devices(); + for (const DevicePtr &device : devices) { removeDevice(device->ubi()); } m_adapters.remove(adapterPath); Q_EMIT adapter->adapterRemoved(adapter); if (m_adapters.isEmpty()) { Q_EMIT q->allAdaptersRemoved(); } disconnect(adapter.data(), &Adapter::adapterChanged, q, &Manager::adapterChanged); disconnect(adapter.data(), &Adapter::poweredChanged, this, &ManagerPrivate::adapterPoweredChanged); } void ManagerPrivate::removeDevice(const QString &devicePath) { DevicePtr device = m_devices.take(devicePath); if (!device) { return; } device->adapter()->d->removeDevice(device); disconnect(device.data(), &Device::deviceChanged, q, &Manager::deviceChanged); } bool ManagerPrivate::rfkillBlocked() const { return m_rfkill->state() == Rfkill::SoftBlocked || m_rfkill->state() == Rfkill::HardBlocked; } void ManagerPrivate::setUsableAdapter(const AdapterPtr &adapter) { if (m_usableAdapter == adapter) { return; } qCDebug(BLUEZQT) << "Setting usable adapter" << adapter; bool wasBtOperational = q->isBluetoothOperational(); m_usableAdapter = adapter; Q_EMIT q->usableAdapterChanged(m_usableAdapter); if (wasBtOperational != q->isBluetoothOperational()) { Q_EMIT q->bluetoothOperationalChanged(q->isBluetoothOperational()); } } void ManagerPrivate::propertiesChanged(const QString &interface, const QVariantMap &changed, const QStringList &invalidated) { // Cut anything after device path to forward it to Device to handle const QString path = message().path().section(QLatin1Char('/'), 0, 4); QTimer::singleShot(0, this, [=]() { AdapterPtr adapter = m_adapters.value(path); if (adapter) { adapter->d->propertiesChanged(interface, changed, invalidated); return; } DevicePtr device = m_devices.value(path); if (device) { device->d->propertiesChanged(interface, changed, invalidated); return; } qCDebug(BLUEZQT) << "Unhandled property change" << interface << changed << invalidated; }); } void ManagerPrivate::dummy() { } } // namespace BluezQt diff --git a/src/mediaplayer_p.cpp b/src/mediaplayer_p.cpp index 64e129e..a57d4f3 100644 --- a/src/mediaplayer_p.cpp +++ b/src/mediaplayer_p.cpp @@ -1,166 +1,166 @@ /* * BluezQt - Asynchronous Bluez wrapper library * * Copyright (C) 2015 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "mediaplayer_p.h" #include "utils.h" #include "macros.h" namespace BluezQt { static MediaPlayer::Equalizer stringToEqualizer(const QString &equalizer) { if (equalizer == QLatin1String("on")) { return MediaPlayer::EqualizerOn; } return MediaPlayer::EqualizerOff; } static MediaPlayer::Repeat stringToRepeat(const QString &repeat) { if (repeat == QLatin1String("singletrack")) { return MediaPlayer::RepeatSingleTrack; } else if (repeat == QLatin1String("alltracks")) { return MediaPlayer::RepeatAllTracks; } else if (repeat == QLatin1String("group")) { return MediaPlayer::RepeatGroup; } return MediaPlayer::RepeatOff; } static MediaPlayer::Shuffle stringToShuffle(const QString &shuffle) { if (shuffle == QLatin1String("alltracks")) { return MediaPlayer::ShuffleAllTracks; } else if (shuffle == QLatin1String("group")) { return MediaPlayer::ShuffleGroup; } return MediaPlayer::ShuffleOff; } static MediaPlayer::Status stringToStatus(const QString &status) { if (status == QLatin1String("playing")) { return MediaPlayer::Playing; } else if (status == QLatin1String("stopped")) { return MediaPlayer::Stopped; } else if (status == QLatin1String("paused")) { return MediaPlayer::Paused; } else if (status == QLatin1String("forward-seek")) { return MediaPlayer::ForwardSeek; } else if (status == QLatin1String("reverse-seek")) { return MediaPlayer::ReverseSeek; } return MediaPlayer::Error; } MediaPlayerPrivate::MediaPlayerPrivate(const QString &path, const QVariantMap &properties) : QObject() , m_dbusProperties(nullptr) , m_path(path) , m_equalizer(MediaPlayer::EqualizerOff) , m_repeat(MediaPlayer::RepeatOff) , m_shuffle(MediaPlayer::ShuffleOff) , m_status(MediaPlayer::Error) , m_position(0) { m_bluezMediaPlayer = new BluezMediaPlayer(Strings::orgBluez(), path, DBusConnection::orgBluez(), this); init(properties); } void MediaPlayerPrivate::init(const QVariantMap &properties) { m_dbusProperties = new DBusProperties(Strings::orgBluez(), m_bluezMediaPlayer->path(), DBusConnection::orgBluez(), this); // Init properties m_name = properties.value(QStringLiteral("Name")).toString(); m_equalizer = stringToEqualizer(properties.value(QStringLiteral("Equalizer")).toString()); m_repeat = stringToRepeat(properties.value(QStringLiteral("Repeat")).toString()); m_shuffle = stringToShuffle(properties.value(QStringLiteral("Shuffle")).toString()); m_status = stringToStatus(properties.value(QStringLiteral("Status")).toString()); m_track = variantToTrack(properties.value(QStringLiteral("Track"))); m_position = properties.value(QStringLiteral("Position")).toUInt(); } QDBusPendingReply<> MediaPlayerPrivate::setDBusProperty(const QString &name, const QVariant &value) { return m_dbusProperties->Set(Strings::orgBluezMediaPlayer1(), name, QDBusVariant(value)); } void MediaPlayerPrivate::propertiesChanged(const QString &interface, const QVariantMap &changed, const QStringList &invalidated) { if (interface != Strings::orgBluezMediaPlayer1()) { return; } QVariantMap::const_iterator i; for (i = changed.constBegin(); i != changed.constEnd(); ++i) { const QVariant &value = i.value(); const QString &property = i.key(); if (property == QLatin1String("Name")) { PROPERTY_CHANGED(m_name, toString, nameChanged); } else if (property == QLatin1String("Equalizer")) { PROPERTY_CHANGED2(m_equalizer, stringToEqualizer(value.toString()), equalizerChanged); } else if (property == QLatin1String("Repeat")) { PROPERTY_CHANGED2(m_repeat, stringToRepeat(value.toString()), repeatChanged); } else if (property == QLatin1String("Shuffle")) { PROPERTY_CHANGED2(m_shuffle, stringToShuffle(value.toString()), shuffleChanged); } else if (property == QLatin1String("Status")) { PROPERTY_CHANGED2(m_status, stringToStatus(value.toString()), statusChanged); } else if (property == QLatin1String("Position")) { PROPERTY_CHANGED(m_position, toUInt, positionChanged); } else if (property == QLatin1String("Track")) { m_track = variantToTrack(value); Q_EMIT q.data()->trackChanged(m_track); } } - Q_FOREACH (const QString &property, invalidated) { + for (const QString &property : invalidated) { if (property == QLatin1String("Name")) { PROPERTY_INVALIDATED(m_name, QString(), nameChanged); } else if (property == QLatin1String("Equalizer")) { PROPERTY_INVALIDATED(m_equalizer, MediaPlayer::EqualizerOff, equalizerChanged); } else if (property == QLatin1String("Repeat")) { PROPERTY_INVALIDATED(m_repeat, MediaPlayer::RepeatOff, repeatChanged); } else if (property == QLatin1String("Shuffle")) { PROPERTY_INVALIDATED(m_shuffle, MediaPlayer::ShuffleOff, shuffleChanged); } else if (property == QLatin1String("Status")) { PROPERTY_INVALIDATED(m_status, MediaPlayer::Error, statusChanged); } else if (property == QLatin1String("Position")) { PROPERTY_INVALIDATED(m_position, 0, positionChanged); } else if (property == QLatin1String("Track")) { m_track = variantToTrack(QVariant()); Q_EMIT q.data()->trackChanged(m_track); } } } MediaPlayerTrack MediaPlayerPrivate::variantToTrack(const QVariant &variant) const { const QVariantMap &properties = qdbus_cast(variant); return MediaPlayerTrack(properties); } } // namespace BluezQt diff --git a/src/obexmanager.cpp b/src/obexmanager.cpp index 3b1baab..36e86fa 100644 --- a/src/obexmanager.cpp +++ b/src/obexmanager.cpp @@ -1,145 +1,145 @@ /* * BluezQt - Asynchronous Bluez wrapper library * * Copyright (C) 2014 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "obexmanager.h" #include "obexmanager_p.h" #include "initobexmanagerjob.h" #include "debug.h" #include "pendingcall.h" #include "obexagent.h" #include "obexagentadaptor.h" #include "obexsession.h" #include "utils.h" #include namespace BluezQt { ObexManager::ObexManager(QObject *parent) : QObject(parent) , d(new ObexManagerPrivate(this)) { Instance::setObexManager(this); } ObexManager::~ObexManager() { delete d; } InitObexManagerJob *ObexManager::init() { return new InitObexManagerJob(this); } bool ObexManager::isInitialized() const { return d->m_initialized; } bool ObexManager::isOperational() const { return d->m_initialized && d->m_obexRunning && d->m_loaded; } QList ObexManager::sessions() const { return d->m_sessions.values(); } ObexSessionPtr ObexManager::sessionForPath(const QDBusObjectPath &path) const { - Q_FOREACH (ObexSessionPtr session, d->m_sessions) { + for (ObexSessionPtr session : qAsConst(d->m_sessions)) { if (path.path().startsWith(session->objectPath().path())) { return session; } } return ObexSessionPtr(); } PendingCall *ObexManager::startService() { QDBusMessage msg = QDBusMessage::createMethodCall(Strings::orgFreedesktopDBus(), QStringLiteral("/org/freedesktop/DBus"), Strings::orgFreedesktopDBus(), QStringLiteral("StartServiceByName")); msg << Strings::orgBluezObex(); msg << quint32(0); return new PendingCall(DBusConnection::orgBluezObex().asyncCall(msg), PendingCall::ReturnUint32); } PendingCall *ObexManager::registerAgent(ObexAgent *agent) { Q_ASSERT(agent); if (!d->m_obexAgentManager) { return new PendingCall(PendingCall::InternalError, QStringLiteral("ObexManager not operational!")); } new ObexAgentAdaptor(agent, this); if (!DBusConnection::orgBluezObex().registerObject(agent->objectPath().path(), agent)) { qCDebug(BLUEZQT) << "Cannot register object" << agent->objectPath().path(); } return new PendingCall(d->m_obexAgentManager->RegisterAgent(agent->objectPath()), PendingCall::ReturnVoid, this); } PendingCall *ObexManager::unregisterAgent(ObexAgent *agent) { Q_ASSERT(agent); if (!d->m_obexAgentManager) { return new PendingCall(PendingCall::InternalError, QStringLiteral("ObexManager not operational!")); } DBusConnection::orgBluezObex().unregisterObject(agent->objectPath().path()); return new PendingCall(d->m_obexAgentManager->UnregisterAgent(agent->objectPath()), PendingCall::ReturnVoid, this); } PendingCall *ObexManager::createSession(const QString &destination, const QVariantMap &args) { if (!d->m_obexClient) { return new PendingCall(PendingCall::InternalError, QStringLiteral("ObexManager not operational!")); } return new PendingCall(d->m_obexClient->CreateSession(destination, args), PendingCall::ReturnObjectPath, this); } PendingCall *ObexManager::removeSession(const QDBusObjectPath &session) { if (!d->m_obexClient) { return new PendingCall(PendingCall::InternalError, QStringLiteral("ObexManager not operational!")); } return new PendingCall(d->m_obexClient->RemoveSession(session), PendingCall::ReturnVoid, this); } } // namespace BluezQt diff --git a/src/obexmanager_p.cpp b/src/obexmanager_p.cpp index 2535b62..e90c298 100644 --- a/src/obexmanager_p.cpp +++ b/src/obexmanager_p.cpp @@ -1,264 +1,264 @@ /* * BluezQt - Asynchronous Bluez wrapper library * * Copyright (C) 2014-2015 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "obexmanager_p.h" #include "obexmanager.h" #include "obexsession.h" #include "obexsession_p.h" #include "debug.h" #include "utils.h" #include "dbusobjectmanager.h" #include namespace BluezQt { typedef org::freedesktop::DBus::ObjectManager DBusObjectManager; ObexManagerPrivate::ObexManagerPrivate(ObexManager *q) : QObject(q) , q(q) , m_obexClient(nullptr) , m_obexAgentManager(nullptr) , m_dbusObjectManager(nullptr) , m_initialized(false) , m_obexRunning(false) , m_loaded(false) { qDBusRegisterMetaType(); qDBusRegisterMetaType(); m_timer.setSingleShot(true); connect(&m_timer, &QTimer::timeout, this, &ObexManagerPrivate::load); } void ObexManagerPrivate::init() { // Keep an eye on org.bluez.obex service QDBusServiceWatcher *serviceWatcher = new QDBusServiceWatcher(Strings::orgBluezObex(), DBusConnection::orgBluezObex(), QDBusServiceWatcher::WatchForRegistration | QDBusServiceWatcher::WatchForUnregistration, this); connect(serviceWatcher, &QDBusServiceWatcher::serviceRegistered, this, &ObexManagerPrivate::serviceRegistered); connect(serviceWatcher, &QDBusServiceWatcher::serviceUnregistered, this, &ObexManagerPrivate::serviceUnregistered); // Update the current state of org.bluez.obex service if (!DBusConnection::orgBluezObex().isConnected()) { Q_EMIT initError(QStringLiteral("DBus session bus is not connected!")); return; } QDBusMessage call = QDBusMessage::createMethodCall(Strings::orgFreedesktopDBus(), QStringLiteral("/"), Strings::orgFreedesktopDBus(), QStringLiteral("NameHasOwner")); call << Strings::orgBluezObex(); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(DBusConnection::orgBluezObex().asyncCall(call)); connect(watcher, &QDBusPendingCallWatcher::finished, this, &ObexManagerPrivate::nameHasOwnerFinished); } void ObexManagerPrivate::nameHasOwnerFinished(QDBusPendingCallWatcher *watcher) { const QDBusPendingReply &reply = *watcher; watcher->deleteLater(); if (reply.isError()) { Q_EMIT initError(reply.error().message()); return; } m_obexRunning = reply.value(); if (m_obexRunning) { load(); } else { m_initialized = true; Q_EMIT initFinished(); } } void ObexManagerPrivate::load() { if (!m_obexRunning || m_loaded) { return; } // Force QDBus to cache owner of org.bluez.obex - this will be the only blocking call on session connection DBusConnection::orgBluezObex().connect(Strings::orgBluezObex(), QStringLiteral("/"), Strings::orgFreedesktopDBus(), QStringLiteral("Dummy"), this, SLOT(dummy())); m_dbusObjectManager = new DBusObjectManager(Strings::orgBluezObex(), QStringLiteral("/"), DBusConnection::orgBluezObex(), this); connect(m_dbusObjectManager, &DBusObjectManager::InterfacesAdded, this, &ObexManagerPrivate::interfacesAdded); connect(m_dbusObjectManager, &DBusObjectManager::InterfacesRemoved, this, &ObexManagerPrivate::interfacesRemoved); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(m_dbusObjectManager->GetManagedObjects(), this); connect(watcher, &QDBusPendingCallWatcher::finished, this, &ObexManagerPrivate::getManagedObjectsFinished); } void ObexManagerPrivate::getManagedObjectsFinished(QDBusPendingCallWatcher *watcher) { const QDBusPendingReply &reply = *watcher; watcher->deleteLater(); if (reply.isError()) { Q_EMIT initError(reply.error().message()); return; } DBusManagerStruct::const_iterator it; const DBusManagerStruct &managedObjects = reply.value(); for (it = managedObjects.constBegin(); it != managedObjects.constEnd(); ++it) { const QString &path = it.key().path(); const QVariantMapMap &interfaces = it.value(); if (interfaces.contains(Strings::orgBluezObexSession1())) { addSession(path, interfaces.value(Strings::orgBluezObexSession1())); } else if (interfaces.contains(Strings::orgBluezObexClient1()) && interfaces.contains(Strings::orgBluezObexAgentManager1())) { m_obexClient = new ObexClient(Strings::orgBluezObex(), path, DBusConnection::orgBluezObex(), this); m_obexAgentManager = new ObexAgentManager(Strings::orgBluezObex(), path, DBusConnection::orgBluezObex(), this); } } if (!m_obexClient) { Q_EMIT initError(QStringLiteral("Cannot find org.bluez.obex.Client1 object!")); return; } if (!m_obexAgentManager) { Q_EMIT initError(QStringLiteral("Cannot find org.bluez.obex.AgentManager1 object!")); return; } m_loaded = true; m_initialized = true; Q_EMIT q->operationalChanged(true); Q_EMIT initFinished(); } void ObexManagerPrivate::clear() { m_loaded = false; // Delete all sessions while (!m_sessions.isEmpty()) { ObexSessionPtr session = m_sessions.begin().value(); m_sessions.remove(m_sessions.begin().key()); Q_EMIT q->sessionRemoved(session); } // Delete all other objects if (m_obexClient) { m_obexClient->deleteLater(); m_obexClient = nullptr; } if (m_obexAgentManager) { m_obexAgentManager->deleteLater(); m_obexAgentManager = nullptr; } if (m_dbusObjectManager) { m_dbusObjectManager->deleteLater(); m_dbusObjectManager = nullptr; } } void ObexManagerPrivate::serviceRegistered() { qCDebug(BLUEZQT) << "Obex service registered"; m_obexRunning = true; // Client1 and AgentManager1 objects are not ready by the time org.bluez.obex is registered // nor will the ObjectManager emits interfacesAdded for adding them... // So we delay the call to load() by 0.5s m_timer.start(500); } void ObexManagerPrivate::serviceUnregistered() { qCDebug(BLUEZQT) << "Obex service unregistered"; m_obexRunning = false; clear(); Q_EMIT q->operationalChanged(false); } void ObexManagerPrivate::interfacesAdded(const QDBusObjectPath &objectPath, const QVariantMapMap &interfaces) { const QString &path = objectPath.path(); QVariantMapMap::const_iterator it; for (it = interfaces.constBegin(); it != interfaces.constEnd(); ++it) { if (it.key() == Strings::orgBluezObexSession1()) { addSession(path, it.value()); } } } void ObexManagerPrivate::interfacesRemoved(const QDBusObjectPath &objectPath, const QStringList &interfaces) { const QString &path = objectPath.path(); - Q_FOREACH (const QString &interface, interfaces) { + for (const QString &interface : interfaces) { if (interface == Strings::orgBluezObexSession1()) { removeSession(path); } } } void ObexManagerPrivate::addSession(const QString &sessionPath, const QVariantMap &properties) { ObexSessionPtr session = ObexSessionPtr(new ObexSession(sessionPath, properties)); session->d->q = session.toWeakRef(); m_sessions.insert(sessionPath, session); Q_EMIT q->sessionAdded(session); } void ObexManagerPrivate::removeSession(const QString &sessionPath) { ObexSessionPtr session = m_sessions.take(sessionPath); if (!session) { return; } Q_EMIT q->sessionRemoved(session); } void ObexManagerPrivate::dummy() { } } // namespace BluezQt diff --git a/src/pendingcall.cpp b/src/pendingcall.cpp index 4f950f1..1e2b6cb 100644 --- a/src/pendingcall.cpp +++ b/src/pendingcall.cpp @@ -1,316 +1,317 @@ /* * BluezQt - Asynchronous Bluez wrapper library * * Copyright (C) 2014 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "pendingcall.h" #include "obextransfer.h" #include "obextransfer_p.h" #include "obexfiletransferentry.h" #include "bluezqt_dbustypes.h" #include "debug.h" #include #include #include namespace BluezQt { static PendingCall::Error nameToError(const QString &name) { if (name.startsWith(QLatin1String("org.freedesktop.DBus.Error"))) { return PendingCall::DBusError; } if (!name.startsWith(QLatin1String("org.bluez.Error"))) { return PendingCall::UnknownError; } #define FROM_BLUEZ_ERROR(string, value) \ if (errorName == QLatin1String(string)) { \ return value; \ } const QString &errorName = name.mid(16); FROM_BLUEZ_ERROR("NotReady", PendingCall::NotReady); FROM_BLUEZ_ERROR("Failed", PendingCall::Failed); FROM_BLUEZ_ERROR("Rejected", PendingCall::Rejected); FROM_BLUEZ_ERROR("Canceled", PendingCall::Canceled); FROM_BLUEZ_ERROR("InvalidArguments", PendingCall::InvalidArguments); FROM_BLUEZ_ERROR("AlreadyExists", PendingCall::AlreadyExists); FROM_BLUEZ_ERROR("DoesNotExist", PendingCall::DoesNotExist); FROM_BLUEZ_ERROR("AlreadyConnected", PendingCall::AlreadyConnected); FROM_BLUEZ_ERROR("ConnectFailed", PendingCall::ConnectFailed); FROM_BLUEZ_ERROR("NotConnected", PendingCall::NotConnected); FROM_BLUEZ_ERROR("NotSupported", PendingCall::NotSupported); FROM_BLUEZ_ERROR("NotAuthorized", PendingCall::NotAuthorized); FROM_BLUEZ_ERROR("AuthenticationCanceled", PendingCall::AuthenticationCanceled); FROM_BLUEZ_ERROR("AuthenticationFailed", PendingCall::AuthenticationFailed); FROM_BLUEZ_ERROR("AuthenticationRejected", PendingCall::AuthenticationRejected); FROM_BLUEZ_ERROR("AuthenticationTimeout", PendingCall::AuthenticationTimeout); FROM_BLUEZ_ERROR("ConnectionAttemptFailed", PendingCall::ConnectionAttemptFailed); #undef FROM_BLUEZ_ERROR return PendingCall::UnknownError; } class PendingCallPrivate : public QObject { public: explicit PendingCallPrivate(PendingCall *parent); void processReply(QDBusPendingCallWatcher *call); void processVoidReply(const QDBusPendingReply<> &reply); void processUint32Reply(const QDBusPendingReply &reply); void processStringReply(const QDBusPendingReply &reply); void processObjectPathReply(const QDBusPendingReply &reply); void processFileTransferListReply(const QDBusPendingReply &reply); void processTransferWithPropertiesReply(const QDBusPendingReply &reply); void processError(const QDBusError &m_error); void emitFinished(); void emitDelayedFinished(); void emitInternalError(const QString &errorText); void pendingCallFinished(QDBusPendingCallWatcher *m_watcher); PendingCall *q; int m_error; QString m_errorText; QVariant m_userData; QVariantList m_value; PendingCall::ReturnType m_type; QDBusPendingCallWatcher *m_watcher; }; PendingCallPrivate::PendingCallPrivate(PendingCall *parent) : QObject(parent) , q(parent) , m_error(PendingCall::NoError) , m_type(PendingCall::ReturnVoid) , m_watcher(nullptr) { } void PendingCallPrivate::processReply(QDBusPendingCallWatcher *call) { switch (m_type) { case PendingCall::ReturnVoid: processVoidReply(*call); break; case PendingCall::ReturnUint32: processUint32Reply(*call); break; case PendingCall::ReturnString: processStringReply(*call); break; case PendingCall::ReturnObjectPath: processObjectPathReply(*call); break; case PendingCall::ReturnFileTransferList: processFileTransferListReply(*call); break; case PendingCall::ReturnTransferWithProperties: processTransferWithPropertiesReply(*call); break; default: break; } } void PendingCallPrivate::processVoidReply(const QDBusPendingReply<> &reply) { processError(reply.error()); } void PendingCallPrivate::processUint32Reply(const QDBusPendingReply &reply) { processError(reply.error()); if (!reply.isError()) { m_value.append(reply.value()); } } void PendingCallPrivate::processStringReply(const QDBusPendingReply &reply) { processError(reply.error()); if (!reply.isError()) { m_value.append(reply.value()); } } void PendingCallPrivate::processObjectPathReply(const QDBusPendingReply &reply) { processError(reply.error()); if (!reply.isError()) { m_value.append(QVariant::fromValue(reply.value())); } } void PendingCallPrivate::processFileTransferListReply(const QDBusPendingReply &reply) { processError(reply.error()); if (!reply.isError()) { QList items; items.reserve(reply.value().size()); - Q_FOREACH (const QVariantMap &map, reply.value()) { + const auto maps = reply.value(); + for (const QVariantMap &map : maps) { items.append(ObexFileTransferEntry(map)); } m_value.append(QVariant::fromValue(items)); } } void PendingCallPrivate::processTransferWithPropertiesReply(const QDBusPendingReply &reply) { processError(reply.error()); if (reply.isError()) { return; } ObexTransferPtr transfer = ObexTransferPtr(new ObexTransfer(reply.argumentAt<0>().path(), reply.argumentAt<1>())); transfer->d->q = transfer.toWeakRef(); transfer->d->m_suspendable = true; m_value.append(QVariant::fromValue(transfer)); } void PendingCallPrivate::processError(const QDBusError &error) { if (error.isValid()) { qCWarning(BLUEZQT) << "PendingCall Error:" << error.message(); m_error = nameToError(error.name()); m_errorText = error.message(); } } void PendingCallPrivate::emitFinished() { m_watcher->deleteLater(); m_watcher = nullptr; Q_EMIT q->finished(q); q->deleteLater(); } void PendingCallPrivate::emitDelayedFinished() { Q_ASSERT(qobject_cast(sender())); Q_EMIT q->finished(q); static_cast(sender())->deleteLater(); } void PendingCallPrivate::emitInternalError(const QString &errorText) { qCWarning(BLUEZQT) << "PendingCall Internal error:" << errorText; m_error = PendingCall::InternalError; m_errorText = errorText; emitFinished(); } void PendingCallPrivate::pendingCallFinished(QDBusPendingCallWatcher *watcher) { processReply(watcher); emitFinished(); } PendingCall::PendingCall(const QDBusPendingCall &call, ReturnType type, QObject *parent) : QObject(parent) , d(new PendingCallPrivate(this)) { qDBusRegisterMetaType(); d->m_type = type; d->m_watcher = new QDBusPendingCallWatcher(call, this); connect(d->m_watcher, &QDBusPendingCallWatcher::finished, d, &PendingCallPrivate::pendingCallFinished); } PendingCall::PendingCall(PendingCall::Error error, const QString &errorText, QObject *parent) : QObject(parent) , d(new PendingCallPrivate(this)) { d->m_error = error; d->m_errorText = errorText; QTimer *timer = new QTimer(this); timer->setSingleShot(true); timer->start(0); connect(timer, &QTimer::timeout, d, &PendingCallPrivate::emitDelayedFinished); } PendingCall::~PendingCall() { delete d; } QVariant PendingCall::value() const { if (d->m_value.isEmpty()) { return QVariant(); } return d->m_value.first(); } QVariantList PendingCall::values() const { return d->m_value; } int PendingCall::error() const { return d->m_error; } QString PendingCall::errorText() const { return d->m_errorText; } bool PendingCall::isFinished() const { if (d->m_watcher) { return d->m_watcher->isFinished(); } return true; } void PendingCall::waitForFinished() { if (d->m_watcher) { d->m_watcher->waitForFinished(); } } QVariant PendingCall::userData() const { return d->m_userData; } void PendingCall::setUserData(const QVariant &userData) { d->m_userData = userData; } } // namespace BluezQt diff --git a/src/rfkill.cpp b/src/rfkill.cpp index 7bf8e52..be8f90b 100644 --- a/src/rfkill.cpp +++ b/src/rfkill.cpp @@ -1,262 +1,262 @@ /* * BluezQt - Asynchronous Bluez wrapper library * * Copyright (C) 2015 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "rfkill.h" #include "debug.h" #ifdef Q_OS_LINUX #include #include #include #include #endif #include namespace BluezQt { #ifdef Q_OS_LINUX enum rfkill_type { RFKILL_TYPE_ALL = 0, RFKILL_TYPE_WLAN, RFKILL_TYPE_BLUETOOTH, RFKILL_TYPE_UWB, RFKILL_TYPE_WIMAX, RFKILL_TYPE_WWAN }; enum rfkill_operation { RFKILL_OP_ADD = 0, RFKILL_OP_DEL, RFKILL_OP_CHANGE, RFKILL_OP_CHANGE_ALL }; struct rfkill_event { quint32 idx; quint8 type; quint8 op; quint8 soft; quint8 hard; }; #endif Rfkill::Rfkill(QObject *parent) : QObject(parent) , m_readFd(-1) , m_writeFd(-1) , m_state(Unknown) { init(); } Rfkill::~Rfkill() { #ifdef Q_OS_LINUX if (m_readFd != -1) { ::close(m_readFd); } if (m_writeFd != -1) { ::close(m_writeFd); } #endif } Rfkill::State Rfkill::state() const { return m_state; } bool Rfkill::block() { if (m_state == SoftBlocked || m_state == HardBlocked) { return true; } if (m_state != Unblocked) { return false; } return setSoftBlock(1); } bool Rfkill::unblock() { if (m_state == Unblocked) { return true; } if (m_state != SoftBlocked) { return false; } return setSoftBlock(0); } void Rfkill::devReadyRead() { State oldState = m_state; updateRfkillDevices(); if (m_state != oldState) { Q_EMIT stateChanged(m_state); } } void Rfkill::init() { #ifdef Q_OS_LINUX m_readFd = ::open("/dev/rfkill", O_RDONLY | O_CLOEXEC); if (m_readFd == -1) { qCWarning(BLUEZQT) << "Cannot open /dev/rfkill for reading!"; return; } if (::fcntl(m_readFd, F_SETFL, O_NONBLOCK) < 0) { ::close(m_readFd); m_readFd = -1; return; } updateRfkillDevices(); QSocketNotifier *notifier = new QSocketNotifier(m_readFd, QSocketNotifier::Read, this); connect(notifier, &QSocketNotifier::activated, this, &Rfkill::devReadyRead); #endif } bool Rfkill::openForWriting() { #ifndef Q_OS_LINUX return false; #else if (m_writeFd != -1) { return true; } m_writeFd = ::open("/dev/rfkill", O_WRONLY | O_CLOEXEC); if (m_writeFd == -1) { qCWarning(BLUEZQT) << "Cannot open /dev/rfkill for writing!"; return false; } if (::fcntl(m_writeFd, F_SETFL, O_NONBLOCK) < 0) { ::close(m_writeFd); m_writeFd = -1; return false; } return true; #endif } #ifdef Q_OS_LINUX static Rfkill::State getState(const rfkill_event &event) { if (event.hard) { return Rfkill::HardBlocked; } else if (event.soft) { return Rfkill::SoftBlocked; } return Rfkill::Unblocked; } #endif void Rfkill::updateRfkillDevices() { #ifdef Q_OS_LINUX if (m_readFd == -1) { return; } rfkill_event event; while (::read(m_readFd, &event, sizeof(event)) == sizeof(event)) { if (event.type != RFKILL_TYPE_BLUETOOTH) { continue; } switch (event.op) { case RFKILL_OP_ADD: case RFKILL_OP_CHANGE: m_devices[event.idx] = getState(event); break; case RFKILL_OP_DEL: m_devices.remove(event.idx); break; case RFKILL_OP_CHANGE_ALL: - Q_FOREACH (quint32 id, m_devices.keys()) { - m_devices[id] = getState(event); + for (auto it = m_devices.begin(); it != m_devices.end(); ++it) { + it.value() = getState(event); } break; default: break; } } // Update global state m_state = Unknown; - Q_FOREACH (State state, m_devices) { // krazy:exclude=foreach + for (State state : qAsConst(m_devices)) { Q_ASSERT(state != Unknown); if (m_state == Unknown) { m_state = state; } else if (state > m_state) { m_state = state; } } qCDebug(BLUEZQT) << "Rfkill global state changed:" << m_state; #endif } bool Rfkill::setSoftBlock(quint8 soft) { #ifndef Q_OS_LINUX Q_UNUSED(soft) return false; #else if (!openForWriting()) { return false; } rfkill_event event; ::memset(&event, 0, sizeof(event)); event.op = RFKILL_OP_CHANGE_ALL; event.type = RFKILL_TYPE_BLUETOOTH; event.soft = soft; bool ret = ::write(m_writeFd, &event, sizeof(event)) == sizeof(event); qCDebug(BLUEZQT) << "Setting Rfkill soft block succeeded:" << ret; return ret; #endif } } // namespace BluezQt diff --git a/src/utils.cpp b/src/utils.cpp index 210e988..69e43cc 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -1,305 +1,305 @@ /* * BluezQt - Asynchronous Bluez wrapper library * * Copyright (C) 2014-2015 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "utils.h" #include "manager.h" #include "obexmanager.h" #include "bluezqt_export.h" #include #include #include namespace BluezQt { class GlobalData { public: explicit GlobalData(); bool testRun; QString orgFreedesktopDBus; QString orgFreedesktopDBusProperties; QString orgBluez; QString orgBluezAdapter1; QString orgBluezDevice1; QString orgBluezInput1; QString orgBluezMedia1; QString orgBluezMediaPlayer1; QString orgBluezAgentManager1; QString orgBluezProfileManager1; QString orgBluezObex; QString orgBluezObexClient1; QString orgBluezObexAgentManager1; QString orgBluezObexSession1; QString orgBluezObexTransfer1; QPointer manager; QPointer obexManager; }; GlobalData::GlobalData() { testRun = false; orgFreedesktopDBus = QStringLiteral("org.freedesktop.DBus"); orgFreedesktopDBusProperties = QStringLiteral("org.freedesktop.DBus.Properties"); orgBluez = QStringLiteral("org.bluez"); orgBluezAdapter1 = QStringLiteral("org.bluez.Adapter1"); orgBluezDevice1 = QStringLiteral("org.bluez.Device1"); orgBluezInput1 = QStringLiteral("org.bluez.Input1"); orgBluezMedia1 = QStringLiteral("org.bluez.Media1"); orgBluezMediaPlayer1 = QStringLiteral("org.bluez.MediaPlayer1"); orgBluezAgentManager1 = QStringLiteral("org.bluez.AgentManager1"); orgBluezProfileManager1 = QStringLiteral("org.bluez.ProfileManager1"); orgBluezObex = QStringLiteral("org.bluez.obex"); orgBluezObexClient1 = QStringLiteral("org.bluez.obex.Client1"); orgBluezObexAgentManager1 = QStringLiteral("org.bluez.obex.AgentManager1"); orgBluezObexSession1 = QStringLiteral("org.bluez.obex.Session1"); orgBluezObexTransfer1 = QStringLiteral("org.bluez.obex.Transfer1"); } Q_GLOBAL_STATIC(GlobalData, globalData) // For fakebluez tests BLUEZQT_EXPORT void bluezqt_initFakeBluezTestRun() { globalData->testRun = true; globalData->orgBluez = QStringLiteral("org.kde.bluezqt.fakebluez"); globalData->orgBluezObex = QStringLiteral("org.kde.bluezqt.fakebluez"); } QString Strings::orgFreedesktopDBus() { return globalData->orgFreedesktopDBus; } QString Strings::orgFreedesktopDBusProperties() { return globalData->orgFreedesktopDBusProperties; } QString Strings::orgBluez() { return globalData->orgBluez; } QString Strings::orgBluezAdapter1() { return globalData->orgBluezAdapter1; } QString Strings::orgBluezDevice1() { return globalData->orgBluezDevice1; } QString Strings::orgBluezInput1() { return globalData->orgBluezInput1; } QString Strings::orgBluezMedia1() { return globalData->orgBluezMedia1; } QString Strings::orgBluezMediaPlayer1() { return globalData->orgBluezMediaPlayer1; } QString Strings::orgBluezAgentManager1() { return globalData->orgBluezAgentManager1; } QString Strings::orgBluezProfileManager1() { return globalData->orgBluezProfileManager1; } QString Strings::orgBluezObex() { return globalData->orgBluezObex; } QString Strings::orgBluezObexClient1() { return globalData->orgBluezObexClient1; } QString Strings::orgBluezObexAgentManager1() { return globalData->orgBluezObexAgentManager1; } QString Strings::orgBluezObexSession1() { return globalData->orgBluezObexSession1; } QString Strings::orgBluezObexTransfer1() { return globalData->orgBluezObexTransfer1; } QDBusConnection DBusConnection::orgBluez() { if (globalData->testRun) { return QDBusConnection::sessionBus(); } return QDBusConnection::systemBus(); } QDBusConnection DBusConnection::orgBluezObex() { return QDBusConnection::sessionBus(); } Manager *Instance::manager() { return globalData->manager; } void Instance::setManager(Manager *manager) { globalData->manager = manager; } ObexManager *Instance::obexManager() { return globalData->obexManager; } void Instance::setObexManager(ObexManager *obexManager) { globalData->obexManager = obexManager; } QStringList stringListToUpper(const QStringList &list) { QStringList converted; converted.reserve(list.size()); - Q_FOREACH (const QString &str, list) { + for (const QString &str : list) { converted.append(str.toUpper()); } return converted; } Device::Type classToType(quint32 classNum) { switch ((classNum & 0x1f00) >> 8) { case 0x01: return Device::Computer; case 0x02: switch ((classNum & 0xfc) >> 2) { case 0x04: return Device::Modem; default: return Device::Phone; } case 0x03: return Device::Network; case 0x04: switch ((classNum & 0xfc) >> 2) { case 0x01: case 0x02: return Device::Headset; case 0x06: return Device::Headphones; default: return Device::AudioVideo; } case 0x05: switch ((classNum & 0xc0) >> 6) { case 0x00: switch ((classNum & 0x1e) >> 2) { case 0x01: case 0x02: return Device::Joypad; } break; case 0x01: return Device::Keyboard; case 0x02: switch ((classNum & 0x1e) >> 2) { case 0x05: return Device::Tablet; default: return Device::Mouse; } } return Device::Peripheral; case 0x06: if (classNum & 0x80) { return Device::Printer; } else if (classNum & 0x20) { return Device::Camera; } return Device::Imaging; case 0x07: return Device::Wearable; case 0x08: return Device::Toy; case 0x09: return Device::Health; default: return Device::Uncategorized; } } Device::Type appearanceToType(quint16 appearance) { switch ((appearance & 0xffc0) >> 6) { case 0x00: return Device::Uncategorized; case 0x01: // Generic Phone return Device::Phone; case 0x02: // Generic Computer return Device::Computer; case 0x05: // Generic Display return Device::AudioVideo; case 0x0a: // Generic Media Player return Device::AudioVideo; case 0x0b: // Generic Barcode Scanner return Device::Peripheral; case 0x0f: // Generic HID switch (appearance & 0x3f) { case 0x01: // Keyboard return Device::Keyboard; case 0x02: // Mouse return Device::Mouse; case 0x03: // Joystick case 0x04: // Gamepad return Device::Joypad; case 0x05: // Digitizer Tablet return Device::Tablet; case 0x08: // Barcode Scanner return Device::Peripheral; } // fall-through default: return Device::Uncategorized; } } } // namespace BluezQt diff --git a/tests/devicereceiver.cpp b/tests/devicereceiver.cpp index 726d5ff..8ab745c 100644 --- a/tests/devicereceiver.cpp +++ b/tests/devicereceiver.cpp @@ -1,122 +1,122 @@ /* * Copyright (C) 2010 Rafael Fernández López * Copyright (C) 2010 UFO Coders * Copyright (C) 2014-2015 David Rosca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "devicereceiver.h" #include #include #include #include "adapter.h" #include "device.h" #include "pendingcall.h" #include "initmanagerjob.h" using namespace BluezQt; Manager *g_manager = nullptr; DeviceReceiver::DeviceReceiver(QObject *parent) : QObject(parent) { } void DeviceReceiver::scanDevices() { AdapterPtr usableAdapter = g_manager->usableAdapter(); if (!usableAdapter && g_manager->adapters().isEmpty()) { qDebug() << "!!! No bluetooth adapters were found. Waiting for bluetooth adapters. Ctrl + C to cancel..."; connect(g_manager, &Manager::adapterAdded, this, &DeviceReceiver::adapterAdded); return; } else if (!usableAdapter) { usableAdapter = g_manager->adapters().at(0); PendingCall *powerOnCall = usableAdapter->setPowered(true); powerOnCall->waitForFinished(); } qDebug() << "*** Will scan devices until stopped..."; qDebug(); connect(usableAdapter.data(), &Adapter::deviceAdded, this, &DeviceReceiver::deviceFound); connect(usableAdapter.data(), &Adapter::deviceChanged, this, &DeviceReceiver::devicePropertyChanged); usableAdapter->startDiscovery(); } void DeviceReceiver::deviceFound(const BluezQt::DevicePtr &device) { qDebug() << "*** Remote device found:" << device->name() << "(" << device->address() << ")"; qDebug(); } void DeviceReceiver::devicePropertyChanged(const BluezQt::DevicePtr &device) { qDebug() << "*** Device with address" << device->address() << "changed some property"; qDebug() << "\tAddress:\t" << device->address(); qDebug() << "\tClass:\t\t" << device->deviceClass(); qDebug() << "\tIcon:\t\t" << device->icon(); qDebug() << "\tLegacy Pairing:\t" << (device->hasLegacyPairing() ? "yes" : "no"); qDebug() << "\tName:\t\t" << device->name(); qDebug() << "\tPaired:\t\t" << (device->isPaired() ? "yes" : "no"); qDebug() << "\tTrusted:\t" << (device->isTrusted() ? "yes" : "no"); qDebug() << "\tServices:\n" << device->uuids(); qDebug(); } void DeviceReceiver::adapterAdded(const BluezQt::AdapterPtr &adapter) { Q_UNUSED(adapter) qDebug() << "*** An adapter has been connected."; qDebug(); scanDevices(); } static void stopDiscovering() { if (g_manager) { - Q_FOREACH (const AdapterPtr &adapter, g_manager->adapters()) { + for (const AdapterPtr &adapter : g_manager->adapters()) { adapter->stopDiscovery(); } } } int main(int argc, char **argv) { QCoreApplication app(argc, argv); qAddPostRoutine(stopDiscovering); g_manager = new Manager(); InitManagerJob *initJob = g_manager->init(); initJob->exec(); if (initJob->error()) { qWarning() << "Error initializing manager:" << initJob->errorText(); return 1; } DeviceReceiver *deviceReceiver = new DeviceReceiver(); deviceReceiver->scanDevices(); return app.exec(); }