comparison 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
comparison
equal deleted inserted replaced
603:b45b8b4cf0f5 604:278f1002b5c7
1 extern crate tokio_core; 1 extern crate tokio_core;
2 extern crate futures; 2 extern crate futures;
3 extern crate futures_cpupool; 3 extern crate futures_cpupool;
4 extern crate regex;
4 5
5 use std::time::Duration; 6 use std::time::Duration;
6 use std::io; 7 use std::io;
7 use std::fs::File; 8 use std::fs::File;
8 use std::io::{Read,BufReader,BufRead}; 9 use std::io::{Read,BufReader,BufRead};
9 use std::path::PathBuf; 10 use std::path::PathBuf;
10 use std::error::Error; 11 use std::error::Error;
11 use std::sync::Arc; 12 use std::sync::Arc;
13 use std::str::FromStr;
12 14
13 use tokio_core::reactor::Interval; 15 use tokio_core::reactor::Interval;
14 use tokio_core::reactor::Handle; 16 use tokio_core::reactor::Handle;
15 use futures::Stream; 17 use futures::Stream;
16 use types::*; 18 use types::*;
17 use ::Config; 19 use ::Config;
18
19
20 20
21 pub trait Sensor { 21 pub trait Sensor {
22 fn stream(&self, handle: &Handle) 22 fn stream(&self, handle: &Handle)
23 -> Box<Stream<Item=Readings, Error=io::Error>>; 23 -> Box<Stream<Item=Readings, Error=io::Error>>;
24 } 24 }
50 debug!("sensor step {:?}", r); 50 debug!("sensor step {:?}", r);
51 r 51 r
52 } 52 }
53 53
54 fn read_sensor(&self, n: &str) -> Result<f32, Box<Error>> { 54 fn read_sensor(&self, n: &str) -> Result<f32, Box<Error>> {
55 lazy_static! {
56 // multiline
57 static ref THERM_RE: regex::Regex = regex::Regex::new("(?m).* YES\n.*t=(.*)\n").unwrap();
58 }
55 let mut path = PathBuf::from(&self.config.SENSOR_BASE_DIR); 59 let mut path = PathBuf::from(&self.config.SENSOR_BASE_DIR);
56 path.push(n); 60 path.push(n);
57 path.push("w1_slave"); 61 path.push("w1_slave");
58 let f = BufReader::new(File::open(path)?); 62 let mut s = String::new();
59 Ok(3.4) 63 File::open(path)?.read_to_string(&mut s)?;
64 let caps = THERM_RE.captures(&s).ok_or_else(|| {
65 TemplogError::new("Bad sensor contents match")
66 })?;
67 let v = caps.get(1).ok_or_else(|| {
68 TemplogError::new("Bad field contents match")
69 })?.as_str();
70
71 Ok(f32::from_str(v)?)
60 } 72 }
61 73
62 fn sensor_names(&self) -> Result<Vec<String>, Box<Error>> { 74 fn sensor_names(&self) -> Result<Vec<String>, Box<Error>> {
63 let mut path = PathBuf::from(&self.config.SENSOR_BASE_DIR); 75 let mut path = PathBuf::from(&self.config.SENSOR_BASE_DIR);
64 path.push("w1_master_slaves"); 76 path.push("w1_master_slaves");