Dienstag, 12. Mai 2015

Qt: Setting dbus-properties and calling dbus-mehtods using QtDBus

The following examples on this page will set the "Powered" property for bluez to true for the first bluetooth adapter (hci0) found.

All examples use the following defines:
 #define BLUEZ_DBUS_SERVICE "org.bluez"  
 #define BLUEZ_DBUS_PATH "/org/bluez/hci0"  
 #define BLUEZ_DBUS_IF "org.bluez.Adapter1"  


Set a dbus property using QtDBus

   QDBusInterface ifc(  
         BLUEZ_DBUS_SERVICE,  
         BLUEZ_DBUS_PATH,  
         BLUEZ_DBUS_IF,  
         QDBusConnection::systemBus());  
   if ( ifc.isValid() ) {  
     ifc.setProperty("Powered", true);  
   }  

Calling methods with QtDBus

Example 1:
   QDBusConnection bus = QDBusConnection::systemBus();  
   if (!bus.isConnected())  
   {  
     qFatal("Cannot connect to the D-Bus session bus.");  
     return;  
   }  
   QDBusInterface dbus_iface(BLUEZ_DBUS_SERVICE,  
                BLUEZ_DBUS_PATH,  
                "org.freedesktop.DBus.Properties",  
                bus);  
   if ( dbus_iface.isValid() ) {  
     QDBusPendingReply<QVariantMap> reply = dbus_iface.asyncCall("Set",  
                                   BLUEZ_DBUS_IF,  
                                   "Powered",  
                                   QVariant::fromValue(QDBusVariant(true)));  
     reply.waitForFinished();  
   }  

Example 2:
   QDBusConnection bus = QDBusConnection::systemBus();  
   if (!bus.isConnected())  
   {  
     qFatal("Cannot connect to the D-Bus session bus.");  
     return;  
   }  
   QDBusMessage message = QDBusMessage::createMethodCall(BLUEZ_DBUS_SERVICE,  
                              BLUEZ_DBUS_PATH,  
                              "org.freedesktop.DBus.Properties",  
                              "Set");  
   QList<QVariant> arguments;  
   arguments << BLUEZ_DBUS_IF
        << "Powered"
        << QVariant::fromValue(QDBusVariant(true));  
   message.setArguments(arguments);  
   QDBusPendingReply<QVariantMap> reply = bus.asyncCall(message);  
   reply.waitForFinished();  

In case there is something not working the reply message can provide some usefull hints:
    qDebug() << reply.error().message();   

qdbusviewer

A really nice tool is the qdbusviewer which you can use to browse the dbus hierarchy:
For methods this tool will also show you types of the parameters.

Footnote

If the rfkill block bits are set for  the bluetooth devices you still have to unblock the bluetooth devices first:
$ rfkill unblock bluetooth  
At least on my system this has the side effect that the Powered property will be set to true. With the code above you can set the property to false without affecting the rfkill setting.

Keine Kommentare:

Kommentar veröffentlichen