Connack

Struct Connack 

Source
pub struct Connack {
    pub props: Properties,
    /* private fields */
}
Expand description

MQTT 5.0 CONNACK packet representation

The CONNACK packet is sent by the MQTT server (broker) in response to a CONNECT packet from a client. It indicates whether the connection attempt was successful and provides various connection-related parameters and capabilities.

According to MQTT 5.0 specification, the CONNACK packet contains:

  • Fixed header with packet type and remaining length
  • Variable header with acknowledgment flags, reason code, and properties
  • No payload

§Acknowledgment Flags

The acknowledgment flags byte contains:

  • Session Present flag (bit 0): Indicates whether the server has stored session state from a previous connection. Set to 1 if the server has session state, 0 if starting a clean session.
  • Bits 1-7: Reserved and must be set to 0

§Reason Codes

The reason code indicates the result of the connection attempt:

  • 0x00 Success - Connection accepted
  • 0x80 Unspecified error
  • 0x81 Malformed packet
  • 0x82 Protocol error
  • 0x83 Implementation specific error
  • 0x84 Unsupported protocol version
  • 0x85 Client identifier not valid
  • 0x86 Bad username or password
  • 0x87 Not authorized
  • 0x88 Server unavailable
  • 0x89 Server busy
  • 0x8A Banned
  • 0x8C Bad authentication method
  • 0x90 Topic name invalid
  • 0x95 Packet too large
  • 0x97 Quota exceeded
  • 0x99 Payload format invalid
  • 0x9A Retain not supported
  • 0x9B QoS not supported
  • 0x9C Use another server
  • 0x9D Server moved
  • 0x9F Connection rate exceeded

§Properties

MQTT 5.0 CONNACK packets can include various properties:

  • Session Expiry Interval
  • Receive Maximum
  • Maximum QoS
  • Retain Available
  • Maximum Packet Size
  • Assigned Client Identifier
  • Topic Alias Maximum
  • Reason String
  • User Properties
  • Wildcard Subscription Available
  • Subscription Identifiers Available
  • Shared Subscription Available
  • Server Keep Alive
  • Response Information
  • Server Reference
  • Authentication Method
  • Authentication Data

§Examples

use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::ConnectReasonCode;

// Create a successful CONNACK with clean session
let connack = mqtt::packet::v5_0::Connack::builder()
    .session_present(false)
    .reason_code(ConnectReasonCode::Success)
    .build()
    .unwrap();

assert_eq!(connack.reason_code(), ConnectReasonCode::Success);
assert!(!connack.session_present());

// Create CONNACK with session present and properties
let props = mqtt::packet::Properties::new();
let connack = mqtt::packet::v5_0::Connack::builder()
    .session_present(true)
    .reason_code(ConnectReasonCode::Success)
    .props(props)
    .build()
    .unwrap();

// Serialize to bytes for network transmission
let buffers = connack.to_buffers();

Fields§

§props: Properties

Implementations§

Source§

impl Connack

Source

pub fn props(&self) -> &Properties

Source§

impl Connack

Source

pub fn builder() -> ConnackBuilder

Create a new ConnackBuilder for constructing CONNACK packets

Returns a builder instance that allows setting the various fields of a CONNACK packet in a fluent interface style. The builder ensures all required fields are set before creating the final packet.

§Returns

A new ConnackBuilder instance

§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::ConnectReasonCode;

let connack = mqtt::packet::v5_0::Connack::builder()
    .session_present(false)
    .reason_code(ConnectReasonCode::Success)
    .build()
    .unwrap();
Source

pub fn packet_type() -> PacketType

Get the packet type for CONNACK packets

Returns the constant packet type identifier for CONNACK packets. This is always PacketType::Connack for CONNACK packets.

§Returns

The packet type PacketType::Connack

§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::packet_type::PacketType;

assert_eq!(mqtt::packet::v5_0::Connack::packet_type(), PacketType::Connack);
Source

pub fn session_present(&self) -> bool

Get the session present flag

Returns true if the server has stored session state for this client from a previous connection, false if this is a clean session or no session state exists. This corresponds to bit 0 of the acknowledgment flags byte.

§Returns

true if session state is present, false for a clean session

§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::ConnectReasonCode;

let connack = mqtt::packet::v5_0::Connack::builder()
    .session_present(true)
    .reason_code(ConnectReasonCode::Success)
    .build()
    .unwrap();

assert!(connack.session_present());
Source

pub fn reason_code(&self) -> ConnectReasonCode

Get the reason code from the CONNACK packet

Returns the reason code that indicates the result of the connection attempt. The reason code provides detailed information about whether the connection was successful or failed, and if failed, the specific reason for failure.

§Returns

The ConnectReasonCode indicating the connection result

§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::ConnectReasonCode;

let connack = mqtt::packet::v5_0::Connack::builder()
    .session_present(false)
    .reason_code(ConnectReasonCode::Success)
    .build()
    .unwrap();

assert_eq!(connack.reason_code(), ConnectReasonCode::Success);
Source

pub fn size(&self) -> usize

Get the total size of the CONNACK packet in bytes

Returns the complete size of the CONNACK packet including the fixed header, variable header, and all properties. This is useful for memory allocation and buffer management.

§Returns

The total packet size in bytes

§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::ConnectReasonCode;

let connack = mqtt::packet::v5_0::Connack::builder()
    .session_present(false)
    .reason_code(ConnectReasonCode::Success)
    .build()
    .unwrap();

let size = connack.size();
// Size includes fixed header + variable header + properties
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 CONNACK 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::ConnectReasonCode;

let connack = mqtt::packet::v5_0::Connack::builder()
    .session_present(false)
    .reason_code(ConnectReasonCode::Success)
    .build()
    .unwrap();

let buffers = connack.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 CONNACK packet serialized according to the MQTT v5.0 protocol specification, including fixed header, remaining length, acknowledgment flags, reason code, property length, and properties.

§Returns

A vector containing the complete packet data

§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::ConnectReasonCode;

let connack = mqtt::packet::v5_0::Connack::builder()
    .session_present(false)
    .reason_code(ConnectReasonCode::Success)
    .build()
    .unwrap();

let buffer = connack.to_continuous_buffer();
// buffer contains all packet bytes
Source

pub fn parse(data: &[u8]) -> Result<(Self, usize), MqttError>

Parse a CONNACK packet from raw bytes

Decodes a CONNACK packet from a byte buffer according to the MQTT 5.0 protocol specification. The buffer should contain the variable header and any properties, but not the fixed header (which should have been processed separately).

The parsing process:

  1. Reads acknowledgment flags (1 byte)
  2. Reads reason code (1 byte)
  3. Parses properties section
  4. Validates the packet structure and properties
§Parameters
  • data - Byte buffer containing the CONNACK packet data (without fixed header)
§Returns
  • Ok((Connack, bytes_consumed)) - Successfully parsed packet and number of bytes consumed
  • Err(MqttError::MalformedPacket) - If the buffer is malformed or too short
  • Err(MqttError::ProtocolError) - If the packet contains invalid properties
§Examples
use mqtt_protocol_core::mqtt;

// Buffer contains: [flags, reason_code, prop_length, ...properties]
let buffer = &[0x00, 0x00, 0x00]; // No session, success, no properties
let (connack, consumed) = mqtt::packet::v5_0::Connack::parse(buffer).unwrap();

assert!(!connack.session_present());
assert_eq!(consumed, 3);

Trait Implementations§

Source§

impl Clone for Connack

Source§

fn clone(&self) -> Connack

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 Connack

Implementation of Debug trait for debugging output

Uses the same JSON formatting as Display for consistent debugging output. This provides detailed, structured information about the CONNACK packet state.

§Examples

use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::ConnectReasonCode;

let connack = mqtt::packet::v5_0::Connack::builder()
    .session_present(false)
    .reason_code(ConnectReasonCode::BadUserNameOrPassword)
    .build()
    .unwrap();

println!("{:?}", connack);
// Output: {"type":"CONNACK","session_present":false,"reason_code":"BadUserNameOrPassword","props":{}}
Source§

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

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

impl Display for Connack

Implementation of Display trait for human-readable output

Formats the CONNACK packet as a JSON string for easy reading and debugging. If serialization fails, it returns an error message in JSON format.

§Examples

use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::ConnectReasonCode;

let connack = mqtt::packet::v5_0::Connack::builder()
    .session_present(true)
    .reason_code(ConnectReasonCode::Success)
    .build()
    .unwrap();

println!("{}", connack);
// Output: {"type":"CONNACK","session_present":true,"reason_code":"Success","props":{}}
Source§

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

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

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

Source§

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

Converts to this type from the input type.
Source§

impl GenericPacketDisplay for Connack

Implementation of GenericPacketDisplay for generic formatting operations

Provides a common interface for formatting operations that can be used generically across different MQTT packet types. This enables uniform display handling in collections and generic contexts.

§Methods

  • fmt_debug(): Delegates to the Debug trait implementation
  • fmt_display(): Delegates to the Display trait implementation

§Examples

use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::GenericPacketDisplay;
use mqtt_protocol_core::mqtt::result_code::ConnectReasonCode;

let connack = mqtt::packet::v5_0::Connack::builder()
    .session_present(false)
    .reason_code(ConnectReasonCode::Success)
    .build()
    .unwrap();

// Use generic display methods
println!("{}", format_args!("{}", connack)); // Uses fmt_display
Source§

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

Source§

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

Source§

impl GenericPacketTrait for Connack

Implementation of GenericPacketTrait for generic packet operations

Provides a common interface for packet operations that can be used generically across different MQTT packet types. This allows for uniform handling of packets in collections and generic contexts.

§Methods

  • size(): Returns the total packet size in bytes
  • to_buffers(): Returns IoSlice buffers for efficient network I/O

§Examples

use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::GenericPacketTrait;
use mqtt_protocol_core::mqtt::result_code::ConnectReasonCode;

let connack = mqtt::packet::v5_0::Connack::builder()
    .session_present(false)
    .reason_code(ConnectReasonCode::Success)
    .build()
    .unwrap();

// Use generic trait methods
let size = connack.size();
let buffers = connack.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 Connack

PacketKind implementation for v5.0 CONNACK packet

Source§

const IS_CONNACK: bool = true

true if this is a CONNACK 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_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_DISCONNECT: bool = false

true if this is a DISCONNECT 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 Connack

Source§

fn eq(&self, other: &Connack) -> 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 Connack

Implementation of Serialize trait for JSON serialization

Serializes the CONNACK packet to a structured format containing:

  • type: The packet type as a string (“CONNACK”)
  • session_present: Boolean indicating session state
  • reason_code: The connection result reason code
  • props: MQTT 5.0 properties (if any)

§Examples

use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::ConnectReasonCode;

let connack = mqtt::packet::v5_0::Connack::builder()
    .session_present(false)
    .reason_code(ConnectReasonCode::Success)
    .build()
    .unwrap();

let json = serde_json::to_string(&connack).unwrap();
// Produces: {"type":"CONNACK","session_present":false,"reason_code":"Success","props":{}}
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<Connack> 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<Connack, <Self as TryInto<Connack>>::Error>

Performs the conversion.
Source§

impl Eq for Connack

Source§

impl SendableRole<Any> for Connack

Source§

impl SendableRole<Server> for Connack

Source§

impl StructuralPartialEq for Connack

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.