## 2 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.

### 2.1 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 dk_make_protocol tool generate them for you. This is possible if an .interface-file containing the introspection data for the interface exists. Calling dk_make_protocol with the “-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 org.freedesktop.Introspectable, dk_make_protocol might generate the following header file:

    #import <Foundation/Foundation.h>
    /*
     * Objective-C protocol declaration for the D-Bus
     * org.freedesktop.Introspectable interface.
     */
    @protocol org_freedesktop_Introspectable

    - (NSString*)Introspect;

    @end

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:

NSNumber | booleans (b), integers (y, n, q, i, u, x, t), floating point values (d)
NSString | strings (s)
DKProxy | object paths (o)
NSArray | arrays (a?), structs ((?*))
NSDictionary | dictionaries (a{??})
id | variants (v)

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 `NameHasOwner()` method from org.freedesktop.DBus:

    - (NSNumber*)NameHasOwner: (NSString*)name;
    - (NSNumber*)NameHasOwner: (char*)name;
    - (BOOL)NameHasOwner: (NSString*)name;
    - (BOOL)NameHasOwner: (char*)name;

### 2.2 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:

    DKPort *sPort = [[DKPort alloc] initWithRemote: @"org.freedesktop.DBus"
                                             onBus: DKDBusSessionBus]
    DKPort *rPort = [DKPort sessionBusPort];

If a service on the system bus was the desired target, one could pass `DKBusSystemBus` as the second argument of the `DKPort` initialiser or use the `+systemBusPort` convenience method to create a port object without remote.

Afterwards, a connection can be obtained to the org.freedesktop.DBus service (which is bus itself) as follows:

    NSConnection *c = [NSConnection connectionWithReceivePort: rPort
                                                     sendPort: sPort];

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 `-rootProxy`:

    id remoteObject = [c rootProxy];

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 `NSConnection` with a `-proxyAtPath:` method, which can be used to obtain proxies to non-root object. It could be used to obtain a proper proxy to org.freedesktop.DBus like this:

    id remoteObject = [c proxyAtPath: @"/org/freedesktop/DBus"];

### 2.3 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:

    NSString *introspectionData = [remoteObject Introspect];

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 `_DKIf_` `_DKIfEnd_` marker and appending the method name.

Assuming a D-Bus object implements a `getBass()` method in the interfaces `org.foo.Fish` and `org.bar.Instruments`, one could distinguish between the methods by constructing the following selectors:

- `-_DKIf_org_foo_Fish_DKIfEnd_getBass`
- `-_DKIf_org_bar_Instruments_DKIfEnd_getBass`

Since this is obviously quite clumsy, it will only be feasible for simple cases.

The other facility provided by DBusKit is the `-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:

    [remoteObject setPrimaryDBusInterface: @"org.bar.Instruments"];
    id anInstrument = [remoteObject getBass];

### 2.4 Accessing and changing D-Bus properties

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:

    <property name="address" type="s" access="readwrite"/>

This property can then be accessed by calling `-address` and changed by calling `-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:

    - (NSString*)address;
    - (char*)address;
    - (void)setaddress: (NSString*)address;
    - (void)setaddress: (char*)address;

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.

### 2.5 Watching D-Bus Signals

Besides responding to method calls, D-Bus objects can also actively inform remote objects about events or state changes by the use of 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 `DKNotificationCenter` class. `DKNotificationCenter` keeps to OpenStep conventions in that it delivers the signals it receives from D-Bus in the form of `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:

    DKNotificationCenter *center = [DKNotificationCenter sessionBusCenter];

(Again, a reference to the notification center for the system bus can be obtained similarly by using `+systemBusCenter`.) In a very simple case, one would simply use the center to add an object as an observer of the NameAcquired signal from the org.freedesktop.DBus interface.

    [center addObserver: myObject
               selector: @selector(didReceiveNotification:)
                   name: @"DKSignal_org.freedesktop.DBus_NameAquired"
                 object: nil];

This example also illustrates the naming convention for signals: They start with the “`DKSignal`”-identifier and continue with the interface name and the signal name separated by underscores (“`_`”). Additionally, it is possible to register a custom notification name for a signal:

    [center registerNotificationName: @"DKNameAquired"
                            asSignal: @"NameAquired"
                         inInterface: @"org.freedesktop.DBus"];

If this method returns YES, it will be possible to register observers for the `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:

    [center addObserver: myObject
               selector: @selector(didReceiveNotification:)
                 signal: @"NameOwnerChanged"
              interface: @"org.freedesktop.DBus"
                 sender: theBus
            destination: nil
                 filter: @"org.gnustep.TextEditor"
                atIndex: 0];

If registered as an observer this way, `myObject` would only receive a notification if a new application took ownership of the name org.gnustep.TextEditor.

When delivering annotification to the observer, the notification center will create a `NSNotification` with a userInfo dictionary that follows a specific format to allow the receiver to process the notification:

member

  The name of the signal being emitted.

interface

  The name of the interface the signal belongs to.

sender

  The unique name of the service emitting the signal.

path

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

destination

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

arg0, ..., n

  If the signal did specify any values to be send alongside the signal, these values will be present in keys called arg0, arg1, ..., argn.

Additionally, calling `-object` on the notification will return a proxy to the object that emitted the signal.

### 2.6 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 `DKPort` used will post a `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 `NSPortDidBecomeInvalidNotification` and additionally the `DKDBus` object for the bus will post a `DKBusDisconnectedNotification` with the `DKDBusBusType` identifier at the `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 `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 `DBUS_SESSION_BUS_ADDRESS` environment variable. Hence your application should assume that the user session died when it looses connection to the session bus.

### 2.7 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 `+enableWorkerThread` method must be called on `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 `+initialize`-methods. The reason for this is that with present Objective-C runtimes, `+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.