Disconnect

Struct Disconnect 

Source
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 error
  • 0x04 Disconnect with Will Message - Normal disconnect, publish Will Message
  • 0x80 Unspecified error
  • 0x81 Malformed packet
  • 0x82 Protocol error
  • 0x83 Implementation specific error
  • 0x87 Not authorized
  • 0x89 Server busy
  • 0x8B Server shutting down
  • 0x8D Keep alive timeout
  • 0x8E Session taken over
  • 0x8F Topic filter invalid
  • 0x90 Topic name invalid
  • 0x93 Receive maximum exceeded
  • 0x94 Topic alias invalid
  • 0x95 Packet too large
  • 0x96 Message rate too high
  • 0x97 Quota exceeded
  • 0x98 Administrative action
  • 0x99 Payload format invalid
  • 0x9A Retain not supported
  • 0x9B QoS not supported
  • 0x9C Use another server
  • 0x9D Server moved
  • 0x9E Shared subscriptions not supported
  • 0x9F Connection rate exceeded
  • 0xA0 Maximum connect time
  • 0xA1 Subscription identifiers not supported
  • 0xA2 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

Source

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

Source

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();
Source

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);
Source

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 present
  • None 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));
Source

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);
Source

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)?;
Source

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
Source

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 consumed
  • Err(MqttError) - If the packet is malformed or contains invalid data
§Errors
  • MqttError::MalformedPacket - If the packet structure is invalid
  • MqttError::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

Source§

fn clone(&self) -> Disconnect

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
Source§

impl Debug for Disconnect

Implements Debug trait for DISCONNECT packets

This provides the same output as the Display implementation, showing the JSON representation for debugging purposes.

§Examples

use mqtt_protocol_core::mqtt;

let disconnect = mqtt::packet::v5_0::Disconnect::builder()
    .build()
    .unwrap();

println!("{:?}", disconnect);
// Output: {"type":"disconnect"}
Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

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§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<PacketIdType> From<Disconnect> for GenericPacket<PacketIdType>
where PacketIdType: IsPacketId + Serialize,

Source§

fn from(v: Disconnect) -> GenericPacket<PacketIdType>

Converts to this type from the input type.
Source§

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§

fn fmt_debug(&self, f: &mut Formatter<'_>) -> Result

Source§

fn fmt_display(&self, f: &mut Formatter<'_>) -> Result

Source§

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§

fn size(&self) -> usize

Source§

fn to_buffers(&self) -> Vec<IoSlice<'_>>

Source§

fn to_continuous_buffer(&self) -> Vec<u8>

Create a continuous buffer containing the complete packet data Read more
Source§

impl PacketKind for Disconnect

Source§

const IS_DISCONNECT: bool = true

true if this is a DISCONNECT packet
Source§

const IS_V5_0: bool = true

true if this is an MQTT v5.0 packet
Source§

const IS_CONNECT: bool = false

true if this is a CONNECT packet
Source§

const IS_CONNACK: bool = false

true if this is a CONNACK packet
Source§

const IS_PUBLISH: bool = false

true if this is a PUBLISH packet
Source§

const IS_PUBACK: bool = false

true if this is a PUBACK packet
Source§

const IS_PUBREC: bool = false

true if this is a PUBREC packet
Source§

const IS_PUBREL: bool = false

true if this is a PUBREL packet
Source§

const IS_PUBCOMP: bool = false

true if this is a PUBCOMP packet
Source§

const IS_SUBSCRIBE: bool = false

true if this is a SUBSCRIBE packet
Source§

const IS_SUBACK: bool = false

true if this is a SUBACK packet
Source§

const IS_UNSUBSCRIBE: bool = false

true if this is an UNSUBSCRIBE packet
Source§

const IS_UNSUBACK: bool = false

true if this is an UNSUBACK packet
Source§

const IS_PINGREQ: bool = false

true if this is a PINGREQ packet
Source§

const IS_PINGRESP: bool = false

true if this is a PINGRESP packet
Source§

const IS_AUTH: bool = false

true if this is an AUTH packet (v5.0 only)
Source§

const IS_V3_1_1: bool = false

true if this is an MQTT v3.1.1 packet
Source§

impl PartialEq for Disconnect

Source§

fn eq(&self, other: &Disconnect) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

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§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<PacketIdType> TryInto<Disconnect> for GenericPacket<PacketIdType>
where PacketIdType: IsPacketId + Serialize,

Source§

type Error = &'static str

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

fn try_into(self) -> Result<Disconnect, <Self as TryInto<Disconnect>>::Error>

Performs the conversion.
Source§

impl Eq for Disconnect

Source§

impl SendableRole<Any> for Disconnect

Source§

impl SendableRole<Client> for Disconnect

Source§

impl SendableRole<Server> for Disconnect

Source§

impl StructuralPartialEq for Disconnect

Auto Trait Implementations§

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<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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<Role, PacketIdType, T> Sendable<Role, PacketIdType> for T
where Role: RoleType, PacketIdType: IsPacketId, T: SendableRole<Role> + SendableVersion + Display + Debug + PacketKind + SendableHelper<Role, PacketIdType>,

Source§

fn dispatch_send( self, connection: &mut GenericConnection<Role, PacketIdType>, ) -> Vec<GenericEvent<PacketIdType>>

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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.