forked from eclipse-paho/paho.mqtt.rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.rs
331 lines (301 loc) · 10.1 KB
/
client.rs
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
// paho-mqtt/src/client.rs
// This file is part of the Eclipse Paho MQTT Rust Client library.
//
/*******************************************************************************
* Copyright (c) 2017-2020 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
*******************************************************************************/
//! This contains the synchronous `Client` interface for the Paho MQTT Rust
//! library.
//!
//! This is a simple convenience wrapper around the asynchronous API in which
//! each function calls the underlying async function, and then blocks waiting
//! for it to complete.
//!
//! The synchronous calls use a default timeout
use crate::{
async_client::AsyncClient, connect_options::ConnectOptions, create_options::CreateOptions,
disconnect_options::DisconnectOptions, errors::Result, message::Message,
properties::Properties, server_response::ServerResponse, subscribe_options::SubscribeOptions,
Receiver,
};
use std::time::Duration;
/////////////////////////////////////////////////////////////////////////////
// Client
/// MQTT Client with a synchronous (blocking) API.
/// This is simply a convenience wrapper around the asynchronous API,
/// providing blocking calls with timeouts.
pub struct Client {
/// The underlying asynchronous client.
cli: AsyncClient,
/// The default timeout for synchronous calls.
timeout: Duration,
}
impl Client {
/// Creates a new MQTT client which can connect to an MQTT broker.
pub fn new<T>(opts: T) -> Result<Client>
where
T: Into<CreateOptions>,
{
let async_cli = AsyncClient::new(opts)?;
let cli = Client {
cli: async_cli,
timeout: Duration::from_secs(5 * 60),
};
//cli.start_consuming();
Ok(cli)
}
/// Gets the default timeout used for synchronous operations.
pub fn timeout(&self) -> Duration {
self.timeout
}
/// Sets the default timeout used for synchronous operations.
///
/// ## Arguments
///
/// `timeout` The timeout to use for synchronous calls, like
/// connect(), disconnect(), publish(), etc.
///
pub fn set_timeout(&mut self, timeout: Duration) {
self.timeout = timeout
}
/// Connects to an MQTT broker using the specified connect options.
pub fn connect<T>(&self, opt_opts: T) -> Result<ServerResponse>
where
T: Into<Option<ConnectOptions>>,
{
self.cli.connect(opt_opts).wait_for(self.timeout)
}
/// Disconnects from the MQTT broker.
///
/// ## Arguments
///
/// `opt_opts` Optional disconnect options. Specifying `None` will use
/// default of immediate (zero timeout) disconnect.
///
pub fn disconnect<T>(&self, opt_opts: T) -> Result<()>
where
T: Into<Option<DisconnectOptions>>,
{
self.cli.disconnect(opt_opts).wait_for(self.timeout)?;
Ok(())
}
/// Disconnect from the MQTT broker with a timeout.
/// This will delay the disconnect for up to the specified timeout to
/// allow in-flight messages to complete.
/// This is the same as calling disconnect with options specifying a
/// timeout.
///
/// # Arguments
///
/// `timeout` The amount of time to wait for the disconnect. This has
/// a resolution in milliseconds.
///
pub fn disconnect_after(&self, timeout: Duration) -> Result<()> {
self.cli.disconnect_after(timeout).wait_for(self.timeout)?;
Ok(())
}
/// Attempts to reconnect to the broker.
/// This can only be called after a connection was initially made or
/// attempted. It will retry with the same connect options.
pub fn reconnect(&self) -> Result<ServerResponse> {
self.cli.reconnect().wait_for(self.timeout)
}
/// Determines if this client is currently connected to an MQTT broker.
pub fn is_connected(&self) -> bool {
self.cli.is_connected()
}
/// Publishes a message to an MQTT broker
pub fn publish(&self, msg: Message) -> Result<()> {
self.cli.publish(msg).wait_for(self.timeout)
}
/// Subscribes to a single topic.
///
/// # Arguments
///
/// `topic` The topic name
/// `qos` The quality of service requested for messages
///
pub fn subscribe(&self, topic: &str, qos: i32) -> Result<ServerResponse> {
self.cli.subscribe(topic, qos).wait_for(self.timeout)
}
/// Subscribes to a single topic with v5 options
///
/// # Arguments
///
/// `topic` The topic name
/// `qos` The quality of service requested for messages
/// `opts` Options for the subscription
/// `props` MQTT v5 properties
///
pub fn subscribe_with_options<S, T, P>(
&self,
topic: S,
qos: i32,
opts: T,
props: P,
) -> Result<ServerResponse>
where
S: Into<String>,
T: Into<SubscribeOptions>,
P: Into<Option<Properties>>,
{
self.cli
.subscribe_with_options(topic, qos, opts, props)
.wait_for(self.timeout)
}
/// Subscribes to multiple topics simultaneously.
///
/// # Arguments
///
/// `topic` The topic name
/// `qos` The quality of service requested for messages
///
pub fn subscribe_many<T>(&self, topics: &[T], qos: &[i32]) -> Result<ServerResponse>
where
T: AsRef<str>,
{
self.cli.subscribe_many(topics, qos).wait_for(self.timeout)
}
/// Subscribes to multiple topics simultaneously with options.
///
/// # Arguments
///
/// `topics` The collection of topic names
/// `qos` The quality of service requested for messages
/// `opts` Subscribe options (one per topic)
/// `props` MQTT v5 properties
///
pub fn subscribe_many_with_options<T, P>(
&self,
topics: &[T],
qos: &[i32],
opts: &[SubscribeOptions],
props: P,
) -> Result<ServerResponse>
where
T: AsRef<str>,
P: Into<Option<Properties>>,
{
self.cli
.subscribe_many_with_options(topics, qos, opts, props)
.wait_for(self.timeout)
}
/// Unsubscribes from a single topic.
///
/// # Arguments
///
/// `topic` The topic to unsubscribe. It must match a topic from a
/// previous subscribe.
///
pub fn unsubscribe(&self, topic: &str) -> Result<()> {
self.cli.unsubscribe(topic).wait_for(self.timeout)?;
Ok(())
}
/// Unsubscribes from a single topic.
///
/// # Arguments
///
/// `topic` The topic to unsubscribe. It must match a topic from a
/// previous subscribe.
/// `props` MQTT v5 properties for the unsubscribe.
///
pub fn unsubscribe_with_options<S>(&self, topic: S, props: Properties) -> Result<()>
where
S: Into<String>,
{
self.cli
.unsubscribe_with_options(topic, props)
.wait_for(self.timeout)?;
Ok(())
}
/// Unsubscribes from multiple topics simultaneously.
///
/// # Arguments
///
/// `topic` The topics to unsubscribe. Each must match a topic from a
/// previous subscribe.
///
pub fn unsubscribe_many<T>(&self, topics: &[T]) -> Result<()>
where
T: AsRef<str>,
{
self.cli.unsubscribe_many(topics).wait_for(self.timeout)?;
Ok(())
}
/// Unsubscribes from multiple topics simultaneously.
///
/// # Arguments
///
/// `topic` The topics to unsubscribe. Each must match a topic from a
/// previous subscribe.
/// `props` MQTT v5 properties for the unsubscribe.
///
pub fn unsubscribe_many_with_options<T>(&self, topics: &[T], props: Properties) -> Result<()>
where
T: AsRef<str>,
{
self.cli
.unsubscribe_many_with_options(topics, props)
.wait_for(self.timeout)?;
Ok(())
}
/// Starts the client consuming messages.
/// This starts the client receiving messages and placing them into an
/// mpsc queue. It returns the receiving-end of the queue for the
/// application to get the messages.
/// This can be called at any time after the client is created, but it
/// should be called before subscribing to any topics, otherwise messages
/// can be lost.
//
pub fn start_consuming(&mut self) -> Receiver<Option<Message>> {
self.cli.start_consuming()
}
}
/////////////////////////////////////////////////////////////////////////////
// Unit Tests
/////////////////////////////////////////////////////////////////////////////
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::thread;
// Determine that a client can be sent across threads and signaled.
// As long as it compiles, this indicates that Client implements the
// Send trait.
#[test]
fn test_send() {
let cli = Client::new("tcp://localhost:1883").unwrap();
let thr = thread::spawn(move || {
assert!(!cli.is_connected());
});
let _ = thr.join().unwrap();
}
// Determine that a client can be shared across threads using an Arc.
// As long as it compiles, this indicates that Client implements the
// Send trait.
// This is a bit redundant with the previous test, but explicitly
// addresses GitHub Issue #31.
#[test]
fn test_send_arc() {
let cli = Client::new("tcp://localhost:1883").unwrap();
let cli = Arc::new(cli);
let cli2 = cli.clone();
let thr = thread::spawn(move || {
assert!(!cli.is_connected());
});
assert!(!cli2.is_connected());
let _ = thr.join().unwrap();
}
}