Development/Tutorials/D-Bus/Accessing Interfaces

From KDE TechBase
Accessing D-Bus Interfaces
Tutorial Series   D-Bus
Previous   Introduction To D-Bus
What's Next   Creating D-Bus Interfaces
Further Reading   n/a

Abstract

D-Bus allows applications to expose internal API to the outside world. These APIs can then be accessed at run-time via the D-Bus protocol using command line applications or D-Bus libraries and bindings themselves. This tutorial looks at the latter method with examples that you can use in your applications.

Using QDBusMessage

QDBusMessage represents a D-Bus messages that can be sent or has been received over a given bus. Each message is one of five types, depending on the purpose of the message:

  • method call
  • signal
  • reply
  • error
  • invalid

An enumeration covering each of these possibilities is defined in QDBusMessage. A message's type can be access via the QDBusMessage::type() method.

Calling a D-Bus Method

A QDBusMessage can be used directly to call methods in D-Bus services using the QDbusMessage::createMethod( const QString & service, const QString & path, const QString & interface, const QString & method ) static method. It returns a QDBusMessage object that you can then use to make the call.

The interface parameter is optional and only necessary if the method to be called is not unique in the accessed object address by the path. This can happen with the object implements multiple interfaces and those interfaces have methods with the same name. In such (rare) cases, if you do not define the interface to use there is not guarantee as to which method will actually get called. However, usually you can simply pass an empty string (e.g. "") as the argument for interface.

By way of example, to access the (fictional) ping method on the /network object in the org.foo.bar service, one might do this:

QDBusMessage m = QDBusMessage::createMessage("org.foo.bar",

                                             "/network",
                                             "",
                                             "ping");

bool queued = QDBusConnection::sessionBus()->send(m);

In line 5 of the above example we queue the message for sending on the current session bus. We get a bool returned letting us know if the queuing was successful or not.

This leaves us with two questions, however:

  • How can one set parameters for a method call?
  • How can one get a return message in the case of D-Bus methods that have a return value?

Setting Parameters

Sending arguments along with the method call is quite straight forward. First we need to create a QList of QVariant objects and then add those to our dbus message. So if the ping method in the above took a hostname as a parameter, we might alter the code in this way (note lines 5 through 7):

QDBusMessage m = QDBusMessage::createMessage("org.foo.bar",

                                             "/network",
                                             "",
                                             "ping");

QList<QVariant> args; args.append("kde.org"); m.setArguments(args); bool queued = QDBusConnection::sessionBus()->send(m);

Note
The arguments must appear in the QList in the same order they are expected by the D-Bus method being called.


Getting Replies

If we wish to actually receive information back from the D-Bus method, we use the QDBusConnect::call method instead. It will block until there is a reply or the call times out. If our ping method returned information on the host we provided in the arguments above, we might alter our code to look like this:


QDBusMessage m = QDBusMessage::createMessage("org.foo.bar",

                                              "/network",
                                              "",
                                              "ping");

QList<QVariant> args; args.append("kde.org"); m.setArguments(args); QDBusMessage response = QDBusConnection::sessionBus()->call(m);

The response will be either of type QDBusMessage::ReplyMessage or QDBusMessage::ErrorMessage depending on whether it was successful or not. We can look through the values returned by retreving the arguments with the QDBusMessage::arguments() method which returns a QList<QVariant>.

Is This The Best Way?

Using QDBusMessage directly in this way to invoke remote D-Bus methods is not the easiest, best or even recommend way of doing things. Next we will look at the more convnient QDBusInterface class and then look at accessing remote D-Bus interfaces as if they were local methods using a class auto-generated from the XML D-Bus interface description.

Using QDBusInterface

QDBusInterface provides a simple and direct method to make D-Bus calls and connect to D-Bus signals.

A QDBusInterface object represents a given D-Bus interface. The constructor accepts as parameters (in order) a service name, an object path, an optional interface and optionally which bus (e.g. system or session) to use. If no bus is explicitly define, it defaults to the session bus.

As QDBusInterface is a QObject, you can also pass it a parent object. This helps simplify the bookkeeping associated with creating new QDBusInterface objects by letting Qt clean up for you when the parent object is deleted.

Here is an example of QDBusInterface usage which we will then step through line by line:

QString hostname("kde.org"); QDBusConnection bus = QDBusConnection::sessionBus(); QDBusInterface interface = new QDBusInterface("org.foo.bar",

                                             "/network",
                                             QString(), 
                                             bus,
                                             this); 

interface->call("ping"); interface->call("ping", hostname);

QList<QVariant> args; args.append("kde.org"); interface->callWithArgumentList("ping", args);

QDBusReply<int> reply = interface->call("ping",

                                             hostname);

if (reply.isValid()) {

    KMessageBox::information(winId(), 
                             i18n("Ping to %1 took %2s")
                              .arg(hostname)
                              .arg(reply.value()),
                             i18n("Pinging %1")
                              .arg(hostname));

}

args.clear(); interface->callWithCallback("listInterfaces", args,

                           this,
                           SLOT(interfaceList(QDBusReply));

connect(interface, SIGNAL(interfaceUp(QString)),

       this, SLOT(interfaceUp(QString)));

Synchronous Calls

The first thing we did was create a QDBusInterface on line 3 that represents the same object we were accessing in the QDBusMessage examples above.

We then called several D-Bus methods on that object using a few different techniques. On line 9 we make a simple call to a method called ping without any arguments. On line 10, we call the same method but with a parameter. Note that we didn't have to create a QList<QVariant> for the arguments. We can pass up to 8 arguments to a D-Bus method this way.

If you need to pass more than 8 arguments or for some other reason a QList<QVariant> is simply a better approach for the circumstances, then you may use the callWithArgumentList method instead as seen on lines 12-14 above.

Handling Replies

On line 16 we call the ping method yet again, but this time save the reply in a QDBusReply object. We check to make sure the reply was valid (e.g. no errors were returned and we did indeed get an int back) and then use the returned data to populate a message in an informational popup.

Asynchronous Method Calls and Signals

Up to this point in the example all of the calls made were synchronous and the application would block until a reply was received. The last two uses of QDBusInterface in the example show asynchronous usage of D-Bus, and in both cases we rely on Qt's signal and slot mechanism.

On line 28 we use callWithCallback and provide a regular QObject slot to be called when the D-Bus reply returns. This way the application will not block as callWithCallback returns immediately after queueing the message to be sent on the bus. Later, the interfaceList slot would get called. Note that this method requires a QList<QVariant>; there is no shortcut for us this time.

Finally, on line 29 we connect to a D-Bus signal. Note that when done using QDBusInterface that is looks exactly like we are connecting to a regular, local signal in our own application. We even use the standard QOjbect::connect method! This is accomplished by QDBusInterface using Qt's meta object system to dynamically add the signals the D-Bus interface we are using advertises. Very slick!


Is This the Best Way?

This ease of use over QDBusMessage does come with some prices, however. First, since QDBusInterface is a QObject it caries the overhead that implies. It also well perform at least one round-trip to the requested D-Bus object on creation to set up the interface object with things such as the available signals. Often this additional overhead is negligable in the larger scheme of things and well made up for by the convenience it provides.

There are still some annoyances we have to deal with, however, such as having to know the name of the service and interface or setting up the correct QDBusReply object such as we did above by templating it with an int. So while it's an improvement over QDBusMessage, it's still not perfect.

And that's precisely where qdbusxml2cpp comes to our rescue.

Using Classes Generated From D-Bus XML

Connecting To Signals

Other Resources