Struct zbus::Connection
source · [−]pub struct Connection { /* private fields */ }
Expand description
A D-Bus connection.
A connection to a D-Bus bus, or a direct peer.
Once created, the connection is authenticated and negotiated and messages can be sent or received, such as method calls or signals.
For higher-level message handling (typed functions, introspection, documentation reasons etc),
it is recommended to wrap the low-level D-Bus messages into Rust functions with the
dbus_proxy
and dbus_interface
macros instead of doing it directly on a Connection
.
Typically, a connection is made to the session bus with Connection::session
, or to the
system bus with Connection::system
. Then the connection is used with crate::Proxy
instances or the on-demand ObjectServer
instance that can be accessed through
Connection::object_server
.
Connection
implements Clone
and cloning it is a very cheap operation, as the underlying
data is not cloned. This makes it very convenient to share the connection between different
parts of your code. Connection
also implements std::marker::Sync
andstd::marker::Send
so you can send and share a connection instance across threads as well.
Connection
keeps an internal queue of incoming message. The maximum capacity of this queue
is configurable through the set_max_queued
method. The default size is 64. When the queue is
full, no more messages can be received until room is created for more. This is why it’s
important to ensure that all crate::MessageStream
and crate::blocking::MessageIterator
instances are continuously polled and iterated on, respectively.
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, the 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.
Since you do not need exclusive access to a zbus::Connection
to send messages on the bus,
Sink
is also implemented on &Connection
.
Caveats
At the moment, a simultaneous flush request from multiple tasks/threads could potentially create a busy loop, thus wasting CPU time. This limitation may be removed in the future.
Examples
Get the session bus ID
use zbus::Connection;
let mut connection = Connection::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::{Connection, MessageStream};
let connection = Connection::session().await?;
connection
.call_method(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
Some("org.freedesktop.DBus.Monitoring"),
"BecomeMonitor",
&(&[] as &[&str], 0u32),
)
.await?;
let mut stream = MessageStream::from(connection);
while let Some(msg) = stream.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
sourceimpl Connection
impl Connection
sourcepub async fn send_message(&self, msg: Message) -> Result<u32>
pub async fn send_message(&self, msg: Message) -> Result<u32>
Send msg
to the peer.
Unlike our 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.
sourcepub async fn call_method<'d, 'p, 'i, 'm, D, P, I, M, B>(
&self,
destination: Option<D>,
path: P,
interface: Option<I>,
method_name: M,
body: &B
) -> Result<Arc<Message>> where
D: TryInto<BusName<'d>>,
P: TryInto<ObjectPath<'p>>,
I: TryInto<InterfaceName<'i>>,
M: TryInto<MemberName<'m>>,
D::Error: Into<Error>,
P::Error: Into<Error>,
I::Error: Into<Error>,
M::Error: Into<Error>,
B: Serialize + DynamicType,
pub async fn call_method<'d, 'p, 'i, 'm, D, P, I, M, B>(
&self,
destination: Option<D>,
path: P,
interface: Option<I>,
method_name: M,
body: &B
) -> Result<Arc<Message>> where
D: TryInto<BusName<'d>>,
P: TryInto<ObjectPath<'p>>,
I: TryInto<InterfaceName<'i>>,
M: TryInto<MemberName<'m>>,
D::Error: Into<Error>,
P::Error: Into<Error>,
I::Error: Into<Error>,
M::Error: Into<Error>,
B: Serialize + DynamicType,
Send a method call.
Create a method-call message, send it over the connection, then wait for the reply.
On successful reply, an Ok(Message)
is returned. On error, an Err
is returned. D-Bus
error replies are returned as Error::MethodError
.
sourcepub async fn emit_signal<'d, 'p, 'i, 'm, D, P, I, M, B>(
&self,
destination: Option<D>,
path: P,
interface: I,
signal_name: M,
body: &B
) -> Result<()> where
D: TryInto<BusName<'d>>,
P: TryInto<ObjectPath<'p>>,
I: TryInto<InterfaceName<'i>>,
M: TryInto<MemberName<'m>>,
D::Error: Into<Error>,
P::Error: Into<Error>,
I::Error: Into<Error>,
M::Error: Into<Error>,
B: Serialize + DynamicType,
pub async fn emit_signal<'d, 'p, 'i, 'm, D, P, I, M, B>(
&self,
destination: Option<D>,
path: P,
interface: I,
signal_name: M,
body: &B
) -> Result<()> where
D: TryInto<BusName<'d>>,
P: TryInto<ObjectPath<'p>>,
I: TryInto<InterfaceName<'i>>,
M: TryInto<MemberName<'m>>,
D::Error: Into<Error>,
P::Error: Into<Error>,
I::Error: Into<Error>,
M::Error: Into<Error>,
B: Serialize + DynamicType,
Emit a signal.
Create a signal message, and send it over the connection.
sourcepub async fn reply<B>(&self, call: &Message, body: &B) -> Result<u32> where
B: Serialize + DynamicType,
pub async fn reply<B>(&self, call: &Message, body: &B) -> Result<u32> where
B: Serialize + DynamicType,
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.
sourcepub async fn reply_error<'e, E, B>(
&self,
call: &Message,
error_name: E,
body: &B
) -> Result<u32> where
B: Serialize + DynamicType,
E: TryInto<ErrorName<'e>>,
E::Error: Into<Error>,
pub async fn reply_error<'e, E, B>(
&self,
call: &Message,
error_name: E,
body: &B
) -> Result<u32> where
B: Serialize + DynamicType,
E: TryInto<ErrorName<'e>>,
E::Error: Into<Error>,
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.
sourcepub async fn reply_dbus_error(
&self,
call: &MessageHeader<'_>,
err: impl DBusError
) -> Result<u32>
pub async fn reply_dbus_error(
&self,
call: &MessageHeader<'_>,
err: impl DBusError
) -> Result<u32>
Reply an error to a message.
Given an existing message (likely a method call), send an error reply back to the caller using one of the standard interface reply types.
Returns the message serial number.
sourcepub async fn request_name<'w, W>(&self, well_known_name: W) -> Result<()> where
W: TryInto<WellKnownName<'w>>,
W::Error: Into<Error>,
pub async fn request_name<'w, W>(&self, well_known_name: W) -> Result<()> where
W: TryInto<WellKnownName<'w>>,
W::Error: Into<Error>,
Register a well-known name for this service on the bus.
You can request multiple names for the same ObjectServer
. Use Connection::release_name
for deregistering names registered through this method.
Note that exclusive ownership without queueing is requested (using
fdo::RequestNameFlags::ReplaceExisting
and fdo::RequestNameFlags::DoNotQueue
flags)
since that is the most typical case. If that is not what you want, you should use
fdo::DBusProxy::request_name
instead (but make sure then that name is requested
after you’ve setup your service implementation with the ObjectServer
).
Errors
Fails with zbus::Error::NameTaken
if the name is already owned by another peer.
sourcepub async fn release_name<'w, W>(&self, well_known_name: W) -> Result<bool> where
W: TryInto<WellKnownName<'w>>,
W::Error: Into<Error>,
pub async fn release_name<'w, W>(&self, well_known_name: W) -> Result<bool> where
W: TryInto<WellKnownName<'w>>,
W::Error: Into<Error>,
Deregister a previously registered well-known name for this service on the bus.
Use this method to deregister a well-known name, registered through
Connection::request_name
.
Unless an error is encountered, returns Ok(true)
if name was previously registered with
the bus through self
and it has now been successfully deregistered, Ok(false)
if name
was not previously registered or already deregistered.
sourcepub fn is_bus(&self) -> bool
pub fn is_bus(&self) -> bool
Checks if self
is a connection to a message bus.
This will return false
for p2p connections.
sourcepub fn assign_serial_num(&self, msg: &mut Message) -> Result<u32>
pub fn assign_serial_num(&self, msg: &mut Message) -> Result<u32>
Assigns a serial number to msg
that is unique to this connection.
This method can fail if msg
is corrupted.
sourcepub fn unique_name(&self) -> Option<&OwnedUniqueName>
pub fn unique_name(&self) -> Option<&OwnedUniqueName>
The unique name as assigned by the message bus or None
if not a message bus connection.
sourcepub fn max_queued(&self) -> usize
pub fn max_queued(&self) -> usize
Max number of messages to queue.
sourcepub fn set_max_queued(&mut self, max: usize)
pub fn set_max_queued(&mut self, max: usize)
Set the max number of messages to queue.
sourcepub fn server_guid(&self) -> &str
pub fn server_guid(&self) -> &str
The server’s GUID.
sourcepub fn executor(&self) -> &Executor<'static>
pub fn executor(&self) -> &Executor<'static>
The underlying executor.
When a connection is built with internal_executor set to false, zbus will not spawn a thread to run the executor. You’re responsible to continuously tick the executor. Failure to do so will result in hangs.
Examples
Here is how one would typically run the zbus executor through tokio’s single-threaded scheduler:
use zbus::ConnectionBuilder;
use tokio::runtime;
runtime::Builder::new_current_thread()
.build()
.unwrap()
.block_on(async {
let conn = ConnectionBuilder::session()
.unwrap()
.internal_executor(false)
.build()
.await
.unwrap();
{
let conn = conn.clone();
tokio::task::spawn(async move {
loop {
conn.executor().tick().await;
}
});
}
// All your other async code goes here.
});
Note: zbus 2.1 added support for tight integration with tokio. This means, if you use
zbus with tokio, you do not need to worry about this at all. All you need to do is enable
tokio
feature and disable the (default) async-io
feature in your Cargo.toml
.
sourcepub fn object_server(&self) -> impl Deref<Target = ObjectServer> + '_
pub fn object_server(&self) -> impl Deref<Target = ObjectServer> + '_
Get a reference to the associated ObjectServer
.
The ObjectServer
is created on-demand.
Note: Once the ObjectServer
is created, it will be replying to all method calls
received on self
. If you want to manually reply to method calls, do not use this
method (or any of the ObjectServer
related API).
sourcepub fn monitor_activity(&self) -> EventListener
pub fn monitor_activity(&self) -> EventListener
Returns a listener, notified on various connection activity.
This function is meant for the caller to implement idle or timeout on inactivity.
Trait Implementations
sourceimpl Clone for Connection
impl Clone for Connection
sourcefn clone(&self) -> Connection
fn clone(&self) -> Connection
Returns a copy of the value. Read more
1.0.0 · sourcefn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source
. Read more
sourceimpl Debug for Connection
impl Debug for Connection
sourceimpl From<&'_ Connection> for MessageStream
impl From<&'_ Connection> for MessageStream
sourcefn from(conn: &Connection) -> Self
fn from(conn: &Connection) -> Self
Converts to this type from the input type.
sourceimpl From<Connection> for Connection
impl From<Connection> for Connection
sourcefn from(conn: Connection) -> Self
fn from(conn: Connection) -> Self
Converts to this type from the input type.
sourceimpl From<Connection> for MessageStream
impl From<Connection> for MessageStream
sourcefn from(conn: Connection) -> Self
fn from(conn: Connection) -> Self
Converts to this type from the input type.
sourceimpl From<Connection> for Connection
impl From<Connection> for Connection
sourcefn from(conn: Connection) -> Self
fn from(conn: Connection) -> Self
Converts to this type from the input type.
sourceimpl From<MessageStream> for Connection
impl From<MessageStream> for Connection
sourcefn from(stream: MessageStream) -> Connection
fn from(stream: MessageStream) -> Connection
Converts to this type from the input type.
sourceimpl Sink<Message> for Connection
impl Sink<Message> for Connection
sourcefn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>>
Attempts to prepare the Sink
to receive a value. Read more
sourcefn start_send(self: Pin<&mut Self>, msg: Message) -> Result<()>
fn start_send(self: Pin<&mut Self>, msg: Message) -> Result<()>
Begin the process of sending a value to the sink.
Each call to this function must be preceded by a successful call to
poll_ready
which returned Poll::Ready(Ok(()))
. Read more
sourceimpl<'a> Sink<Message> for &'a Connection
impl<'a> Sink<Message> for &'a Connection
sourcefn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>>
fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>>
Attempts to prepare the Sink
to receive a value. Read more
sourcefn start_send(self: Pin<&mut Self>, msg: Message) -> Result<()>
fn start_send(self: Pin<&mut Self>, msg: Message) -> Result<()>
Begin the process of sending a value to the sink.
Each call to this function must be preceded by a successful call to
poll_ready
which returned Poll::Ready(Ok(()))
. Read more
Auto Trait Implementations
impl !RefUnwindSafe for Connection
impl Send for Connection
impl Sync for Connection
impl Unpin for Connection
impl !UnwindSafe for Connection
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T, Item> SinkExt<Item> for T where
T: Sink<Item> + ?Sized,
impl<T, Item> SinkExt<Item> for T where
T: Sink<Item> + ?Sized,
sourcefn with<U, Fut, F, E>(self, f: F) -> With<Self, Item, U, Fut, F> where
F: FnMut(U) -> Fut,
Fut: Future<Output = Result<Item, E>>,
E: From<Self::Error>,
fn with<U, Fut, F, E>(self, f: F) -> With<Self, Item, U, Fut, F> where
F: FnMut(U) -> Fut,
Fut: Future<Output = Result<Item, E>>,
E: From<Self::Error>,
Composes a function in front of the sink. Read more
sourcefn with_flat_map<U, St, F>(self, f: F) -> WithFlatMap<Self, Item, U, St, F> where
F: FnMut(U) -> St,
St: Stream<Item = Result<Item, Self::Error>>,
fn with_flat_map<U, St, F>(self, f: F) -> WithFlatMap<Self, Item, U, St, F> where
F: FnMut(U) -> St,
St: Stream<Item = Result<Item, Self::Error>>,
Composes a function in front of the sink. Read more
sourcefn sink_map_err<E, F>(self, f: F) -> SinkMapErr<Self, F> where
F: FnOnce(Self::Error) -> E,
fn sink_map_err<E, F>(self, f: F) -> SinkMapErr<Self, F> where
F: FnOnce(Self::Error) -> E,
Transforms the error returned by the sink.
sourcefn sink_err_into<E>(self) -> SinkErrInto<Self, Item, E> where
Self::Error: Into<E>,
fn sink_err_into<E>(self) -> SinkErrInto<Self, Item, E> where
Self::Error: Into<E>,
Map this sink’s error to a different error type using the Into
trait. Read more
sourcefn buffer(self, capacity: usize) -> Buffer<Self, Item>
fn buffer(self, capacity: usize) -> Buffer<Self, Item>
Adds a fixed-size buffer to the current sink. Read more
sourcefn fanout<Si>(self, other: Si) -> Fanout<Self, Si> where
Item: Clone,
Si: Sink<Item, Error = Self::Error>,
fn fanout<Si>(self, other: Si) -> Fanout<Self, Si> where
Item: Clone,
Si: Sink<Item, Error = Self::Error>,
Fanout items to multiple sinks. Read more
sourcefn flush(&mut self) -> Flush<'_, Self, Item> where
Self: Unpin,
fn flush(&mut self) -> Flush<'_, Self, Item> where
Self: Unpin,
Flush the sink, processing all pending items. Read more
sourcefn send(&mut self, item: Item) -> Send<'_, Self, Item> where
Self: Unpin,
fn send(&mut self, item: Item) -> Send<'_, Self, Item> where
Self: Unpin,
A future that completes after the given item has been fully processed into the sink, including flushing. Read more
sourcefn feed(&mut self, item: Item) -> Feed<'_, Self, Item> where
Self: Unpin,
fn feed(&mut self, item: Item) -> Feed<'_, Self, Item> where
Self: Unpin,
A future that completes after the given item has been received by the sink. Read more
sourcefn send_all<St>(&'a mut self, stream: &'a mut St) -> SendAll<'a, Self, St> where
St: TryStream<Ok = Item, Error = Self::Error> + Stream + Unpin + ?Sized,
Self: Unpin,
fn send_all<St>(&'a mut self, stream: &'a mut St) -> SendAll<'a, Self, St> where
St: TryStream<Ok = Item, Error = Self::Error> + Stream + Unpin + ?Sized,
Self: Unpin,
A future that completes after the given stream has been fully processed into the sink, including flushing. Read more
sourcefn left_sink<Si2>(self) -> Either<Self, Si2> where
Si2: Sink<Item, Error = Self::Error>,
fn left_sink<Si2>(self) -> Either<Self, Si2> where
Si2: Sink<Item, Error = Self::Error>,
Wrap this sink in an Either
sink, making it the left-hand variant
of that Either
. Read more
sourcefn right_sink<Si1>(self) -> Either<Si1, Self> where
Si1: Sink<Item, Error = Self::Error>,
fn right_sink<Si1>(self) -> Either<Si1, Self> where
Si1: Sink<Item, Error = Self::Error>,
Wrap this stream in an Either
stream, making it the right-hand variant
of that Either
. Read more
sourcefn poll_ready_unpin(
&mut self,
cx: &mut Context<'_>
) -> Poll<Result<(), Self::Error>> where
Self: Unpin,
fn poll_ready_unpin(
&mut self,
cx: &mut Context<'_>
) -> Poll<Result<(), Self::Error>> where
Self: Unpin,
A convenience method for calling Sink::poll_ready
on Unpin
sink types. Read more
sourcefn start_send_unpin(&mut self, item: Item) -> Result<(), Self::Error> where
Self: Unpin,
fn start_send_unpin(&mut self, item: Item) -> Result<(), Self::Error> where
Self: Unpin,
A convenience method for calling Sink::start_send
on Unpin
sink types. Read more
sourceimpl<T> ToOwned for T where
T: Clone,
impl<T> ToOwned for T where
T: Clone,
type Owned = T
type Owned = T
The resulting type after obtaining ownership.
sourcefn clone_into(&self, target: &mut T)
fn clone_into(&self, target: &mut T)
toowned_clone_into
)Uses borrowed data to replace owned data, usually by cloning. Read more