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
impl Connect
pub fn props(&self) -> &Properties
pub fn will_props(&self) -> &Properties
Source§impl Connect
impl Connect
Sourcepub fn packet_type() -> PacketType
pub fn packet_type() -> PacketType
Sourcepub fn protocol_name(&self) -> &str
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
Sourcepub fn protocol_version(&self) -> u8
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
Sourcepub fn clean_start(&self) -> bool
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
Sourcepub fn will_flag(&self) -> bool
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
Sourcepub fn will_qos(&self) -> Qos
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
)
Sourcepub fn will_retain(&self) -> bool
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
Sourcepub fn password_flag(&self) -> bool
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
Sourcepub fn user_name_flag(&self) -> bool
pub fn user_name_flag(&self) -> bool
Sourcepub fn keep_alive(&self) -> u16
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
Sourcepub fn client_id(&self) -> &str
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
Sourcepub fn will_topic(&self) -> Option<&str>
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
Sourcepub fn will_payload(&self) -> Option<&[u8]>
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
Sourcepub fn user_name(&self) -> Option<&str>
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
Sourcepub fn password(&self) -> Option<&[u8]>
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
Sourcepub fn size(&self) -> usize
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
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 CONNECT packet in wire format.
§Returns
A vector of IoSlice
objects for 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 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 CONNECT packet serialized according to the MQTT v5.0 protocol specification, including fixed header, variable header, properties, and payload.
§Returns
A vector containing the complete packet data
§Examples
use mqtt_protocol_core::mqtt;
let connect = mqtt::packet::v5_0::Connect::builder()
.client_id("client-123")
.build()
.unwrap();
let buffer = connect.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 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.
§Parameters
data
- Raw bytes containing the variable header and payload (excluding fixed header)
§Returns
Ok((Connect, usize))
- The parsed packet and number of bytes consumedErr(MqttError)
- If parsing fails due to malformed data or protocol violations
§Errors
MqttError::MalformedPacket
- Invalid packet structureMqttError::ProtocolError
- Protocol specification violationMqttError::UnsupportedProtocolVersion
- Wrong protocol versionMqttError::ClientIdentifierNotValid
- Invalid client identifierMqttError::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 Debug for Connect
Implements Debug trait for CONNECT packets
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§impl Display for Connect
Implements Display trait for CONNECT packets
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§impl<PacketIdType> From<Connect> for GenericPacket<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
impl<PacketIdType> From<Connect> for GenericPacket<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
Source§fn from(v: Connect) -> GenericPacket<PacketIdType>
fn from(v: Connect) -> GenericPacket<PacketIdType>
Source§impl GenericPacketDisplay for Connect
Implements generic packet display behavior for CONNECT packets
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 core::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§impl GenericPacketTrait for Connect
Implements generic packet behavior for CONNECT packets
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§impl PacketKind for Connect
PacketKind
implementation for v5.0 CONNECT packet
impl PacketKind for Connect
PacketKind
implementation for v5.0 CONNECT packet
Source§const IS_CONNECT: bool = true
const IS_CONNECT: bool = true
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§const IS_DISCONNECT: bool = false
const IS_DISCONNECT: bool = false
true
if this is a DISCONNECT packetSource§impl Serialize for Connect
Implements JSON serialization for CONNECT packets
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 identifierclean_start
: Clean start flagkeep_alive
: Keep alive intervalprops
: 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§impl<PacketIdType> TryInto<Connect> for GenericPacket<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
impl<PacketIdType> TryInto<Connect> for GenericPacket<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
impl Eq for Connect
impl SendableRole<Any> for Connect
impl SendableRole<Client> for Connect
impl StructuralPartialEq for Connect
Auto Trait Implementations§
impl Freeze for Connect
impl RefUnwindSafe for Connect
impl Send for Connect
impl Sync for Connect
impl Unpin for Connect
impl UnwindSafe for Connect
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.