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