1 <?xml version="1.0" standalone="no"?>
2 <!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
3 "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd"
9 <title>D-Bus Tutorial</title>
10 <releaseinfo>Version 0.4.1</releaseinfo>
11 <date>15 July 2005</date>
14 <firstname>Havoc</firstname>
15 <surname>Pennington</surname>
17 <orgname>Red Hat, Inc.</orgname>
18 <address><email>hp@pobox.com</email></address>
22 <firstname>David</firstname>
23 <surname>Wheeler</surname>
26 <firstname>John</firstname>
27 <surname>Palmieri</surname>
29 <orgname>Red Hat, Inc.</orgname>
30 <address><email>johnp@redhat.com</email></address>
34 <firstname>Colin</firstname>
35 <surname>Walters</surname>
37 <orgname>Red Hat, Inc.</orgname>
38 <address><email>walters@redhat.com</email></address>
45 <title>What is D-Bus?</title>
47 D-Bus is a system for <firstterm>interprocess communication</firstterm>
48 (IPC). Architecturally, it has several layers:
53 A library, <firstterm>libdbus</firstterm>, that allows two
54 applications to connect to each other and exchange messages.
59 A <firstterm>message bus daemon</firstterm> executable, built on
60 libdbus, that multiple applications can connect to. The daemon can
61 route messages from one application to zero or more other
67 <firstterm>Wrapper libraries</firstterm> based on particular
68 application frameworks. For example, libdbus-glib and
69 libdbus-qt. There are also bindings to languages such as
70 Python. These wrapper libraries are the API most people should use,
71 as they simplify the details of D-Bus programming. libdbus is
72 intended to be a low-level backend for the higher level bindings.
73 Much of the libdbus API is only useful for binding implementation.
80 If you just want to use D-Bus and don't care how it works, jump directly
81 to <xref linkend="concepts"/>.
86 libdbus only supports one-to-one connections, just like a raw network
87 socket. However, rather than sending byte streams over the connection, you
88 send <firstterm>messages</firstterm>. Messages have a header identifying
89 the kind of message, and a body containing a data payload. libdbus also
90 abstracts the exact transport used (sockets vs. whatever else), and
91 handles details such as authentication.
95 The message bus daemon forms the hub of a wheel. Each spoke of the wheel
96 is a one-to-one connection to an application using libdbus. An
97 application sends a message to the bus daemon over its spoke, and the bus
98 daemon forwards the message to other connected applications as
99 appropriate. Think of the daemon as a router.
103 The bus daemon has multiple instances on a typical computer. The
104 first instance is a machine-global singleton, that is, a system daemon
105 similar to sendmail or Apache. This instance has heavy security
106 restrictions on what messages it will accept, and is used for systemwide
107 communication. The other instances are created one per user login session.
108 These instances allow applications in the user's session to communicate
113 The systemwide and per-user daemons are separate. Normal within-session
114 IPC does not involve the systemwide message bus process and vice versa.
118 <title>D-Bus applications</title>
120 There are many, many technologies in the world that have "Inter-process
121 communication" or "networking" in their stated purpose: <ulink
122 url="http://www.omg.org">CORBA</ulink>, <ulink
123 url="http://www.opengroup.org/dce/">DCE</ulink>, <ulink
124 url="http://www.microsoft.com/com/">DCOM</ulink>, <ulink
125 url="http://developer.kde.org/documentation/library/kdeqt/dcop.html">DCOP</ulink>, <ulink
126 url="http://www.xmlrpc.com">XML-RPC</ulink>, <ulink
127 url="http://www.w3.org/TR/SOAP/">SOAP</ulink>, <ulink
128 url="http://www.mbus.org/">MBUS</ulink>, <ulink
129 url="http://www.zeroc.com/ice.html">Internet Communications Engine (ICE)</ulink>,
130 and probably hundreds more.
131 Each of these is tailored for particular kinds of application.
132 D-Bus is designed for two specific cases:
136 Communication between desktop applications in the same desktop
137 session; to allow integration of the desktop session as a whole,
138 and address issues of process lifecycle (when do desktop components
139 start and stop running).
144 Communication between the desktop session and the operating system,
145 where the operating system would typically include the kernel
146 and any system daemons or processes.
152 For the within-desktop-session use case, the GNOME and KDE desktops
153 have significant previous experience with different IPC solutions
154 such as CORBA and DCOP. D-Bus is built on that experience and
155 carefully tailored to meet the needs of these desktop projects
156 in particular. D-Bus may or may not be appropriate for other
157 applications; the FAQ has some comparisons to other IPC systems.
160 The problem solved by the systemwide or communication-with-the-OS case
161 is explained well by the following text from the Linux Hotplug project:
164 A gap in current Linux support is that policies with any sort of
165 dynamic "interact with user" component aren't currently
166 supported. For example, that's often needed the first time a network
167 adapter or printer is connected, and to determine appropriate places
168 to mount disk drives. It would seem that such actions could be
169 supported for any case where a responsible human can be identified:
170 single user workstations, or any system which is remotely
175 This is a classic "remote sysadmin" problem, where in this case
176 hotplugging needs to deliver an event from one security domain
177 (operating system kernel, in this case) to another (desktop for
178 logged-in user, or remote sysadmin). Any effective response must go
179 the other way: the remote domain taking some action that lets the
180 kernel expose the desired device capabilities. (The action can often
181 be taken asynchronously, for example letting new hardware be idle
182 until a meeting finishes.) At this writing, Linux doesn't have
183 widely adopted solutions to such problems. However, the new D-Bus
184 work may begin to solve that problem.
189 D-Bus may happen to be useful for purposes other than the one it was
190 designed for. Its general properties that distinguish it from
191 other forms of IPC are:
195 Binary protocol designed to be used asynchronously
196 (similar in spirit to the X Window System protocol).
201 Stateful, reliable connections held open over time.
206 The message bus is a daemon, not a "swarm" or
207 distributed architecture.
212 Many implementation and deployment issues are specified rather
218 Semantics are similar to the existing DCOP system, allowing
219 KDE to adopt it more easily.
224 Security features to support the systemwide mode of the
232 <sect1 id="concepts">
233 <title>Concepts</title>
235 Some basic concepts apply no matter what application framework you're
236 using to write a D-Bus application. The exact code you write will be
237 different for GLib vs. Qt vs. Python applications, however.
241 Here is a diagram (<ulink url="diagram.png">png</ulink> <ulink
242 url="diagram.svg">svg</ulink>) that may help you visualize the concepts
247 <title>Objects and Object Paths</title>
249 Each application using D-Bus contains <firstterm>objects</firstterm>,
250 which generally map to GObject, QObject, C++ objects, or Python objects
251 (but need not). An object is an <emphasis>instance</emphasis> rather
252 than a type. When messages are received over a D-Bus connection, they
253 are sent to a specific object, not to the application as a whole.
256 To allow messages to specify their destination object, there has to be a
257 way to refer to an object. In your favorite programming language, this
258 is normally called a <firstterm>pointer</firstterm> or
259 <firstterm>reference</firstterm>. However, these references are
260 implemented as memory addresses relative to the address space of your
261 application, and thus can't be passed from one application to another.
264 To solve this, D-Bus introduces a name for each object. The name
265 looks like a filesystem path, for example an object could be
266 named <literal>/org/kde/kspread/sheets/3/cells/4/5</literal>.
267 Human-readable paths are nice, but you are free to create an
268 object named <literal>/com/mycompany/c5yo817y0c1y1c5b</literal>
269 if it makes sense for your application.
272 Namespacing object paths is smart, by starting them with the components
273 of a domain name you own (e.g. <literal>/org/kde</literal>). This
274 keeps different code modules in the same process from stepping
275 on one another's toes.
279 <sect2 id="interfaces">
280 <title>Interfaces</title>
282 Each object supports one or more <firstterm>interfaces</firstterm>.
283 Think of an interface as a named group of methods and signals,
284 just as it is in GLib or Qt or Java. Interfaces define the
285 <emphasis>type</emphasis> of an object instance.
289 <sect2 id="messages">
290 <title>Message Types</title>
292 Messages are not all the same; in particular, D-Bus has
293 4 built-in message types:
297 Method call messages ask to invoke a method
303 Method return messages return the results
304 of invoking a method.
309 Error messages return an exception caused by
315 Signal messages are notifications that a given signal
316 has been emitted (that an event has occurred).
317 You could also think of these as "event" messages.
323 A method call maps very simply to messages, then: you send a method call
324 message, and receive either a method return message or an error message
329 <sect2 id="bus-names">
330 <title>Bus Names</title>
333 Object paths, interfaces, and messages exist on the level of
334 libdbus and the D-Bus protocol; they are used even in the
335 1-to-1 case with no message bus involved.
339 Bus names, on the other hand, are a property of the message bus daemon.
340 The bus maintains a mapping from names to message bus connections.
341 These names are used to specify the origin and destination
342 of messages passing through the message bus. When a name is mapped
343 to a particular application's connection, that application is said to
344 <firstterm>own</firstterm> that name.
348 On connecting to the bus daemon, each application immediately owns a
349 special name called the <firstterm>unique connection name</firstterm>.
350 A unique name begins with a ':' (colon) character; no other names are
351 allowed to begin with that character. Unique names are special because
352 they are created dynamically, and are never re-used during the lifetime
353 of the same bus daemon. You know that a given unique name will have the
354 same owner at all times. An example of a unique name might be
355 <literal>:34-907</literal>. The numbers after the colon have
356 no meaning other than their uniqueness.
360 Applications may ask to own additional <firstterm>well-known
361 names</firstterm>. For example, you could write a specification to
362 define a name called <literal>com.mycompany.TextEditor</literal>.
363 Your definition could specify that to own this name, an application
364 should have an object at the path
365 <literal>/com/mycompany/TextFileManager</literal> supporting the
366 interface <literal>org.freedesktop.FileHandler</literal>.
370 Applications could then send messages to this bus name,
371 object, and interface to execute method calls.
375 You could think of the unique names as IP addresses, and the
376 well-known names as domain names. So
377 <literal>com.mycompany.TextEditor</literal> might map to something like
378 <literal>:34-907</literal> just as <literal>mycompany.com</literal> maps
379 to something like <literal>192.168.0.5</literal>.
383 Names have a second important use, other than routing messages. They
384 are used to track lifecycle. When an application exits (or crashes), its
385 connection to the message bus will be closed by the operating system
386 kernel. The message bus then sends out notification messages telling
387 remaining applications that the application's names have lost their
388 owner. By tracking these notifications, your application can reliably
389 monitor the lifetime of other applications.
394 <sect2 id="addresses">
395 <title>Addresses</title>
398 Applications using D-Bus are either servers or clients. A server
399 listens for incoming connections; a client connects to a server. Once
400 the connection is established, it is a symmetric flow of messages; the
401 client-server distinction only matters when setting up the
406 A D-Bus <firstterm>address</firstterm> specifies where a server will
407 listen, and where a client will connect. For example, the address
408 <literal>unix:path=/tmp/abcdef</literal> specifies that the server will
409 listen on a UNIX domain socket at the path
410 <literal>/tmp/abcdef</literal> and the client will connect to that
411 socket. An address can also specify TCP/IP sockets, or any other
412 transport defined in future iterations of the D-Bus specification.
416 When using D-Bus with a message bus, the bus daemon is a server
417 and all other applications are clients of the bus daemon.
418 libdbus automatically discovers the address of the per-session bus
419 daemon by reading an environment variable. It discovers the
420 systemwide bus daemon by checking a well-known UNIX domain socket path
421 (though you can override this address with an environment variable).
425 If you're using D-Bus without a bus daemon, it's up to you to
426 define which application will be the server and which will be
427 the client, and specify a mechanism for them to agree on
428 the server's address.
433 <sect2 id="bigpicture">
434 <title>Big Conceptual Picture</title>
437 Pulling all these concepts together, to specify a particular
438 method call on a particular object instance, a number of
439 nested components have to be named:
441 Address -> [Bus Name] -> Path -> Interface -> Method
443 The bus name is in brackets to indicate that it's optional -- you only
444 provide a name to route the method call to the right application
445 when using the bus daemon. If you have a direct connection to another
446 application, bus names aren't used; there's no bus daemon.
450 The interface is also optional, primarily for historical
451 reasons; DCOP does not require specifying the interface,
452 instead simply forbidding duplicate method names
453 on the same object instance. D-Bus will thus let you
454 omit the interface, but if your method name is ambiguous
455 it is undefined which method will be invoked.
462 <sect1 id="glib-client">
463 <title>GLib API: Using Remote Objects</title>
466 The GLib binding is defined in the header file
467 <literal><dbus/dbus-glib.h></literal>.
470 <sect2 id="glib-typemappings">
471 <title>D-Bus - GLib type mappings</title>
473 The heart of the GLib bindings for D-Bus is the mapping it
474 provides between D-Bus "type signatures" and GLib types
475 (<literal>GType</literal>). The D-Bus type system is composed of
476 a number of "basic" types, along with several "container" types.
478 <sect3 id="glib-basic-typemappings">
479 <title>Basic type mappings</title>
481 Below is a list of the basic types, along with their associated
482 mapping to a <literal>GType</literal>.
487 <entry>D-Bus basic type</entry>
489 <entry>Free function</entry>
495 <entry><literal>BYTE</literal></entry>
496 <entry><literal>G_TYPE_UCHAR</literal></entry>
500 <entry><literal>BOOLEAN</literal></entry>
501 <entry><literal>G_TYPE_BOOLEAN</literal></entry>
505 <entry><literal>INT16</literal></entry>
506 <entry><literal>G_TYPE_INT</literal></entry>
508 <entry>Will be changed to a <literal>G_TYPE_INT16</literal> once GLib has it</entry>
510 <entry><literal>UINT16</literal></entry>
511 <entry><literal>G_TYPE_UINT</literal></entry>
513 <entry>Will be changed to a <literal>G_TYPE_UINT16</literal> once GLib has it</entry>
515 <entry><literal>INT32</literal></entry>
516 <entry><literal>G_TYPE_INT</literal></entry>
518 <entry>Will be changed to a <literal>G_TYPE_INT32</literal> once GLib has it</entry>
520 <entry><literal>UINT32</literal></entry>
521 <entry><literal>G_TYPE_UINT</literal></entry>
523 <entry>Will be changed to a <literal>G_TYPE_UINT32</literal> once GLib has it</entry>
525 <entry><literal>INT64</literal></entry>
526 <entry><literal>G_TYPE_GINT64</literal></entry>
530 <entry><literal>UINT64</literal></entry>
531 <entry><literal>G_TYPE_GUINT64</literal></entry>
535 <entry><literal>DOUBLE</literal></entry>
536 <entry><literal>G_TYPE_DOUBLE</literal></entry>
540 <entry><literal>STRING</literal></entry>
541 <entry><literal>G_TYPE_STRING</literal></entry>
542 <entry><literal>g_free</literal></entry>
545 <entry><literal>OBJECT_PATH</literal></entry>
546 <entry><literal>DBUS_TYPE_G_PROXY</literal></entry>
547 <entry><literal>g_object_unref</literal></entry>
548 <entry>The returned proxy does not have an interface set; use <literal>dbus_g_proxy_set_interface</literal> to invoke methods</entry>
553 As you can see, the basic mapping is fairly straightforward.
556 <sect3 id="glib-container-typemappings">
557 <title>Container type mappings</title>
559 The D-Bus type system also has a number of "container"
560 types, such as <literal>DBUS_TYPE_ARRAY</literal> and
561 <literal>DBUS_TYPE_STRUCT</literal>. The D-Bus type system
562 is fully recursive, so one can for example have an array of
563 array of strings (i.e. type signature
564 <literal>aas</literal>).
567 However, not all of these types are in common use; for
568 example, at the time of this writing the author knows of no
569 one using <literal>DBUS_TYPE_STRUCT</literal>, or a
570 <literal>DBUS_TYPE_ARRAY</literal> containing any non-basic
571 type. The approach the GLib bindings take is pragmatic; try
572 to map the most common types in the most obvious way, and
573 let using less common and more complex types be less
577 First, D-Bus type signatures which have an "obvious"
578 corresponding built-in GLib type are mapped using that type:
583 <entry>D-Bus type signature</entry>
584 <entry>Description</entry>
586 <entry>C typedef</entry>
587 <entry>Free function</entry>
593 <entry><literal>as</literal></entry>
594 <entry>Array of strings</entry>
595 <entry><literal>G_TYPE_STRV</literal></entry>
596 <entry><literal>char **</literal></entry>
597 <entry><literal>g_strfreev</literal></entry>
600 <entry><literal>v</literal></entry>
601 <entry>Generic value container</entry>
602 <entry><literal>G_TYPE_VALUE</literal></entry>
603 <entry><literal>GValue *</literal></entry>
604 <entry><literal>g_value_unset</literal></entry>
605 <entry>The calling conventions for values expect that method callers have allocated return values; see below.</entry>
612 The next most common recursive type signatures are arrays of
613 basic values. The most obvious mapping for arrays of basic
614 types is a <literal>GArray</literal>. Now, GLib does not
615 provide a builtin <literal>GType</literal> for
616 <literal>GArray</literal>. However, we actually need more than
617 that - we need a "parameterized" type which includes the
618 contained type. Why we need this we will see below.
621 The approach taken is to create these types in the D-Bus GLib
622 bindings; however, there is nothing D-Bus specific about them.
623 In the future, we hope to include such "fundamental" types in GLib
629 <entry>D-Bus type signature</entry>
630 <entry>Description</entry>
632 <entry>C typedef</entry>
633 <entry>Free function</entry>
639 <entry><literal>ay</literal></entry>
640 <entry>Array of bytes</entry>
641 <entry><literal>DBUS_TYPE_G_BYTE_ARRAY</literal></entry>
642 <entry><literal>GArray *</literal></entry>
643 <entry>g_array_free</entry>
647 <entry><literal>au</literal></entry>
648 <entry>Array of uint</entry>
649 <entry><literal>DBUS_TYPE_G_UINT_ARRAY</literal></entry>
650 <entry><literal>GArray *</literal></entry>
651 <entry>g_array_free</entry>
655 <entry><literal>ai</literal></entry>
656 <entry>Array of int</entry>
657 <entry><literal>DBUS_TYPE_G_INT_ARRAY</literal></entry>
658 <entry><literal>GArray *</literal></entry>
659 <entry>g_array_free</entry>
663 <entry><literal>ax</literal></entry>
664 <entry>Array of int64</entry>
665 <entry><literal>DBUS_TYPE_G_INT64_ARRAY</literal></entry>
666 <entry><literal>GArray *</literal></entry>
667 <entry>g_array_free</entry>
671 <entry><literal>at</literal></entry>
672 <entry>Array of uint64</entry>
673 <entry><literal>DBUS_TYPE_G_UINT64_ARRAY</literal></entry>
674 <entry><literal>GArray *</literal></entry>
675 <entry>g_array_free</entry>
679 <entry><literal>ad</literal></entry>
680 <entry>Array of double</entry>
681 <entry><literal>DBUS_TYPE_G_DOUBLE_ARRAY</literal></entry>
682 <entry><literal>GArray *</literal></entry>
683 <entry>g_array_free</entry>
687 <entry><literal>ab</literal></entry>
688 <entry>Array of boolean</entry>
689 <entry><literal>DBUS_TYPE_G_BOOLEAN_ARRAY</literal></entry>
690 <entry><literal>GArray *</literal></entry>
691 <entry>g_array_free</entry>
699 D-Bus also includes a special type DBUS_TYPE_DICT_ENTRY which
700 is only valid in arrays. It's intended to be mapped to a "dictionary"
701 type by bindings. The obvious GLib mapping here is GHashTable. Again,
702 however, there is no builtin <literal>GType</literal> for a GHashTable.
703 Moreover, just like for arrays, we need a parameterized type so that
704 the bindings can communiate which types are contained in the hash table.
707 At present, only strings are supported. Work is in progress to
713 <entry>D-Bus type signature</entry>
714 <entry>Description</entry>
716 <entry>C typedef</entry>
717 <entry>Free function</entry>
723 <entry><literal>a{ss}</literal></entry>
724 <entry>Dictionary mapping strings to strings</entry>
725 <entry><literal>DBUS_TYPE_G_STRING_STRING_HASHTABLE</literal></entry>
726 <entry><literal>GHashTable *</literal></entry>
727 <entry>g_hash_table_destroy</entry>
735 <sect3 id="glib-generic-typemappings">
736 <title>Arbitrarily recursive type mappings</title>
738 Finally, it is possible users will want to write or invoke D-Bus
739 methods which have arbitrarily complex type signatures not
740 directly supported by these bindings. For this case, we have a
741 <literal>DBusGValue</literal> which acts as a kind of special
742 variant value which may be iterated over manually. The
743 <literal>GType</literal> associated is
744 <literal>DBUS_TYPE_G_VALUE</literal>.
747 TODO insert usage of <literal>DBUS_TYPE_G_VALUE</literal> here.
751 <sect2 id="sample-program-1">
752 <title>A sample program</title>
753 <para>Here is a D-Bus program using the GLib bindings.
756 main (int argc, char **argv)
758 DBusGConnection *connection;
762 char **name_list_ptr;
767 connection = dbus_g_bus_get (DBUS_BUS_SESSION,
769 if (connection == NULL)
771 g_printerr ("Failed to open connection to bus: %s\n",
773 g_error_free (error);
777 /* Create a proxy object for the "bus driver" (name "org.freedesktop.DBus") */
779 proxy = dbus_g_proxy_new_for_name (connection,
782 DBUS_INTERFACE_DBUS);
784 /* Call ListNames method, wait for reply */
786 if (!dbus_g_proxy_call (proxy, "ListNames", &error, G_TYPE_INVALID,
787 G_TYPE_STRV, &name_list, G_TYPE_INVALID))
789 /* Just do demonstrate remote exceptions versus regular GError */
790 if (error->domain == DBUS_GERROR && error->code == DBUS_GERROR_REMOTE_EXCEPTION)
791 g_printerr ("Caught remote method exception %s: %s",
792 dbus_g_error_get_name (error),
795 g_printerr ("Error: %s\n", error->message);
796 g_error_free (error);
800 /* Print the results */
802 g_print ("Names on the message bus:\n");
804 for (name_list_ptr = name_list; *name_list_ptr; name_list_ptr++)
806 g_print (" %s\n", *name_list_ptr);
808 g_strfreev (name_list);
810 g_object_unref (proxy);
817 <sect2 id="glib-program-setup">
818 <title>Program initalization</title>
820 A connection to the bus is acquired using
821 <literal>dbus_g_bus_get</literal>. Next, a proxy
822 is created for the object "/org/freedesktop/DBus" with
823 interface <literal>org.freedesktop.DBus</literal>
824 on the service <literal>org.freedesktop.DBus</literal>.
825 This is a proxy for the message bus itself.
828 <sect2 id="glib-method-invocation">
829 <title>Understanding method invocation</title>
831 You have a number of choices for method invocation. First, as
832 used above, <literal>dbus_g_proxy_call</literal> sends a
833 method call to the remote object, and blocks until a reply is
834 recieved. The outgoing arguments are specified in the varargs
835 array, terminated with <literal>G_TYPE_INVALID</literal>.
836 Next, pointers to return values are specified, followed again
837 by <literal>G_TYPE_INVALID</literal>.
840 To invoke a method asynchronously, use
841 <literal>dbus_g_proxy_begin_call</literal>. This returns a
842 <literal>DBusGPendingCall</literal> object; you may then set a
843 notification function using
844 <literal>dbus_g_pending_call_set_notify</literal>.
847 <sect2 id="glib-signal-connection">
848 <title>Connecting to object signals</title>
850 You may connect to signals using
851 <literal>dbus_g_proxy_add_signal</literal> and
852 <literal>dbus_g_proxy_connect_signal</literal>. You must
853 invoke <literal>dbus_g_proxy_add_signal</literal> to specify
854 the signature of your signal handlers; you may then invoke
855 <literal>dbus_g_proxy_connect_signal</literal> multiple times.
858 Note that it will often be the case that there is no builtin
859 marshaller for the type signature of a remote signal. In that
860 case, you must generate a marshaller yourself by using
861 <application>glib-genmarshal</application>, and then register
862 it using <literal>dbus_g_object_register_marshaller</literal>.
865 <sect2 id="glib-error-handling">
866 <title>Error handling and remote exceptions</title>
868 All of the GLib binding methods such as
869 <literal>dbus_g_proxy_end_call</literal> return a
870 <literal>GError</literal>. This <literal>GError</literal> can
871 represent two different things:
875 An internal D-Bus error, such as an out-of-memory
876 condition, an I/O error, or a network timeout. Errors
877 generated by the D-Bus library itself have the domain
878 <literal>DBUS_GERROR</literal>, and a corresponding code
879 such as <literal>DBUS_GERROR_NO_MEMORY</literal>. It will
880 not be typical for applications to handle these errors
886 A remote D-Bus exception, thrown by the peer, bus, or
887 service. D-Bus remote exceptions have both a textual
888 "name" and a "message". The GLib bindings store this
889 information in the <literal>GError</literal>, but some
893 The set error will have the domain
894 <literal>DBUS_GERROR</literal> as above, and will also
896 <literal>DBUS_GERROR_REMOTE_EXCEPTION</literal>. In order
897 to access the remote exception name, you must use a
898 special accessor, such as
899 <literal>dbus_g_error_has_name</literal> or
900 <literal>dbus_g_error_get_name</literal>. The remote
901 exception detailed message is accessible via the regular
902 GError <literal>message</literal> member.
908 <sect2 id="glib-more-examples">
909 <title>More examples of method invocation</title>
910 <sect3 id="glib-sending-stuff">
911 <title>Sending an integer and string, receiving an array of bytes</title>
917 if (!dbus_g_proxy_call (proxy, "Foobar", &error,
918 G_TYPE_INT, 42, G_TYPE_STRING, "hello",
920 DBUS_TYPE_G_UCHAR_ARRAY, &arr, G_TYPE_INVALID))
924 g_assert (arr != NULL);
925 printf ("got back %u values", arr->len);
929 <sect3 id="glib-sending-hash">
930 <title>Sending a GHashTable</title>
933 GHashTable *hash = g_hash_table_new (g_str_hash, g_str_equal);
936 g_hash_table_insert (hash, "foo", "bar");
937 g_hash_table_insert (hash, "baz", "whee");
940 if (!dbus_g_proxy_call (proxy, "HashSize", &error,
941 DBUS_TYPE_G_STRING_STRING_HASH, hash, G_TYPE_INVALID,
942 G_TYPE_UINT, &ret, G_TYPE_INVALID))
947 g_hash_table_destroy (hash);
951 <sect3 id="glib-receiving-bool-int">
952 <title>Receiving a boolean and a string</title>
959 if (!dbus_g_proxy_call (proxy, "GetStuff", &error,
961 G_TYPE_BOOLEAN, &boolret,
962 G_TYPE_STRING, &strret,
967 printf ("%s %s", boolret ? "TRUE" : "FALSE", strret);
972 <sect3 id="glib-sending-str-arrays">
973 <title>Sending two arrays of strings</title>
977 char *strs_static[] = {"foo", "bar", "baz", NULL};
978 /* Take pointer to array; cannot pass array directly */
979 char **strs_static_p = strs_static;
982 strs_dynamic = g_new (char *, 4);
983 strs_dynamic[0] = g_strdup ("hello");
984 strs_dynamic[1] = g_strdup ("world");
985 strs_dynamic[2] = g_strdup ("!");
987 strs_dynamic[3] = NULL;
990 if (!dbus_g_proxy_call (proxy, "TwoStrArrays", &error,
991 G_TYPE_STRV, strs_static_p,
992 G_TYPE_STRV, strs_dynamic,
998 g_strfreev (strs_dynamic);
1002 <sect3 id="glib-getting-str-array">
1003 <title>Sending a boolean, receiving an array of strings</title>
1012 if (!dbus_g_proxy_call (proxy, "GetStrs", &error,
1013 G_TYPE_BOOLEAN, blah,
1015 G_TYPE_STRV, &strs,
1020 for (strs_p = strs; *strs_p; strs_p++)
1021 printf ("got string: \"%s\"", *strs_p);
1026 <sect3 id="glib-sending-variant">
1027 <title>Sending a variant</title>
1032 g_value_init (&val, G_TYPE_STRING);
1033 g_value_set_string (&val, "hello world");
1036 if (!dbus_g_proxy_call (proxy, "SendVariant", &error,
1037 G_TYPE_VALUE, &val, G_TYPE_INVALID,
1042 g_assert (ret == 2);
1043 g_value_unset (&val);
1047 <sect3 id="glib-receiving-variant">
1048 <title>Receiving a variant</title>
1054 if (!dbus_g_proxy_call (proxy, "GetVariant", &error, G_TYPE_INVALID,
1055 G_TYPE_VALUE, &val, G_TYPE_INVALID))
1059 if (G_VALUE_TYPE (&val) == G_TYPE_STRING)
1060 printf ("%s\n", g_value_get_string (&val));
1061 else if (G_VALUE_TYPE (&val) == G_TYPE_INT)
1062 printf ("%d\n", g_value_get_int (&val));
1065 g_value_unset (&val);
1071 <sect2 id="glib-generated-bindings">
1072 <title>Generated Bindings</title>
1074 By using the Introspection XML files, convenient client-side bindings
1075 can be automatically created to ease the use of a remote DBus object.
1078 Here is a sample XML file which describes an object that exposes
1079 one method, named <literal>ManyArgs</literal>.
1081 <?xml version="1.0" encoding="UTF-8" ?>
1082 <node name="/com/example/MyObject">
1083 <interface name="com.example.MyObject">
1084 <method name="ManyArgs">
1085 <arg type="u" name="x" direction="in" />
1086 <arg type="s" name="str" direction="in" />
1087 <arg type="d" name="trouble" direction="in" />
1088 <arg type="d" name="d_ret" direction="out" />
1089 <arg type="s" name="str_ret" direction="out" />
1096 Run <literal>dbus-binding-tool --mode=glib-client
1097 <replaceable>FILENAME</replaceable> >
1098 <replaceable>HEADER_NAME</replaceable></literal> to generate the header
1099 file. For example: <command>dbus-binding-tool --mode=glib-client
1100 my-object.xml > my-object-bindings.h</command>. This will generate
1101 inline functions with the following prototypes:
1103 /* This is a blocking call */
1105 com_example_MyObject_many_args (DBusGProxy *proxy, const guint IN_x,
1106 const char * IN_str, const gdouble IN_trouble,
1107 gdouble* OUT_d_ret, char ** OUT_str_ret,
1110 /* This is a non-blocking call */
1112 com_example_MyObject_many_args_async (DBusGProxy *proxy, const guint IN_x,
1113 const char * IN_str, const gdouble IN_trouble,
1114 com_example_MyObject_many_args_reply callback,
1117 /* This is the typedef for the non-blocking callback */
1119 (*com_example_MyObject_many_args_reply)
1120 (DBusGProxy *proxy, gdouble OUT_d_ret, char * OUT_str_ret,
1121 GError *error, gpointer userdata);
1123 The first argument in all functions is a <literal>DBusGProxy
1124 *</literal>, which you should create with the usual
1125 <literal>dbus_g_proxy_new_*</literal> functions. Following that are the
1126 "in" arguments, and then either the "out" arguments and a
1127 <literal>GError *</literal> for the synchronous (blocking) function, or
1128 callback and user data arguments for the asynchronous (non-blocking)
1129 function. The callback in the asynchronous function passes the
1130 <literal>DBusGProxy *</literal>, the returned "out" arguments, an
1131 <literal>GError *</literal> which is set if there was an error otherwise
1132 <literal>NULL</literal>, and the user data.
1135 As with the server-side bindings support (see <xref
1136 linkend="glib-server"/>), the exact behaviour of the client-side
1137 bindings can be manipulated using "annotations". Currently the only
1138 annotation used by the client bindings is
1139 <literal>org.freedesktop.DBus.GLib.NoReply</literal>, which sets the
1140 flag indicating that the client isn't expecting a reply to the method
1141 call, so a reply shouldn't be sent. This is often used to speed up
1142 rapid method calls where there are no "out" arguments, and not knowing
1143 if the method succeeded is an acceptable compromise to half the traffic
1149 <sect1 id="glib-server">
1150 <title>GLib API: Implementing Objects</title>
1152 At the moment, to expose a GObject via D-Bus, you must
1153 write XML by hand which describes the methods exported
1154 by the object. In the future, this manual step will
1155 be obviated by the upcoming GLib introspection support.
1158 Here is a sample XML file which describes an object that exposes
1159 one method, named <literal>ManyArgs</literal>.
1161 <?xml version="1.0" encoding="UTF-8" ?>
1163 <node name="/com/example/MyObject">
1165 <interface name="com.example.MyObject">
1166 <annotation name="org.freedesktop.DBus.GLib.CSymbol" value="my_object"/>
1167 <method name="ManyArgs">
1168 <!-- This is optional, and in this case is redunundant -->
1169 <annotation name="org.freedesktop.DBus.GLib.CSymbol" value="my_object_many_args"/>
1170 <arg type="u" name="x" direction="in" />
1171 <arg type="s" name="str" direction="in" />
1172 <arg type="d" name="trouble" direction="in" />
1173 <arg type="d" name="d_ret" direction="out" />
1174 <arg type="s" name="str_ret" direction="out" />
1181 This XML is in the same format as the D-Bus introspection XML
1182 format. Except we must include an "annotation" which give the C
1183 symbols corresponding to the object implementation prefix
1184 (<literal>my_object</literal>). In addition, if particular
1185 methods symbol names deviate from C convention
1186 (i.e. <literal>ManyArgs</literal> ->
1187 <literal>many_args</literal>), you may specify an annotation
1188 giving the C symbol.
1191 Once you have written this XML, run <literal>dbus-binding-tool --mode=glib-server <replaceable>FILENAME</replaceable> > <replaceable>HEADER_NAME</replaceable>.</literal> to
1192 generate a header file. For example: <command>dbus-binding-tool --mode=glib-server my-object.xml > my-object-glue.h</command>.
1195 Next, include the generated header in your program, and invoke
1196 <literal>dbus_g_object_class_install_info</literal> in the class
1197 initializer, passing the object class and "object info" included in the
1198 header. For example:
1200 dbus_g_object_type_install_info (COM_FOO_TYPE_MY_OBJECT, &com_foo_my_object_info);
1202 This should be done exactly once per object class.
1205 To actually implement the method, just define a C function named e.g.
1206 <literal>my_object_many_args</literal> in the same file as the info
1207 header is included. At the moment, it is required that this function
1208 conform to the following rules:
1212 The function must return a value of type <literal>gboolean</literal>;
1213 <literal>TRUE</literal> on success, and <literal>FALSE</literal>
1219 The first parameter is a pointer to an instance of the object.
1224 Following the object instance pointer are the method
1230 Following the input values are pointers to return values.
1235 The final parameter must be a <literal>GError **</literal>.
1236 If the function returns <literal>FALSE</literal> for an
1237 error, the error parameter must be initalized with
1238 <literal>g_set_error</literal>.
1244 Finally, you can export an object using <literal>dbus_g_connection_register_g_object</literal>. For example:
1246 dbus_g_connection_register_g_object (connection,
1247 "/com/foo/MyObject",
1252 <sect2 id="glib-annotations">
1253 <title>Server-side Annotations</title>
1255 There are several annotations that are used when generating the
1256 server-side bindings. The most common annotation is
1257 <literal>org.freedesktop.DBus.GLib.CSymbol</literal> but there are other
1258 annotations which are often useful.
1261 <term><literal>org.freedesktop.DBus.GLib.CSymbol</literal></term>
1264 This annotation is used to specify the C symbol names for
1265 the various types (interface, method, etc), if it differs from the
1266 name DBus generates.
1271 <term><literal>org.freedesktop.DBus.GLib.Async</literal></term>
1274 This annotation marks the method implementation as an
1275 asynchronous function, which doesn't return a response straight
1276 away but will send the response at some later point to complete
1277 the call. This is used to implement non-blocking services where
1278 method calls can take time.
1281 When a method is asynchronous, the function prototype is
1282 different. It is required that the function conform to the
1287 The function must return a value of type <literal>gboolean</literal>;
1288 <literal>TRUE</literal> on success, and <literal>FALSE</literal>
1289 otherwise. TODO: the return value is currently ignored.
1294 The first parameter is a pointer to an instance of the object.
1299 Following the object instance pointer are the method
1305 The final parameter must be a
1306 <literal>DBusGMethodInvocation *</literal>. This is used
1307 when sending the response message back to the client, by
1308 calling <literal>dbus_g_method_return</literal> or
1309 <literal>dbus_g_method_return_error</literal>.
1317 <term><literal>org.freedesktop.DBus.GLib.Const</literal></term>
1319 <para>This attribute can only be applied to "out"
1320 <literal><arg></literal> nodes, and specifies that the
1321 parameter isn't being copied when returned. For example, this
1322 turns a 's' argument from a <literal>char **</literal> to a
1323 <literal>const char **</literal>, and results in the argument not
1324 being freed by DBus after the message is sent.
1329 <term><literal>org.freedesktop.DBus.GLib.ReturnVal</literal></term>
1332 This attribute can only be applied to "out"
1333 <literal><arg></literal> nodes, and alters the expected
1334 function signature. It currently can be set to two values:
1335 <literal>""</literal> or <literal>"error"</literal>. The
1336 argument marked with this attribute is not returned via a
1337 pointer argument, but by the function's return value. If the
1338 attribute's value is the empty string, the <literal>GError
1339 *</literal> argument is also omitted so there is no standard way
1340 to return an error value. This is very useful for interfacing
1341 with existing code, as it is possible to match existing APIs.
1342 If the attribute's value is <literal>"error"</literal>, then the
1343 final argument is a <literal>GError *</literal> as usual.
1346 Some examples to demonstrate the usage. This introspection XML:
1348 <method name="Increment">
1349 <arg type="u" name="x" />
1350 <arg type="u" direction="out" />
1353 Expects the following function declaration:
1356 my_object_increment (MyObject *obj, gint32 x, gint32 *ret, GError **error);
1360 This introspection XML:
1362 <method name="IncrementRetval">
1363 <arg type="u" name="x" />
1364 <arg type="u" direction="out" >
1365 <annotation name="org.freedesktop.DBus.GLib.ReturnVal" value=""/>
1369 Expects the following function declaration:
1372 my_object_increment_retval (MyObject *obj, gint32 x)
1376 This introspection XML:
1378 <method name="IncrementRetvalError">
1379 <arg type="u" name="x" />
1380 <arg type="u" direction="out" >
1381 <annotation name="org.freedesktop.DBus.GLib.ReturnVal" value="error"/>
1385 Expects the following function declaration:
1388 my_object_increment_retval_error (MyObject *obj, gint32 x, GError **error)
1398 <sect1 id="python-client">
1399 <title>Python API: Using Remote Objects</title>
1401 The Python bindings provide a simple to use interface for talking over D-Bus.
1402 Where possible much of the inner-workings of D-Bus are hidden behind what looks
1403 like normal Python objects.
1405 <sect2 id="python-typemappings">
1406 <title>D-Bus - Python type mappings</title>
1408 While python itself is a largely untyped language D-Bus provides a simple type system
1409 for talking with other languages which may be strongly typed. Python for the most part
1410 tries automatically map python objects to types on the bus. It is none the less good to
1411 know what the type mappings are so one can better utilize services over the bus.
1413 <sect3 id="python-basic-typemappings">
1414 <title>Basic type mappings</title>
1416 Below is a list of the basic types, along with their associated
1417 mapping to a Python object.
1422 <entry>D-Bus basic type</entry>
1423 <entry>Python wrapper</entry>
1424 <entry>Notes</entry>
1429 <entry><literal>BYTE</literal></entry>
1430 <entry><literal>dbus.Byte</literal></entry>
1433 <entry><literal>BOOLEAN</literal></entry>
1434 <entry><literal>dbus.Boolean</literal></entry>
1435 <entry>Any variable assigned a True or False boolean value will automatically be converted into a BOOLEAN over the bus</entry>
1437 <entry><literal>INT16</literal></entry>
1438 <entry><literal>dbus.Int16</literal></entry>
1441 <entry><literal>UINT16</literal></entry>
1442 <entry><literal>dbus.UInt16</literal></entry>
1445 <entry><literal>INT32</literal></entry>
1446 <entry><literal>dbus.Int32</literal></entry>
1447 <entry>This is the default mapping for Python integers</entry>
1449 <entry><literal>UINT32</literal></entry>
1450 <entry><literal>dbus.UInt32</literal></entry>
1453 <entry><literal>INT64</literal></entry>
1454 <entry><literal>dbus.Int64</literal></entry>
1457 <entry><literal>UINT64</literal></entry>
1458 <entry><literal>dbus.UInt64</literal></entry>
1461 <entry><literal>DOUBLE</literal></entry>
1462 <entry><literal>dbus.Double</literal></entry>
1463 <entry>Any variable assigned a floating point number will automatically be converted into a DOUBLE over the bus</entry>
1465 <entry><literal>STRING</literal></entry>
1466 <entry><literal>dbus.String</literal></entry>
1467 <entry>Any variable assigned a quoted string will automatically be converted into a STRING over the bus</entry>
1469 <entry><literal>OBJECT_PATH</literal></entry>
1470 <entry><literal>dbus.ObjectPath</literal></entry>
1478 <sect3 id="python-container-typemappings">
1479 <title>Container type mappings</title>
1481 The D-Bus type system also has a number of "container"
1482 types, such as <literal>DBUS_TYPE_ARRAY</literal> and
1483 <literal>DBUS_TYPE_STRUCT</literal>. The D-Bus type system
1484 is fully recursive, so one can for example have an array of
1485 array of strings (i.e. type signature
1486 <literal>aas</literal>).
1489 D-Bus container types have native corresponding built-in Python types
1490 so it is easy to use them.
1495 <entry>D-Bus type</entry>
1496 <entry>Python type</entry>
1497 <entry>Python wrapper</entry>
1498 <entry>Notes</entry>
1503 <entry><literal>ARRAY</literal></entry>
1504 <entry><literal>Python lists</literal></entry>
1505 <entry><literal>dbus.Array</literal></entry>
1506 <entry>Python lists, denoted by square brackets [], are converted into arrays and visa versa.
1507 The one restriction is that when sending a Python list each element of the list must be of the same
1508 type. This is because D-Bus arrays can contain only one element type. Use Python tuples for mixed types.
1510 When using the wrapper you may also specify a type or signature of the elements contained in the Array.
1511 This is manditory when passing an empty Array to a method on the bus because Python can not guess at the
1512 contents of an empty array. For example if a method is expecting an Array of int32's and you need to pass
1513 it an empty Array you would do it as such:
1515 <programlisting>emptyint32array = dbus.Array([], type=dbus.Int32)</programlisting>
1519 <programlisting>emptyint32array = dbus.Array([], signature="i")</programlisting>
1521 Note that dbus.Array derives from list so it acts just like a python list.
1525 <entry><literal>STRUCT</literal></entry>
1526 <entry><literal>Python tuple</literal></entry>
1527 <entry><literal>dbus.Struct</literal></entry>
1528 <entry>Python tuples, denoted by parentheses (,), are converted into structs and visa versa.
1529 Tuples can have mixed types.</entry>
1532 <entry><literal>DICTIONARY</literal></entry>
1533 <entry><literal>Python dictionary</literal></entry>
1534 <entry><literal>dbus.Dictionary</literal></entry>
1535 <entry>D-Bus doesn't have an explicit dictionary type. Instead it uses LISTS of DICT_ENTRIES to
1536 represent a dictionary. A DICT_ENTRY is simply a two element struct containing a key/value pair.
1537 Python dictionaries are automatically converted to a LIST of DICT_ENTRIES and visa versa.
1539 Since dictonaries are described as lists of dict_entries we also need the signature in order
1540 to pass empty dictionaries. The wrapper provides a way of specifying this through the key_type/value_type
1541 type parameters or the signature parameters. To send an empty Dictionary where the key is a string
1542 and the value is a string you would do it as such:
1544 <programlisting>emptystringstringdict = dbus.Dictionary({}, key_type=dbus.String, value_type=dbus.Value)</programlisting>
1548 <programlisting>emptystringstringdict = dbus.Dictionary({}, signature="ss")</programlisting>
1550 Note that dbus.Dictionary derives from dict so it acts just like a python dictionary.
1554 <entry><literal>VARIANT</literal></entry>
1555 <entry><literal>any type</literal></entry>
1556 <entry><literal>dbus.Variant</literal></entry>
1557 <entry>A variant is a container for any type. Python exports its methods to accept only variants
1558 since we are an untyped language and can demarshal into any Python type.
1560 To send a variant you must first wrap it in a<literal>dbus.Variant</literal>. If no type or signiture is
1561 given to the variant the marshaler will get the type from the contents.</entry>
1570 <sect2 id="python-invoking-methods">
1571 <title>Invoking Methods</title>
1572 <para>Here is a D-Bus program using the Python bindings to get a listing of all names on the session bus.
1576 bus = dbus.SessionBus()
1577 proxy_obj = bus.bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus')
1578 dbus_iface = dbus.Interface(proxy_obj, 'org.freedesktop.DBus')
1580 print dbus_iface.ListNames()
1584 Notice I get an interface on the proxy object and use that to make the call. While the specifications
1585 state that you do not need to specify an interface if the call is unambiguous (i.e. only one method implements
1586 that name) due to a bug on the bus that drops messages which don't have an interface field you need to specify
1587 interfaces at this time. In any event it is always good practice to specify the interface of the method you
1588 wish to call to avoid any side effects should a method of the same name be implemented on another interface.
1591 You can specify the interface for a single call using the dbus_interface keyword.
1593 proxy_obj.ListNames(dbus_interface = 'org.freedesktop.DBus')
1597 This is all fine and good if all you want to do is call methods on the bus and then exit. In order to
1598 do more complex things such as use a GUI or make asynchronous calls you will need a mainloop. You would use
1599 asynchronous calls because in GUI applications it is very bad to block for any long period of time. This cause
1600 the GUI to seem to freeze. Since replies to D-Bus messages can take an indeterminate amount of time using async
1601 calls allows you to return control to the GUI while you wait for the reply. This is exceedingly easy to do in
1602 Python. Here is an example using the GLib/GTK+ mainloop.
1606 if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
1609 def print_list_names_reply(list):
1615 bus = dbus.SessionBus()
1616 proxy_obj = bus.bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus')
1617 dbus_iface = dbus.Interface(proxy_obj, 'org.freedesktop.DBus')
1619 dbus_iface.ListNames(reply_handler=print_list_names_reply, error_handler=print_error)
1621 mainloop = gobject.MainLoop()
1626 In the above listing you will notice the reply_handler and error_handler keywords. These tell the method that
1627 it should be called async and to call print_list_names_reply or print_error depending if you get a reply or an error.
1628 The signature for replys depends on the number of arguments being sent back. Error handlers always take one parameter
1629 which is the error object returned.
1632 You will also notice that I check the version of the dbus bindings before importing dbus.glib. In older versions
1633 glib was the only available mainloop. As of version 0.41.0 we split out the glib dependency to allow for other mainloops
1634 to be implemented. Notice also the python binding version does not match up with the D-Bus version. Once we reach 1.0
1635 this should change with Python changes simply tracking the D-Bus changes.
1636 While the glib mainloop is the only mainloop currently implemented, integrating other mainloops should
1637 be very easy to do. There are plans for creating a a generic mainloop to be the default for non gui programs.
1640 <sect2 id="python-listening-for-signals">
1641 <title>Listening for Signals</title>
1643 Signals are emitted by objects on the bus to notify listening programs that an event has occurred. There are a couple of ways
1644 to register a signal handler on the bus. One way is to attach to an already created proxy using the connect_to_signal method
1645 which takes a signal name and handler as arguments. Let us look at an example of connecting to the HAL service to receive
1646 signals when devices are added and removed and when devices register a capability. This example assumes you have HAL already running.
1650 if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
1653 def device_added_callback(udi):
1654 print 'Device with udi %s was added' % (udi)
1656 def device_removed_callback(udi):
1657 print 'Device with udi %s was added' % (udi)
1659 def device_capability_callback(udi, capability):
1660 print 'Device with udi %s added capability %s' % (udi, capability)
1662 bus = dbus.SystemBus()
1663 hal_manager_obj = bus.get_object('org.freedesktop.Hal',
1664 '/org/freedesktop/Hal/Manager')
1665 hal_manager = dbus.Interface(hal_manager_obj,
1666 'org.freedesktop.Hal.Manager')
1668 hal_manager.connect_to_signal('DeviceAdded', device_added_callback)
1669 hal_manager.connect_to_signal('DeviceRemoved', device_removed_callback)
1670 hal_manager.connect_to_signal('NewCapability', device_capability_callback)
1672 mainloop = gobject.MainLoop()
1677 The drawback of using this method is that the service that you are connecting to has to be around when you register
1678 your signal handler. While HAL is guaranteed to be around on systems that use it this is not always the case for every
1679 service on the bus. Say our program started up before HAL, we could connect to the signal by adding a signal receiver
1680 directly to the bus.
1682 bus.add_signal_receiver(device_added_callback,
1684 'org.freedesktop.Hal.Manager',
1685 'org.freedesktop.Hal',
1686 '/org/freedesktop/Hal/Manager')
1688 bus.add_signal_receiver(device_removed_callback,
1690 'org.freedesktop.Hal.Manager',
1691 'org.freedesktop.Hal',
1692 '/org/freedesktop/Hal/Manager')
1694 bus.add_signal_receiver(device_capability_callback,
1696 'org.freedesktop.Hal.Manager',
1697 'org.freedesktop.Hal',
1698 '/org/freedesktop/Hal/Manager')
1702 All this can be done without creating the proxy object if one wanted to but in most cases you would want to have
1703 a reference to the object so once a signal was received operations could be executed on the object.
1706 <title>Signal matching on arguments</title>
1708 Starting with D-Bus 0.36 and the (0, 43, 0) version of the python
1709 bindings you can now add a match on arguments being sent in a signal.
1710 This is useful for instance for only getting NameOwnerChanged
1711 signals for your service. Lets say we create a name on the bus called
1712 'org.foo.MyName' we could also add a match to just get
1713 NameOwnerChanges for that name as such:
1715 bus.add_signal_receiver(myname_changed,
1717 'org.freedesktop.DBus',
1718 'org.freedesktop.DBus',
1719 '/org/freedesktop/DBus',
1720 arg0='org.foo.MyName')
1723 It is as simple as that. To match the second arg you would use arg1=,
1724 the third arg2=, etc.
1728 <title>Cost of Creating a Proxy Object</title>
1730 Note that creating proxy objects can have an associated processing cost. When introspection is implemented
1731 a proxy may wait for introspection data before processing any requests. It is generally good practice to
1732 create proxies once and reuse the proxy when calling into the object. Constantly creating the same proxy
1733 over and over again can become a bottleneck for your program.
1737 TODO: example of getting information about devices from HAL
1742 <sect1 id="python-server">
1743 <title>Python API: Implementing Objects</title>
1745 Implementing object on the bus is just as easy as invoking methods or listening for signals on the bus.
1748 <title>Version Alert</title>
1750 The Python D-Bus bindings require version 2.4 or greater of Python when creating D-Bus objects.
1754 <sect2 id="python-inheriting-from-dbus-object">
1755 <title>Inheriting From dbus.service.Object</title>
1757 In order to export a Python object over the bus one must first get a bus name and then create
1758 a Python object that inherits from dbus.service.Object. The following is the start of an example
1759 HelloWorld object that we want to export over the session bus.
1764 if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
1767 class HelloWorldObject(dbus.service.Object):
1768 def __init__(self, bus_name, object_path='/org/freedesktop/HelloWorldObject'):
1769 dbus.service.Object.__init__(self, bus_name, object_path)
1771 session_bus = dbus.SessionBus()
1772 bus_name = dbus.service.BusName('org.freedesktop.HelloWorld', bus=session_bus)
1773 object = HelloWorldObject(bus_name)
1775 mainloop = gobject.MainLoop()
1780 Here we got the session bus, then created a BusName object which requests a name on the bus.
1781 We pass that bus name to the HelloWorldObject object which inherits from dbus.service.Object.
1782 We now have an object on the bus but it is pretty useless.
1785 <sect2 id="python-exporting-methods">
1786 <title>Exporting Methods Over The Bus</title>
1788 Let's make this object do something and export a method over the bus.
1793 if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
1796 class HelloWorldObject(dbus.service.Object):
1797 def __init__(self, bus_name, object_path='/org/freedesktop/HelloWorldObject'):
1798 dbus.service.Object.__init__(self, bus_name, object_path)
1800 @dbus.service.method('org.freedesktop.HelloWorldIFace')
1802 return 'Hello from the HelloWorldObject'
1804 session_bus = dbus.SessionBus()
1805 bus_name = dbus.service.BusName('org.freedesktop.HelloWorld', bus=session_bus)
1806 object = HelloWorldObject(bus_name)
1808 mainloop = gobject.MainLoop()
1813 <title>Python Decorators</title>
1815 Notice the @ symbol on the line before the hello method. This is a new directive introduced in
1816 Python 2.4. It is called a decorator and it "decorates" methods. All you have to know is that
1817 it provides metadata that can then be used to alter the behavior of the method being decorated.
1818 In this case we are telling the bindings that the hello method should be exported as a D-Bus method
1823 As you can see we exported the hello method as part of the org.freedesktop.HelloWorldIFace interface.
1824 It takes no arguments and returns a string to the calling program. Let's create a proxy and invoke this
1829 bus = dbus.SessionBus()
1830 proxy_obj = bus.bus.get_object('org.freedesktop.HelloWorld', '/org/freedesktop/HelloWorldObject')
1831 iface = dbus.Interface(proxy_obj, 'org.freedesktop.HelloWorldIFace')
1837 When invoking methods exported over the bus the bindings automatically know how many parameters
1838 the method exports. You can even make a method that exports an arbitrary number of parameters.
1839 Also, whatever you return will automatically be transfered as a reply over the bus. Some examples.
1841 @dbus.service.method('org.freedesktop.HelloWorldIFace')
1842 def one_arg(self, first_arg):
1843 return 'I got arg %s' % first_arg
1845 @dbus.service.method('org.freedesktop.HelloWorldIFace')
1846 def two_args(self, first_arg, second_arg):
1847 return ('I got 2 args', first_arg, second_arg)
1849 @dbus.service.method('org.freedesktop.HelloWorldIFace')
1850 def return_list(self):
1851 return [1, 2, 3, 4, 5, 6]
1853 @dbus.service.method('org.freedesktop.HelloWorldIFace')
1854 def return_dict(self):
1855 return {one: '1ne', two: '2wo', three: '3ree'}
1859 <sect2 id="python-emitting-signals">
1860 <title>Emitting Signals</title>
1862 Setting up signals to emit is just as easy as exporting methods. It uses the same syntax as methods.
1867 if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
1870 class HelloWorldObject(dbus.service.Object):
1871 def __init__(self, bus_name, object_path='/org/freedesktop/HelloWorldObject'):
1872 dbus.service.Object.__init__(self, bus_name, object_path)
1874 @dbus.service.method('org.freedesktop.HelloWorldIFace')
1876 return 'Hello from the HelloWorldObject'
1878 @dbus.service.signal('org.freedesktop.HelloWorldIFace')
1879 def hello_signal(self, message):
1882 session_bus = dbus.SessionBus()
1883 bus_name = dbus.service.BusName('org.freedesktop.HelloWorld', bus=session_bus)
1884 object = HelloWorldObject(bus_name)
1886 object.hello_signal('I sent a hello signal')
1888 mainloop = gobject.MainLoop()
1893 Adding a @dbus.service.signal decorator to a method turns it into a signal emitter. You can put code
1894 in this method to do things like keep track of how many times you call the emitter or to print out debug
1895 messages but for the most part a pass noop will do. Whenever you call the emitter a signal will be emitted
1896 with the parameters you passed in as arguments. In the above example we send the message 'I sent a hello signal'
1900 <sect2 id="python-inheriting-and-overriding">
1901 <title>Inheriting from HelloWorldObject</title>
1903 One of the cool things you can do in Python is inherit from another D-Bus object. We use this trick in
1904 the bindings to provide a default implementation for the org.freedesktop.DBus.Introspectable interface.
1905 Let's inherit from the HelloWorldObject example above and overide the hello method to say goodbye.
1907 class HelloWorldGoodbyeObject(HelloWorldObject):
1908 def __init__(self, bus_name, object_path='/org/freedesktop/HelloWorldGoodbyeObject'):
1909 HelloWorldObject.__init__(self, bus_name, object_path)
1911 @dbus.service.method('org.freedesktop.HelloWorldGoodbyeIFace')
1915 goodbye_object = HelloWorldGoodbyeObject(bus_name)
1919 Let's now call both methods with a little help from interfaces.
1923 bus = dbus.SessionBus()
1924 proxy_obj = bus.bus.get_object('org.freedesktop.HelloWorld', '/org/freedesktop/HelloWorldGoodbyeObject')
1926 print proxy_obj.hello(dbus_interface='org.freedesktop.HelloWorldIFace')
1927 print proxy_obj.hello(dbus_interface='org.freedesktop.HelloWorldGoodbyeIFace')
1931 This should print out 'Hello from the HelloWorldObject' followed by a 'Goodbye'.
1934 <sect2 id="python-conclusion">
1935 <title>Conclusion</title>
1937 As you can see, using D-Bus from Python is an extremely easy proposition. Hopefully
1938 the tutorial has been helpful in getting you started. If you need anymore help please
1939 feel free to post on the <ulink url="http://lists.freedesktop.org/mailman/listinfo/dbus/">mailing list</ulink>.
1940 The Python bindings are still in a state of flux and there may be API changes in the future.
1941 This tutorial will be updated if such changes occur.
1946 <sect1 id="qt-client">
1947 <title>Qt API: Using Remote Objects</title>
1950 The Qt bindings are not yet documented.
1955 <sect1 id="qt-server">
1956 <title>Qt API: Implementing Objects</title>
1958 The Qt bindings are not yet documented.