-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtokio_async_mqtt_all_sync_operations.rs
More file actions
381 lines (334 loc) · 15.6 KB
/
Copy pathtokio_async_mqtt_all_sync_operations.rs
File metadata and controls
381 lines (334 loc) · 15.6 KB
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
// SPDX-License-Identifier: MPL-2.0
/// Comprehensive example demonstrating all synchronous MQTT operations
///
/// This example shows how to use the sync API for:
/// - connect_sync() - Wait for CONNACK
/// - subscribe_sync() - Wait for SUBACK
/// - publish_sync() - Wait for PUBACK/PUBCOMP
/// - unsubscribe_sync() - Wait for UNSUBACK
/// - ping_sync() - Wait for PINGRESP
///
/// Run with: cargo run --example tokio_async_mqtt_all_sync_operations
use flowsdk::mqtt_client::client::{
ConnectionResult, PublishResult, SubscribeResult, UnsubscribeResult,
};
use flowsdk::mqtt_client::tokio_async_client::{
TokioAsyncClientConfig, TokioAsyncMqttClient, TokioMqttEventHandler,
};
use flowsdk::mqtt_client::{MqttClientError, MqttClientOptions};
use flowsdk::mqtt_serde::mqttv5::publishv5::MqttPublish;
use std::sync::Arc;
use tokio::sync::Mutex;
/// Event handler that tracks all events
#[derive(Clone)]
struct EventTracker {
events: Arc<Mutex<Vec<String>>>,
}
impl EventTracker {
fn new() -> Self {
Self {
events: Arc::new(Mutex::new(Vec::new())),
}
}
async fn log(&self, msg: String) {
println!(" [Event] {}", msg);
self.events.lock().await.push(msg);
}
}
#[async_trait::async_trait]
impl TokioMqttEventHandler for EventTracker {
async fn on_connected(&mut self, result: &ConnectionResult) {
self.log(format!(
"Connected: reason_code={}, session_present={}",
result.reason_code, result.session_present
))
.await;
}
async fn on_subscribed(&mut self, result: &SubscribeResult) {
self.log(format!(
"Subscribed: packet_id={}, reason_codes={:?}",
result.packet_id, result.reason_codes
))
.await;
}
async fn on_published(&mut self, result: &PublishResult) {
self.log(format!(
"Published: packet_id={:?}, qos={}",
result.packet_id, result.qos
))
.await;
}
async fn on_unsubscribed(&mut self, result: &UnsubscribeResult) {
self.log(format!(
"Unsubscribed: packet_id={}, reason_codes={:?}",
result.packet_id, result.reason_codes
))
.await;
}
async fn on_message_received(&mut self, publish: &MqttPublish) {
let payload = String::from_utf8_lossy(&publish.payload);
self.log(format!(
"Message received: topic='{}', payload='{}'",
publish.topic_name, payload
))
.await;
}
async fn on_error(&mut self, error: &MqttClientError) {
self.log(format!("Error: {}", error.user_message())).await;
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("╔═══════════════════════════════════════════════════════════════╗");
println!("║ Tokio Async MQTT Client - All Synchronous Operations Demo ║");
println!("╚═══════════════════════════════════════════════════════════════╝\n");
// Create event handler
let handler = EventTracker::new();
let handler_clone = handler.clone();
// Configure MQTT client using builder pattern
let options = MqttClientOptions::builder()
.peer("localhost:1883")
.client_id("tokio_all_sync_ops_client")
.build();
let config = TokioAsyncClientConfig::default();
println!("📦 Creating MQTT client...");
let client = Arc::new(TokioAsyncMqttClient::new(options, Box::new(handler), config).await?);
println!("✅ Client created\n");
// ============================================================
// 1. CONNECT SYNC - Wait for CONNACK
// ============================================================
println!("╭─────────────────────────────────────────╮");
println!("│ 1️⃣ CONNECT SYNC - Wait for CONNACK │");
println!("╰─────────────────────────────────────────╯");
match client.connect_sync().await {
Ok(result) => {
println!("✓ Connected successfully!");
println!(" Reason code: {}", result.reason_code);
println!(" Session present: {}", result.session_present);
println!(" Success: {}\n", result.is_success());
}
Err(e) => {
eprintln!("✗ Connection failed: {}\n", e);
return Err(e.into());
}
}
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
// ============================================================
// 2. SUBSCRIBE SYNC - Wait for SUBACK
// ============================================================
println!("╭─────────────────────────────────────────╮");
println!("│ 2️⃣ SUBSCRIBE SYNC - Wait for SUBACK │");
println!("╰─────────────────────────────────────────╯");
let test_topic = "test/sync/demo/#";
match client.subscribe_sync(test_topic, 1).await {
Ok(result) => {
println!("✓ Subscribed to '{}'", test_topic);
println!(" Packet ID: {}", result.packet_id);
println!(" Granted QoS: {:?}\n", result.reason_codes);
}
Err(e) => {
eprintln!("✗ Subscribe failed: {}\n", e);
}
}
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
// ============================================================
// 3. PUBLISH SYNC - Wait for PUBACK/PUBCOMP
// ============================================================
println!("╭─────────────────────────────────────────╮");
println!("│ 3️⃣ PUBLISH SYNC - Wait for ACKs │");
println!("╰─────────────────────────────────────────╯");
// QoS 0 - Fire and forget
println!("📤 QoS 0 (fire-and-forget):");
match client
.publish_sync("test/sync/demo/qos0", b"QoS 0 message", 0, false)
.await
{
Ok(result) => {
println!(" ✓ Sent immediately (no ack)");
println!(" Packet ID: {:?}", result.packet_id);
}
Err(e) => println!(" ✗ Failed: {}", e),
}
// QoS 1 - Wait for PUBACK
println!("\n📤 QoS 1 (wait for PUBACK):");
match client
.publish_sync("test/sync/demo/qos1", b"QoS 1 message", 1, false)
.await
{
Ok(result) => {
println!(" ✓ PUBACK received!");
println!(" Packet ID: {:?}", result.packet_id);
println!(" Reason code: {:?}", result.reason_code);
println!(" Success: {}", result.is_success());
}
Err(e) => println!(" ✗ Failed: {}", e),
}
// QoS 2 - Wait for PUBCOMP
println!("\n📤 QoS 2 (wait for PUBCOMP):");
match client
.publish_sync("test/sync/demo/qos2", b"QoS 2 message", 2, false)
.await
{
Ok(result) => {
println!(" ✓ PUBCOMP received!");
println!(" Packet ID: {:?}", result.packet_id);
println!(" Reason code: {:?}", result.reason_code);
println!(" Success: {}", result.is_success());
}
Err(e) => println!(" ✗ Failed: {}", e),
}
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
// ============================================================
// 4. PING SYNC - Wait for PINGRESP
// ============================================================
println!("\n╭─────────────────────────────────────────╮");
println!("│ 4️⃣ PING SYNC - Wait for PINGRESP │");
println!("╰─────────────────────────────────────────╯");
match client.ping_sync().await {
Ok(result) => {
println!("✓ PINGRESP received!");
println!(" Success: {}\n", result.success);
}
Err(e) => {
eprintln!("✗ Ping failed: {}\n", e);
}
}
// ============================================================
// 5. PING WITH TIMEOUT
// ============================================================
println!("╭─────────────────────────────────────────╮");
println!("│ 5️⃣ PING SYNC with Timeout │");
println!("╰─────────────────────────────────────────╯");
match tokio::time::timeout(tokio::time::Duration::from_secs(5), client.ping_sync()).await {
Ok(Ok(result)) => {
println!("✓ Ping completed within timeout");
println!(" Success: {}\n", result.success);
}
Ok(Err(e)) => {
println!("✗ Ping error: {}\n", e);
}
Err(_) => {
println!("✗ Ping timed out after 5 seconds\n");
}
}
// ============================================================
// 6. BATCH OPERATIONS
// ============================================================
println!("╭─────────────────────────────────────────╮");
println!("│ 6️⃣ BATCH SYNCHRONOUS PUBLISHES │");
println!("╰─────────────────────────────────────────╯");
for i in 1..=5 {
let topic = format!("test/sync/demo/batch/{}", i);
let payload = format!("Batch message {}", i);
match client
.publish_sync(&topic, payload.as_bytes(), 1, false)
.await
{
Ok(result) => {
println!(
" ✓ Message {} acknowledged (packet_id: {:?})",
i, result.packet_id
);
}
Err(e) => {
println!(" ✗ Message {} failed: {}", i, e);
}
}
}
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
// ============================================================
// 7. PARALLEL OPERATIONS
// ============================================================
println!("\n╭─────────────────────────────────────────╮");
println!("│ 7️⃣ PARALLEL SYNCHRONOUS PUBLISHES │");
println!("╰─────────────────────────────────────────╯");
let mut handles = vec![];
for i in 1..=3 {
let client_clone = client.clone();
let topic = format!("test/sync/demo/parallel/{}", i);
let handle = tokio::spawn(async move {
let payload = format!("Parallel message {}", i);
client_clone
.publish_sync(&topic, payload.as_bytes(), 1, false)
.await
});
handles.push((i, handle));
}
for (i, handle) in handles {
match handle.await {
Ok(Ok(result)) => {
println!(
" ✓ Parallel message {} completed: packet_id={:?}",
i, result.packet_id
);
}
Ok(Err(e)) => {
println!(" ✗ Parallel message {} failed: {}", i, e);
}
Err(e) => {
println!(" ✗ Parallel message {} task error: {}", i, e);
}
}
}
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
// ============================================================
// 8. UNSUBSCRIBE SYNC - Wait for UNSUBACK
// ============================================================
println!("\n╭─────────────────────────────────────────╮");
println!("│ 8️⃣ UNSUBSCRIBE SYNC - Wait for UNSUBACK│");
println!("╰─────────────────────────────────────────╯");
match client.unsubscribe_sync(vec![test_topic]).await {
Ok(result) => {
println!("✓ Unsubscribed from '{}'", test_topic);
println!(" Packet ID: {}", result.packet_id);
println!(" Reason codes: {:?}\n", result.reason_codes);
}
Err(e) => {
eprintln!("✗ Unsubscribe failed: {}\n", e);
}
}
// ============================================================
// 9. ERROR HANDLING DEMONSTRATION
// ============================================================
println!("╭─────────────────────────────────────────╮");
println!("│ 9️⃣ ERROR HANDLING │");
println!("╰─────────────────────────────────────────╯");
// Disconnect first
println!("🔌 Disconnecting...");
client.disconnect().await?;
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
// Try to publish after disconnect (should fail gracefully)
println!("📤 Attempting publish after disconnect:");
match tokio::time::timeout(
tokio::time::Duration::from_secs(2),
client.publish_sync("test/after/disconnect", b"Should fail", 1, false),
)
.await
{
Ok(Ok(result)) => {
println!(" ⚠️ Unexpected success: {:?}", result);
}
Ok(Err(e)) => {
println!(" ✓ Failed as expected: {}", e);
}
Err(_) => {
println!(" ✓ Timed out as expected");
}
}
// ============================================================
// 10. SUMMARY
// ============================================================
println!("\n╭─────────────────────────────────────────╮");
println!("│ 📊 EVENT SUMMARY │");
println!("╰─────────────────────────────────────────╯");
let events = handler_clone.events.lock().await;
println!("Total events captured: {}", events.len());
println!("\nRecent events:");
for (i, event) in events.iter().rev().take(10).enumerate() {
println!(" {}. {}", i + 1, event);
}
println!("\n╔═══════════════════════════════════════════════════════════════╗");
println!("║ ✅ All operations completed! ║");
println!("╚═══════════════════════════════════════════════════════════════╝");
Ok(())
}