File: UsingDBus.texi

package info (click to toggle)
dbuskit 0.1.1-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 3,552 kB
  • sloc: objc: 10,309; sh: 9,443; ansic: 200; makefile: 20
file content (315 lines) | stat: -rw-r--r-- 13,892 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
@c This file is part of the GNUstep DBusKit and D-Bus Programming Manual
@c Copyright (C) 2010
@c   Free Software Foundation, Inc.
@c See the file DBusKit.texi for copying conditions.

@paragraphindent 0
@node Using D-Bus From Objective-C
@chapter Using D-Bus From Objective-C
In order to access D-Bus services from an Objective-C application, the
DBusKit framework is required. It provides infrastructure for
managing connections to D-Bus message buses and translating Objective-C
message sends to D-Bus method calls. This way, DBusKit can make
interacting with D-Bus objects appear quite similar to the way one
usually interacts with the DO system.

@section Generating Protocol Declarations With dk_make_protocol

If your application wants to invoke methods on D-Bus objects, some
preparations are required: As with all other code, you need to provide
declarations for the methods you want to invoke. You can either do this
by writing them manually or let the @b{dk_make_protocol} tool
generate them for you. This is possible if an .interface-file containing
the introspection data for the interface exists. Calling @b{dk_make_protocol} with the ``@b{-i}''
switch and the name of the .interface-file will generate a header file
with an Objective-C protocol declaration for that interface. For the
hypothetical interface file for @emph{org.freedesktop.Introspectable},
@b{dk_make_protocol} might generate the following header file:
@example
#import <Foundation/Foundation.h>
/*
 * Objective-C protocol declaration for the D-Bus
 * org.freedesktop.Introspectable interface.
 */
@@protocol org_freedesktop_Introspectable

- (NSString*)Introspect;

@@end
@end example
The generated header file does only contain method declarations with
arguments and return values that are Objective-C classes. The following
default mappings between Foundation classes and D-Bus types are defined:

@multitable @columnfractions .15 .8
@item NSNumber @tab
booleans (b), integers (y, n, q, i, u, x, t), floating point values (d)

@item NSString @tab
strings (s)

@item DKProxy @tab
object paths (o)

@item NSArray @tab
arrays (a?), structs ((?*))

@item NSDictionary @tab
dictionaries (a@{??@})

@item id @tab
variants (v)
@end multitable
Here ``?'' denotes a single complete D-Bus type signature and ``*''
denotes possible repetition. It is, however, possible to use the plain C
types corresponding to the D-Bus types, because DBusKit is capable of
determining all necessary conversions. Thus the following declarations
all specify valid ways to invoke @code{NameHasOwner()} method from
@emph{org.freedesktop.DBus}:
@example
- (NSNumber*)NameHasOwner: (NSString*)name;
- (NSNumber*)NameHasOwner: (char*)name;
- (BOOL)NameHasOwner: (NSString*)name;
- (BOOL)NameHasOwner: (char*)name;
@end example

@section Obtaining a Proxy to a D-Bus Object
With these provisions in place, it is quite easy to obtain a proxy to a
D-Bus object. The process is quite similar to creating a proxy to a
distant object using DO. First, you create the required ports:
@example
DKPort *sPort = [[DKPort alloc] initWithRemote: @@"org.freedesktop.DBus"
                                         onBus: DKDBusSessionBus]
DKPort *rPort = [DKPort sessionBusPort];
@end example
If a service on the system bus was the desired target, one could pass
@code{DKBusSystemBus} as the second argument of the @code{DKPort}
initialiser or use the @code{+systemBusPort} convenience method to
create a port object without remote.
 
Afterwards, a connection can be obtained to the
@emph{org.freedesktop.DBus} service (which is bus itself) as follows:

@example
NSConnection *c = [NSConnection connectionWithReceivePort: rPort
                                                 sendPort: sPort];
@end example
Please note that this is exactly the way one would create a Distributed
Objects connection. Consequentially, on can obtain a proxy to an object
of this service by using @code{-rootProxy}:

@example
id remoteObject = [c rootProxy];
@end example
Unfortunately, a proxy to the root object of a D-Bus service is very
often not useful because services tend to install their primary object
at a path corresponding to the service name. DBusKit thus
extends @code{NSConnection} with a @code{-proxyAtPath:} method, which
can be used to obtain proxies to non-root object. It could be used to
obtain a proper proxy to @emph{org.freedesktop.DBus} like this:
@example
id remoteObject = [c proxyAtPath: @@"/org/freedesktop/DBus"];
@end example

@section Sending Messages to D-Bus Objects
All further interactions with the remote object are indistinguishable
from interactions with an object in the local process. E.g. the
introspection data of the remote object could be obtained like this:
@example
NSString *introspectionData = [remoteObject Introspect];
@end example

@cindex interface, D-Bus
@cindex method, D-Bus
@cindex D-Bus interface
@cindex D-Bus method
In some cases it is, however, necessary to treat D-Bus objects special:
Since D-Bus allows method names to be overloaded per interface, it might
be necessary to specify which method to call. DBusKit provides two
facilities to cope with this kind of situation. For one, it is possible
to embed the information about the required interface in the selector
string of the method to call. This is done by replacing all dots in the
interface string with underscores, placing it between @code{_DKIf_}
@code{_DKIfEnd_} marker and appending the method name.

Assuming a D-Bus object  implements a @code{getBass()} method in the
interfaces @code{org.foo.Fish} and @code{org.bar.Instruments}, one could
distinguish between the methods by constructing the following selectors:
@itemize @bullet
@item @code{-_DKIf_org_foo_Fish_DKIfEnd_getBass}
@item @code{-_DKIf_org_bar_Instruments_DKIfEnd_getBass}
@end itemize
Since this is obviously quite clumsy, it will only be feasible for
simple cases. 

The other facility provided by DBusKit is the
@code{-setPrimaryDBusInterface:} method, which instructs the proxy to
prefer the named interface when looking up methods. E.g. the following
statements would result in a call to the correct method:
@example
[remoteObject setPrimaryDBusInterface: @@"org.bar.Instruments"];
id anInstrument = [remoteObject getBass];
@end example

@section Accessing and changing D-Bus properties
@cindex property, D-Bus
@cindex D-Bus property
DBusKit will automatically generate getters and setters for D-Bus properties. A
D-Bus interface might, for example, specifythe following property in its
introspection data:
@example
<property name="address" type="s" access="readwrite"/>
@end example
This property can then be accessed by calling @code{-address} and changed by
calling @code{-setaddress:} on the proxy object. Just like with other methods,
both the plain C types and the corresponding Foundation classes are valid as
parameters to the getter and setter methods:
@example
- (NSString*)address;
- (char*)address;
- (void)setaddress: (NSString*)address;
- (void)setaddress: (char*)address;
@end example
If other methods with the same names exist within the same interface of the
remote object, those will take precedence over the generated getter and setter
methods.

@section Watching D-Bus Signals
@cindex signal, D-Bus
@cindex D-Bus signal
Besides responding to method calls, D-Bus objects can also actively
inform remote objects about events or state changes by the use of
@emph{signals}. These signals are published to the bus and the bus will
re-broadcast them to all connected entities that subscribe to the
signals. DBusKit includes support for receiving D-Bus signals through
the @code{DKNotificationCenter} class. @code{DKNotificationCenter} keeps
to OpenStep conventions in that it delivers the signals it receives from
D-Bus in the form of @code{NSNotification}s and is thus similar to the
notification center classes provided by the Foundation library
(gnustep-base).

To make use of the notification feature, it is sometimes not even
necessary to create any explicit proxies. It is enough to just obtain a
reference to one of the notification centers:

@example
DKNotificationCenter *center = [DKNotificationCenter sessionBusCenter];
@end example
(Again, a reference to the notification center for the system bus can be
obtained similarly by using @code{+systemBusCenter}.) In a very simple
case, one would simply use the center to add an object as an observer of
the @emph{NameAcquired} signal from the @emph{org.freedesktop.DBus}
interface.
@example
[center addObserver: myObject
           selector: @@selector(didReceiveNotification:)
               name: @@"DKSignal_org.freedesktop.DBus_NameAquired"
             object: nil];
@end example
This example also illustrates the naming convention for signals: They
start with the ``@code{DKSignal}''-identifier and continue with the
interface name and the signal name separated by underscores
(``@code{_}''). Additionally, it is possible to register a custom
notification name for a signal:
@example
[center registerNotificationName: @@"DKNameAquired"
                        asSignal: @@"NameAquired"
                     inInterface: @@"org.freedesktop.DBus"];
@end example
If this method returns YES, it will be possible to register observers for the
@code{DKNameAquired} notification (it might fail if the signal was
already registered under another name).

Since D-Bus provides a fine-grained matching mechanism for signals,
Objective-C applications can specify in great detail what kind of signal
they want to receive. The full-blown version of the registration method
could be called as follows:
@example
[center addObserver: myObject
           selector: @@selector(didReceiveNotification:)
             signal: @@"NameOwnerChanged"
          interface: @@"org.freedesktop.DBus"
             sender: theBus
        destination: nil
             filter: @@"org.gnustep.TextEditor"
            atIndex: 0];
@end example
If registered as an observer this way, @code{myObject} would only
receive a notification if a new application took ownership of the name
@emph{org.gnustep.TextEditor}. 

When delivering annotification to the observer, the notification center
will create a @code{NSNotification} with a userInfo dictionary that
follows a specific format to allow the receiver to process the
notification:
@table @emph
@item member
The name of the signal being emitted.

@item interface
The name of the interface the signal belongs to.

@item sender
The @emph{unique} name of the service emitting the signal.

@item path
The path to the object of the service that emitted the signal.

@item destination
The intended receiver of the signal; might be empty if the signal was
broadcast, which is usually the case.

@item arg0, ..., n
If the signal did specify any values to be send alongside the signal,
these values will be present in keys called @emph{arg0}, @emph{arg1},
..., @emph{argn}. 
@end table

Additionally, calling @code{-object} on the notification will return a
proxy to the object that emitted the signal.

@section Recovering from Failure
There are two common reasons for failure when communicating with objects on
D-Bus. One is that the service your application is accessing is going away. In
that case, DBusKit will notify you in a way similar to Distributed Objects. This
means that when the service disappears from the bus, the @code{DKPort} used will
post a @code{NSPortDidBecomeInvalidNotification} to the default notification
center. You can watch for this notification and attempt recovery afterwards. 

A more critical reason for failure is a malfunction or restart of the D-Bus
daemon. In that case, all affected ports will issue a
@code{NSPortDidBecomeInvalidNotification} and additionally the @code{DKDBus}
object for the bus will post a @code{DKBusDisconnectedNotification} with the
@code{DKDBusBusType} identifier at the @code{busType} key of the userInfo
dictionary. Afterwards, DBusKit will attempt to recover from the failure in the
background and you cannot use D-Bus services until you receive a
@code{DKBusReconnectedNotification}. After receiving the notification, you can
perform recovery as your application requires.

Please note that usually, such recovery from bus failures will only be
successful for the system bus, for which one connects to a socket
address that is persistent across restarts. For the session bus the socket
address is not persistent, but stored in the @code{DBUS_SESSION_BUS_ADDRESS}
environment variable. Hence your application should assume that the user session
died when it looses connection to the session bus. 

@section Multi-Threading Considerations
By default, DBusKit runs in single-threaded mode. This means that all
interaction with the D-Bus daemon happens on the runloop of the calling thread.
If multiple threads try to send messages D-Bus objects, this model of execution
cannot guarantee that message delivery from and to the bus daemon are
successful. The framework should still be thread-safe in the sense that it will
continue functioning after raising an exception due to timeouts, but the desired
behaviour can only be acheived by putting DBusKit in multi-threaded mode.

In multi-threaded mode, DBusKit will exchange messages with the D-Bus daemons
via a dedicated worker-thread. To enable this behaviour the
@code{+enableWorkerThread} method must be called on @code{DKPort}. All
processing will then be taking place on the worker thread. Developers should
note that after doing so, it is no longer safe to call into DBusKit from
@code{+initialize}-methods. The reason for this is that with present
Objective-C runtimes, @code{+initialize} will obtain a global lock and
subsequent initialisations of classes on the worker thread might cause a
deadlock. This is also the reason multi-threaded operation is not the default.
But developers are encouraged to use this feature if it does not interfere with
their application design.