diff rust/src/sensor.rs @ 604:278f1002b5c7 rust

sensor regex, custom error type
author Matt Johnston <matt@ucc.asn.au>
date Thu, 16 Feb 2017 23:53:46 +0800
parents b45b8b4cf0f5
children 8dd63473b6d8
line wrap: on
line diff
--- a/rust/src/sensor.rs	Thu Feb 16 23:19:12 2017 +0800
+++ b/rust/src/sensor.rs	Thu Feb 16 23:53:46 2017 +0800
@@ -1,6 +1,7 @@
 extern crate tokio_core;
 extern crate futures;
 extern crate futures_cpupool;
+extern crate regex;
 
 use std::time::Duration;
 use std::io;
@@ -9,6 +10,7 @@
 use std::path::PathBuf;
 use std::error::Error;
 use std::sync::Arc;
+use std::str::FromStr;
 
 use tokio_core::reactor::Interval;
 use tokio_core::reactor::Handle;
@@ -16,8 +18,6 @@
 use types::*;
 use ::Config;
 
-
-
 pub trait Sensor {
     fn stream(&self, handle: &Handle)
         -> Box<Stream<Item=Readings, Error=io::Error>>;
@@ -52,11 +52,23 @@
     }
 
     fn read_sensor(&self, n: &str) -> Result<f32, Box<Error>> {
+        lazy_static! {
+            // multiline
+            static ref THERM_RE: regex::Regex = regex::Regex::new("(?m).* YES\n.*t=(.*)\n").unwrap();
+        }
         let mut path = PathBuf::from(&self.config.SENSOR_BASE_DIR);
         path.push(n);
         path.push("w1_slave");
-        let f = BufReader::new(File::open(path)?);
-        Ok(3.4)
+        let mut s = String::new();
+        File::open(path)?.read_to_string(&mut s)?;
+        let caps = THERM_RE.captures(&s).ok_or_else(|| {
+                TemplogError::new("Bad sensor contents match")
+            })?;
+        let v = caps.get(1).ok_or_else(|| {
+                TemplogError::new("Bad field contents match")
+            })?.as_str();
+
+        Ok(f32::from_str(v)?)
     }
 
     fn sensor_names(&self) -> Result<Vec<String>, Box<Error>> {