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
// create_options.rs
//
// The set of options for creating an MQTT client.
// This file is part of the Eclipse Paho MQTT Rust Client library.
//

/*******************************************************************************
 * Copyright (c) 2017-2018 Frank Pagliughi <fpagliughi@mindspring.com>
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 *
 * The Eclipse Public License is available at
 *    http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 *   http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *    Frank Pagliughi - initial implementation and documentation
 *******************************************************************************/

use std::{
    fmt,
    os::raw::c_int,
};

use crate::{
    ffi,
    Result,
    UserData,
    client_persistence::ClientPersistence,
    async_client::AsyncClient,
};

/*
Remember the C constants (c_uint)
  MQTTCLIENT_PERSISTENCE_DEFAULT = 0
  MQTTCLIENT_PERSISTENCE_NONE    = 1
  MQTTCLIENT_PERSISTENCE_USER    = 2
*/

/// The type of persistence for the client
pub enum PersistenceType {
	/// Data and messages are persisted to a local file (default)
	File,
	/// No persistence is used.
	None,
	/// A user-defined persistence provided by the application.
	User(Box<Box<dyn ClientPersistence>>),
}

impl fmt::Debug for PersistenceType {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match *self {
			PersistenceType::File => write!(f, "File"),
			PersistenceType::None => write!(f, "None"),
			PersistenceType::User(_) => write!(f, "User"),
		}
	}
}

impl Default for PersistenceType {
    fn default() -> Self {
        PersistenceType::File
    }
}

/////////////////////////////////////////////////////////////////////////////
//							Create Options
/////////////////////////////////////////////////////////////////////////////

/// The options for creating an MQTT client.
/// This can be constructed using a
/// [CreateOptionsBuilder](struct.CreateOptionsBuilder.html).
#[derive(Debug, Default)]
pub struct CreateOptions {
	/// The underlying C option structure
	pub(crate) copts: ffi::MQTTAsync_createOptions,
	/// The URI for the MQTT broker.
	pub(crate) server_uri: String,
	/// The unique name for the client.
	/// This can be left empty for the server to assign a random name.
	pub(crate) client_id: String,
	/// The type of persistence used by the client.
	pub(crate) persistence: PersistenceType,
    /// User-defined data, if any
    pub(crate) user_data: Option<UserData>,
}

impl CreateOptions {
	pub fn new() -> CreateOptions {
		CreateOptions::default()
	}
}

impl<'a> From<&'a str> for CreateOptions {
	fn from(server_uri: &'a str) -> Self {
		let mut opts = CreateOptions::default();
		opts.server_uri = server_uri.to_string();
		opts
	}
}

impl From<String> for CreateOptions {
	fn from(server_uri: String) -> Self {
		let mut opts = CreateOptions::default();
		opts.server_uri = server_uri;
		opts
	}
}

impl<'a, 'b> From<(&'a str, &'b str)> for CreateOptions {
	fn from((server_uri, client_id): (&'a str, &'b str)) -> Self {
		let mut opts = CreateOptions::default();
		opts.server_uri = server_uri.to_string();
		opts.client_id = client_id.to_string();
		opts
	}
}

impl From<(String, String)> for CreateOptions {
	fn from((server_uri, client_id): (String, String)) -> Self {
		let mut opts = CreateOptions::default();
		opts.server_uri = server_uri;
		opts.client_id = client_id;
		opts
	}
}

/*
impl Default for CreateOptions {
	/// Constructs a set of CreatieOptions with reasonable defaults.
	fn default() -> CreateOptions {
		CreateOptions {
			copts: ffi::MQTTAsync_createOptions::default(),
			server_uri: "".to_string(),
			client_id: "".to_string(),
			persistence: PersistenceType::File,
		}
	}
}
*/

/////////////////////////////////////////////////////////////////////////////
//								Builder
/////////////////////////////////////////////////////////////////////////////

/// Builder to construct client creation options.
///
/// # Examples
///
/// ```
/// use paho_mqtt as mqtt;
///
/// let opts = mqtt::CreateOptionsBuilder::new()
///                    .server_uri("tcp://localhost:1883")
///                    .client_id("client1")
///                    .finalize();
///
/// let cli = mqtt::AsyncClient::new(opts).unwrap();
/// ```

#[derive(Default)]
pub struct CreateOptionsBuilder {
	copts: ffi::MQTTAsync_createOptions,
	server_uri: String,
	client_id: String,
	persistence: PersistenceType,
    user_data: Option<UserData>
}

impl CreateOptionsBuilder {
	/// Constructs a builder with default options.
	pub fn new() -> Self { Self::default() }

	/// Sets the the URI to the MQTT broker.
	/// Alternately, the application can specify multiple servers via the
	/// connect options.
	///
	/// # Arguments
	///
	/// `server_uri` The URI string to specify the server in the form
	///              _protocol://host:port_, where the protocol can be
	///              _tcp_ or _ssl_, and the host can be an IP address
	///              or domain name.
	pub fn server_uri<S>(mut self, server_uri: S) -> Self
			where S: Into<String> {
		self.server_uri = server_uri.into();
		self
	}

	/// Sets the client identifier string that is sent to the server.
	/// The client ID is a unique name to identify the client to the server,
	/// which can be used if the client desires the server to hold state
	/// about the session. If the client requests a clean sesstion, this can
	/// be an empty string.
	///
	/// The broker is required to honor a client ID of up to 23 bytes, but
	/// could honor longer ones, depending on the broker.
	///
	/// Note that if this is an empty string, the clean session parameter
	/// *must* be set to _true_.
	///
	/// # Arguments
	///
	/// `client_id` A UTF-8 string identifying the client to the server.
	///
	pub fn client_id<S>(mut self, client_id: S) -> Self
			where S: Into<String> {
		self.client_id = client_id.into();
		self
	}

	/// Sets the type of persistence used by the client.
	/// The default is for the library to automatically use file persistence,
	/// although this can be turned off by specify `None` for a more
	/// performant, though possibly less reliable system.
	///
	/// # Arguments
	///
	/// `persist` The type of persistence to use.
	///
	pub fn persistence(mut self, persist: PersistenceType) -> Self {
		self.persistence = persist;
		self
	}

	/// Sets a user-defined persistence store.
	/// This sets the persistence to use a custom one defined by the
	/// application. This can be anything that implements the
	/// `ClientPersistence` trait.
	///
	/// # Arguments
	///
	/// `persist` An application-defined custom persistence store.
	///
	pub fn user_persistence<T>(mut self, persistence: T) -> Self
			where T: ClientPersistence + 'static
	{
		let persistence: Box<Box<dyn ClientPersistence>> = Box::new(Box::new(persistence));
		self.persistence = PersistenceType::User(persistence);
		self
	}

	/// Sets the maximum number of messages that can be buffered for delivery
	/// when the client is off-line.
	/// The client has limited support for bufferering messages when the
	/// client is temporarily disconnected. This specifies the maximum number
	/// of messages that can be buffered.
	///
	/// # Arguments
	///
	/// `n` The maximum number of messages that can be buffered. Setting this
	///     to zero disables off-line buffering.
	///
	pub fn max_buffered_messages(mut self, n: i32) -> Self {
		self.copts.maxBufferedMessages = n;
		self.copts.sendWhileDisconnected = if n == 0 { 0 } else { 1 };
		self
	}

    /// Sets the version of MQTT to use on the connect.
    ///
    /// # Arguments
    ///
    /// `ver` The version of MQTT to use when connecting to the broker.
    ///       * (0) try the latest version (3.1.1) and work backwards
    ///       * (3) only try v3.1
    ///       * (4) only try v3.1.1
    ///       * (5) only try v5
    ///
    pub fn mqtt_version(mut self, ver: u32) -> Self {
        self.copts.MQTTVersion = ver as c_int;
        self
    }

    /// Sets the uer-defined data structure for the client.
    pub fn user_data(mut self, data: UserData) -> Self {
        self.user_data = Some(data);
        self
    }

	/// Constructs a set of create options from the builder information.
	pub fn finalize(self) -> CreateOptions {
		CreateOptions {
			copts: self.copts,
			server_uri: self.server_uri,
			client_id: self.client_id,
			persistence: self.persistence,
            user_data: self.user_data,
		}
	}

    /// Finalize the builder and create an asynchronous client.
    pub fn create_client(self) -> Result<AsyncClient> {
        AsyncClient::new(self.finalize())
    }
}

/////////////////////////////////////////////////////////////////////////////
//								Unit Tests
/////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
	use super::*;
    use std::os::raw::{c_char};

    // The currently supported MQTTAsync_createOptions::struct_version
    const STRUCT_VER: c_int = 1;

    // The identifier for the create options structure
    const STRUCT_ID: [c_char; 4] = [ b'M' as c_char, b'Q' as c_char, b'C' as c_char, b'O' as c_char];

	// Rust options should be the same as the C options
	#[test]
	fn test_default() {
		let opts = CreateOptions::default();
		// Get default C options for comparison
		let copts = ffi::MQTTAsync_createOptions::default();

		// First, make sure C options valid
        assert_eq!(STRUCT_ID, copts.struct_id);
		assert_eq!(STRUCT_VER, copts.struct_version);

		assert_eq!(copts.struct_id, opts.copts.struct_id);
		assert_eq!(copts.struct_version, opts.copts.struct_version);
		assert_eq!(copts.sendWhileDisconnected, opts.copts.sendWhileDisconnected);
		assert_eq!(copts.maxBufferedMessages, opts.copts.maxBufferedMessages);

		assert_eq!("", &opts.server_uri);
		assert_eq!("", &opts.client_id);
		//assert_eq!(PersistenceType::default(), opts.persistence);
	}

	#[test]
	fn test_from_string() {
		const HOST: &str = "localhost";

        let opts = CreateOptions::from(HOST);
		let copts = ffi::MQTTAsync_createOptions::default();

		assert_eq!(STRUCT_ID, opts.copts.struct_id);
		assert_eq!(STRUCT_VER, opts.copts.struct_version);
		assert_eq!(copts.sendWhileDisconnected, opts.copts.sendWhileDisconnected);
		assert_eq!(copts.maxBufferedMessages, opts.copts.maxBufferedMessages);

		assert_eq!(HOST, &opts.server_uri);
		assert_eq!("", &opts.client_id);
		//assert_eq!(PersistenceType::File, opts.persistence);
	}


	#[test]
	fn test_from_tuple() {
		const HOST: &str = "localhost";
		const ID: &str = "bubba";

        let opts = CreateOptions::from((HOST,ID));
		let copts = ffi::MQTTAsync_createOptions::default();

		assert_eq!(STRUCT_ID, opts.copts.struct_id);
		assert_eq!(STRUCT_VER, opts.copts.struct_version);
		assert_eq!(copts.sendWhileDisconnected, opts.copts.sendWhileDisconnected);
		assert_eq!(copts.maxBufferedMessages, opts.copts.maxBufferedMessages);

		assert_eq!(HOST, &opts.server_uri);
		assert_eq!(ID, &opts.client_id);
		//assert_eq!(PersistenceType::File, opts.persistence);
	}

	#[test]
	fn test_default_builder() {
		let opts = CreateOptionsBuilder::new().finalize();
		let copts = ffi::MQTTAsync_createOptions::default();

		// First, make sure C options valid
		assert_eq!(STRUCT_ID, copts.struct_id);
		assert_eq!(STRUCT_VER, copts.struct_version);

		assert_eq!(copts.struct_id, opts.copts.struct_id);
		assert_eq!(copts.struct_version, opts.copts.struct_version);
		assert_eq!(copts.sendWhileDisconnected, opts.copts.sendWhileDisconnected);
		assert_eq!(copts.maxBufferedMessages, opts.copts.maxBufferedMessages);

		assert_eq!("", &opts.server_uri);
		assert_eq!("", &opts.client_id);
		//assert_eq!(PersistenceType::File, opts.persistence);
	}

	#[test]
	fn test_builder() {
		const HOST: &str = "localhost";
		const ID: &str = "bubba";
		const MAX_BUF_MSGS: i32 = 100;

		let opts = CreateOptionsBuilder::new()
						.server_uri(HOST)
						.client_id(ID)
						// TODO: Test persistence
						.max_buffered_messages(MAX_BUF_MSGS)
						.finalize();

		assert_eq!(STRUCT_ID, opts.copts.struct_id);
		assert_eq!(STRUCT_VER, opts.copts.struct_version);

		assert_eq!(HOST, &opts.server_uri);
		assert_eq!(ID, &opts.client_id);
		//assert_eq!(PersistenceType::File, opts.persistence);
		assert!(0 != opts.copts.sendWhileDisconnected);
		assert_eq!(MAX_BUF_MSGS, opts.copts.maxBufferedMessages);
	}
}