[][src]Struct zbus::azync::connection::Connection

pub struct Connection(_);

The asynchronous sibling of zbus::Connection.

Most of the API is very similar to zbus::Connection, except it's asynchronous. However, there are a few differences:

Sending Messages

For sending messages you can either use Connection::send_message method or make use of the futures_sink::Sink implementation that is returned by Connection::sink method. For latter, you might find SinkExt API very useful. Keep in mind that Connection will not manage the serial numbers (cookies) on the messages for you when they are sent through the Sink. You can manually assign unique serial numbers to them using the Connection::assign_serial_num method before sending them off, if needed. Having said that, Sink is mainly useful for sending out signals, as they do not expect a reply, and serial numbers are not very useful for signals either for the same reason.

Receiving Messages

Unlike zbus::Connection, there is no direct async equivalent of zbus::Connection::receive_message method provided. This is because the futures crate already provides a nice rich API that makes use of the stream::Stream implementation that is returned by Connection::stream method.

However, there is Connection::receive_specific method, which takes a predicate function, using which you get to decided which message you're interested in. It first checks if there was already a message received by a previous call to Connection::receive_specific or during a Connection::call_method call that fits the predicate and returns that immediate. Otherwise, it awaits on the connection for the message of interest to be received. All other messages received, while waiting, are appended to the end of the incoming message queue to be picked up by a following or already awaiting receive_specific call or stream::Stream API.

In summary, if you're going to call D-Bus methods on the connection in one task, while receiving messages in another, it's best to use receive_specific method. Otherwise, you'd want to make use of the stream method.

Examples

Get the session bus ID

use zbus::azync::Connection;

let mut connection = Connection::new_session().await?;

let reply = connection
    .call_method(
        Some("org.freedesktop.DBus"),
        "/org/freedesktop/DBus",
        Some("org.freedesktop.DBus"),
        "GetId",
        &(),
    )
    .await?;

let id: &str = reply.body()?;
println!("Unique ID of the bus: {}", id);

Monitoring all messages

Let's eavesdrop on the session bus 😈 using the Monitor interface:

use futures_util::stream::TryStreamExt;
use zbus::azync::Connection;

let mut connection = Connection::new_session().await?;

connection
    .call_method(
        Some("org.freedesktop.DBus"),
        "/org/freedesktop/DBus",
        Some("org.freedesktop.DBus.Monitoring"),
        "BecomeMonitor",
        &(&[] as &[&str], 0u32),
    )
    .await?;

while let Some(msg) = connection.stream().await.try_next().await? {
    println!("Got message: {}", msg);
}

This should print something like:

Got message: Signal NameAcquired from org.freedesktop.DBus
Got message: Signal NameLost from org.freedesktop.DBus
Got message: Method call GetConnectionUnixProcessID from :1.1324
Got message: Error org.freedesktop.DBus.Error.NameHasNoOwner:
             Could not get PID of name ':1.1332': no such name from org.freedesktop.DBus
Got message: Method call AddMatch from :1.918
Got message: Method return from org.freedesktop.DBus

Implementations

impl Connection[src]

pub async fn new_unix_client(
    stream: UnixStream,
    bus_connection: bool
) -> Result<Self>
[src]

Create and open a D-Bus connection from a UnixStream.

The connection may either be set up for a bus connection, or not (for peer-to-peer communications).

Upon successful return, the connection is fully established and negotiated: D-Bus messages can be sent and received.

pub async fn new_unix_server(stream: UnixStream, guid: &Guid) -> Result<Self>[src]

Create a server Connection for the given UnixStream and the server guid.

The connection will wait for incoming client authentication handshake & negotiation messages, for peer-to-peer communications.

Upon successful return, the connection is fully established and negotiated: D-Bus messages can be sent and received.

pub async fn stream(&self) -> Stream<'_>[src]

Get a stream to receive incoming messages.

pub async fn sink(&self) -> Sink<'_>[src]

Get a sink to send out messages.

pub async fn receive_specific<P>(&self, predicate: P) -> Result<Message> where
    P: Fn(&Message) -> Result<bool>, 
[src]

Receive a specific message.

This is the same as receiving messages from Stream, except that this takes a predicate function that decides if the message received should be returned by this method or not. All messages received during this call that are not returned by it, are pushed to the queue to be picked by the susubsequent or awaiting call to this method or by the Stream.

pub async fn send_message(&self, msg: Message) -> Result<u32>[src]

Send msg to the peer.

Unlike Sink, this method sets a unique (to this connection) serial number on the message before sending it off, for you.

On successfully sending off msg, the assigned serial number is returned.

pub async fn call_method<B>(
    &self,
    destination: Option<&str>,
    path: &str,
    iface: Option<&str>,
    method_name: &str,
    body: &B
) -> Result<Message> where
    B: Serialize + Type
[src]

Send a method call.

Create a method-call message, send it over the connection, then wait for the reply.

On succesful reply, an Ok(Message) is returned. On error, an Err is returned. D-Bus error replies are returned as Error::MethodError.

pub async fn emit_signal<B>(
    &self,
    destination: Option<&str>,
    path: &str,
    iface: &str,
    signal_name: &str,
    body: &B
) -> Result<()> where
    B: Serialize + Type
[src]

Emit a signal.

Create a signal message, and send it over the connection.

pub async fn reply<B>(&self, call: &Message, body: &B) -> Result<u32> where
    B: Serialize + Type
[src]

Reply to a message.

Given an existing message (likely a method call), send a reply back to the caller with the given body.

Returns the message serial number.

pub async fn reply_error<B>(
    &self,
    call: &Message,
    error_name: &str,
    body: &B
) -> Result<u32> where
    B: Serialize + Type
[src]

Reply an error to a message.

Given an existing message (likely a method call), send an error reply back to the caller with the given error_name and body.

Returns the message serial number.

pub fn is_bus(&self) -> bool[src]

Checks if self is a connection to a message bus.

This will return false for p2p connections.

pub async fn assign_serial_num(&self, msg: &mut Message) -> Result<u32>[src]

Assigns a serial number to msg that is unique to this connection.

This method can fail if msg is corrupt.

pub fn unique_name(&self) -> Option<&str>[src]

The unique name as assigned by the message bus or None if not a message bus connection.

pub async fn max_queued(&self) -> usize[src]

Max number of messages to queue.

pub async fn set_max_queued(self, max: usize) -> Self[src]

Set the max number of messages to queue.

Since typically you'd want to set this at instantiation time, this method takes ownership of self and returns an owned Connection instance so you can use the builder pattern to set the value.

Example

let conn = Connection::new_session()
    .await?
    .set_max_queued(30)
    .await;
assert_eq!(conn.max_queued().await, 30);

// Do something usefull with `conn`..

pub fn server_guid(&self) -> &str[src]

The server's GUID.

pub async fn as_raw_fd(&self) -> RawFd[src]

Get the raw file descriptor of this connection.

pub async fn new_session() -> Result<Self>[src]

Create a Connection to the session/user message bus.

pub async fn new_system() -> Result<Self>[src]

Create a Connection to the system-wide message bus.

pub async fn new_for_address(
    address: &str,
    bus_connection: bool
) -> Result<Self>
[src]

Create a Connection for the given D-Bus address.

Trait Implementations

impl Clone for Connection[src]

impl Debug for Connection[src]

Auto Trait Implementations

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.