pub struct Client<'c, N: Transport, B: BufferProvider<'c>, const MAX_SUBSCRIBES: usize, const RECEIVE_MAXIMUM: usize, const SEND_MAXIMUM: usize, const MAX_SUBSCRIPTION_IDENTIFIERS: usize> { /* private fields */ }Expand description
An MQTT client.
Configuration via const parameters:
MAX_SUBSCRIBES: The maximum amount of in-flight/unacknowledged SUBSCRIBE packets (one per call toSelf::subscribe).RECEIVE_MAXIMUM: MQTT’s control flow mechanism. The maximum amount of incomingQoS::AtLeastOnceandQoS::ExactlyOncepublications (accumulated). Must not be 0 and must not be greater than 65535.SEND_MAXIMUM: The maximum amount of outgoingQoS::AtLeastOnceandQoS::ExactlyOncepublications. The server can further limit this with its receive maximum. The client will use the minimum of this value andSelf::server_config.MAX_SUBSCRIPTION_IDENTIFIERS: The maximum amount of subscription identifier properties the client can receive within a single PUBLISH packet. If a packet with more subscription identifiers is received, the later identifers will be discarded.
Implementations§
Source§impl<'c, N: Transport, B: BufferProvider<'c>, const MAX_SUBSCRIBES: usize, const RECEIVE_MAXIMUM: usize, const SEND_MAXIMUM: usize, const MAX_SUBSCRIPTION_IDENTIFIERS: usize> Client<'c, N, B, MAX_SUBSCRIBES, RECEIVE_MAXIMUM, SEND_MAXIMUM, MAX_SUBSCRIPTION_IDENTIFIERS>
impl<'c, N: Transport, B: BufferProvider<'c>, const MAX_SUBSCRIBES: usize, const RECEIVE_MAXIMUM: usize, const SEND_MAXIMUM: usize, const MAX_SUBSCRIPTION_IDENTIFIERS: usize> Client<'c, N, B, MAX_SUBSCRIBES, RECEIVE_MAXIMUM, SEND_MAXIMUM, MAX_SUBSCRIPTION_IDENTIFIERS>
Sourcepub fn new(buffer: &'c mut B) -> Self
pub fn new(buffer: &'c mut B) -> Self
Creates a new, disconnected MQTT client using a buffer provider to store
dynamically sized fields of received packets.
The session state is initialised as a new session. If you want to start the
client with an existing session, use Self::with_session.
Sourcepub fn with_session(
session: Session<RECEIVE_MAXIMUM, SEND_MAXIMUM>,
buffer: &'c mut B,
) -> Self
pub fn with_session( session: Session<RECEIVE_MAXIMUM, SEND_MAXIMUM>, buffer: &'c mut B, ) -> Self
Creates a new, disconnected MQTT client using a buffer provider to store dynamically sized fields of received packets.
Sourcepub fn client_config(&self) -> &ClientConfig
pub fn client_config(&self) -> &ClientConfig
Returns configuration for this client.
Sourcepub fn server_config(&self) -> &ServerConfig
pub fn server_config(&self) -> &ServerConfig
Returns the configuration of the currently or last connected server if there is one.
Returns the configuration negotiated between the client and server.
Sourcepub fn session(&self) -> &Session<RECEIVE_MAXIMUM, SEND_MAXIMUM>
pub fn session(&self) -> &Session<RECEIVE_MAXIMUM, SEND_MAXIMUM>
Returns session related configuration and tracking information.
Sourcepub fn buffer(&self) -> &B
pub fn buffer(&self) -> &B
Returns an immutable reference to the supplied BufferProvider implementation.
Sourcepub fn buffer_mut(&mut self) -> &mut B
pub fn buffer_mut(&mut self) -> &mut B
Returns a mutable reference to the supplied BufferProvider implementation.
This can for example be used to reset the underlying buffer if using BumpBuffer.
Sourcepub async fn connect<'d>(
&mut self,
net: N,
options: &ConnectOptions<'_>,
client_identifier: Option<MqttString<'d>>,
) -> Result<ConnectInfo<'d>, MqttError<'c>>where
'c: 'd,
pub async fn connect<'d>(
&mut self,
net: N,
options: &ConnectOptions<'_>,
client_identifier: Option<MqttString<'d>>,
) -> Result<ConnectInfo<'d>, MqttError<'c>>where
'c: 'd,
Connect the client to an MQTT server on the other end of the net argument.
Sends a CONNECT message and awaits the CONNACK response by the server.
Only call this when
- the client is newly constructed.
- a non-recoverable error has occured and
Self::aborthas been called. Self::disconnecthas been called.
The session expiry interval in ConnectOptions overrides the one in the session of the client.
Configuration that was negotiated with the server is stored in the client_config,
server_config, shared_config, and session fields, which have getters
(Self::client_config, Self::server_config, Self::shared_config,
Self::session).
If the server does not have a session present, the client’s session is cleared. In case you would want
to keep the session state, you can call Self::session and clone the session before.
§Returns:
Information about the session/connection that the client does currently not use and therefore not store in its configuration fields.
§Errors
MqttError::Serverif:- the server sends a malformed packet
- the first received packet is something other than a CONNACK packet
client_identifierisNoneand the server did not assign a client identifier- the server causes a protocol error
MqttError::Disconnectif the CONNACK packet’s reason code is not successful (>= 0x80)MqttError::Networkif the underlyingTransportreturned an errorMqttError::Allocif the underlyingBufferProviderreturned an error
Sourcepub async fn ping(&mut self) -> Result<(), MqttError<'c>>
pub async fn ping(&mut self) -> Result<(), MqttError<'c>>
Start a ping handshake by sending a PINGRESP packet.
§Errors
MqttError::RecoveryRequiredif an unrecoverable error occured previouslyMqttError::Networkif the underlyingTransportreturned an error
Sourcepub async fn subscribe(
&mut self,
topic_filter: TopicFilter<'_>,
options: SubscriptionOptions,
) -> Result<PacketIdentifier, MqttError<'c>>
pub async fn subscribe( &mut self, topic_filter: TopicFilter<'_>, options: SubscriptionOptions, ) -> Result<PacketIdentifier, MqttError<'c>>
Subscribes to a single topic with the given options.
The client keeps track of the packet identifier sent in the SUBSCRIBE packet.
If no Event::Suback is received within a custom time,
this method can be used to send the SUBSCRIBE packet again.
A subscription identifier should only be set if the server supports
subscription identifiers (Can be checked with Self::server_config).
The client does not double-check whether this feature is supported and will
always include the subscription identifier argument if present.
§Returns:
The packet identifier of the sent SUBSCRIBE packet.
§Errors
MqttError::RecoveryRequiredif an unrecoverable error occured previouslyMqttError::Networkif the underlyingTransportreturned an errorMqttError::SessionBufferif the buffer for outgoing SUBSCRIBE packet identifiers is fullMqttError::ServerMaximumPacketSizeExceededif the server’s maximum packet size would be exceeded by sending this SUBSCRIBE packet
Sourcepub async fn unsubscribe(
&mut self,
topic_filter: TopicFilter<'_>,
) -> Result<PacketIdentifier, MqttError<'c>>
pub async fn unsubscribe( &mut self, topic_filter: TopicFilter<'_>, ) -> Result<PacketIdentifier, MqttError<'c>>
Unsubscribes from a single topic filter.
The client keeps track of the packet identifier sent in the UNSUBSCRIBE packet.
If no Event::Unsuback is received within a custom time,
this method can be used to send the UNSUBSCRIBE packet again.
§Returns:
The packet identifier of the sent UNSUBSCRIBE packet.
§Errors
MqttError::RecoveryRequiredif an unrecoverable error occured previouslyMqttError::Networkif the underlyingTransportreturned an errorMqttError::SessionBufferif the buffer for outgoing UNSUBSCRIBE packet identifiers is fullMqttError::ServerMaximumPacketSizeExceededif the server’s maximum packet size would be exceeded by sending this UNSUBSCRIBE packet
Sourcepub async fn publish(
&mut self,
options: &PublicationOptions<'_>,
message: Bytes<'_>,
) -> Result<Option<PacketIdentifier>, MqttError<'c>>
pub async fn publish( &mut self, options: &PublicationOptions<'_>, message: Bytes<'_>, ) -> Result<Option<PacketIdentifier>, MqttError<'c>>
Publish a message. If QoS is greater than 0, the packet identifier is also kept track of by the client
§Returns:
- In case of
QoS0:None - In case of
QoS1 or 2:Somewith the packet identifier of the published packet
§Errors
MqttError::RecoveryRequiredif an unrecoverable error occured previouslyMqttError::Networkif the underlyingTransportreturned an errorMqttError::SendQuotaExceededif the server’s control flow limit is reached and sending the PUBLISH would exceed the limit causing a protocol errorMqttError::SessionBufferif the buffer for outgoing PUBLISH packet identifiers is fullMqttError::InvalidTopicAliasif a topic alias is used and- its value is 0
- its value is greater than the server’s maximum topic alias
MqttError::PacketMaximumLengthExceededif the PUBLISH packet is too long to be encoded with MQTT’sVarByteIntMqttError::ServerMaximumPacketSizeExceededif the server’s maximum packet size would be exceeded by sending this PUBLISH packet
Sourcepub async fn republish(
&mut self,
packet_identifier: PacketIdentifier,
options: &PublicationOptions<'_>,
message: Bytes<'_>,
) -> Result<(), MqttError<'c>>
pub async fn republish( &mut self, packet_identifier: PacketIdentifier, options: &PublicationOptions<'_>, message: Bytes<'_>, ) -> Result<(), MqttError<'c>>
Resends a PUBLISH packet with DUP flag set.
This method must be called and must only be called after a reconnection with clean start set to 0, as resending packets at any other time is a protocol error. (Compare Message delivery retry, [MQTT-4.4.0-1]).
For a packet to be resent:
- it must have a quality of service > 0
- its packet identifier must have an in flight entry with a quality of service matching the quality of service in the options parameter
- in case of quality of service 2, it must not already be awaiting a PUBCOMP packet
§Errors
MqttError::RecoveryRequiredif an unrecoverable error occured previouslyMqttError::Networkif the underlyingTransportreturned an errorMqttError::RepublishQoSNotMatchingif theQoSof this republish does not match theQoSthat this packet identifier was originally published withMqttError::PacketIdentifierAwaitingPubcompif a PUBREC packet with this packet identifier has already been received and the server has therefore already received the PUBLISHMqttError::PacketIdentifierNotInFlightif this packet identifier is not tracked in the client’s sessionMqttError::InvalidTopicAliasif a topic alias is used and- its value is 0
- its value is greater than the server’s maximum topic alias
MqttError::PacketMaximumLengthExceededif the PUBLISH packet is too long to be encoded with MQTT’sVarByteIntMqttError::ServerMaximumPacketSizeExceededif the server’s maximum packet size would be exceeded by sending this PUBLISH packet
§Panics
This function may panic if the QoS in the options is QoS::AtMostOnce.
Sourcepub async fn rerelease(&mut self) -> Result<(), MqttError<'c>>
pub async fn rerelease(&mut self) -> Result<(), MqttError<'c>>
Resends all pending PUBREL packets.
This method must be called and must only be called after a reconnection with clean start set to 0, as resending packets at any other time is a protocol error. (Compare Message delivery retry, [MQTT-4.4.0-1]).
This method assumes that the server’s receive maximum after the reconnection is great enough to handle as many publication flows as dragged between the two connections.
§Errors
MqttError::RecoveryRequiredif an unrecoverable error occured previouslyMqttError::Networkif the underlyingTransportreturned an error
Sourcepub async fn abort(&mut self)
pub async fn abort(&mut self)
Disconnects from the server after an error occured in a situation-aware way by either:
- dropping the connection
- sending a DISCONNECT with the deposited reason code and dropping the connection.
After an MQTT communication fails, usually either the client or the server closes the connection.
This is not cancel-safe but you can set a timeout if reconnecting later anyway or you don’t reuse the client.
Sourcepub async fn disconnect(
&mut self,
options: &DisconnectOptions,
) -> Result<(), MqttError<'c>>
pub async fn disconnect( &mut self, options: &DisconnectOptions, ) -> Result<(), MqttError<'c>>
Disconnects gracefully from the server by sending a DISCONNECT packet.
§Preconditions:
- The client did not return a non-recoverable Error before
§Errors
MqttError::RecoveryRequiredif an unrecoverable error occured previouslyMqttError::Networkif the underlyingTransportreturned an errorMqttError::IllegalDisconnectSessionExpiryIntervalif the session expiry interval in the CONNECT packet was zero and the session expiry interval in theDisconnectOptionsisSomeand notSessionExpiryInterval::EndOnDisconnect.
Sourcepub async fn poll(
&mut self,
) -> Result<Event<'c, MAX_SUBSCRIPTION_IDENTIFIERS>, MqttError<'c>>
pub async fn poll( &mut self, ) -> Result<Event<'c, MAX_SUBSCRIPTION_IDENTIFIERS>, MqttError<'c>>
Combines Self::poll_header and Self::poll_body.
Polls the network for a full packet. Not cancel-safe.
§Preconditions:
- The last MQTT packet was received completely
- The client did not return a non-recoverable Error before
§Returns:
MQTT Events. Their further meaning is documented in Event.
§Errors
Returns the errors that Client::poll_header and Client::poll_body return.
For further information view their docs.
Sourcepub async fn poll_header(&mut self) -> Result<FixedHeader, MqttError<'c>>
pub async fn poll_header(&mut self) -> Result<FixedHeader, MqttError<'c>>
Polls the network for a fixed header in a cancel-safe way.
If a fixed header is received, the first 4 bits (packet type) are checked for correctness.
§Preconditions:
- The last MQTT packet was received completely
- The client did not return a non-recoverable Error before
§Returns:
The received fixed header with a valid packet type. It can be used to call Self::poll_body.
§Errors
MqttError::RecoveryRequiredif an unrecoverable error occured previouslyMqttError::Networkif the underlyingTransportreturned an errorMqttError::Serverif:- the server sends a malformed packet header
- the packet following this header exceeds the client’s maximum packet size
Sourcepub async fn poll_body(
&mut self,
header: FixedHeader,
) -> Result<Event<'c, MAX_SUBSCRIPTION_IDENTIFIERS>, MqttError<'c>>
pub async fn poll_body( &mut self, header: FixedHeader, ) -> Result<Event<'c, MAX_SUBSCRIPTION_IDENTIFIERS>, MqttError<'c>>
Polls the network for the variable header and payload of a packet. Not cancel-safe.
§Preconditions:
- The
FixedHeaderargument was received from the network right before. - The client did not return a non-recoverable
MqttErrorbefore
§Returns:
MQTT Events for regular communication. Their further meaning is documented in Event.
§Errors
MqttError::RecoveryRequiredif an unrecoverable error occured previouslyMqttError::Networkif the underlyingTransportreturned an errorMqttError::Allocif the underlyingBufferProviderreturned an errorMqttError::Serverif:- the server sends a malformed packet
- the server causes a protocol error
- the packet following this header exceeds the client’s maximum packet size
- the server sends a PUBLISH packet with an invalid topic alias
- the server exceeded the client’s receive maximum with a new
QoS2 PUBLISH - the server sends a PUBACK/PUBREC/PUBREL/PUBCOMP packet which mismatches what the client expects for this packet identifier from its session state
- the fixed header has the packet type CONNECT/SUBSCRIBE/UNSUBSCRIBE/PINGREQ
MqttError::Disconnectif a DISCONNECT packet is receivedMqttError::AuthPacketReceivedif the fixed header has the packet type AUTH