mqute_codec/protocol/v3/
connect.rs

1//! # Connect Packet V3
2//!
3//! This module initializes the `Connect` packet for MQTT v3 (3.1) protocol.
4//! It uses the `connect!` macro to define the `Connect` packet structure with specific
5//! configurations for MQTT v3 compatibility.
6use crate::protocol::common::connect;
7use crate::protocol::v4::{Propertyless, Will};
8use crate::protocol::Protocol;
9
10// Defines the `Connect` packet for MQTT V3
11connect!(Connect<Propertyless, Will>, Protocol::V3);
12
13#[cfg(test)]
14mod tests {
15    use std::time::Duration;
16    use super::*;
17    use crate::codec::*;
18    use crate::protocol::*;
19    use bytes::{Bytes, BytesMut};
20    use tokio_util::codec::Decoder;
21
22    fn connect_sample() -> [u8; 45] {
23        [
24            (PacketType::Connect as u8) << 4, // Packet type
25            0x2b,                             // Remaining len
26            0x00,                             // Protocol name len
27            0x06,
28            b'M', // Protocol name
29            b'Q',
30            b'I',
31            b's',
32            b'd',
33            b'p',
34            Protocol::V3.into(), // Protocol level
35            0b1101_0110,         // Flags
36            0x00,                // Keep alive
37            0x10,
38            0x00, // Client ID
39            0x06,
40            b'c',
41            b'l',
42            b'i',
43            b'e',
44            b'n',
45            b't',
46            0x00, // Will topic
47            0x04,
48            b'/',
49            b'a',
50            b'b',
51            b'c',
52            0x00, // Will message
53            0x03,
54            b'b',
55            b'y',
56            b'e',
57            0x00, // Username
58            0x04,
59            b'u',
60            b's',
61            b'e',
62            b'r',
63            0x00, // Password
64            0x04,
65            b'p',
66            b'a',
67            b's',
68            b's',
69        ]
70    }
71
72    fn connect_packet() -> Connect {
73        let auth = Some(Credentials::login("user", "pass"));
74        let will = Some(Will::new(
75            "/abc",
76            Bytes::from("bye"),
77            QoS::ExactlyOnce,
78            false,
79        ));
80
81        Connect::new("client", auth, will, Duration::from_secs(16), true)
82    }
83
84    #[test]
85    fn connect_decode() {
86        let mut codec = PacketCodec::new(None, None);
87
88        let mut buf = BytesMut::new();
89
90        buf.extend_from_slice(&connect_sample());
91
92        let raw_packet = codec.decode(&mut buf).unwrap().unwrap();
93        let packet = Connect::decode(raw_packet).unwrap();
94        assert_eq!(packet, connect_packet());
95    }
96
97    #[test]
98    fn connect_encode() {
99        let packet = connect_packet();
100        let mut buf = BytesMut::new();
101        packet.encode(&mut buf).unwrap();
102        assert_eq!(buf, Vec::from(connect_sample()));
103    }
104}