Difference between revisions of "Development/Tutorials/D-Bus/Accessing Interfaces"

Jump to: navigation, search
m (Text replace - "<code cppqt n>" to "<syntaxhighlight lang="cpp-qt" line>")
m (Text replace - "<code>" to "<syntaxhighlight lang="text">")
Line 188: Line 188:
With the path to the XML in hand, we then add something like this to our {{path|CMakeLists.txt}}:
With the path to the XML in hand, we then add something like this to our {{path|CMakeLists.txt}}:
<syntaxhighlight lang="text">
set(network_xml ${DBUS_PREFIX}/interfaces/org.foo.bar.xml)
set(network_xml ${DBUS_PREFIX}/interfaces/org.foo.bar.xml)

Revision as of 21:44, 29 June 2011



Accessing D-Bus Interfaces
Tutorial Series   D-Bus
Previous   Introduction
What's Next   Creating Interfaces, Intermediate D-Bus
Further Reading   n/a


D-Bus allows applications to expose their 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 four types, depending on the purpose of the message:

  • method call
  • signal
  • reply
  • error

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::createMethodCall( 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 object associated with the path. This can happen if the object implements multiple interfaces which have methods that are named the same. In such (rare) cases, if you do not explicitly 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:

  1. QDBusMessage m = QDBusMessage::createMethodCall("org.foo.bar",
  2.                                               "/network",
  3.                                               "",
  4.                                               "ping");
  5. bool queued = QDBusConnection::sessionBus().send(m);
  6. </code>
  7. <!-- </pre> -->
  9. In line 5 of the above example we queue the message for sending on the current session bus. We get a <tt>bool</tt> returned letting us know if the queueing was successful or not.
  11. This leaves us with two questions, however:
  12. * How can one set parameters for a method call?
  13. * How can one get a return message in the case of D-Bus methods that have a return value?
  15. === Setting Parameters ===
  17. Sending arguments along with the method call is quite straight forward. First we need to create a {{qt|QList}} of {{qt|QVariant}} objects and then add those to our D-Bus message. So if the <tt>ping</tt> method in the above took a hostname as a parameter, we might alter the code in this way (note lines 5 through 7):
  19. <syntaxhighlight lang="cpp-qt" line>QDBusMessage m = QDBusMessage::createMethodCall("org.foo.bar",
  20.                                               "/network",
  21.                                               "",
  22.                                               "ping");
  23. QList<QVariant> args;
  24. args.append("kde.org");
  25. m.setArguments(args);
  26. bool queued = QDBusConnection::sessionBus().send(m);</code>
  28. Alternatively, {{qt|QDBusMessage}} provides a convenience method to appending parameters to the message, by way of its "operator<<" function. The above example becomes:
  30. <syntaxhighlight lang="cpp-qt" line>QDBusMessage m = QDBusMessage::createMethodCall("org.foo.bar",
  31.                                               "/network",
  32.                                               "",
  33.                                               "ping");
  34. m << "kde.org";
  35. bool queued = QDBusConnection::sessionBus().send(m);</code>
  37. {{note|The arguments must appear in the {{qt|QList}} in the same order they are expected by the D-Bus method being called.}}
  39. === Getting Replies ===
  41. If we wish to actually receive information back from the D-Bus method, we use the <tt>{{qt|QDBusConnection}}::call</tt> method instead. It will block until there is a reply or the call times out. If our <tt>ping</tt> method returned information on the host we provided in the arguments above, we might alter our code to look like this:
  44. <syntaxhighlight lang="cpp-qt" line>QDBusMessage m = QDBusMessage::createMethodCall("org.foo.bar",
  45.                                                "/network",
  46.                                                "",
  47.                                                "ping");
  48. m << "kde.org";
  49. QDBusMessage response = QDBusConnection::sessionBus().call(m);</code>
  51. The <tt>response</tt> will be either of type <tt>QDBusMessage::ReplyMessage</tt> or <tt>QDBusMessage::ErrorMessage</tt> depending on whether it was successful or not. We can look through the values returned by retrieving the arguments with the <tt>{{qt|QDBusMessage}}::arguments()</tt> method which returns a <tt>{{qt|QList}}&lt;{{qt|QVariant}}&gt;</tt>.
  53. === Is This The Best Way? ===
  55. Using QDBusMessage directly in this way to invoke remote D-Bus methods is not the easiest, best or even recommend way of doing things. We will now look at the more convenient {{qt|QDBusInterface}} class and then look at accessing remote D-Bus interfaces as if they were local methods using proxy classes auto-generated from XML.
  57. == Using QDBusInterface ==
  59. {{qt|QDBusInterface}} provides a simple and direct method to make D-Bus calls and connect to D-Bus signals.
  61. A {{qt|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 defined, it defaults to the session bus. If no interface is given, the returned object will be used to call all interfaces on the bus.
  63. However, note that explicitly passing an interface name to the {{qt|QDBusInterface}} constructor is recommended. Due to the internals of QtDBus, if you pass an empty interface, you will always cause a round-trip to the remote application to verify which methods are available. On the other hand, if you pass a non-empty interface name, QtDBus may cache the result for further uses.
  65. As {{qt|QDBusInterface}} is a QObject, you can also pass it a parent object. This helps simplify the bookkeeping associated with creating new {{qt|QDBusInterface}} objects by letting Qt clean up for you when the parent object is deleted.
  67. Here is an example of {{qt|QDBusInterface}} usage which we will then step through line by line:
  69. <syntaxhighlight lang="cpp-qt" line>
  70. QString hostname("kde.org");
  71. QDBusConnection bus = QDBusConnection::sessionBus();
  72. QDBusInterface *interface = new QDBusInterface("org.foo.bar",
  73.                                                "/network",
  74.                                                "org.foo.bar.network", 
  75.                                                bus,
  76.                                                this); 
  78. interface->call("ping");
  79. interface->call("ping", hostname);
  81. QList<QVariant> args;
  82. args.append("kde.org");
  83. interface->callWithArgumentList("ping", args);
  85. QDBusReply<int> reply = interface->call("ping",
  86.                                         hostname);
  87. if (reply.isValid())
  88. {
  89.      KMessageBox::information(winId(), 
  90.                               i18n("Ping to %1 took %2s")
  91.                                .arg(hostname)
  92.                                .arg(reply.value()),
  93.                               i18n("Pinging %1")
  94.                                .arg(hostname));
  95. }
  97. args.clear();
  98. interface->callWithCallback("listInterfaces", args,
  99.                             this,
  100.                             SLOT(interfaceList(QDBusMessage)));
  102. connect(interface, SIGNAL(interfaceUp(QString)),
  103.         this, SLOT(interfaceUp(QString)));
  104. </code>
  106. === Synchronous Calls ===
  108. The first thing we did was create a {{qt|QDBusInterface}} on line 3 that represents the same object we were accessing in the QDBusMessage examples above. 
  110. 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 <tt>ping</tt> without any arguments. On line 10, we call the same method but with a parameter. Note that we didn't have to create a <tt>{{qt|QList}}&lt;{{qt|QVariant}}&gt;</tt> for the arguments. We can pass up to 8 arguments to a D-Bus method this way.
  112. If you need to pass more than 8 arguments or for some other reason a <tt>{{qt|QList}}&lt;{{qt|QVariant}}&gt;</tt> is simply a better approach for the circumstances, then you may use the <tt>callWithArgumentList</tt> method instead as seen on lines 12-14 above.
  114. === Handling Replies ===
  116. On line 16 we call the <tt>ping</tt> method yet again, but this time save the reply in a {{qt|QDBusReply}} object. We check to make sure the reply was valid (e.g. no errors were returned and we did indeed get an <tt>int</tt> back) and then use the returned data to populate a message in an informational popup.
  118. === Asynchronous Method Calls and Signals ===
  120. 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 {{qt|QDBusInterface}} in the example show asynchronous usage of D-Bus, and in both cases we rely on Qt's signal and slot mechanism.
  122. On line 29 we use <tt>callWithCallback</tt> and provide a regular QObject slot to be called when the D-Bus reply returns. This way the application will not block as <tt>callWithCallback</tt> returns immediately after queueing the message to be sent on the bus. Later, the <tt>interfaceList</tt> slot would get called. Note that this method requires a <tt>{{qt|QList}}&lt;{{qt|QVariant}}&gt;</tt>; there is no shortcut for us this time.
  124. Finally, on line 33 we connect to a D-Bus signal. Using {{qt|QDBusInterface}} to do this looks exactly like connecting to a regular, local signal in our own application. We even use the standard <tt>{{qt|QObject}}::{{qt|connect}}</tt> method! This is accomplished by {{qt|QDBusInterface}} using Qt's meta object system to dynamically add the signals the D-Bus interface advertises. Very slick!
  126. === Is ''This'' the Best Way? ===
  128. This ease of use over {{qt|QDBusMessage}} does come with some prices, however. First, since {{qt|QDBusInterface}} is a {{qt|QObject}} it carries the overhead that implies. It also will 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 negligible in the larger scheme of things and well made up for by the convenience it provides.
  130. There are still some annoyances we have to deal with, however, such as having to know the name of the interface, setting up the correct {{qt|QDBusReply}} object such as we did above by templating it with an <tt>int</tt> and having to debug method name typos and the like at runtime versus letting the compiler do it for us. So while it's an improvement over {{qt|QDBusMessage}}, it's still not perfect.
  132. And that's precisely where <tt>qdbusxml2cpp</tt> comes to our rescue.
  134. == Using Classes Generated From D-Bus XML ==
  136. What would be truly great is if we could simply instantiate a local object that represented a given service and start using it right away. Perhaps something like this:
  138. <syntaxhighlight lang="cpp-qt" line>
  139. org::foo::bar::network *interface = 
  140.     new org::foo::bar::network("org.foo.bar", "/network",
  141.                             QDBusConnection::sessionBus(),
  142.                             this);
  143. interface->ping("kde.org");
  144. </code>
  146. Fortunately for us, this is precisely what Qt allows us to do. The only requirement is an XML file describing the D-Bus service. Such files are installed in the D-Bus prefix in the {{path|interfaces}} directory. 
  148. {{tip|The D-Bus prefix can be found by issuing the following command in a terminal:<br><tt><nowiki>pkg-config dbus-1 --variable=prefix</nowiki></tt>}}
  150. We can also create our own XML files from the C++ header files and use those directly. This is covered in the next tutorial, [[../Creating_Interfaces|Creating D-Bus Interfaces]].
  152. With the path to the XML in hand, we then add something like this to our {{path|CMakeLists.txt}}:
  154. <syntaxhighlight lang="text">
  155. PKGCONFIG_GETVAR(dbus-1 prefix DBUS_PREFIX)
  156. set(network_xml ${DBUS_PREFIX}/interfaces/org.foo.bar.xml)
  157. qt4_add_dbus_interface(myapp_SRCS ${network_xml} network_interface )
  158. </code>
  160. This will generate two files at build time, {{path|network_interface.h}} and {{path|network_interface.cpp}}, and add them to the compiled application. We can then simply <tt>#include "network_interface.h"</tt> and use the generated class as seen in the example above.
  162. Examining the generated header file, we can see exactly what methods, signals as well as their signatures and return values are according to the provider of the service. Using the class directly will let the compiler do type checking on method calls leaving fewer run-time breakages to track down.
  164. Due to the generated class being a subclass of {{qt|QDBusAbstractInterface}} just as {{qt|QDBusInterface}} is, anything we can do with {{qt|QDBusInterface}} is also available to us.
  166. Due to this combination of ease of use and compile-time checking, this is generally the preferred mechanism to use when accessing D-Bus interfaces.
  168. {{tip|If your CMake installation does not provide the PKGCONFIG_GETVAR, you can add [[Development/Tutorials/D-Bus/Accessing Interfaces/PkgConfigGetVar.cmake|this cmake module]] to your project.}}
  170. == Doing A Little Introspection ==
  172. It may also be helpful to find out if a given service is available or to check which application is providing it. Another {{qt|QDBusAbstractInterface}} subclass, {{qt|QDBusConnectionInterface}}, provides methods to query for such information as which services are registered and who owns them.
  174. Once you have a service name, you can then use {{qt|QDBusInterface}} to get the <tt>org.freedesktop.DBus.Introspectable</tt> interface and call <tt>Introspect</tt> on it. This will return an XML block describing the objects, which can in turn be introspected for what they provide. The XML itself can be processed using <tt>QDomDocument</tt>, making it a fairly simple process.
  176. The {{path|qdbus}} application that ships with Qt4 provides a nice example of code doing exactly this. It can be found in {{path|tools/qdbus/tools/qdbus/qdbus.cpp}} in the Qt4 source distribution.
  178. [[Category:C++]]

KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V.Legal