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

pub struct Connection<S> { /* fields omitted */ }

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:

Generic over Socket

This type is generic over zbus::raw::Socket so that support for new socket types can be added with the same type easily later on.

Cloning and Mutability

Unlike zbus::Connection, this type does not implement std::clone::Clone. The reason is that implementation will be very difficult (and still prone to deadlocks) if connection is owned by multiple tasks/threads. Create separate connection instances or use futures::stream::StreamExt::split to split reading and writing between two separate async tasks.

Also notice that unlike zbus::Connection, most methods take a &mut self, rather than a &self. If they'd take &self, Connection will need to manage mutability internally, which is not a very good match with the general async/await machinery and runtimes in Rust and could easily lead into some hard-to-debug deadlocks. You can use std::cell::Cell, std::sync::Mutex or other related API combined with std::rc::Rc or std::sync::Arc for sharing a mutable Connection instance between different parts of your code (or threads).

Sending Messages

For sending messages you can either use Connection::send_message method or make use of the Sink implementation. 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 implementation. 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 implementation.

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::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.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<S> Connection<S> where
    S: AsRawFd + Debug + Unpin + Socket,
    Async<S>: Socket
[src]

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

Create and open a D-Bus connection from the given stream.

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_server(stream: S, guid: &Guid) -> Result<Self>[src]

Create a server Connection for the given stream 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 send_message(&mut self, msg: Message) -> Result<u32>[src]

Send msg to the peer.

Unlike Sink implementation, 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>(
    &mut 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>(
    &mut 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>(&mut 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>(
    &mut 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 set_unique_name(self, name: String) -> Result<Self, String>[src]

Sets the unique name for this connection.

This method should only be used when initializing a client bus connection with Connection::new_authenticated. Setting the unique name to anything other than the return value of the bus hello is a protocol violation.

Returns and error if the name has already been set.

pub fn assign_serial_num(&mut 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 fn max_queued(&self) -> usize[src]

Max number of messages to queue.

pub 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

use futures::executor::block_on;

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

// Do something usefull with `conn`..

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

The server's GUID.

impl Connection<UnixStream>[src]

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

Create a Connection to the session/user message bus.

Although, session bus hardly ever runs on anything other than UNIX domain sockets, if you want your code to be able to handle those rare cases, use ConnectionType::new_session instead.

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

Create a Connection to the system-wide message bus.

Although, system bus hardly ever runs on anything other than UNIX domain sockets, if you want your code to be able to handle those rare cases, use ConnectionType::new_system instead.

Trait Implementations

impl<S: Debug> Debug for Connection<S>[src]

impl<S> Sink<Message> for Connection<S> where
    S: AsRawFd + Debug + Unpin + Socket,
    Async<S>: Socket
[src]

type Error = Error

The type of value produced by the sink when an error occurs.

impl<S> Stream for Connection<S> where
    S: Socket,
    Async<S>: Socket
[src]

type Item = Result<Message>

Values yielded by the stream.

Auto Trait Implementations

impl<S> RefUnwindSafe for Connection<S> where
    S: RefUnwindSafe
[src]

impl<S> Send for Connection<S> where
    S: Send
[src]

impl<S> Sync for Connection<S> where
    S: Sync
[src]

impl<S> Unpin for Connection<S>[src]

impl<S> UnwindSafe for Connection<S> where
    S: UnwindSafe
[src]

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, Item> SinkExt<Item> for T where
    T: Sink<Item> + ?Sized
[src]

impl<S> StreamExt for S where
    S: Stream + ?Sized

impl<T> StreamExt for T where
    T: Stream + ?Sized
[src]

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.

impl<S, T, E> TryStream for S where
    S: Stream<Item = Result<T, E>> + ?Sized
[src]

type Ok = T

The type of successful values yielded by this future

type Error = E

The type of failures yielded by this future

impl<S> TryStreamExt for S where
    S: TryStream + ?Sized
[src]