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
use async_channel::Receiver;
use std::marker::PhantomData;
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::available_packet_ids::AvailablePacketIds;
use crate::connect_options::ConnectOptions;
use crate::error::ConnectionError;
use crate::packets::DisconnectReasonCode;
use crate::packets::{Disconnect, Packet, PacketType};
use crate::{AsyncEventHandler, NetworkStatus, StateHandler};
use super::stream::StreamExt;
/// [`Network`] reads and writes to the network based on tokios [`::tokio::io::AsyncReadExt`] [`::tokio::io::AsyncWriteExt`].
/// This way you can provide the `connect` function with a TLS and TCP stream of your choosing.
/// The most import thing to remember is that you have to provide a new stream after the previous has failed.
/// (i.e. you need to reconnect after any expected or unexpected disconnect).
pub struct Network<H, S> {
handler: PhantomData<H>,
network: Option<S>,
/// Options of the current mqtt connection
options: ConnectOptions,
last_network_action: Instant,
perform_keep_alive: bool,
state_handler: Arc<StateHandler>,
to_network_r: Receiver<Packet>,
}
impl<H, S> Network<H, S> {
pub(crate) fn new(options: ConnectOptions, to_network_r: Receiver<Packet>, apkids: AvailablePacketIds) -> Self {
Self {
handler: PhantomData,
network: None,
last_network_action: Instant::now(),
perform_keep_alive: true,
state_handler: Arc::new(StateHandler::new(&options, apkids)),
options,
to_network_r,
}
}
}
impl<H, S> Network<H, S>
where
H: AsyncEventHandler,
S: tokio::io::AsyncReadExt + tokio::io::AsyncWriteExt + Sized + Unpin + Send + 'static,
{
/// Initializes an MQTT connection with the provided configuration an stream
///
/// It is recommended to use a buffered stream. [`tokio::io::BufStream`] could be used to easily buffer both read and write.
pub async fn connect(&mut self, mut stream: S, handler: &mut H) -> Result<(), ConnectionError> {
let conn_ack = stream.connect(&self.options).await?;
self.last_network_action = Instant::now();
if let Some(keep_alive_interval) = conn_ack.connack_properties.server_keep_alive {
self.options.keep_alive_interval = Duration::from_secs(keep_alive_interval as u64)
}
if self.options.keep_alive_interval.is_zero() {
self.perform_keep_alive = false;
}
let packets = self.state_handler.handle_incoming_connack(&conn_ack)?;
handler.handle(Packet::ConnAck(conn_ack)).await;
if let Some(packets) = packets {
stream.write_packets(&packets).await?;
self.last_network_action = Instant::now();
}
self.network = Some(stream);
Ok(())
}
}
impl<H, S> Network<H, S>
where
H: AsyncEventHandler,
S: tokio::io::AsyncReadExt + tokio::io::AsyncWriteExt + Sized + Unpin + Send + 'static,
{
/// A single call to run will perform one of three tasks:
/// - Read from the stream and parse the bytes to packets for the user to handle
/// - Write user packets to stream
/// - Perform keepalive if necessary
///
/// In all other cases the network is unusable anymore.
/// The stream will be dropped and the internal buffers will be cleared.
pub async fn run(&mut self, handler: &mut H) -> Result<NetworkStatus, ConnectionError> {
if self.network.is_none() {
return Err(ConnectionError::NoNetwork);
}
let result = self.tokio_select(handler).await;
self.network = None;
result
}
async fn tokio_select(&mut self, handler: &mut H) -> Result<NetworkStatus, ConnectionError> {
let Network {
network,
options,
last_network_action,
perform_keep_alive,
to_network_r,
handler: _,
state_handler,
} = self;
let mut await_pingresp = None;
loop {
let sleep;
if let Some(instant) = await_pingresp {
sleep = instant + options.get_keep_alive_interval() - Instant::now();
} else {
sleep = *last_network_action + options.get_keep_alive_interval() - Instant::now();
}
if let Some(stream) = network {
tokio::select! {
res = stream.read_packet() => {
#[cfg(feature = "logs")]
tracing::trace!("Received incoming packet {:?}", &res);
let packet = res?;
match packet{
Packet::PingResp => {
handler.handle(packet).await;
await_pingresp = None;
},
Packet::Disconnect(_) => {
handler.handle(packet).await;
return Ok(NetworkStatus::IncomingDisconnect);
}
packet => {
match state_handler.handle_incoming_packet(&packet)? {
(maybe_reply_packet, true) => {
handler.handle(packet).await;
if let Some(reply_packet) = maybe_reply_packet {
stream.write_packet(&reply_packet).await?;
*last_network_action = Instant::now();
}
},
(Some(reply_packet), false) => {
stream.write_packet(&reply_packet).await?;
*last_network_action = Instant::now();
},
(None, false) => (),
}
}
}
},
outgoing = to_network_r.recv() => {
#[cfg(feature = "logs")]
tracing::trace!("Received outgoing item {:?}", &outgoing);
let packet = outgoing?;
#[cfg(feature = "logs")]
tracing::trace!("Sending packet {}", packet);
stream.write_packet(&packet).await?;
let disconnect = packet.packet_type() == PacketType::Disconnect;
state_handler.handle_outgoing_packet(packet)?;
*last_network_action = Instant::now();
if disconnect{
return Ok(NetworkStatus::OutgoingDisconnect);
}
},
_ = tokio::time::sleep(sleep), if await_pingresp.is_none() && *perform_keep_alive => {
let packet = Packet::PingReq;
stream.write_packet(&packet).await?;
*last_network_action = Instant::now();
await_pingresp = Some(Instant::now());
},
_ = tokio::time::sleep(sleep), if await_pingresp.is_some() => {
let disconnect = Disconnect{ reason_code: DisconnectReasonCode::KeepAliveTimeout, properties: Default::default() };
stream.write_packet(&Packet::Disconnect(disconnect)).await?;
return Ok(NetworkStatus::KeepAliveTimeout);
}
}
} else {
return Err(ConnectionError::NoNetwork);
}
}
}
// async fn concurrent_tokio_select(&mut self, handler: &mut H) -> Result<NetworkStatus, ConnectionError> {
// let Network {
// network,
// options,
// last_network_action,
// perform_keep_alive,
// to_network_r,
// handler: _,
// state_handler,
// } = self;
// let mut await_pingresp = None;
// loop {
// let sleep;
// if let Some(instant) = await_pingresp {
// sleep = instant + options.get_keep_alive_interval() - Instant::now();
// } else {
// sleep = *last_network_action + options.get_keep_alive_interval() - Instant::now();
// }
// if let Some(stream) = network {
// tokio::select! {
// res = stream.read_packet() => {
// let packet = res?;
// match packet{
// Packet::PingResp => {
// handler.handle(packet).await;
// await_pingresp = None;
// },
// Packet::Disconnect(_) => {
// handler.handle(packet).await;
// return Ok(NetworkStatus::IncomingDisconnect);
// }
// packet => {
// match state_handler.handle_incoming_packet(&packet)? {
// (maybe_reply_packet, true) => {
// handler.handle(packet).await;
// if let Some(reply_packet) = maybe_reply_packet {
// stream.write_packet(&reply_packet).await?;
// *last_network_action = Instant::now();
// }
// },
// (Some(reply_packet), false) => {
// stream.write_packet(&reply_packet).await?;
// *last_network_action = Instant::now();
// },
// (None, false) => (),
// }
// }
// }
// },
// outgoing = to_network_r.recv() => {
// let packet = outgoing?;
// stream.write_packet(&packet).await?;
// let disconnect = packet.packet_type() == PacketType::Disconnect;
// state_handler.handle_outgoing_packet(packet)?;
// *last_network_action = Instant::now();
// if disconnect{
// return Ok(NetworkStatus::OutgoingDisconnect);
// }
// },
// _ = tokio::time::sleep(sleep), if await_pingresp.is_none() && *perform_keep_alive => {
// let packet = Packet::PingReq;
// stream.write_packet(&packet).await?;
// *last_network_action = Instant::now();
// await_pingresp = Some(Instant::now());
// },
// _ = tokio::time::sleep(sleep), if await_pingresp.is_some() => {
// let disconnect = Disconnect{ reason_code: DisconnectReasonCode::KeepAliveTimeout, properties: Default::default() };
// stream.write_packet(&Packet::Disconnect(disconnect)).await?;
// return Ok(NetworkStatus::KeepAliveTimeout);
// }
// }
// } else {
// return Err(ConnectionError::NoNetwork);
// }
// }
// }
}