|
|
@@ -1,12 +1,32 @@
|
|
1
|
1
|
//! Interface to a publish values via MQTT.
|
|
2
|
2
|
|
|
3
|
|
-use protocol::{Location, Value};
|
|
|
3
|
+use std::collections::HashMap;
|
|
|
4
|
+use std::mem;
|
|
|
5
|
+use std::ops::DerefMut;
|
|
|
6
|
+use std::sync::Arc;
|
|
|
7
|
+use std::time::Duration;
|
|
|
8
|
+
|
|
|
9
|
+use log::{error, info};
|
|
|
10
|
+use mqtt::control::variable_header::ConnectReturnCode;
|
|
|
11
|
+use mqtt::packet::*;
|
|
|
12
|
+use mqtt::{Encodable, TopicName};
|
|
|
13
|
+use tokio::io::AsyncWriteExt;
|
|
|
14
|
+use tokio::net::TcpStream;
|
|
|
15
|
+use tokio::sync::{Mutex, Notify};
|
|
|
16
|
+use tokio::time::sleep;
|
|
4
|
17
|
|
|
5
|
|
-// TODO: Configuration mechanism.
|
|
|
18
|
+use super::config::MQTTConfig;
|
|
|
19
|
+use protocol::{Location, Value};
|
|
6
|
20
|
|
|
7
|
21
|
/// Interface to MQTT.
|
|
8
|
22
|
pub struct Publish {
|
|
9
|
|
- // TODO
|
|
|
23
|
+ // We only want to send the latest values if we do not have a connection, so we simply buffer
|
|
|
24
|
+ // the values until the sender thread collects them.
|
|
|
25
|
+ to_be_published: Arc<Mutex<HashMap<Location, Vec<Value>>>>,
|
|
|
26
|
+ trigger: Arc<Notify>,
|
|
|
27
|
+ /*config: MQTTConfig,
|
|
|
28
|
+ //publish_send: UnboundedSender<(Location, Vec<Value>)>,
|
|
|
29
|
+ stream: Option<OwnedWriteHalf>,*/
|
|
10
|
30
|
}
|
|
11
|
31
|
|
|
12
|
32
|
impl Publish {
|
|
|
@@ -15,9 +35,184 @@ impl Publish {
|
|
15
|
35
|
/// The function does not return an error. Instead, the code will automatically retry
|
|
16
|
36
|
/// connection in case the connection cannot be established or the server closes the
|
|
17
|
37
|
/// connection.
|
|
18
|
|
- pub fn init() -> Publish {
|
|
19
|
|
- // TODO
|
|
20
|
|
- Publish {}
|
|
|
38
|
+ pub fn init(config: &MQTTConfig) -> Publish {
|
|
|
39
|
+ let to_be_published = Arc::new(Mutex::new(HashMap::new()));
|
|
|
40
|
+ let to_be_published2 = to_be_published.clone();
|
|
|
41
|
+ let trigger = Arc::new(Notify::new());
|
|
|
42
|
+ let trigger2 = trigger.clone();
|
|
|
43
|
+ let config = config.clone();
|
|
|
44
|
+
|
|
|
45
|
+ tokio::spawn(async move {
|
|
|
46
|
+ let mut currently_sending = HashMap::new();
|
|
|
47
|
+ loop {
|
|
|
48
|
+ // When we are not connected, try to connect.
|
|
|
49
|
+ let stream = match Self::connect(&config).await {
|
|
|
50
|
+ Some(stream) => stream,
|
|
|
51
|
+ None => {
|
|
|
52
|
+ sleep(Duration::from_millis(500)).await;
|
|
|
53
|
+ continue;
|
|
|
54
|
+ }
|
|
|
55
|
+ };
|
|
|
56
|
+ let (mut read, write) = stream.into_split();
|
|
|
57
|
+ let write = Arc::new(Mutex::new(write));
|
|
|
58
|
+
|
|
|
59
|
+ // When we are connected, listen for ping packets and send a response.
|
|
|
60
|
+ {
|
|
|
61
|
+ let write = write.clone();
|
|
|
62
|
+ tokio::spawn(async move {
|
|
|
63
|
+ loop {
|
|
|
64
|
+ let packet = match VariablePacket::parse(&mut read).await {
|
|
|
65
|
+ Ok(packet) => packet,
|
|
|
66
|
+ Err(e) => {
|
|
|
67
|
+ error!("could not receive MQTT packet: {:?}", e);
|
|
|
68
|
+ return;
|
|
|
69
|
+ }
|
|
|
70
|
+ };
|
|
|
71
|
+
|
|
|
72
|
+ match packet {
|
|
|
73
|
+ VariablePacket::PingreqPacket(..) => {
|
|
|
74
|
+ let pingresp = PingrespPacket::new();
|
|
|
75
|
+ let mut data = Vec::new();
|
|
|
76
|
+ pingresp.encode(&mut data).unwrap();
|
|
|
77
|
+ let mut write = write.lock().await;
|
|
|
78
|
+ if let Err(e) = write.write_all(&data[..]).await {
|
|
|
79
|
+ error!("could not reply to MQTT ping packet: {:?}", e);
|
|
|
80
|
+ return;
|
|
|
81
|
+ }
|
|
|
82
|
+ }
|
|
|
83
|
+ VariablePacket::DisconnectPacket(..) => {
|
|
|
84
|
+ // Nothing to do here, the other end closes the connection.
|
|
|
85
|
+ error!("MQTT server closed the connection.");
|
|
|
86
|
+ return;
|
|
|
87
|
+ }
|
|
|
88
|
+ _ => {}
|
|
|
89
|
+ }
|
|
|
90
|
+ }
|
|
|
91
|
+ });
|
|
|
92
|
+ }
|
|
|
93
|
+
|
|
|
94
|
+ // Whenever we receive values to be sent, send them until the server disconnects or
|
|
|
95
|
+ // until we are told to shut down.
|
|
|
96
|
+ loop {
|
|
|
97
|
+ // Fetch values to be sent.
|
|
|
98
|
+ let to_be_published = {
|
|
|
99
|
+ let mut new = HashMap::<Location, Vec<Value>>::new();
|
|
|
100
|
+ mem::swap(&mut new, to_be_published2.lock().await.deref_mut());
|
|
|
101
|
+ new
|
|
|
102
|
+ };
|
|
|
103
|
+ for (location, values) in to_be_published {
|
|
|
104
|
+ // TODO: Merge values.
|
|
|
105
|
+ currently_sending.insert(location, values);
|
|
|
106
|
+ }
|
|
|
107
|
+
|
|
|
108
|
+ // If there is nothing else to send, wait and try again.
|
|
|
109
|
+ if currently_sending.len() == 0 {
|
|
|
110
|
+ trigger2.notified().await;
|
|
|
111
|
+ continue;
|
|
|
112
|
+ }
|
|
|
113
|
+
|
|
|
114
|
+ // Publish one value, then start again.
|
|
|
115
|
+ let first_location = *currently_sending.keys().next().unwrap();
|
|
|
116
|
+ let count = currently_sending[&first_location].len();
|
|
|
117
|
+ let first_value = currently_sending[&first_location][count - 1];
|
|
|
118
|
+ let (label, value) = match first_value {
|
|
|
119
|
+ Value::Temperature(temperature) => {
|
|
|
120
|
+ let temperature =
|
|
|
121
|
+ temperature as f32 / first_value.decimal_factor() as f32;
|
|
|
122
|
+ ("temperature", temperature)
|
|
|
123
|
+ }
|
|
|
124
|
+ Value::Pressure(pressure) => {
|
|
|
125
|
+ let pressure = pressure as f32 / first_value.decimal_factor() as f32;
|
|
|
126
|
+ ("pressure", pressure)
|
|
|
127
|
+ }
|
|
|
128
|
+ Value::Humidity(humidity) => {
|
|
|
129
|
+ let humidity = humidity as f32 / first_value.decimal_factor() as f32;
|
|
|
130
|
+ ("humidity", humidity)
|
|
|
131
|
+ }
|
|
|
132
|
+ _ => {
|
|
|
133
|
+ // Invalid value, remove it from the queue and try again.
|
|
|
134
|
+ currently_sending.get_mut(&first_location).unwrap().pop();
|
|
|
135
|
+ if currently_sending[&first_location].len() == 0 {
|
|
|
136
|
+ currently_sending.remove(&first_location);
|
|
|
137
|
+ }
|
|
|
138
|
+ continue;
|
|
|
139
|
+ }
|
|
|
140
|
+ };
|
|
|
141
|
+ let topic = format!(
|
|
|
142
|
+ "smarthome/{}/{}",
|
|
|
143
|
+ first_location.to_str().to_lowercase(),
|
|
|
144
|
+ label
|
|
|
145
|
+ );
|
|
|
146
|
+ let topic = TopicName::new(topic).unwrap();
|
|
|
147
|
+ let publish_packet = PublishPacket::new(
|
|
|
148
|
+ topic,
|
|
|
149
|
+ QoSWithPacketIdentifier::Level0,
|
|
|
150
|
+ format!("{}", value),
|
|
|
151
|
+ );
|
|
|
152
|
+ let mut buf = Vec::new();
|
|
|
153
|
+ publish_packet.encode(&mut buf).unwrap();
|
|
|
154
|
+ if let Err(e) = write.lock().await.write_all(&buf[..]).await {
|
|
|
155
|
+ error!("could not send value to MQTT: {:?}", e);
|
|
|
156
|
+ break;
|
|
|
157
|
+ } else {
|
|
|
158
|
+ // The value was sent, remove it from the queue.
|
|
|
159
|
+ currently_sending.get_mut(&first_location).unwrap().pop();
|
|
|
160
|
+ if currently_sending[&first_location].len() == 0 {
|
|
|
161
|
+ currently_sending.remove(&first_location);
|
|
|
162
|
+ }
|
|
|
163
|
+ }
|
|
|
164
|
+ }
|
|
|
165
|
+ }
|
|
|
166
|
+ });
|
|
|
167
|
+ Publish {
|
|
|
168
|
+ to_be_published,
|
|
|
169
|
+ trigger,
|
|
|
170
|
+ }
|
|
|
171
|
+ }
|
|
|
172
|
+
|
|
|
173
|
+ async fn connect(config: &MQTTConfig) -> Option<TcpStream> {
|
|
|
174
|
+ info!("Connecting to MQTT broker...");
|
|
|
175
|
+ let mut stream = match TcpStream::connect(&config.address).await {
|
|
|
176
|
+ Ok(stream) => stream,
|
|
|
177
|
+ Err(e) => {
|
|
|
178
|
+ error!("Failed to connect to the MQTT broker: {:?}", e);
|
|
|
179
|
+ return None;
|
|
|
180
|
+ }
|
|
|
181
|
+ };
|
|
|
182
|
+
|
|
|
183
|
+ let mut conn = ConnectPacket::new("72711cd2-faaf-44f0-8490-b92eb063ff4b");
|
|
|
184
|
+ conn.set_clean_session(true);
|
|
|
185
|
+ let mut buf = Vec::new();
|
|
|
186
|
+ conn.encode(&mut buf).unwrap();
|
|
|
187
|
+ match stream.write_all(&buf[..]).await {
|
|
|
188
|
+ Ok(stream) => stream,
|
|
|
189
|
+ Err(e) => {
|
|
|
190
|
+ error!("Failed to send MQTT connect packet: {:?}", e);
|
|
|
191
|
+ return None;
|
|
|
192
|
+ }
|
|
|
193
|
+ };
|
|
|
194
|
+
|
|
|
195
|
+ let connack = match VariablePacket::parse(&mut stream).await {
|
|
|
196
|
+ Ok(VariablePacket::ConnackPacket(connack)) => connack,
|
|
|
197
|
+ Ok(_) => {
|
|
|
198
|
+ error!("Received wrong MQTT packet, expected CONNACK!");
|
|
|
199
|
+ return None;
|
|
|
200
|
+ }
|
|
|
201
|
+ Err(e) => {
|
|
|
202
|
+ error!("Failed to receive MQTT CONNACK packet: {:?}", e);
|
|
|
203
|
+ return None;
|
|
|
204
|
+ }
|
|
|
205
|
+ };
|
|
|
206
|
+ if connack.connect_return_code() != ConnectReturnCode::ConnectionAccepted {
|
|
|
207
|
+ error!(
|
|
|
208
|
+ "Failed to connect to server, return code {:?}",
|
|
|
209
|
+ connack.connect_return_code()
|
|
|
210
|
+ );
|
|
|
211
|
+ return None;
|
|
|
212
|
+ }
|
|
|
213
|
+
|
|
|
214
|
+ info!("Connected to MQTT broker.");
|
|
|
215
|
+ Some(stream)
|
|
21
|
216
|
}
|
|
22
|
217
|
|
|
23
|
218
|
/// Publishes values received from a device.
|
|
|
@@ -30,7 +225,16 @@ impl Publish {
|
|
30
|
225
|
///
|
|
31
|
226
|
/// * `location` - the location of the device
|
|
32
|
227
|
/// * `values` - a list of values to be published
|
|
33
|
|
- pub async fn publish(&mut self, _location: Location, _values: &[Value]) {
|
|
34
|
|
- // TODO
|
|
|
228
|
+ pub async fn publish(&mut self, location: Location, values: &[Value]) {
|
|
|
229
|
+ let mut buffer = self.to_be_published.lock().await;
|
|
|
230
|
+ // TODO: Merge the values?
|
|
|
231
|
+ *buffer.entry(location).or_insert(Vec::new()) = values.to_vec();
|
|
|
232
|
+ self.trigger.notify_one();
|
|
|
233
|
+ }
|
|
|
234
|
+}
|
|
|
235
|
+
|
|
|
236
|
+impl Drop for Publish {
|
|
|
237
|
+ fn drop(&mut self) {
|
|
|
238
|
+ // TODO: Stop the thread.
|
|
35
|
239
|
}
|
|
36
|
240
|
}
|