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
use embedded_nal::{IpAddr, Ipv4Addr};
use mqttrs::LastWill;

#[derive(Clone, Debug, PartialEq)]
pub enum Broker<'a> {
    Hostname(&'a str),
    IpAddr(IpAddr),
}

impl<'a> From<&'a str> for Broker<'a> {
    fn from(s: &'a str) -> Self {
        Broker::Hostname(s)
    }
}

impl<'a> From<IpAddr> for Broker<'a> {
    fn from(ip: IpAddr) -> Self {
        Broker::IpAddr(ip)
    }
}

impl<'a> From<Ipv4Addr> for Broker<'a> {
    fn from(ip: Ipv4Addr) -> Self {
        Broker::IpAddr(ip.into())
    }
}

type Certificate<'a> = &'a [u8];
type PrivateKey<'a> = &'a [u8];
type Password<'a> = &'a [u8];

/// Options to configure the behaviour of mqtt connection
///
/// **Lifetimes**:
/// - 'a: The lifetime of option fields, not referenced in any MQTT packets at any point
/// - 'b: The lifetime of the packet fields, backed by a slice buffer
#[derive(Clone, Debug)]
pub struct MqttOptions<'a> {
    /// broker address that you want to connect to
    broker_addr: Broker<'a>,
    /// broker port
    port: u16,
    /// keep alive time to send pingreq to broker when the connection is idle
    keep_alive_ms: u32,
    /// clean (or) persistent session
    clean_session: bool,
    /// client identifier
    client_id: &'a str,
    /// certificate authority certificate
    ca: Option<&'a [u8]>,
    /// tls client_authentication
    client_auth: Option<(Certificate<'a>, PrivateKey<'a>, Option<Password<'a>>)>,
    /// alpn settings
    // alpn: Option<Vec<Vec<u8>>>,
    /// username and password
    credentials: Option<(&'a str, &'a [u8])>,
    /// Minimum delay time between consecutive outgoing packets
    // throttle: Duration,
    /// maximum number of outgoing inflight messages
    inflight: usize,
    /// Last will that will be issued on unexpected disconnect
    last_will: Option<LastWill<'a>>,
}

impl<'a> MqttOptions<'a> {
    /// New mqtt options
    pub fn new(id: &'a str, broker: Broker<'a>, port: u16) -> MqttOptions<'a> {
        if id.starts_with(' ') || id.is_empty() {
            panic!("Invalid client id")
        }

        MqttOptions {
            broker_addr: broker,
            port,
            keep_alive_ms: 60_000,
            clean_session: true,
            client_id: id,
            ca: None,
            client_auth: None,
            // alpn: None,
            credentials: None,
            // throttle: Duration::from_micros(0),
            inflight: 3,
            last_will: None,
        }
    }

    /// Broker address
    pub fn broker(&self) -> (Broker, u16) {
        (self.broker_addr.clone(), self.port)
    }

    pub fn set_last_will(self, will: LastWill<'a>) -> Self {
        Self {
            last_will: Some(will),
            ..self
        }
    }

    pub fn last_will(&self) -> Option<LastWill<'a>> {
        self.last_will.clone()
    }

    pub fn set_ca(self, ca: &'a [u8]) -> Self {
        Self {
            ca: Some(ca),
            ..self
        }
    }

    pub fn ca(&self) -> Option<&[u8]> {
        self.ca
    }

    pub fn set_client_auth(
        self,
        cert: Certificate<'a>,
        key: PrivateKey<'a>,
        password: Option<Password<'a>>,
    ) -> Self {
        Self {
            client_auth: Some((cert, key, password)),
            ..self
        }
    }

    pub fn client_auth(&self) -> Option<(Certificate<'a>, PrivateKey<'a>, Option<Password<'a>>)> {
        self.client_auth
    }

    // pub fn set_alpn(self, alpn: Vec<Vec<u8>>) -> Self {
    //     Self {
    //         alpn: Some(alpn),
    //         ..self
    //     }
    // }

    // pub fn alpn(&self) -> Option<Vec<Vec<u8>>> {
    //     self.alpn.clone()
    // }

    /// Set number of seconds after which client should ping the broker
    /// if there is no other data exchange
    pub fn set_keep_alive(self, secs: u16) -> Self {
        if secs < 5 {
            panic!("Keep alives should be >= 5  secs");
        }

        Self {
            keep_alive_ms: secs as u32 * 1000,
            ..self
        }
    }

    /// Keep alive time
    pub fn keep_alive_ms(&self) -> u32 {
        self.keep_alive_ms
    }

    /// Client identifier
    pub fn client_id(&self) -> &'a str {
        self.client_id
    }

    /// `clean_session = true` removes all the state from queues & instructs the broker
    /// to clean all the client state when client disconnects.
    ///
    /// When set `false`, broker will hold the client state and performs pending
    /// operations on the client when reconnection with same `client_id`
    /// happens. Local queue state is also held to retransmit packets after reconnection.
    pub fn set_clean_session(self, clean_session: bool) -> Self {
        Self {
            clean_session,
            ..self
        }
    }

    /// Clean session
    pub fn clean_session(&self) -> bool {
        self.clean_session
    }

    /// Username and password
    pub fn set_credentials(self, username: &'a str, password: &'a [u8]) -> Self {
        Self {
            credentials: Some((username, password)),
            ..self
        }
    }

    /// Security options
    pub fn credentials(&self) -> (Option<&'a str>, Option<&'a [u8]>) {
        if let Some((username, password)) = self.credentials {
            (Some(username), Some(password))
        } else {
            (None, None)
        }
    }

    // /// Enables throttling and sets outoing message rate to the specified 'rate'
    // pub fn set_throttle(self, duration: Duration) -> Self {
    //     self.throttle = duration;
    //     self
    // }

    // /// Outgoing message rate
    // pub fn throttle(&self) -> Duration {
    //     self.throttle
    // }

    /// Set number of concurrent in flight messages
    pub fn set_inflight(self, inflight: usize) -> Self {
        if inflight == 0 {
            panic!("zero in flight is not allowed")
        }

        Self { inflight, ..self }
    }

    /// Number of concurrent in flight messages
    pub fn inflight(&self) -> usize {
        self.inflight
    }
}

#[cfg(test)]
mod test {
    use super::{Ipv4Addr, MqttOptions};
    use embedded_nal::{IpAddr, Ipv6Addr};
    use mqttrs::LastWill;

    #[test]
    #[should_panic]
    fn client_id_starts_with_space() {
        let _mqtt_opts = MqttOptions::new(" client_a", Ipv4Addr::new(127, 0, 0, 1).into(), 1883)
            .set_clean_session(true);
    }

    #[test]
    #[should_panic]
    fn no_client_id() {
        let _mqtt_opts =
            MqttOptions::new("", Ipv4Addr::localhost().into(), 1883).set_clean_session(true);
    }

    #[test]
    fn broker() {
        let opts = MqttOptions::new("client_a", Ipv4Addr::localhost().into(), 1883);
        assert_eq!(opts.broker_addr, Ipv4Addr::localhost().into());
        assert_eq!(opts.port, 1883);
        assert_eq!(opts.broker(), (Ipv4Addr::localhost().into(), 1883));
        assert_eq!(
            MqttOptions::new("client_a", "localhost".into(), 1883).broker_addr,
            "localhost".into()
        );
        assert_eq!(
            MqttOptions::new("client_a", IpAddr::V4(Ipv4Addr::localhost()).into(), 1883)
                .broker_addr,
            IpAddr::V4(Ipv4Addr::localhost()).into()
        );
        assert_eq!(
            MqttOptions::new("client_a", IpAddr::V6(Ipv6Addr::localhost()).into(), 1883)
                .broker_addr,
            IpAddr::V6(Ipv6Addr::localhost()).into()
        );
    }

    #[test]
    fn client_id() {
        let opts = MqttOptions::new("client_a", Ipv4Addr::localhost().into(), 1883);
        assert_eq!(opts.client_id(), "client_a");
    }

    #[test]
    fn inflight() {
        let opts = MqttOptions::new("client_a", Ipv4Addr::localhost().into(), 1883);
        assert_eq!(opts.inflight, 3);
        assert_eq!(opts.set_inflight(5).inflight(), 5);
    }

    #[test]
    #[should_panic]
    fn zero_inflight() {
        let opts = MqttOptions::new("client_a", Ipv4Addr::localhost().into(), 1883);
        assert_eq!(opts.inflight, 3);
        assert_eq!(opts.set_inflight(0).inflight(), 5);
    }

    #[test]
    fn client_auth() {
        let opts = MqttOptions::new("client_a", Ipv4Addr::localhost().into(), 1883);
        assert_eq!(opts.client_auth, None);
        assert_eq!(
            opts.clone()
                .set_client_auth(b"Certificate", b"PrivateKey", None)
                .client_auth(),
            Some((&b"Certificate"[..], &b"PrivateKey"[..], None))
        );
        assert_eq!(
            opts.set_client_auth(b"Certificate", b"PrivateKey", Some(b"Password"))
                .client_auth(),
            Some((
                &b"Certificate"[..],
                &b"PrivateKey"[..],
                Some(&b"Password"[..])
            ))
        );
    }

    #[test]
    fn ca() {
        let opts = MqttOptions::new("client_a", Ipv4Addr::localhost().into(), 1883);
        assert_eq!(opts.ca, None);
        assert_eq!(
            opts.set_ca(b"My Certificate Authority").ca(),
            Some(&b"My Certificate Authority"[..])
        );
    }

    #[test]
    fn keep_alive_ms() {
        let opts = MqttOptions::new("client_a", Ipv4Addr::localhost().into(), 1883);
        assert_eq!(opts.keep_alive_ms, 60_000);
        assert_eq!(opts.set_keep_alive(120).keep_alive_ms(), 120_000);
    }

    #[test]
    #[should_panic]
    fn keep_alive_panic() {
        let opts = MqttOptions::new("client_a", Ipv4Addr::localhost().into(), 1883);
        assert_eq!(opts.keep_alive_ms, 60_000);
        assert_eq!(opts.set_keep_alive(4).keep_alive_ms(), 120_000);
    }

    #[test]
    fn last_will() {
        let opts = MqttOptions::new("client_a", Ipv4Addr::localhost().into(), 1883);
        assert_eq!(opts.last_will, None);
        let will = LastWill {
            topic: "topic",
            message: b"Will message",
            qos: mqttrs::QoS::AtLeastOnce,
            retain: false,
        };
        assert_eq!(opts.set_last_will(will.clone()).last_will(), Some(will));
    }

    #[test]
    fn clean_session() {
        let opts = MqttOptions::new("client_a", Ipv4Addr::localhost().into(), 1883);
        assert_eq!(opts.clean_session, true);
        assert_eq!(opts.set_clean_session(false).clean_session(), false);
    }

    #[test]
    fn credentials() {
        let opts = MqttOptions::new("client_a", Ipv4Addr::localhost().into(), 1883);
        assert_eq!(opts.credentials, None);
        assert_eq!(opts.credentials(), (None, None));
        assert_eq!(
            opts.set_credentials("some_user", &[]).credentials(),
            (Some("some_user"), Some(&b""[..]))
        );
    }
}