logo

Crate zbus[][src]

Expand description

This crate provides the main API you will use to interact with D-Bus from Rust. It takes care of the establishment of a connection, the creation, sending and receiving of different kind of D-Bus messages (method calls, signals etc) for you.

zbus crate is currently Linux-specific1.

Getting Started

The best way to get started with zbus is the book, where we start with basic D-Bus concepts and explain with code samples, how zbus makes D-Bus easy.

Example code

Client

This code display a notification on your Freedesktop.org-compatible OS:

use std::{collections::HashMap, error::Error};

use zbus::{Connection, dbus_proxy};
use zvariant::Value;

#[dbus_proxy(
    interface = "org.freedesktop.Notifications",
    default_service = "org.freedesktop.Notifications",
    default_path = "/org/freedesktop/Notifications"
)]
trait Notifications {
    fn notify(
        &self,
        app_name: &str,
        replaces_id: u32,
        app_icon: &str,
        summary: &str,
        body: &str,
        actions: &[&str],
        hints: &HashMap<&str, &Value<'_>>,
        expire_timeout: i32,
    ) -> zbus::Result<u32>;
}

// Although we use `async-std` here, you can use any async runtime of choice.
#[async_std::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let connection = Connection::session().await?;

    // `dbus_proxy` macro creates `NotificationProxy` based on `Notifications` trait.
    let proxy = NotificationsProxy::new(&connection).await?;
    let reply = proxy.notify(
        "my-app",
        0,
        "dialog-information",
        "A summary",
        "Some body",
        &[],
        &HashMap::new(),
        5000,
    ).await?;
    dbg!(reply);

    Ok(())
}
Server

A simple service that politely greets whoever calls its SayHello method:

use std::{
    error::Error,
    thread::sleep,
    time::Duration,
};
use zbus::{ObjectServer, ConnectionBuilder, dbus_interface, fdo};

struct Greeter {
    count: u64
}

#[dbus_interface(name = "org.zbus.MyGreeter1")]
impl Greeter {
    // Can be `async` as well.
    fn say_hello(&mut self, name: &str) -> String {
        self.count += 1;
        format!("Hello {}! I have been called: {}", name, self.count)
    }
}

// Although we use `async-std` here, you can use any async runtime of choice.
#[async_std::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let greeter = Greeter { count: 0 };
    let _ = ConnectionBuilder::session()?
        .name("org.zbus.MyGreeter")?
        .serve_at("/org/zbus/MyGreeter", greeter)?
        .build()
        .await?;

    // Do other things or go to sleep.
    sleep(Duration::from_secs(60));

    Ok(())
}

You can use the following command to test it:

$ busctl --user call \
    org.zbus.MyGreeter \
    /org/zbus/MyGreeter \
    org.zbus.MyGreeter1 \
    SayHello s "Maria"
Hello Maria!
$

Blocking API

While zbus is primarily asynchronous (since 2.0), blocking wrappers are provided for convenience.

Compatibility with async runtimes

zbus is runtime-agnostic and should work out of the box with different Rust async runtimes. However, in order to achieve that, zbus spawns a thread per connection to handle various internal tasks. If that is something you would like to avoid, you need to:


  1. Support for other OS exist, but it is not supported to the same extent. D-Bus clients in javascript (running from any browser) do exist though. And zbus may also be working from the browser sometime in the future too, thanks to Rust 🦀 and WebAssembly 🕸. 

Re-exports

pub use zbus_names as names;
pub use zvariant;

Modules

The blocking API.

D-Bus standard interfaces.

Introspection XML support (xml feature)

Structs

A D-Bus connection.

A D-Bus server GUID.

Opaque structure that derefs to an Interface type.

Opaque structure that mutably derefs to an Interface type.

Wrapper over an interface, along with its corresponding SignalContext instance. A reference to the underlying interface may be obtained via InterfaceRef::get and InterfaceRef::get_mut.

A D-Bus Message.

A builder for Message

A collection of MessageField instances.

The message header, containing all the metadata about the message.

The primary message header, which is present in all D-Bus messages.

A position in the stream of Message objects received by a single zbus::Connection.

A stream::Stream implementation that yields Message items.

An object server, holding server-side D-Bus objects & interfaces.

A stream::Stream implementation that yields UniqueName when the bus owner changes.

A property changed event.

A stream::Stream implementation that yields property change notifications.

A client-side interface proxy.

Builder for proxies.

A signal emission context.

A stream::Stream implementation that yields signal messages.

Enums

A bus address

The properties caching mode.

A helper type returned by Interface callbacks.

D-Bus code for endianness.

The error type for zbus.

The dynamic message header.

The message field code.

Pre-defined flags that can be passed in Message header.

Message header representing the D-Bus type of the message.

Constants

Signature of the target’s native endian.

Traits

A trait that needs to be implemented by error types to be returned from D-Bus methods.

The trait used to dispatch messages to an interface instance.

Trait for the default associated values of a proxy.

Helper trait for macro-generated code.

Trait representing some transport layer over which the DBus protocol can be used

Type Definitions

Alias for a Result with the error type zbus::Error.

Attribute Macros

Attribute macro for implementing a D-Bus interface.

Attribute macro for defining D-Bus proxies (using zbus::Proxy and zbus::blocking::Proxy).

Derive Macros

Derive macro for implementing zbus::DBusError trait.