Struct Connect

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

MQTT 5.0 CONNECT packet representation

The CONNECT packet is the first packet sent by a client to the MQTT server (broker) to establish an MQTT connection. It contains information about the client’s identity, session preferences, authentication credentials, and last will testament.

According to MQTT 5.0 specification, the CONNECT packet contains:

  • Fixed header with packet type and remaining length
  • Variable header with protocol name, version, connect flags, keep alive, and properties
  • Payload with client identifier, will properties/topic/payload (if set), username, and password (if set)

§Protocol Information

  • Protocol Name: Always “MQTT” (4 bytes)
  • Protocol Version: 0x05 for MQTT 5.0

§Connect Flags

The connect flags byte contains several important flags:

  • Bit 0: Reserved (must be 0)
  • Bit 1: Clean Start flag - if set, the server discards any existing session state
  • Bit 2: Will flag - indicates presence of will message
  • Bits 3-4: Will QoS level (0, 1, or 2)
  • Bit 5: Will Retain flag - if set, will message is retained
  • Bit 6: Password flag - indicates presence of password
  • Bit 7: User Name flag - indicates presence of user name

§Properties

MQTT 5.0 CONNECT packets can include various properties:

  • Session Expiry Interval
  • Receive Maximum
  • Maximum Packet Size
  • Topic Alias Maximum
  • Request Response Information
  • Request Problem Information
  • User Properties
  • Authentication Method
  • Authentication Data

§Will Properties

If a will message is present, it can include its own properties:

  • Will Delay Interval
  • Payload Format Indicator
  • Message Expiry Interval
  • Content Type
  • Response Topic
  • Correlation Data
  • User Properties

§Examples

use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::qos::Qos;

// Create a basic CONNECT packet with client ID
let connect = mqtt::packet::v5_0::Connect::builder()
    .client_id("my-client-123")
    .clean_start(true)
    .build()
    .unwrap();

assert_eq!(connect.client_id(), "my-client-123");
assert!(connect.clean_start());
assert_eq!(connect.protocol_version(), 5);

// Create CONNECT with will message and credentials
let connect = mqtt::packet::v5_0::Connect::builder()
    .client_id("client-with-will")
    .clean_start(false)
    .will_message("my/status", b"offline", Qos::AtLeastOnce, true)
    .user_name("username")
    .password(b"password")
    .keep_alive(60)
    .build()
    .unwrap();

assert_eq!(connect.will_topic(), Some("my/status"));
assert_eq!(connect.will_payload(), Some(b"offline".as_slice()));
assert_eq!(connect.will_qos(), Qos::AtLeastOnce);
assert!(connect.will_retain());
assert_eq!(connect.user_name(), Some("username"));
assert_eq!(connect.keep_alive(), 60);

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

Fields§

§props: Properties§will_props: Properties

Implementations§

Source§

impl Connect

Source

pub fn props(&self) -> &Properties

Source

pub fn will_props(&self) -> &Properties

Source§

impl Connect

Source

pub fn builder() -> ConnectBuilder

Creates a new builder for constructing a CONNECT packet

§Returns

A ConnectBuilder instance with default values

§Examples
use mqtt_protocol_core::mqtt;

let connect = mqtt::packet::v5_0::Connect::builder()
    .client_id("my-client")
    .build()
    .unwrap();
Source

pub fn packet_type() -> PacketType

Returns the packet type for CONNECT packets

§Returns

PacketType::Connect (value 1)

Source

pub fn protocol_name(&self) -> &str

Returns the MQTT protocol name

For MQTT 5.0, this is always “MQTT”

§Returns

The protocol name as a string slice

Source

pub fn protocol_version(&self) -> u8

Returns the MQTT protocol version

For MQTT 5.0, this is always 5 (0x05)

§Returns

The protocol version number

Source

pub fn clean_start(&self) -> bool

Returns the Clean Start flag value

When true, the server discards any existing session state for this client and starts a new clean session. When false, the server attempts to resume an existing session if one exists.

§Returns

true if Clean Start is enabled, false otherwise

Source

pub fn will_flag(&self) -> bool

Returns whether a will message is present

The will message is published by the server when the client disconnects unexpectedly or fails to send keep-alive messages.

§Returns

true if a will message is configured, false otherwise

Source

pub fn will_qos(&self) -> Qos

Returns the QoS level for the will message

The will QoS specifies the quality of service level to use when publishing the will message. Only valid when will_flag() returns true.

§Returns

The QoS level (AtMostOnce, AtLeastOnce, or ExactlyOnce)

Source

pub fn will_retain(&self) -> bool

Returns whether the will message should be retained

When true, the will message is stored by the server and delivered to new subscribers on the will topic. Only valid when will_flag() returns true.

§Returns

true if the will message should be retained, false otherwise

Source

pub fn password_flag(&self) -> bool

Returns whether a password is present

According to MQTT specification, if password flag is set, the user name flag must also be set.

§Returns

true if a password is included, false otherwise

Source

pub fn user_name_flag(&self) -> bool

Returns whether a user name is present

§Returns

true if a user name is included, false otherwise

Source

pub fn keep_alive(&self) -> u16

Returns the keep alive interval in seconds

The keep alive interval specifies the maximum time interval between control packets sent by the client. A value of 0 disables keep alive.

§Returns

Keep alive interval in seconds

Source

pub fn client_id(&self) -> &str

Returns the client identifier

The client identifier uniquely identifies the client to the server. It must be unique across all clients connected to the server.

§Returns

The client identifier as a string slice

Source

pub fn will_topic(&self) -> Option<&str>

Returns the will topic if a will message is configured

The will topic specifies where the will message should be published when the client disconnects unexpectedly.

§Returns

Some(&str) containing the will topic if will flag is set, None otherwise

Source

pub fn will_payload(&self) -> Option<&[u8]>

Returns the will message payload if a will message is configured

The will payload contains the message content to be published when the client disconnects unexpectedly.

§Returns

Some(&[u8]) containing the will payload if will flag is set, None otherwise

Source

pub fn user_name(&self) -> Option<&str>

Returns the user name if present

The user name is used for authentication with the MQTT server.

§Returns

Some(&str) containing the user name if user name flag is set, None otherwise

Source

pub fn password(&self) -> Option<&[u8]>

Returns the password if present

The password is used for authentication with the MQTT server. According to the MQTT specification, password can only be present if user name is also present.

§Returns

Some(&[u8]) containing the password if password flag is set, None otherwise

Source

pub fn size(&self) -> usize

Returns the total size of the packet in bytes

This includes the fixed header, variable header, and payload.

§Returns

Total packet size in bytes

Source

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

Converts the packet to a vector of I/O slices for efficient network transmission

This method creates a zero-copy representation of the packet by returning references to the internal buffers. This is more efficient than copying all data into a single buffer.

§Returns

A vector of IoSlice references that can be used with vectored I/O operations

§Examples
use mqtt_protocol_core::mqtt;

let connect = mqtt::packet::v5_0::Connect::builder()
    .client_id("client-123")
    .build()
    .unwrap();

let buffers = connect.to_buffers();
// Use buffers for vectored write operations
Source

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

Parses a CONNECT packet from raw bytes

This method parses the variable header and payload of a CONNECT packet according to the MQTT 5.0 specification. It validates the protocol name, version, and flag consistency.

§Arguments
  • data - Raw bytes containing the variable header and payload (excluding fixed header)
§Returns
  • Ok((Connect, usize)) - The parsed packet and number of bytes consumed
  • Err(MqttError) - If parsing fails due to malformed data or protocol violations
§Errors
  • MqttError::MalformedPacket - Invalid packet structure
  • MqttError::ProtocolError - Protocol specification violation
  • MqttError::UnsupportedProtocolVersion - Wrong protocol version
  • MqttError::ClientIdentifierNotValid - Invalid client identifier
  • MqttError::BadUserNameOrPassword - Invalid credentials
§Examples
use mqtt_protocol_core::mqtt;

// Assuming 'packet_data' contains a valid CONNECT packet payload
match mqtt::packet::v5_0::Connect::parse(&packet_data) {
    Ok((connect, bytes_consumed)) => {
        println!("Client ID: {}", connect.client_id());
        println!("Consumed {} bytes", bytes_consumed);
    }
    Err(e) => println!("Parse error: {:?}", e),
}

Trait Implementations§

Source§

impl AsConcrete<Connect> for Packet

Source§

impl Clone for Connect

Source§

fn clone(&self) -> Connect

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 Connect

Implements Debug trait for CONNECT packets

Uses the same JSON representation as Display for consistent debugging output. This provides structured, readable information about the packet contents.

§Examples

use mqtt_protocol_core::mqtt;

let connect = mqtt::packet::v5_0::Connect::builder()
    .client_id("debug-client")
    .build()
    .unwrap();

println!("{:?}", connect);
// Output: {"type":"connect","client_id":"debug-client",...}
Source§

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

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

impl Display for Connect

Implements Display trait for CONNECT packets

Formats the packet as JSON string for human-readable output. This is useful for logging, debugging, and displaying packet information. On serialization errors, returns an error JSON object.

§Examples

use mqtt_protocol_core::mqtt;

let connect = mqtt::packet::v5_0::Connect::builder()
    .client_id("display-client")
    .build()
    .unwrap();

println!("CONNECT packet: {}", connect);
// Output: {"type":"connect","client_id":"display-client",...}
Source§

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

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

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

Source§

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

Converts to this type from the input type.
Source§

impl GenericPacketDisplay for Connect

Implements generic packet display behavior for CONNECT packets

This trait provides standardized display formatting methods that work across different MQTT packet types. This allows for uniform handling of packets across different MQTT packet types. This enables uniform display handling in generic packet processing contexts.

§Purpose

Enables consistent display behavior when working with collections of different packet types or in generic packet processing scenarios.

§Examples

use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::GenericPacketDisplay;
use std::fmt::Write;

let connect = mqtt::packet::v5_0::Connect::builder()
    .client_id("display-generic")
    .build()
    .unwrap();

let mut output = String::new();
write!(&mut output, "{}", connect).unwrap();
Source§

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

Source§

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

Source§

impl GenericPacketTrait for Connect

Implements generic packet behavior for CONNECT packets

This trait provides common functionality shared across all MQTT packet types, enabling polymorphic handling of different packet types through a common interface. It provides methods for getting packet size and converting to I/O buffers.

§Purpose

This implementation allows CONNECT packets to be used polymorphically with other MQTT packet types in generic contexts, such as packet processing pipelines.

§Examples

use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::GenericPacketTrait;

let connect = mqtt::packet::v5_0::Connect::builder()
    .client_id("generic-client")
    .build()
    .unwrap();

// Use as generic packet
let size = connect.size();
let buffers = connect.to_buffers();
Source§

fn size(&self) -> usize

Source§

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

Source§

impl IntoConcreteOwned<Connect> for Packet

Source§

impl PacketKind for Connect

PacketKind implementation for v5.0 CONNECT packet

Source§

const IS_CONNECT: bool = true

true if this is a CONNECT packet
Source§

const IS_V5_0: bool = true

true if this is an MQTT v5.0 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_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 Connect

Source§

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

Implements JSON serialization for CONNECT packets

Provides structured JSON representation of the packet contents, useful for debugging, logging, and API responses. Sensitive data like passwords are masked for security.

§JSON Format

The serialized JSON includes:

  • type: Always “connect”
  • client_id: Client identifier
  • clean_start: Clean start flag
  • keep_alive: Keep alive interval
  • props: MQTT properties (if present)
  • user_name: User name (if present)
  • password: Always “*****” (masked for security)
  • will_qos: Will QoS level (if will message present)
  • will_retain: Will retain flag (if will message present)
  • will_props: Will properties (if present)
  • will_topic: Will topic (if will message present)
  • will_payload: Will payload as escaped binary string (if will message present)

§Examples

use mqtt_protocol_core::mqtt;
use serde_json;

let connect = mqtt::packet::v5_0::Connect::builder()
    .client_id("test-client")
    .user_name("user")
    .password(b"secret")
    .build()
    .unwrap();

let json = serde_json::to_string(&connect).unwrap();
// JSON will contain masked password: "password": "*****"
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<Connect> 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<Connect, <Self as TryInto<Connect>>::Error>

Performs the conversion.
Source§

impl Eq for Connect

Source§

impl SendableRole<Any> for Connect

Source§

impl SendableRole<Client> for Connect

Source§

impl StructuralPartialEq for Connect

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> AsConcrete<T> for T

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> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoConcreteOwned<T> for T

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

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more