Browse Source

Add range checks for the received values and fix formatting

Bernd Gottschlag 5 years ago
parent
commit
b837785f8e

+ 1
- 1
base-station/software/rustfmt.toml View File

1
-edition = 2018
1
+edition = "2018"

+ 18
- 11
base-station/software/src/main.rs View File

1
 use std::env;
1
 use std::env;
2
 use std::io;
2
 use std::io;
3
+use std::sync::mpsc;
3
 use std::thread::sleep;
4
 use std::thread::sleep;
4
 use std::time::Duration;
5
 use std::time::Duration;
5
-use std::sync::mpsc;
6
 
6
 
7
-use log::error;
8
 use ::mqtt::control::variable_header::ConnectReturnCode;
7
 use ::mqtt::control::variable_header::ConnectReturnCode;
8
+use log::error;
9
 
9
 
10
 use crate::mqtt::MQTT;
10
 use crate::mqtt::MQTT;
11
 
11
 
45
             _ => {
45
             _ => {
46
                 error!("Unknown location in sensor update.");
46
                 error!("Unknown location in sensor update.");
47
                 continue;
47
                 continue;
48
-            },
48
+            }
49
         };
49
         };
50
         for value in update.data.iter() {
50
         for value in update.data.iter() {
51
             match value {
51
             match value {
52
                 SensorData::Temperature(value) => {
52
                 SensorData::Temperature(value) => {
53
-                    m.publish(&format!("gottschlag/{}/temperature", location), &format!("{}", value))?;
54
-                },
53
+                    m.publish(
54
+                        &format!("gottschlag/{}/temperature", location),
55
+                        &format!("{}", value),
56
+                    )?;
57
+                }
55
                 SensorData::Humidity(value) => {
58
                 SensorData::Humidity(value) => {
56
-                    m.publish(&format!("gottschlag/{}/humidity", location), &format!("{}", value))?;
57
-                },
59
+                    m.publish(
60
+                        &format!("gottschlag/{}/humidity", location),
61
+                        &format!("{}", value),
62
+                    )?;
63
+                }
58
                 SensorData::Pressure(value) => {
64
                 SensorData::Pressure(value) => {
59
-                    m.publish(&format!("gottschlag/{}/pressure", location), &format!("{}", value))?;
65
+                    m.publish(
66
+                        &format!("gottschlag/{}/pressure", location),
67
+                        &format!("{}", value),
68
+                    )?;
60
                 }
69
                 }
61
             }
70
             }
62
         }
71
         }
74
     Pressure(f32),
83
     Pressure(f32),
75
 }
84
 }
76
 
85
 
77
-
78
-
79
 #[derive(thiserror::Error, Debug)]
86
 #[derive(thiserror::Error, Debug)]
80
 pub enum Error {
87
 pub enum Error {
81
     #[error("I/O error")]
88
     #[error("I/O error")]
83
     #[error("connection refused, return code {0:?}")]
90
     #[error("connection refused, return code {0:?}")]
84
     ConnectionRefused(ConnectReturnCode),
91
     ConnectionRefused(ConnectReturnCode),
85
     #[error("radio error: {0:?}")]
92
     #[error("radio error: {0:?}")]
86
-    Radio(embedded_nrf24l01::Error<std::io::Error>)
93
+    Radio(embedded_nrf24l01::Error<std::io::Error>),
87
 }
94
 }
88
 
95
 
89
 impl From<embedded_nrf24l01::Error<std::io::Error>> for Error {
96
 impl From<embedded_nrf24l01::Error<std::io::Error>> for Error {

+ 3
- 5
base-station/software/src/mqtt.rs View File

2
 use std::net::TcpStream;
2
 use std::net::TcpStream;
3
 use std::thread;
3
 use std::thread;
4
 
4
 
5
-use log::{info, error};
5
+use log::{error, info};
6
 use mqtt::control::variable_header::ConnectReturnCode;
6
 use mqtt::control::variable_header::ConnectReturnCode;
7
 use mqtt::packet::*;
7
 use mqtt::packet::*;
8
 use mqtt::{Decodable, Encodable, QualityOfService};
8
 use mqtt::{Decodable, Encodable, QualityOfService};
57
                         // Nothing to do here, the other end closes the connection.
57
                         // Nothing to do here, the other end closes the connection.
58
                         break;
58
                         break;
59
                     }
59
                     }
60
-                    _ => {},
60
+                    _ => {}
61
                 }
61
                 }
62
             }
62
             }
63
         });
63
         });
64
 
64
 
65
-        Ok(MQTT{
66
-            stream
67
-        })
65
+        Ok(MQTT { stream })
68
     }
66
     }
69
 
67
 
70
     pub fn publish(&mut self, topic: &str, value: &str) -> Result<(), Error> {
68
     pub fn publish(&mut self, topic: &str, value: &str) -> Result<(), Error> {

+ 41
- 11
base-station/software/src/radio.rs View File

1
 use std::convert::TryInto;
1
 use std::convert::TryInto;
2
+use std::sync::mpsc;
2
 use std::thread;
3
 use std::thread;
3
 use std::time::{Duration, Instant};
4
 use std::time::{Duration, Instant};
4
-use std::sync::mpsc;
5
 
5
 
6
 use embedded_nrf24l01::{Configuration, CrcMode, DataRate, NRF24L01};
6
 use embedded_nrf24l01::{Configuration, CrcMode, DataRate, NRF24L01};
7
 use linux_embedded_hal::spidev::{SpiModeFlags, Spidev, SpidevOptions};
7
 use linux_embedded_hal::spidev::{SpiModeFlags, Spidev, SpidevOptions};
11
 
11
 
12
 use crate::spi::EmbeddedHalSpidev;
12
 use crate::spi::EmbeddedHalSpidev;
13
 use crate::Error;
13
 use crate::Error;
14
-use crate::{SensorUpdate, SensorData};
14
+use crate::{SensorData, SensorUpdate};
15
 
15
 
16
 pub fn start(updates: mpsc::Sender<SensorUpdate>) {
16
 pub fn start(updates: mpsc::Sender<SensorUpdate>) {
17
     // TODO: Channels for sensor readings.
17
     // TODO: Channels for sensor readings.
70
     nrf24.set_rf(DataRate::R2Mbps, 3)?;
70
     nrf24.set_rf(DataRate::R2Mbps, 3)?;
71
     nrf24.set_crc(Some(CrcMode::OneByte))?;
71
     nrf24.set_crc(Some(CrcMode::OneByte))?;
72
     nrf24.set_auto_retransmit(250, 3)?;
72
     nrf24.set_auto_retransmit(250, 3)?;
73
-    nrf24
74
-        .set_pipes_rx_enable(&[true, false, false, false, false, false])
75
-        ?;
73
+    nrf24.set_pipes_rx_enable(&[true, false, false, false, false, false])?;
76
     nrf24
74
     nrf24
77
         .set_rx_addr(0, &[0x56, 0x34, 0x12, 0x00, 0x00])
75
         .set_rx_addr(0, &[0x56, 0x34, 0x12, 0x00, 0x00])
78
         .unwrap();
76
         .unwrap();
92
     loop {
90
     loop {
93
         if let Some(pipe) = nrf24.can_read().unwrap() {
91
         if let Some(pipe) = nrf24.can_read().unwrap() {
94
             let payload = nrf24.read().unwrap();
92
             let payload = nrf24.read().unwrap();
95
-            info!("packet received on pipe {}: {:?}, {}", pipe, payload.as_ref(), payload.len());
93
+            info!(
94
+                "packet received on pipe {}: {:?}, {}",
95
+                pipe,
96
+                payload.as_ref(),
97
+                payload.len()
98
+            );
99
+            if payload.len() != 12 {
100
+                continue;
101
+            }
102
+
96
             let pressure = u32::from_le_bytes(payload.as_ref()[0..4].try_into().unwrap());
103
             let pressure = u32::from_le_bytes(payload.as_ref()[0..4].try_into().unwrap());
97
-            let temperature = u32::from_le_bytes(payload.as_ref()[4..8].try_into().unwrap());
104
+
105
+            if pressure < 50000 || pressure > 150000 {
106
+                info!("pressure outside of range: {}", pressure);
107
+                continue;
108
+            }
109
+
110
+            let temperature = i32::from_le_bytes(payload.as_ref()[4..8].try_into().unwrap());
111
+
112
+            if temperature < -50 * 100 || temperature > 100 * 100 {
113
+                info!("temperature outside of range: {}", temperature);
114
+                continue;
115
+            }
116
+
98
             let humidity = u32::from_le_bytes(payload.as_ref()[8..12].try_into().unwrap());
117
             let humidity = u32::from_le_bytes(payload.as_ref()[8..12].try_into().unwrap());
118
+            if humidity > 100 * 1024 {
119
+                info!("humidity outside of range: {}", humidity);
120
+                continue;
121
+            }
122
+
99
             let pressure = pressure as f32 / 100.0;
123
             let pressure = pressure as f32 / 100.0;
100
             let temperature = temperature as f32 / 100.0;
124
             let temperature = temperature as f32 / 100.0;
101
             let humidity = humidity as f32 / 1024.0;
125
             let humidity = humidity as f32 / 1024.0;
102
             info!("pressure: {}", pressure);
126
             info!("pressure: {}", pressure);
103
             info!("temperature: {}", temperature);
127
             info!("temperature: {}", temperature);
104
             info!("humidity: {}", humidity);
128
             info!("humidity: {}", humidity);
105
-            updates.send(SensorUpdate{
106
-                location: 0,
107
-                data: vec![SensorData::Temperature(temperature), SensorData::Pressure(pressure), SensorData::Humidity(humidity)],
108
-            }).unwrap();
129
+            updates
130
+                .send(SensorUpdate {
131
+                    location: 0,
132
+                    data: vec![
133
+                        SensorData::Temperature(temperature),
134
+                        SensorData::Pressure(pressure),
135
+                        SensorData::Humidity(humidity),
136
+                    ],
137
+                })
138
+                .unwrap();
109
             let end = Instant::now();
139
             let end = Instant::now();
110
             let elapsed = end.duration_since(start);
140
             let elapsed = end.duration_since(start);
111
             info!("Debug: {:?}", elapsed);
141
             info!("Debug: {:?}", elapsed);

Loading…
Cancel
Save