Client

Struct Client 

Source
pub struct Client { /* private fields */ }
Expand description

A clonable, thread-safe handle to an MQTT client that can be used to publish messages, and subscribe/unsubscribe to/from topics.

It can also be used to disconnect the client from the broker, however it is recommended to disconnect using the ClientShutdownHandle linked to this client.

Implementations§

Source§

impl Client

Source

pub async fn connect<'a, C, CC>( host: &str, options: OptionsT<'a, CC>, ) -> Result<(Client, ClientShutdownHandle), ConnectError>
where CC: ConnectionConfig<C>,

Attempts to connect to the MQTT broker at the specified host using the specified Options.

The host parameter should only contain a hostname or an IP address, optionally followed by a port number, separated by colons (e.g. example.com or 127.0.0.1:1234). If the port is missing, the default port (specified in options) will be used to establish the connection.

If the connection succeeds and is accepted by the broker, two handles will be returned:

  • A Client handle that can be used to publish messages and (un)susbcribe to/from topics
  • A ClientShutdownHandle that can be used to disconnect the client’s transceiver task

An example can be found in this module’s documentation.

Source

pub fn was_session_present(&self) -> bool

Returns the session_present flags returned by the broker when connecting. Indicates if a session corresponding to this client’s ID was already existing and has been resumed.

Source

pub fn try_publish( &self, topic: &str, payload: &[u8], qos: QoS, retain: bool, ) -> Result<(), TryPublishError>

Attempts to publish a message. This flavour is non-blocking and does not need to be awaited on, but can fail if the client’s command queue is full.

There is no guarantee that the message will be transmitted to the broker as soon as this call returns, so the developer should wait a bit before shutting the client down. If this is not the expected behaviour, check the other publish methods.

For details regarding this method’s parameters, check the MQTT protocol.

Source

pub async fn publish_no_wait( &self, topic: &str, payload: &[u8], qos: QoS, retain: bool, ) -> Result<(), PublishError>

Waits for a free spot in the client’s command queue and enqueues a publish command.

There is no guarantee that the message will be transmitted to the broker as soon as this call returns, so the developer should wait a bit before shutting the client down. If this is not the expected behaviour, check the other publish methods.

For details regarding this method’s parameters, check the MQTT protocol.

Source

pub async fn publish_qos_0( &self, topic: &str, payload: &[u8], retain: bool, ) -> Result<(), PublishError>

Waits for a free spot in the client’s command queue and enqueues a publish command with the lowest possible Quality of Service (QoS::AtMostOnce). This is exactly the same as calling Self::publish_no_wait() with QoS::AtMostOnce.

There is no guarantee that the message will be transmitted to the broker as soon as this call returns, so the developer should wait a bit before shutting the client down. Reception by the broker will also never be guaranteed for a message with QoS::AtMostOnce; it is thus recommended to use Self::publish_qos_1() or Self::publish_qos_2() if the developer needs to ensure that the message has been successfully received by the broker.

For details regarding this method’s parameters, check the MQTT protocol.

Source

pub async fn publish_qos_1( &self, topic: &str, payload: &[u8], retain: bool, await_ack: bool, ) -> Result<(), PublishError>

Waits for a free spot in the client’s command queue, enqueues a publish command with QoS::AtLeastOnce, and optionally waits for the corresponding PUBACK packet, indicating that the message was successfully received by the broker (based on the value of await_ack).

If await_ack is false, then this is exactly the same as calling Self::publish_no_wait() with QoS::AtLeastOnce, and there will be no guarantee that the message will be transmitted to the broker as soon as this call returns.

Note that the broker is free to not relay the message to any clients if, for instance, this client does not have the permission to publish to the specified topic. On top of that, clients subscribed to the topic may have chosen a different Quality of Service. So, even if this method succeeds with await_ack set to true true, there is no guarantee that the message was received by any client.

For details regarding this method’s parameters, check the MQTT protocol.

Source

pub async fn publish_qos_2( &self, topic: &str, payload: &[u8], retain: bool, await_event: PublishEvent, ) -> Result<(), PublishError>

Waits for a free spot in the client’s command queue, enqueues a publish command with QoS::ExactlyOnce, and optionally waits for (based on the value of await_event):

  • The corresponding PUBREC packet, indicating that the message was successfully received by the broker
  • The corresponding PUBCOMP packet, indicating the end of the QoS 2 message transmission

If await_event is PublishEvent::None, then this is exactly the same as calling Self::publish_no_wait() with QoS::ExactlyOnce, and there will be no guarantee that the message will be transmitted to the broker as soon as this call returns.

Note that the broker is free to not relay the message to any clients if, for instance, this client does not have the permission to publish to the specified topic. On top of that, clients subscribed to the topic may have chosen a different Quality of Service. So, even if this method succeeds with await_event different from PublishEvent::None, there is no guarantee that the message was received by any client.

For details regarding this method’s parameters, check the MQTT protocol.

Source

pub async fn subscribe_void( &self, topic: String, qos_hint: QoS, ) -> Result<QoS, SubscribeError>

Creates a “void” subscription to the specified topic. This will only send a subscription request to the broker, and the caller will not have any way to retrieve the messages. If you wish to read messages, use any other subscribe methods.

If the client is already subscribed to the topic, then this function will only wait for a free spot on the command queue to submit the subscribe command, and will completely ignore qos_hint. Otherwise, it will send a SUBSCRIBE packet to the broker with the specified qos_hint and wait for a response. Because this is “void” subscription will be the sole subscription for this topic, all incoming messages (including the retained messages, if any) will be dropped, until a new subscription is created using any of the other subscribe methods.

The returned value is the actual QoS of this subscription as specified by the broker.

Source

pub fn subscribe_lossy<'a>( &'a self, topic: &'a str, qos_hint: QoS, queue_cap: usize, ) -> impl Future<Output = Result<(Receiver<Message>, QoS), SubscribeError>> + 'a

Creates a “lossy” subscription to the specified topic, with the specified capacity. “Lossy” subscriptions use a bounded MPSC channel to read incoming messages. Because the transceiver task cannot afford to wait, messages on the queue are sent using mpsc::Sender::try_send() and are dropped if the queue is full, meaning that messages can be lost if they are not dequeued quickly enough or if the queue capacity is too low. If this behaviour is not wanted, use Self::subscribe_unbounded() which relies on a mpsc::UnboundedSender instead, for a slightly higher cost in performance.

If the client is already subscribed to the topic, then this function will only wait for a free spot on the command queue to submit the subscribe command, and will completely ignore qos_hint. Otherwise, it will send a SUBSCRIBE packet to the broker with the specified qos_hint and wait for a response. In that case, retained packets (if there are any) are guarateed to be pushed onto the returned queue, unless the queue is full.

The returned value contains the mpsc::Receiver end of the queue as well as the actual QoS of this subscription as specified by the broker. Since v0.2, closing the receiving end of the queue will not cause the client to unsubscribe. To unsubscribe from a topic, use Client::unsubscribe().

Source

pub fn subscribe_unbounded<'a>( &'a self, topic: &'a str, qos_hint: QoS, ) -> impl Future<Output = Result<(UnboundedReceiver<Message>, QoS), SubscribeError>> + 'a

Creates an “unbounded” subscription to the specified topic. “Unbounded” subscriptions use an unbounded channel to read incoming messages. This is the safest way to receive messages, but may come at a slighly increased performance cost. If performance is an issue, use Self::subscribe_lossy().

If the client is already subscribed to the topic, then this function will only wait for a free spot on the command queue to submit the subscribe command, and will completely ignore qos_hint. Otherwise, it will send a SUBSCRIBE packet to the broker with the specified qos_hint and wait for a response. In that case, retained packets (if there are any) are guarateed to be pushed onto the returned queue.

The returned value contains the mpsc::UnboundedReceiver end of the queue as well as the actual QoS of this subscription as specified by the broker. Since v0.2, closing the receiving end of the queue will not cause the client to unsubscribe. To unsubscribe from a topic, use Client::unsubscribe().

Source

pub async fn subscribe_fast_callback<C>( &self, topic: String, qos_hint: QoS, callback: C, ) -> Result<(Callback, QoS), SubscribeError>
where C: FnMut(Message) + Send + Sync + 'static,

Creates a subs::Callback subscription to the specified topic. Callback subscriptions simply call the specified function whenever a message is received. This is the lightest form of subscription, however it does come with some constraints:

  • callback must be thread-safe (implement Send and Sync)
  • callback must never block

If the client is already subscribed to the topic, then this function will only wait for a free spot on the command queue to submit the subscribe command, and will completely ignore qos_hint. Otherwise, it will send a SUBSCRIBE packet to the broker with the specified qos_hint and wait for a response. In that case, callback is guaranteed to be called for each retained messages (should there be any).

The returned value contains the subscription object (which can be used to cancel the subscription), as well as the actual QoS of this subscription as specified by the broker.

Source

pub fn get_subscription_status(&self, topic: &str) -> SubscriptionStatus

Queries the status of a subscription to the specified topic. See SubscriptionStatus for details regarding the return value.

Source

pub async fn unsubscribe(&self, topic: String)

Unsubscribes from the specified topic, regardless of any existing subscription to that topic. If there are valid MPSC channels for that topic, they will be closed. If the client is not subscribed to this topic, this call will have no effect.

Source

pub fn is_transceiver_task_running(&self) -> bool

Returns true if the transceiver task is still running, meaning the MQTT client is probably still connected.

Source

pub fn did_transceiver_task_stop(&self) -> bool

Returns true if the transceiver task stopped, which may occur if Client::disconnect() or ClientShutdownHandle::disconnect() are closed, but also if the connection is closed unexpectedly.

Source

pub async fn disconnect(self)

Enqueues a disconnect command, causing the transceiver task to attempt to disconnect gracefully and shutdown. This will take some time to complete and the task might still be alive when this function returns. Self::is_transceiver_task_running() or Self::did_transceiver_task_stop() can be used to check if the task is still running. Ideally, ClientShutdownHandle::disconnect() should be used instead as it waits for the task’s completion.

Pending publish packets may not be sent, and existing subscriptions will be closed.

Trait Implementations§

Source§

impl Clone for Client

Source§

fn clone(&self) -> Client

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl Freeze for Client

§

impl !RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl !UnwindSafe for Client

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

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

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.