pub struct Disconnect {
pub props: Option<Properties>,
/* private fields */
}
Expand description
MQTT 5.0 DISCONNECT packet representation
The DISCONNECT packet is sent by either the client or the server to indicate graceful disconnection from the MQTT connection. In MQTT 5.0, both the client and server can send DISCONNECT packets to cleanly terminate the connection.
According to MQTT 5.0 specification, the DISCONNECT packet contains:
- Fixed header with packet type and remaining length
- Variable header with reason code and properties (both optional)
- No payload
§Reason Codes
The reason code indicates why the connection is being terminated:
0x00
Normal disconnection - Clean disconnect without error0x04
Disconnect with Will Message - Normal disconnect, publish Will Message0x80
Unspecified error0x81
Malformed packet0x82
Protocol error0x83
Implementation specific error0x87
Not authorized0x89
Server busy0x8B
Server shutting down0x8D
Keep alive timeout0x8E
Session taken over0x8F
Topic filter invalid0x90
Topic name invalid0x93
Receive maximum exceeded0x94
Topic alias invalid0x95
Packet too large0x96
Message rate too high0x97
Quota exceeded0x98
Administrative action0x99
Payload format invalid0x9A
Retain not supported0x9B
QoS not supported0x9C
Use another server0x9D
Server moved0x9E
Shared subscriptions not supported0x9F
Connection rate exceeded0xA0
Maximum connect time0xA1
Subscription identifiers not supported0xA2
Wildcard subscriptions not supported
§Properties
MQTT 5.0 DISCONNECT packets can include the following properties:
- Session Expiry Interval: Overrides the session expiry interval set in CONNECT
- Reason String: Human-readable string describing the reason for disconnect
- User Properties: Key-value pairs for application-specific metadata
- Server Reference: Alternative server for client to connect to
§Packet Structure Rules
- If no reason code is present, the remaining length is 0
- If reason code is present but no properties, remaining length is 1
- If properties are present, reason code must also be present
- Properties must not contain duplicate entries except for User Properties
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::DisconnectReasonCode;
// Create a simple normal disconnection
let disconnect = mqtt::packet::v5_0::Disconnect::builder()
.build()
.unwrap();
// Create disconnect with reason code
let disconnect = mqtt::packet::v5_0::Disconnect::builder()
.reason_code(DisconnectReasonCode::NormalDisconnection)
.build()
.unwrap();
assert_eq!(disconnect.reason_code(), Some(DisconnectReasonCode::NormalDisconnection));
// Create disconnect with reason code and properties
let props = vec![
mqtt::packet::ReasonString::new("Session timeout").unwrap().into(),
mqtt::packet::UserProperty::new("client_id", "device123").unwrap().into(),
];
let disconnect = mqtt::packet::v5_0::Disconnect::builder()
.reason_code(DisconnectReasonCode::KeepAliveTimeout)
.props(props)
.build()
.unwrap();
// Serialize to bytes for network transmission
let buffers = disconnect.to_buffers();
let size = disconnect.size();
Fields§
§props: Option<Properties>
Optional MQTT 5.0 properties for the DISCONNECT packet
Properties provide additional metadata about the disconnection. Valid properties for DISCONNECT packets include:
- Session Expiry Interval
- Reason String
- User Properties
- Server Reference
Implementations§
Source§impl Disconnect
impl Disconnect
Sourcepub fn props(&self) -> &Option<Properties>
pub fn props(&self) -> &Option<Properties>
Optional MQTT 5.0 properties for the DISCONNECT packet
Properties provide additional metadata about the disconnection. Valid properties for DISCONNECT packets include:
- Session Expiry Interval
- Reason String
- User Properties
- Server Reference
Source§impl Disconnect
impl Disconnect
Sourcepub fn builder() -> DisconnectBuilder
pub fn builder() -> DisconnectBuilder
Creates a new builder for constructing a DISCONNECT packet
The builder pattern allows for flexible construction of DISCONNECT packets with optional reason codes and properties.
§Returns
A new DisconnectBuilder
instance
§Examples
use mqtt_protocol_core::mqtt;
let disconnect = mqtt::packet::v5_0::Disconnect::builder()
.build()
.unwrap();
Sourcepub fn packet_type() -> PacketType
pub fn packet_type() -> PacketType
Returns the packet type for DISCONNECT packets
This is always PacketType::Disconnect
(14) for DISCONNECT packets.
§Returns
PacketType::Disconnect
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::packet_type::PacketType;
assert_eq!(mqtt::packet::v5_0::Disconnect::packet_type(), PacketType::Disconnect);
Sourcepub fn reason_code(&self) -> Option<DisconnectReasonCode>
pub fn reason_code(&self) -> Option<DisconnectReasonCode>
Returns the reason code for the disconnection
The reason code indicates why the connection is being terminated.
If no reason code is present in the packet, None
is returned,
which implies normal disconnection (0x00).
§Returns
Some(DisconnectReasonCode)
if a reason code is presentNone
if no reason code is present (implies normal disconnection)
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::DisconnectReasonCode;
// Disconnect without explicit reason code
let disconnect = mqtt::packet::v5_0::Disconnect::builder()
.build()
.unwrap();
assert_eq!(disconnect.reason_code(), None);
// Disconnect with reason code
let disconnect = mqtt::packet::v5_0::Disconnect::builder()
.reason_code(DisconnectReasonCode::ServerShuttingDown)
.build()
.unwrap();
assert_eq!(disconnect.reason_code(), Some(DisconnectReasonCode::ServerShuttingDown));
Sourcepub fn size(&self) -> usize
pub fn size(&self) -> usize
Returns the total size of the DISCONNECT packet in bytes
This includes the fixed header (1 byte), remaining length field, optional reason code (1 byte), optional property length field, and optional properties.
§Returns
The total packet size in bytes
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::DisconnectReasonCode;
// Simple disconnect (2 bytes: fixed header + remaining length 0)
let disconnect = mqtt::packet::v5_0::Disconnect::builder()
.build()
.unwrap();
let size = disconnect.size();
// Disconnect with reason code (4 bytes: fixed header + remaining length 1 + reason code + property length 0)
let disconnect = mqtt::packet::v5_0::Disconnect::builder()
.reason_code(DisconnectReasonCode::NormalDisconnection)
.build()
.unwrap();
let size_with_reason = disconnect.size();
assert!(size_with_reason > size);
Sourcepub fn to_buffers(&self) -> Vec<IoSlice<'_>>
pub fn to_buffers(&self) -> Vec<IoSlice<'_>>
Create IoSlice buffers for efficient network I/O
Returns a vector of IoSlice
objects that can be used for vectored I/O
operations, allowing zero-copy writes to network sockets. The buffers
represent the complete DISCONNECT packet in wire format.
§Returns
A vector of IoSlice
objects for vectored I/O operations
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::DisconnectReasonCode;
let disconnect = mqtt::packet::v5_0::Disconnect::builder()
.reason_code(DisconnectReasonCode::NormalDisconnection)
.build()
.unwrap();
let buffers = disconnect.to_buffers();
// Use with vectored write: socket.write_vectored(&buffers)?;
Sourcepub fn to_continuous_buffer(&self) -> Vec<u8> ⓘ
pub fn to_continuous_buffer(&self) -> Vec<u8> ⓘ
Create a continuous buffer containing the complete packet data
Returns a vector containing all packet bytes in a single continuous buffer.
This method provides an alternative to to_buffers()
for no-std environments
where vectored I/O is not available.
The returned buffer contains the complete DISCONNECT packet serialized according to the MQTT v5.0 protocol specification, including fixed header, remaining length, optional reason code, and optional properties.
§Returns
A vector containing the complete packet data
§Examples
use mqtt_protocol_core::mqtt;
let disconnect = mqtt::packet::v5_0::Disconnect::new();
let buffer = disconnect.to_continuous_buffer();
// buffer contains all packet bytes
Sourcepub fn parse(data: &[u8]) -> Result<(Self, usize), MqttError>
pub fn parse(data: &[u8]) -> Result<(Self, usize), MqttError>
Parses a DISCONNECT packet from byte data
This method parses the variable header portion of a DISCONNECT packet, extracting the optional reason code and properties. The fixed header should have been parsed separately before calling this method.
§Parameters
data
- Byte slice containing the variable header data
§Returns
Ok((Disconnect, usize))
- The parsed packet and number of bytes consumedErr(MqttError)
- If the packet is malformed or contains invalid data
§Errors
MqttError::MalformedPacket
- If the packet structure is invalidMqttError::ProtocolError
- If properties violate MQTT 5.0 rules
§Examples
use mqtt_protocol_core::mqtt;
// Parse disconnect with reason code and empty properties
let data = [0x00, 0x00]; // Normal disconnection + empty properties
let (disconnect, consumed) = mqtt::packet::v5_0::Disconnect::parse(&data).unwrap();
assert_eq!(consumed, 2);
// Parse empty disconnect (no reason code, no properties)
let data = [];
let (disconnect, consumed) = mqtt::packet::v5_0::Disconnect::parse(&data).unwrap();
assert_eq!(consumed, 0);
Trait Implementations§
Source§impl Clone for Disconnect
impl Clone for Disconnect
Source§fn clone(&self) -> Disconnect
fn clone(&self) -> Disconnect
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moreSource§impl Debug for Disconnect
Implements Debug
trait for DISCONNECT packets
impl Debug for Disconnect
Implements Debug
trait for DISCONNECT packets
Source§impl Display for Disconnect
Implements Display
trait for DISCONNECT packets
impl Display for Disconnect
Implements Display
trait for DISCONNECT packets
This provides a human-readable JSON representation of the packet, making it useful for debugging and logging purposes.
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::DisconnectReasonCode;
let disconnect = mqtt::packet::v5_0::Disconnect::builder()
.reason_code(DisconnectReasonCode::NormalDisconnection)
.build()
.unwrap();
println!("Packet: {}", disconnect);
// Output: {"type":"disconnect","reason_code":"NormalDisconnection"}
Source§impl<PacketIdType> From<Disconnect> for GenericPacket<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
impl<PacketIdType> From<Disconnect> for GenericPacket<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
Source§fn from(v: Disconnect) -> GenericPacket<PacketIdType>
fn from(v: Disconnect) -> GenericPacket<PacketIdType>
Source§impl GenericPacketDisplay for Disconnect
Implements the generic packet display trait for DISCONNECT packets
impl GenericPacketDisplay for Disconnect
Implements the generic packet display trait for DISCONNECT packets
This trait provides a common display interface for all MQTT packet types, enabling consistent formatting across different packet implementations.
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::GenericPacketDisplay;
let disconnect = mqtt::packet::v5_0::Disconnect::builder()
.build()
.unwrap();
// Format through the generic trait
println!("{}", disconnect);
Source§impl GenericPacketTrait for Disconnect
Implements the generic packet trait for DISCONNECT packets
impl GenericPacketTrait for Disconnect
Implements the generic packet trait for DISCONNECT packets
This trait provides a common interface for all MQTT packet types, allowing them to be used polymorphically in packet processing code.
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::GenericPacketTrait;
let disconnect = mqtt::packet::v5_0::Disconnect::builder()
.build()
.unwrap();
// Use through the generic trait
let size = disconnect.size();
let buffers = disconnect.to_buffers();
Source§impl PacketKind for Disconnect
impl PacketKind for Disconnect
Source§const IS_DISCONNECT: bool = true
const IS_DISCONNECT: bool = true
true
if this is a DISCONNECT packetSource§const IS_CONNECT: bool = false
const IS_CONNECT: bool = false
true
if this is a CONNECT packetSource§const IS_CONNACK: bool = false
const IS_CONNACK: bool = false
true
if this is a CONNACK packetSource§const IS_PUBLISH: bool = false
const IS_PUBLISH: bool = false
true
if this is a PUBLISH packetSource§const IS_PUBCOMP: bool = false
const IS_PUBCOMP: bool = false
true
if this is a PUBCOMP packetSource§const IS_SUBSCRIBE: bool = false
const IS_SUBSCRIBE: bool = false
true
if this is a SUBSCRIBE packetSource§const IS_UNSUBSCRIBE: bool = false
const IS_UNSUBSCRIBE: bool = false
true
if this is an UNSUBSCRIBE packetSource§const IS_UNSUBACK: bool = false
const IS_UNSUBACK: bool = false
true
if this is an UNSUBACK packetSource§const IS_PINGREQ: bool = false
const IS_PINGREQ: bool = false
true
if this is a PINGREQ packetSource§const IS_PINGRESP: bool = false
const IS_PINGRESP: bool = false
true
if this is a PINGRESP packetSource§impl PartialEq for Disconnect
impl PartialEq for Disconnect
Source§impl Serialize for Disconnect
Implements JSON serialization for DISCONNECT packets
impl Serialize for Disconnect
Implements JSON serialization for DISCONNECT packets
This implementation converts the DISCONNECT packet to a JSON representation suitable for debugging, logging, or API responses. The serialization includes the packet type, optional reason code, and optional properties.
§JSON Structure
{
"type": "disconnect",
"reason_code": "NormalDisconnection", // Optional
"props": [ ... ] // Optional
}
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::DisconnectReasonCode;
let disconnect = mqtt::packet::v5_0::Disconnect::builder()
.reason_code(DisconnectReasonCode::ServerShuttingDown)
.build()
.unwrap();
let json = serde_json::to_string(&disconnect).unwrap();
println!("DISCONNECT packet: {}", json);
Source§impl<PacketIdType> TryInto<Disconnect> for GenericPacket<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
impl<PacketIdType> TryInto<Disconnect> for GenericPacket<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
impl Eq for Disconnect
impl SendableRole<Any> for Disconnect
impl SendableRole<Client> for Disconnect
impl SendableRole<Server> for Disconnect
impl StructuralPartialEq for Disconnect
Auto Trait Implementations§
impl Freeze for Disconnect
impl RefUnwindSafe for Disconnect
impl Send for Disconnect
impl Sync for Disconnect
impl Unpin for Disconnect
impl UnwindSafe for Disconnect
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.