-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtokio_async_mqtt_quic_example.rs
More file actions
275 lines (233 loc) · 8.67 KB
/
Copy pathtokio_async_mqtt_quic_example.rs
File metadata and controls
275 lines (233 loc) · 8.67 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
// SPDX-License-Identifier: MPL-2.0
// QUIC-enabled async MQTT client example
// Demonstrates using TokioAsyncMqttClient with QUIC transport
use flowsdk::mqtt_client::client::{
ConnectionResult, PingResult, PublishResult, SubscribeResult, UnsubscribeResult,
};
use flowsdk::mqtt_client::{
MqttClientError, MqttClientOptions, MqttMessage, TokioAsyncClientConfig, TokioAsyncMqttClient,
TokioMqttEventHandler,
};
use tokio::time::{sleep, Duration};
/// Simple event handler for the QUIC async client
struct QuicExampleHandler {
name: String,
}
impl QuicExampleHandler {
fn new(name: &str) -> Self {
QuicExampleHandler {
name: name.to_string(),
}
}
}
#[async_trait::async_trait]
impl TokioMqttEventHandler for QuicExampleHandler {
async fn on_connected(&mut self, result: &ConnectionResult) {
if result.is_success() {
println!(
"[{}] ✅ Connected successfully over QUIC! Session present: {}",
self.name, result.session_present
);
if let Some(properties) = &result.properties {
println!("[{}] 📋 Broker properties: {:?}", self.name, properties);
}
} else {
println!(
"[{}] ❌ Connection failed: {} (code: {})",
self.name,
result.reason_description(),
result.reason_code
);
}
}
async fn on_disconnected(&mut self, reason: Option<u8>) {
match reason {
Some(code) => println!("[{}] 👋 Disconnected (reason code: {})", self.name, code),
None => println!("[{}] 👋 Disconnected (connection lost)", self.name),
}
}
async fn on_published(&mut self, result: &PublishResult) {
if result.is_success() {
println!(
"[{}] 📤 Message published successfully (QoS: {}, ID: {:?})",
self.name, result.qos, result.packet_id
);
} else {
println!(
"[{}] ❌ Publish failed: {} (code: {:?})",
self.name,
result.reason_description(),
result.reason_code
);
}
}
async fn on_subscribed(&mut self, result: &SubscribeResult) {
if result.is_success() {
println!(
"[{}] 📥 Subscribed successfully! ({} subscriptions)",
self.name,
result.successful_subscriptions()
);
} else {
println!(
"[{}] ❌ Subscription failed: {:?}",
self.name, result.reason_codes
);
}
}
async fn on_unsubscribed(&mut self, result: &UnsubscribeResult) {
if result.is_success() {
println!("[{}] 📤 Unsubscribed successfully!", self.name);
} else {
println!(
"[{}] ❌ Unsubscribe failed: {:?}",
self.name, result.reason_codes
);
}
}
async fn on_message_received(&mut self, publish: &MqttMessage) {
let payload_str = String::from_utf8_lossy(&publish.payload);
println!(
"[{}] 📨 Message received on '{}': {}",
self.name, publish.topic_name, payload_str
);
println!(
" QoS: {}, Retain: {}, Packet ID: {:?}",
publish.qos, publish.retain, publish.packet_id
);
}
async fn on_ping_response(&mut self, result: &PingResult) {
if result.success {
println!("[{}] 🏓 Ping response received", self.name);
} else {
println!("[{}] ❌ Ping failed", self.name);
}
}
async fn on_error(&mut self, error: &MqttClientError) {
println!("[{}] ❌ Error: {}", self.name, error.user_message());
}
async fn on_connection_lost(&mut self) {
println!(
"[{}] 💔 Connection lost! Attempting to reconnect...",
self.name
);
}
async fn on_reconnect_attempt(&mut self, attempt: u32) {
println!("[{}] 🔄 Reconnection attempt #{}", self.name, attempt);
}
async fn on_pending_operations_cleared(&mut self) {
println!("[{}] 🧹 Pending operations cleared", self.name);
}
}
/// Initialize the default crypto provider for rustls (required in 0.23+)
fn init_crypto() {
#[cfg(feature = "quic-proto-openssl")]
let _ = rustls_openssl::default_provider().install_default();
#[cfg(not(feature = "quic-proto-openssl"))]
let _ = rustls::crypto::ring::default_provider().install_default();
}
async fn run_example(test_mode: bool) -> Result<(), Box<dyn std::error::Error>> {
init_crypto();
println!("🚀 Starting Tokio Async MQTT Client with QUIC Transport");
println!();
println!("⚠️ NOTE: This example uses insecure_skip_verify for testing.");
println!(" For production, use proper certificate validation!");
println!();
let broker_addr = "broker.emqx.io:14567";
let peer_url = format!("quic://{}", broker_addr);
println!("📡 Connecting to broker: {}", peer_url);
println!();
// Configure MQTT client options with quic:// scheme
let mqtt_options = MqttClientOptions::builder()
.peer(&peer_url)
.client_id("tokio_quic_example_client")
.keep_alive(60)
.clean_start(true)
.build();
// Enable TLS key logging if SSLKEYLOGFILE is set (for Wireshark decryption)
let enable_key_log = std::env::var("SSLKEYLOGFILE").is_ok();
if enable_key_log {
println!("🔑 SSLKEYLOGFILE is set — TLS session keys will be logged");
}
// Configure tokio async client settings with QUIC options
let async_config = TokioAsyncClientConfig::builder()
.auto_reconnect(true)
.max_reconnect_delay_ms(1000)
.max_reconnect_attempts(5)
.quic_insecure_skip_verify(true) // ⚠️ For testing only!
.quic_enable_0rtt(false)
.quic_datagram_receive_buffer_size(0) // disable datagram
.quic_enable_key_log(enable_key_log)
.build();
// Create event handler
let event_handler = Box::new(QuicExampleHandler::new("QuicClient"));
// Create tokio async MQTT client
let client = TokioAsyncMqttClient::new(mqtt_options, event_handler, async_config).await?;
println!("📡 Initiating QUIC connection...");
client.connect().await?;
sleep(Duration::from_secs(2)).await;
println!("📋 Subscribing to test topic...");
client.subscribe("test/quic/topic", 1).await?;
sleep(Duration::from_secs(1)).await;
if test_mode {
println!("📤 Publishing test messages...");
for i in 1..=3 {
let message = format!("Hello from QUIC! Message #{}", i);
match client
.publish("test/quic/topic", message.as_bytes(), 1, false)
.await
{
Ok(_) => println!("📤 Published message #{}", i),
Err(e) => eprintln!("❌ Failed to publish message #{}: {}", i, e),
}
sleep(Duration::from_millis(500)).await;
}
} else {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
println!("📤 Publishing messages continuously (Press Ctrl-C to stop)...");
// Set up Ctrl-C handler
let running = Arc::new(AtomicBool::new(true));
let r = running.clone();
ctrlc::set_handler(move || {
println!("\n🛑 Ctrl-C received, stopping...");
r.store(false, Ordering::SeqCst);
})
.expect("Error setting Ctrl-C handler");
let mut counter = 0u64;
while running.load(Ordering::SeqCst) {
counter += 1;
let message = format!("Hello from QUIC! Message #{}", counter);
match client
.publish("test/quic/topic", message.as_bytes(), 1, false)
.await
{
Ok(_) => println!("📤 Published message #{}", counter),
Err(e) => eprintln!("❌ Failed to publish message #{}: {}", counter, e),
}
sleep(Duration::from_secs(1)).await;
}
}
println!("🏓 Sending ping...");
client.ping().await?;
sleep(Duration::from_secs(1)).await;
println!("👋 Disconnecting...");
client.disconnect().await?;
sleep(Duration::from_secs(1)).await;
println!("🛑 Shutting down client...");
client.shutdown().await?;
println!("✅ QUIC MQTT Client Example completed!");
Ok(())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
run_example(false).await
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_example() {
run_example(true).await.unwrap();
}
}