gmqtt 0.1.1

A no_std, no_alloc MQTTv5 packet parsing library for embedded devices
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
use core::convert::TryFrom;

use heapless::Vec;

use crate::{protocol::Protocol, utils::*, MqttError, QoS};

use super::{property, PropertyType};

/// Connection packet initiated by the client
///
/// [MQTT5 SPECIFICATION](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901033)
#[derive(Debug, Clone, PartialEq)]
pub struct Connect<'a> {
    /// The one byte unsigned value that represents the revision level of the protocol used by the Client.
    /// The value of the Protocol Version field for version 5.0 of the protocol is 5 (0x05).
    pub protocol: Protocol,

    /// Position: bit 1 of the Connect Flags byte.
    ///
    /// This bit specifies whether the Connection starts a new Session or is a continuation of an existing Session
    pub clean_start: bool,

    /// The Keep Alive is a Two Byte Integer which is a time interval measured in seconds.
    /// It is the maximum time interval that is permitted to elapse between the point at which
    /// the Client finishes transmitting one MQTT Control Packet and the point it starts sending the next.
    pub keep_alive: u16,

    /// The Client Identifier (ClientID) identifies the Client to the Server.
    /// Each Client connecting to the Server has a unique ClientID.
    pub client_id: &'a str,

    /// The Will Properties field defines the Application Message properties to be sent with
    /// the Will Message when it is published, and properties which define when to publish the Will Message.
    /// The Will Properties consists of a Property Length and the Properties.
    pub last_will: Option<LastWill<'a>>,

    /// Login credentials
    pub login: Option<Login<'a>>,

    /// Properties
    pub properties: Option<ConnectProperties<'a>>,
}

impl<'a> Connect<'a> {
    pub fn new(id: &'a str) -> Self {
        Connect {
            protocol: Protocol::V5,
            keep_alive: 10,
            properties: None,
            client_id: id,
            clean_start: true,
            last_will: None,
            login: None,
        }
    }

    pub fn read(buf: &'a [u8], offset: &mut usize) -> Result<Self, MqttError> {
        let protocol = Protocol::read(buf, offset)?;

        let connect_flags = buf[*offset];

        // Validate that the reserved flag in the CONNECT packet is set to 0
        if (connect_flags & 0x01) != 0 {
            return Err(MqttError::MalformedPacket);
        }

        let clean_start = (connect_flags & 0b10) != 0;

        // Move offset to `keep_alive` field
        *offset += 1;

        let keep_alive = read_u16(buf, *offset);

        let properties = match protocol {
            Protocol::V5 => {
                // Move offset to `properties` length field
                *offset += 2;
                let props = ConnectProperties::read(buf, offset)?;

                // Move offset by `client_id` field
                *offset += 1;
                props
            }
            Protocol::V4 => None,
        };

        let client_id = read_str(buf, offset)?;
        let last_will = LastWill::read(connect_flags, buf, offset)?;
        let login = Login::read(connect_flags, buf, offset)?;

        let connect = Connect {
            protocol,
            clean_start,
            keep_alive,
            client_id,
            last_will,
            login,
            properties,
        };

        Ok(connect)
    }

    pub fn write(&self, buf: &mut [u8], offset: &mut usize) -> Result<usize, MqttError> {
        //  Connect Command (0x10);
        let header: u8 = 0x10;
        let mut connect_flags = 0b0000_0000;

        if self.clean_start {
            connect_flags |= 0b10;
        };

        if let Some(last_will) = &self.last_will {
            connect_flags |= 0b0000_0100;
            connect_flags |= (last_will.qos as u8) << 3;
            if last_will.retain {
                connect_flags |= 0b0010_0000;
            }
        }

        if self.login.is_some() {
            connect_flags |= 0b1000_0000;
            connect_flags |= 0b0100_0000;
        }

        check_remaining(buf, offset, self.len() + 1)?;

        write_u8(buf, offset, header);
        let write_len = write_length(buf, offset, self.len())? + 1;

        self.protocol.write(buf, offset);

        write_u8(buf, offset, connect_flags);
        write_u16(buf, offset, self.keep_alive);

        match &self.properties {
            Some(properties) => properties.write(buf, offset)?,
            None => write_u8(buf, offset, 0),
        }

        write_bytes_with_len(buf, offset, self.client_id.as_bytes());

        if let Some(last_will) = &self.last_will {
            last_will.write(buf, offset)?;
        };

        if let Some(login) = &self.login {
            login.write(buf, offset);
        };

        Ok(write_len)
    }

    fn len(&self) -> usize {
        let mut len = 2 + "MQTT".len() // protocol name
                              + 1  // protocol version
                              + 1  // connect flags
                              + 2; // keep alive

        match &self.properties {
            Some(properties) => {
                let properties_len = properties.len();
                let properties_len_len = len_len(properties_len);
                len += properties_len_len + properties_len;
            }
            None => {
                // just 1 byte representing 0 len
                len += 1;
            }
        }

        len += 2 + self.client_id.len();

        // last will len
        if let Some(last_will) = &self.last_will {
            len += last_will.len();
        }

        // username and password len
        if let Some(login) = &self.login {
            len += login.len();
        }

        len
    }

    pub fn set_login(&mut self, username: &'a str, password: &'a [u8]) -> &mut Connect<'a> {
        let login = Login { username, password };

        self.login = Some(login);
        self
    }
}

/// LastWill that broker forwards on behalf of the client
///
/// [MQTT5 SPECIFICATION](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901040)
#[derive(Debug, Clone, PartialEq)]
pub struct LastWill<'a> {
    /// If the Will Flag is set to 1, the Will Topic is the next field in the Payload.
    /// The Will Topic MUST be a UTF-8 Encoded String
    pub topic: &'a str,

    /// If the Will Flag is set to 1 the Will Payload is the next field in the Payload.
    /// The Will Payload defines the Application Message Payload that is to be published to the Will Topic
    pub message: &'a [u8],

    /// Position: bits 4 and 3 of the Connect Flags.
    ///
    /// These two bits specify the QoS level to be used when publishing the Will Message.
    pub qos: QoS,

    /// Position: bit 5 of the Connect Flags.
    ///
    /// This bit specifies if the Will Message is to be retained when it is published.
    pub retain: bool,

    /// If the Will Flag is set to 1, the Will Properties is the next field in the Payload.
    pub properties: Option<WillProperties<'a>>,
}

impl<'a> LastWill<'a> {
    pub fn new(topic: &'a str, payload: &'a [u8], qos: QoS, retain: bool) -> Self {
        LastWill {
            topic,
            message: payload,
            qos,
            retain,
            properties: None,
        }
    }

    pub fn read(
        connect_flags: u8,
        buf: &'a [u8],
        offset: &mut usize,
    ) -> Result<Option<Self>, MqttError> {
        let last_will = match connect_flags & 0b100 {
            0 if (connect_flags & 0b0011_1000) != 0 => {
                return Err(MqttError::IncorrectPacketFormat);
            }
            0 => None,
            _ => {
                // Properties in variable header
                let properties = WillProperties::read(buf, offset)?;

                // Move offset to `will topic` field
                *offset += 1;

                let will_topic = read_str(buf, offset)?;
                let will_message = read_bytes(buf, offset)?;
                let will_qos = QoS::try_from((connect_flags & 0b11000) >> 3)?;

                Some(LastWill {
                    topic: will_topic,
                    message: will_message,
                    qos: will_qos,
                    retain: (connect_flags & 0b0010_0000) != 0,
                    properties,
                })
            }
        };

        Ok(last_will)
    }

    pub fn write(&self, buf: &mut [u8], offset: &mut usize) -> Result<(), MqttError> {
        if let Some(properties) = &self.properties {
            properties.write(buf, offset)?;
        }
        write_bytes_with_len(buf, offset, self.topic.as_bytes());
        write_bytes_with_len(buf, offset, self.message);

        Ok(())
    }

    fn len(&self) -> usize {
        let mut len = 0;

        match &self.properties {
            Some(properties) => {
                let properties_len = properties.len();
                let properties_len_len = len_len(properties_len);
                len += properties_len_len + properties_len;
            }
            None => {
                // just 1 byte representing 0 len
                len += 1;
            }
        };

        len += 2 + self.topic.len() + 2 + self.message.len();
        len
    }
}

/// The Will Properties field defines the Application Message properties to be
/// sent with the Will Message when it is published,
/// and properties which define when to publish the Will Message.
///
/// [MQTT5 SPECIFICATION](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901060)
#[derive(Debug, Clone, PartialEq, Default)]
pub struct WillProperties<'a> {
    /// `1 (0x01)` Byte, Identifier of the Payload Format Indicator.
    ///
    /// Followed by the value of the Payload Format Indicator, either of:
    /// - `0 (0x00)` Byte Indicates that the Will Message is unspecified bytes, which is equivalent to not sending a Payload Format Indicator.
    /// - `1 (0x01)` Byte Indicates that the Will Message is UTF-8 Encoded Character Data.
    pub payload_format_indicator: Option<u8>,

    /// `2 (0x02)` Byte, Identifier of the Message Expiry Interval.
    ///
    /// Followed by the Four Byte Integer representing the Message Expiry Interval.
    pub message_expiry_interval: Option<u32>,

    /// `3 (0x03)` Identifier of the Content Type.
    ///
    /// Followed by a UTF-8 Encoded String describing the content of the Will Message.
    pub content_type: Option<&'a str>,

    /// `8 (0x08)` Byte, Identifier of the Response Topic.
    ///
    /// Followed by a UTF-8 Encoded String which is used as the Topic Name for a response message.
    pub response_topic: Option<&'a str>,

    /// `9 (0x09)` Byte, Identifier of the Correlation Data.
    ///
    /// Followed by Binary Data. The Correlation Data is used by the sender of the
    /// Request Message to identify which request the Response Message is for when it is received.
    pub correlation_data: Option<&'a [u8]>,

    /// `24 (0x18)` Byte, Identifier of the Will Delay Interval.
    ///
    /// Followed by the Four Byte Integer representing the Will Delay Interval in seconds.
    pub delay_interval: Option<u32>,

    /// `38 (0x26)` Byte, Identifier of the User Property.
    ///
    /// Followed by a UTF-8 String Pair.
    pub user_properties: Vec<(&'a str, &'a str), 32>,
}

impl<'a> WillProperties<'a> {
    pub fn read(buf: &'a [u8], offset: &mut usize) -> Result<Option<Self>, MqttError> {
        let mut properties = Self::default();

        let properties_len = buf[*offset];

        if properties_len == 0 {
            return Ok(None);
        }

        let mut cursor: usize = 1;

        while cursor < properties_len.into() {
            let mut prop_offset = *offset + cursor;
            let prop = buf[prop_offset];

            prop_offset += 1;
            cursor += 1;

            match property(prop)? {
                PropertyType::WillDelayInterval => {
                    properties.delay_interval = Some(read_u32(buf, prop_offset));
                    cursor += 4;
                }

                PropertyType::PayloadFormatIndicator => {
                    properties.payload_format_indicator = Some(buf[prop_offset]);
                    cursor += 1;
                }

                PropertyType::MessageExpiryInterval => {
                    properties.message_expiry_interval = Some(read_u32(buf, prop_offset));
                    cursor += 4;
                }

                PropertyType::ContentType => {
                    let typ = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + typ.len();
                    properties.content_type = Some(typ);
                }

                PropertyType::ResponseTopic => {
                    let topic = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + topic.len();
                    properties.response_topic = Some(topic)
                }

                PropertyType::CorrelationData => {
                    let data = read_bytes(buf, &mut prop_offset)?;
                    cursor += 2 + data.len();
                    properties.correlation_data = Some(data);
                }

                PropertyType::UserProperty => {
                    let key = read_str(buf, &mut prop_offset)?;
                    let value = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + key.len() + 2 + value.len();
                    properties
                        .user_properties
                        .push((key, value))
                        .map_err(|_| MqttError::TooManyUserProperties)?;
                }

                prop => return Err(MqttError::InvalidPropertyType(prop)),
            }
        }

        *offset += properties.len();
        Ok(Some(properties))
    }

    pub fn write(&self, buf: &mut [u8], offset: &mut usize) -> Result<(), MqttError> {
        write_length(buf, offset, self.len())?;
        if let Some(payload) = self.payload_format_indicator {
            write_u8(buf, offset, PropertyType::PayloadFormatIndicator as u8);
            write_u8(buf, offset, payload);
        }

        if let Some(expiry_interval) = self.message_expiry_interval {
            write_u8(buf, offset, PropertyType::MessageExpiryInterval as u8);
            write_bytes(buf, offset, &expiry_interval.to_be_bytes());
        }

        if let Some(content_type) = self.content_type {
            write_u8(buf, offset, PropertyType::ContentType as u8);
            write_bytes_with_len(buf, offset, content_type.as_bytes());
        }

        if let Some(response_topic) = self.response_topic {
            write_u8(buf, offset, PropertyType::ResponseTopic as u8);
            write_bytes_with_len(buf, offset, response_topic.as_bytes());
        }

        if let Some(correlation_data) = self.correlation_data {
            write_u8(buf, offset, PropertyType::CorrelationData as u8);
            write_bytes_with_len(buf, offset, correlation_data);
        }

        if let Some(delay_interval) = self.delay_interval {
            write_u8(buf, offset, PropertyType::WillDelayInterval as u8);
            write_bytes(buf, offset, &delay_interval.to_be_bytes());
        }

        for (key, value) in self.user_properties.iter() {
            write_u8(buf, offset, PropertyType::UserProperty as u8);
            write_bytes_with_len(buf, offset, key.as_bytes());
            write_bytes_with_len(buf, offset, value.as_bytes());
        }

        Ok(())
    }

    fn len(&self) -> usize {
        let mut len = 0;

        if self.delay_interval.is_some() {
            len += 1 + 4;
        }

        if self.payload_format_indicator.is_some() {
            len += 1 + 1;
        }

        if self.message_expiry_interval.is_some() {
            len += 1 + 4;
        }

        if let Some(typ) = &self.content_type {
            len += 1 + 2 + typ.len()
        }

        if let Some(topic) = &self.response_topic {
            len += 1 + 2 + topic.len()
        }

        if let Some(data) = &self.correlation_data {
            len += 1 + 2 + data.len()
        }

        for (key, value) in self.user_properties.iter() {
            len += 1 + 2 + key.len() + 2 + value.len();
        }

        len
    }
}

/// Login credentials used for authentication
#[derive(Debug, Clone, PartialEq)]
pub struct Login<'a> {
    /// If the User Name Flag is set to 1, the User Name is the next field in the Payload.
    /// The User Name MUST be a UTF-8 Encoded String
    pub username: &'a str,

    /// If the Password Flag is set to 1, the Password is the next field in the Payload.
    /// The Password field is Binary Data.
    pub password: &'a [u8],
}

impl<'a> Login<'a> {
    pub fn write(&self, buf: &mut [u8], offset: &mut usize) {
        write_bytes_with_len(buf, offset, self.username.as_bytes());
        write_bytes_with_len(buf, offset, self.password);
    }

    pub fn read(
        connect_flags: u8,
        buf: &'a [u8],
        offset: &mut usize,
    ) -> Result<Option<Self>, MqttError> {
        let username = match connect_flags & 0b1000_0000 {
            0 => return Ok(None),
            _ => read_str(buf, offset)?,
        };

        let password = match connect_flags & 0b0100_0000 {
            0 => return Ok(None),
            _ => read_bytes(buf, offset)?,
        };

        if username.is_empty() && password.is_empty() {
            Ok(None)
        } else {
            Ok(Some(Login { username, password }))
        }
    }

    fn len(&self) -> usize {
        let mut len = 0;

        if !self.username.is_empty() {
            len += 2 + self.username.len();
        }

        if !self.password.is_empty() {
            len += 2 + self.password.len();
        }

        len
    }
}

/// [MQTT5 SPECIFICATION](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901046)
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ConnectProperties<'a> {
    /// `17 (0x11)` Byte, Identifier of the Session Expiry Interval.
    ///
    /// Followed by the Four Byte Integer representing the Session Expiry Interval in seconds.
    pub session_expiry_interval: Option<u32>,

    /// `33 (0x21)` Byte, Identifier of the Receive Maximum.
    ///
    /// Followed by the Two Byte Integer representing the Receive Maximum value.
    pub receive_maximum: Option<u16>,

    /// `39 (0x27)` Byte, Identifier of the Maximum Packet Size.
    ///
    /// Followed by a Four Byte Integer representing the Maximum Packet Size the Client is willing to accept.
    pub max_packet_size: Option<u32>,

    /// `34 (0x22)` Byte, Identifier of the Topic Alias Maximum.
    ///
    /// Followed by the Two Byte Integer representing the Topic Alias Maximum value.
    pub topic_alias_max: Option<u16>,

    /// `25 (0x19)` Byte, Identifier of the Request Response Information.
    ///
    /// Followed by a Byte with a value of either 0 or 1.
    pub request_response_info: Option<u8>,

    /// `23 (0x17)` Byte, Identifier of the Request Problem Information.
    ///
    /// Followed by a Byte with a value of either 0 or 1.
    pub request_problem_info: Option<u8>,

    /// `38 (0x26)` Byte, Identifier of the User Property.
    ///
    /// Followed by a UTF-8 String Pair.
    pub user_properties: Vec<(&'a str, &'a str), 32>,

    /// `21 (0x15)` Byte, Identifier of the Authentication Method.
    ///
    /// Followed by a UTF-8 Encoded String containing the name of the authentication method used for extended authentication.
    pub authentication_method: Option<&'a str>,

    /// `22 (0x16)` Byte, Identifier of the Authentication Data.
    ///
    /// Followed by Binary Data containing authentication data.
    pub authentication_data: Option<&'a [u8]>,
}

impl<'a> ConnectProperties<'a> {
    pub fn write(&self, buf: &mut [u8], offset: &mut usize) -> Result<(), MqttError> {
        write_length(buf, offset, self.len())?;
        if let Some(session_expiry_interval) = self.session_expiry_interval {
            write_u8(buf, offset, PropertyType::SessionExpiryInterval as u8);
            write_bytes(buf, offset, &session_expiry_interval.to_be_bytes());
        }

        if let Some(receive_maximum) = self.receive_maximum {
            write_u8(buf, offset, PropertyType::ReceiveMaximum as u8);
            write_u16(buf, offset, receive_maximum);
        }

        if let Some(max_packet_size) = self.max_packet_size {
            write_u8(buf, offset, PropertyType::MaximumPacketSize as u8);
            write_bytes(buf, offset, &max_packet_size.to_be_bytes());
        }

        if let Some(topic_alias_max) = self.topic_alias_max {
            write_u8(buf, offset, PropertyType::TopicAliasMaximum as u8);
            write_u16(buf, offset, topic_alias_max);
        }

        if let Some(request_response_info) = self.request_response_info {
            write_u8(buf, offset, PropertyType::RequestResponseInformation as u8);
            write_u8(buf, offset, request_response_info);
        }

        if let Some(request_problem_info) = self.request_problem_info {
            write_u8(buf, offset, PropertyType::RequestProblemInformation as u8);
            write_u8(buf, offset, request_problem_info);
        }

        if let Some(authentication_method) = self.authentication_method {
            write_u8(buf, offset, PropertyType::AuthenticationMethod as u8);
            write_bytes_with_len(buf, offset, authentication_method.as_bytes());
        }

        if let Some(authentication_data) = self.authentication_data {
            write_u8(buf, offset, PropertyType::AuthenticationData as u8);
            write_bytes_with_len(buf, offset, authentication_data);
        }

        for (key, value) in self.user_properties.iter() {
            write_u8(buf, offset, PropertyType::UserProperty as u8);
            write_bytes_with_len(buf, offset, key.as_bytes());
            write_bytes_with_len(buf, offset, value.as_bytes());
        }

        Ok(())
    }
    pub fn read(buf: &'a [u8], offset: &mut usize) -> Result<Option<Self>, MqttError> {
        let mut properties = Self::default();

        let properties_len = buf[*offset];

        if properties_len == 0 {
            return Ok(None);
        }

        let mut cursor: usize = 1;

        while cursor < properties_len.into() {
            let mut prop_offset = *offset + cursor;
            let prop = buf[prop_offset];

            prop_offset += 1;
            cursor += 1;

            match property(prop)? {
                PropertyType::SessionExpiryInterval => {
                    properties.session_expiry_interval = Some(read_u32(buf, prop_offset));
                    cursor += 4;
                }

                PropertyType::ReceiveMaximum => {
                    properties.receive_maximum = Some(read_u16(buf, prop_offset));
                    cursor += 2;
                }

                PropertyType::MaximumPacketSize => {
                    properties.max_packet_size = Some(read_u32(buf, prop_offset));
                    cursor += 4;
                }

                PropertyType::TopicAliasMaximum => {
                    properties.topic_alias_max = Some(read_u16(buf, prop_offset));
                    cursor += 2;
                }

                PropertyType::RequestResponseInformation => {
                    properties.request_response_info = Some(buf[prop_offset]);
                    cursor += 1;
                }

                PropertyType::RequestProblemInformation => {
                    properties.request_problem_info = Some(buf[prop_offset]);
                    cursor += 1;
                }

                PropertyType::UserProperty => {
                    let key = read_str(buf, &mut prop_offset)?;
                    let value = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + key.len() + 2 + value.len();
                    properties
                        .user_properties
                        .push((key, value))
                        .map_err(|_| MqttError::TooManyUserProperties)?;
                }

                PropertyType::AuthenticationMethod => {
                    let method = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + method.len();
                    properties.authentication_method = Some(method);
                }

                PropertyType::AuthenticationData => {
                    let data = read_bytes(buf, &mut prop_offset)?;
                    cursor += 2 + data.len();
                    properties.authentication_data = Some(data);
                }

                prop => return Err(MqttError::InvalidPropertyType(prop)),
            }
        }

        *offset += properties.len();
        Ok(Some(properties))
    }

    fn len(&self) -> usize {
        let mut len = 0;

        if self.session_expiry_interval.is_some() {
            len += 1 + 4;
        }

        if self.receive_maximum.is_some() {
            len += 1 + 2;
        }

        if self.max_packet_size.is_some() {
            len += 1 + 4;
        }

        if self.topic_alias_max.is_some() {
            len += 1 + 2;
        }

        if self.request_response_info.is_some() {
            len += 1 + 1;
        }

        if self.request_problem_info.is_some() {
            len += 1 + 1;
        }

        for (key, value) in self.user_properties.iter() {
            len += 1 + 2 + key.len() + 2 + value.len();
        }

        if let Some(authentication_method) = &self.authentication_method {
            len += 1 + 2 + authentication_method.len();
        }

        if let Some(authentication_data) = &self.authentication_data {
            len += 1 + 2 + authentication_data.len();
        }

        len
    }
}

#[cfg(test)]
mod tests {
    use super::{Connect, ConnectProperties, LastWill, Login, WillProperties};
    use crate::{protocol::Protocol, QoS};

    fn sample_bytes() -> Vec<u8> {
        vec![
            0x10, // Message Type: Connect Command (1)
            0x1a, // Remaining len
            0x00, 0x04, // Protocol Name Length: 4
            0x4d, 0x51, 0x54, 0x54, // Protocol Name: MQTT
            0x05, // Version: MQTT v5.0 (5)
            0xc2, // Connect flags
            0x00, 0x3c, // keep alive
            //
            // ------ Properties start ------
            0x19, // Total length: 25
            0x11, // ID: Session Expiry Interval,
            0x00, 0x00, 0x00, 0x78, // Value: 120
            0x21, // ID: Receive Maximum
            0x01, 0x00, // Value: 256,
            0x27, // ID: Maximum Packet Size
            0x00, 0x00, 0x01, 0x09, // Value: 265
            0x16, // ID: Authentication Data
            0x00, 0x09, // Length: 9
            0x61, 0x75, 0x74, 0x68, 0x2d, 0x64, 0x61, 0x74, 0x61, // Value: "auth-data"
            // ------ Properties end   ------
            //
            0x00, 0x00, // Client ID Length: 0
            0x00, 0x02, // User Name length: 2
            0x69, 0x7a, // User Name: iz
            0x00, 0x04, // Password length: 4
            0x31, 0x32, 0x33, 0x34, // Password: 1234
        ]
    }

    #[rustfmt::skip::macros(vec)]
    fn sample_bytes_with_will() -> Vec<u8> {
        vec![
            0x10, // Message Type: Connect Command (1) 
            0x71, // Msg Len: 113
            0x00, 0x04, // Protocol Name Length: 4 
            0x4d, 0x51, 0x54, 0x54, // Protocol Name: MQTT 
            0x05, // Version: MQTT v5.0 (5) 
            0xf4, // Connect flags
            0x00, 0x3c, // Keep Alive: 60
            //
            //
            // ------ Properties start ------
            0x03, // Total Length: 3
            0x21, // ID: Receive Maximum
            0x00, 0x14, // Value: 20
            //
            // ------ Properties end ------
            //
            0x00, 0x07, // Client ID Length: 7
            0x74, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, // Client ID: test_id
            //
            // ------ Will Properties start ------
            //
            0x3f, // Total Length: 63 

            0x01, // ID: Payload Format Indicator
            0x01, // Value: 1

            0x02, // ID: Publication Expiry Interval 
            0x00, 0x00, 0x00, 0x78, // Value: 120

            0x03, // ID: Content Type
            0x00, 0x04, // Length: 4 
            0x74, 0x65, 0x78, 0x74, // Value: "text"

            0x08, // ID: Response Topic
            0x00, 0x0c, // Length: 12
            0x77, 0x69, 0x6c, 0x6c, 0x5f, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x64, // Value: will_respond

            0x09, // ID: Correlation Data
            0x00, 0x04, // Length: 4
            0x31, 0x32, 0x33, 0x34, // Value: "1234"

            0x18, // ID: Will Delay Interval
            0x00, 0x00, 0x00, 0x05, // Value: 5

            0x26, // ID: User Property
            0x00, 0x09, // Key Length: 9
            0x73, 0x66, 0x69, 0x6c, 0x65, 0x6e, 0x61, 0x6d, 0x65, // Key: "sfilename"
            0x00, 0x08, // Value Length: 8 
            0x74, 0x65, 0x73, 0x74, 0x2e, 0x74, 0x78, 0x74, // Value: "test.txt"
            //
            // ------ Will Properties end ------
            //
            0x00, 0x04, // Will  Topic Length: 4
            0x77, 0x69, 0x6c, 0x6c, // Will  Topic: "will"
            0x00, 0x08, // Will Message Length: 8
            0x6c, 0x61, 0x73, 0x74, 0x77, 0x69, 0x6c, 0x6c, // Will Message: "lastwill"
            0x00, 0x02, // User Name length: 2
            0x69, 0x7a, // User Name: iz
            0x00, 0x04, // Password length: 4
            0x31, 0x32, 0x33, 0x34, // Password: 1234
        ]
    }

    fn sample_connect_properties<'a>() -> ConnectProperties<'a> {
        let props = ConnectProperties {
            authentication_data: Some("auth-data".as_bytes()),
            max_packet_size: Some(265),
            receive_maximum: Some(256),
            session_expiry_interval: Some(120),
            ..Default::default()
        };
        props
    }

    fn sample_last_will<'a>() -> LastWill<'a> {
        LastWill {
            topic: "will",
            message: "lastwill".as_bytes(),
            qos: QoS::ExactlyOnce,
            retain: true,
            properties: Some(sample_will_properties()),
        }
    }

    fn sample_will_properties<'a>() -> WillProperties<'a> {
        let props = WillProperties {
            delay_interval: Some(5),
            payload_format_indicator: Some(1),
            message_expiry_interval: Some(120),
            content_type: Some("text"),
            response_topic: Some("will_respond"),
            correlation_data: Some("1234".as_bytes()),
            user_properties: heapless::Vec::<_, 32>::from_slice(&[("sfilename", "test.txt")])
                .unwrap(),
        };
        props
    }

    fn sample_login<'a>() -> Login<'a> {
        Login {
            username: "iz",
            password: "1234".as_bytes(),
        }
    }

    #[test]
    fn connect_properties_write() {
        let expected = &sample_bytes()[12..38];
        let props = sample_connect_properties();
        let mut buf = [0u8; 26];
        let mut offset = 0;

        props.write(&mut buf, &mut offset).unwrap();
        assert_eq!(buf, expected);
    }

    #[test]
    fn login_read() {
        let packet = sample_bytes();
        let connect_flags = packet[9];
        let login = Login::read(connect_flags, &packet, &mut 40)
            .unwrap()
            .unwrap();
        let username = "iz";
        let password: &[u8] = &[b'1', b'2', b'3', b'4'];
        assert_eq!(login, Login { username, password });
    }

    #[test]
    fn login_props_len() {
        let packet = sample_bytes();
        let connect_flags = packet[9];
        let props = Login::read(connect_flags, &packet, &mut 40)
            .unwrap()
            .unwrap();

        assert_eq!(props.len(), 10);
    }

    #[test]
    fn connect_props_read() {
        let packet = sample_bytes();
        let props = ConnectProperties::read(&packet, &mut 12).unwrap().unwrap();
        assert_eq!(props.receive_maximum, Some(256));
    }

    #[test]
    fn connect_props_len() {
        let packet = sample_bytes();
        let props = ConnectProperties::read(&packet, &mut 12).unwrap().unwrap();

        assert_eq!(props.len(), 25);
    }

    #[test]
    fn connect_props_read_2() {
        let packet = sample_bytes();
        let props = ConnectProperties::read(&packet, &mut 12).unwrap().unwrap();

        assert_eq!(props.authentication_data, Some("auth-data".as_bytes()));
        assert_eq!(props.max_packet_size, Some(265));
        assert_eq!(props.receive_maximum, Some(256));
        assert_eq!(props.session_expiry_interval, Some(120));
    }

    #[test]
    fn will_props_read() {
        let packet = sample_bytes_with_will();
        let mut props = WillProperties::read(&packet, &mut 25).unwrap().unwrap();

        assert_eq!(props.response_topic, Some("will_respond"));
        assert_eq!(props.content_type, Some("text"));
        assert_eq!(props.correlation_data, Some("1234".as_bytes()));
        assert_eq!(props.message_expiry_interval, Some(120));
        assert_eq!(props.payload_format_indicator, Some(1));
        assert_eq!(props.delay_interval, Some(5));
        assert_eq!(props.user_properties.pop(), Some(("sfilename", "test.txt")));
    }

    #[test]
    fn will_props_len() {
        let packet = sample_bytes_with_will();
        let props = WillProperties::read(&packet, &mut 25).unwrap().unwrap();

        assert_eq!(props.len(), 63);
    }

    #[test]
    fn last_will_read() {
        let packet = sample_bytes_with_will();
        let connect_flags = packet[9];
        let last_will = LastWill::read(connect_flags, &packet, &mut 25)
            .unwrap()
            .unwrap();

        assert_eq!(last_will.topic, "will");
        assert_eq!(last_will.message, "lastwill".as_bytes());
        assert_eq!(last_will.qos, QoS::ExactlyOnce);
        assert!(last_will.retain);

        let mut props = last_will.properties.unwrap();

        assert_eq!(props.response_topic, Some("will_respond"));
        assert_eq!(props.content_type, Some("text"));
        assert_eq!(props.correlation_data, Some("1234".as_bytes()));
        assert_eq!(props.message_expiry_interval, Some(120));
        assert_eq!(props.payload_format_indicator, Some(1));
        assert_eq!(props.delay_interval, Some(5));
        assert_eq!(props.user_properties.pop(), Some(("sfilename", "test.txt")));
    }

    #[test]
    fn last_will_len() {
        let packet = sample_bytes_with_will();
        let connect_flags = packet[9];
        let props = LastWill::read(connect_flags, &packet, &mut 25)
            .unwrap()
            .unwrap();

        assert_eq!(props.len(), 80);
    }

    #[test]
    fn connect_read() {
        let packet = sample_bytes_with_will();
        let connect = Connect::read(&packet, &mut 2).unwrap();

        assert_eq!(connect.protocol, Protocol::V5);
        assert_eq!(connect.keep_alive, 60);
        assert_eq!(connect.client_id, "test_id");
        assert!(!connect.clean_start);

        let last_will = connect.last_will.unwrap();

        assert_eq!(last_will.topic, "will");
        assert_eq!(last_will.message, "lastwill".as_bytes());
        assert_eq!(last_will.qos, QoS::ExactlyOnce);
        assert!(last_will.retain);

        let mut last_will_props = last_will.properties.unwrap();

        assert_eq!(last_will_props.response_topic, Some("will_respond"));
        assert_eq!(last_will_props.content_type, Some("text"));
        assert_eq!(last_will_props.correlation_data, Some("1234".as_bytes()));
        assert_eq!(last_will_props.message_expiry_interval, Some(120));
        assert_eq!(last_will_props.payload_format_indicator, Some(1));
        assert_eq!(last_will_props.delay_interval, Some(5));
        assert_eq!(
            last_will_props.user_properties.pop(),
            Some(("sfilename", "test.txt"))
        );

        let login = connect.login.unwrap();

        assert_eq!(login.username, "iz");
        assert_eq!(login.password, "1234".as_bytes());

        let connect_props = connect.properties.unwrap();

        assert_eq!(connect_props.receive_maximum, Some(20));
    }

    #[test]
    fn connect_len() {
        let packet = sample_bytes_with_will();
        let props = Connect::read(&packet, &mut 2).unwrap();

        assert_eq!(props.len(), 113);
    }
    #[test]
    fn last_will_write() {
        let expected = &sample_bytes_with_will()[25..106];
        let last_will = sample_last_will();

        // Size without the length field
        assert_eq!(last_will.len(), 80);

        let mut buf = [0u8; 81];
        let mut offset = 0;

        last_will.write(&mut buf, &mut offset).unwrap();

        assert_eq!(buf, expected);
    }

    #[test]
    fn will_properties_write() {
        let expected = &sample_bytes_with_will()[25..89];
        let props = sample_will_properties();

        assert_eq!(props.len(), 63);

        let mut buf = [0u8; 64];
        let mut offset = 0;

        props.write(&mut buf, &mut offset).unwrap();

        assert_eq!(buf, expected);
    }

    #[test]
    fn login_to_bufer() {
        let login = sample_login();

        let expected = &sample_bytes_with_will()[105..];
        let mut buf = [0u8; 10];
        let mut offset = 0;
        login.write(&mut buf, &mut offset);

        assert_eq!(buf, expected);
    }

    #[test]
    fn test_connect_write() {
        let connect = Connect {
            protocol: Protocol::V5,
            keep_alive: 60,
            client_id: "test_id",
            clean_start: false,
            last_will: Some(sample_last_will()),
            login: Some(sample_login()),
            properties: Some(ConnectProperties {
                receive_maximum: Some(20),
                ..Default::default()
            }),
        };

        let expected = &sample_bytes_with_will();

        let mut buf = [0u8; 115];
        assert_eq!(connect.len() + 2, expected.len());
        let mut offset = 0;
        connect.write(&mut buf, &mut offset).unwrap();
        assert_eq!(buf, expected.as_slice());
    }

    fn sample<'a>() -> Connect<'a> {
        let connect_properties = ConnectProperties {
            session_expiry_interval: Some(1234),
            receive_maximum: Some(432),
            max_packet_size: Some(100),
            topic_alias_max: Some(456),
            request_response_info: Some(1),
            request_problem_info: Some(1),
            user_properties: heapless::Vec::<_, 32>::from_slice(&[("test", "test")]).unwrap(),
            authentication_method: Some("test"),
            authentication_data: Some(&[1, 2, 3, 4]),
        };

        let will_properties = WillProperties {
            delay_interval: Some(1234),
            payload_format_indicator: Some(0),
            message_expiry_interval: Some(4321),
            content_type: Some("test"),
            response_topic: Some("topic"),
            correlation_data: Some(&[1, 2, 3, 4]),

            user_properties: heapless::Vec::<_, 32>::from_slice(&[("test", "test")]).unwrap(),
        };

        let will = LastWill {
            topic: "mydevice/status",
            message: &[b'd', b'e', b'a', b'd'],
            qos: QoS::AtMostOnce,
            retain: false,
            properties: Some(will_properties),
        };

        let login = Login {
            username: "matteo",
            password: "collina".as_bytes(),
        };

        Connect {
            protocol: Protocol::V5,
            keep_alive: 0,
            properties: Some(connect_properties),
            client_id: "my-device",
            clean_start: true,
            last_will: Some(will),
            login: Some(login),
        }
    }

    fn sample_bytes_2() -> Vec<u8> {
        vec![
            0x10, // packet type
            0x9d, // remaining len
            0x01, // remaining len
            0x00, 0x04, // 4
            0x4d, // M
            0x51, // Q
            0x54, // T
            0x54, // T
            0x05, // Level
            0xc6, // connect flags
            0x00, 0x00, // keep alive
            0x2f, // properties len
            0x11, 0x00, 0x00, 0x04, 0xd2, // session expiry interval
            0x21, 0x01, 0xb0, // receive_maximum
            0x27, 0x00, 0x00, 0x00, 0x64, // max packet size
            0x22, 0x01, 0xc8, // topic_alias_max
            0x19, 0x01, // request_response_info
            0x17, 0x01, // request_problem_info
            0x15, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // authentication_method
            0x16, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04, // authentication_data
            0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
            0x74, // user
            0x00, 0x09, 0x6d, 0x79, 0x2d, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, // client id
            0x2f, // will properties len
            0x01, 0x00, // payload format indicator
            0x02, 0x00, 0x00, 0x10, 0xe1, // message expiry interval
            0x03, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // content type
            0x08, 0x00, 0x05, 0x74, 0x6f, 0x70, 0x69, 0x63, // response topic
            0x09, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04, // correlation_data
            0x18, 0x00, 0x00, 0x04, 0xd2, // will delay interval
            0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
            0x74, // will user properties
            0x00, 0x0f, 0x6d, 0x79, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x2f, 0x73, 0x74, 0x61,
            0x74, 0x75, 0x73, // will topic
            0x00, 0x04, 0x64, 0x65, 0x61, 0x64, // will payload
            0x00, 0x06, 0x6d, 0x61, 0x74, 0x74, 0x65, 0x6f, // username
            0x00, 0x07, 0x63, 0x6f, 0x6c, 0x6c, 0x69, 0x6e, 0x61, // password
        ]
    }

    #[test]
    fn connect_encode() {
        let expected = sample_bytes_2();
        let mut buf = [0u8; 160];

        sample().write(&mut buf, &mut 0).unwrap();

        assert_eq!(expected, buf);
    }

    #[test]
    fn connect_decode() {
        let bytes = sample_bytes_2();
        let expected = sample();

        let actual = Connect::read(&bytes, &mut 3).unwrap();
        assert_eq!(expected, actual);
    }
}