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
use std::error::Error;
use std::fmt;

#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub struct PacketType {
    pub control_type: ControlType,
    pub flags: u8,
}

#[repr(u8)]
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum ControlType {
    /// Client request to connect to Server
    Connect                         = value::CONNECT,

    /// Connect acknowledgment
    ConnectAcknowledgement          = value::CONNACK,

    /// Publish message
    Publish                         = value::PUBLISH,

    /// Publish acknowledgment
    PublishAcknowledgement          = value::PUBACK,

    /// Publish received (assured delivery part 1)
    PublishReceived                 = value::PUBREC,

    /// Publish release (assured delivery part 2)
    PublishRelease                  = value::PUBREL,

    /// Publish complete (assured delivery part 3)
    PublishComplete                 = value::PUBCOMP,

    /// Client subscribe request
    Subscribe                       = value::SUBSCRIBE,

    /// Subscribe acknowledgment
    SubscribeAcknowledgement        = value::SUBACK,

    /// Unsubscribe request
    Unsubscribe                     = value::UNSUBSCRIBE,

    /// Unsubscribe acknowledgment
    UnsubscribeAcknowledgement      = value::UNSUBACK,

    /// PING request
    PingRequest                     = value::PINGREQ,

    /// PING response
    PingResponse                    = value::PINGRESP,

    /// Client is disconnecting
    Disconnect                      = value::DISCONNECT,
}

impl PacketType {
    #[inline]
    pub fn new(t: ControlType, flags: u8) -> PacketType {
        PacketType {
            control_type: t,
            flags: flags,
        }
    }

    #[inline]
    pub fn with_default(t: ControlType) -> PacketType {
        match t {
            ControlType::Connect => PacketType::new(t, 0),
            ControlType::ConnectAcknowledgement => PacketType::new(t, 0),

            ControlType::Publish => PacketType::new(t, 0),
            ControlType::PublishAcknowledgement => PacketType::new(t, 0),
            ControlType::PublishReceived => PacketType::new(t, 0),
            ControlType::PublishRelease => PacketType::new(t, 0x02),
            ControlType::PublishComplete => PacketType::new(t, 0),

            ControlType::Subscribe => PacketType::new(t, 0x02),
            ControlType::SubscribeAcknowledgement => PacketType::new(t, 0),

            ControlType::Unsubscribe => PacketType::new(t, 0x02),
            ControlType::UnsubscribeAcknowledgement => PacketType::new(t, 0),

            ControlType::PingRequest => PacketType::new(t, 0),
            ControlType::PingResponse => PacketType::new(t, 0),

            ControlType::Disconnect => PacketType::new(t, 0),
        }
    }

    pub fn to_u8(&self) -> u8 {
        (self.control_type as u8) << 4
            | (self.flags & 0x0F)
    }

    pub fn from_u8(val: u8) -> Result<PacketType, PacketTypeError> {

        let type_val = val >> 4;
        let flag = val & 0x0F;

        macro_rules! vconst {
            ($flag:expr, $ret:path) => (
                if flag != $flag {
                    Err(PacketTypeError::InvalidFlag($ret, flag))
                } else {
                    Ok(PacketType::new($ret, flag))
                }
            )
        }

        match type_val {
            value::CONNECT      => vconst!(0x00, ControlType::Connect),
            value::CONNACK      => vconst!(0x00, ControlType::ConnectAcknowledgement),

            value::PUBLISH      =>
                Ok(PacketType::new(ControlType::Publish, flag)),
            value::PUBACK       => vconst!(0x00, ControlType::PublishAcknowledgement),
            value::PUBREC       => vconst!(0x00, ControlType::PublishReceived),
            value::PUBREL       => vconst!(0x02, ControlType::PublishRelease),
            value::PUBCOMP      => vconst!(0x00, ControlType::PublishComplete),

            value::SUBSCRIBE    => vconst!(0x02, ControlType::Subscribe),
            value::SUBACK       => vconst!(0x00, ControlType::SubscribeAcknowledgement),

            value::UNSUBSCRIBE  => vconst!(0x02, ControlType::Unsubscribe),
            value::UNSUBACK     => vconst!(0x00, ControlType::UnsubscribeAcknowledgement),

            value::PINGREQ      => vconst!(0x00, ControlType::PingRequest),
            value::PINGRESP     => vconst!(0x00, ControlType::PingResponse),

            value::DISCONNECT   => vconst!(0x00, ControlType::Disconnect),

            0 | 15              => Err(PacketTypeError::ReservedType(type_val, flag)),
            _                   => Err(PacketTypeError::UndefinedType(type_val, flag)),
        }
    }
}

#[derive(Debug)]
pub enum PacketTypeError {
    ReservedType(u8, u8),
    UndefinedType(u8, u8),
    InvalidFlag(ControlType, u8),
}

impl fmt::Display for PacketTypeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &PacketTypeError::ReservedType(t, flag) => write!(f, "Reserved type {:?} ({:#X})", t, flag),
            &PacketTypeError::InvalidFlag(t, flag) => write!(f, "Invalid flag for {:?} ({:#X})", t, flag),
            &PacketTypeError::UndefinedType(t, flag) => write!(f, "Undefined type {:?} ({:#X})", t, flag),
        }
    }
}

impl Error for PacketTypeError {
    fn description(&self) -> &str {
        match self {
            &PacketTypeError::ReservedType(..) => "Reserved type",
            &PacketTypeError::UndefinedType(..) => "Undefined type",
            &PacketTypeError::InvalidFlag(..) => "Invalid flag",
        }
    }
}

mod value {
    pub const CONNECT: u8 = 1;
    pub const CONNACK: u8 = 2;
    pub const PUBLISH: u8 = 3;
    pub const PUBACK: u8 = 4;
    pub const PUBREC: u8 = 5;
    pub const PUBREL: u8 = 6;
    pub const PUBCOMP: u8 = 7;
    pub const SUBSCRIBE: u8 = 8;
    pub const SUBACK: u8 = 9;
    pub const UNSUBSCRIBE: u8 = 10;
    pub const UNSUBACK: u8 = 11;
    pub const PINGREQ: u8 = 12;
    pub const PINGRESP: u8 = 13;
    pub const DISCONNECT: u8 = 14;
}