Mercurial > templog
view rust/src/sensor.rs @ 594:aff50ee77252 rust
rust working better now with streams and sinks.
author | Matt Johnston <matt@ucc.asn.au> |
---|---|
date | Wed, 04 Jan 2017 17:18:44 +0800 |
parents | 03b48ec0bb03 |
children | e87655ed8429 |
line wrap: on
line source
extern crate tokio_core; extern crate futures; use std::time::Duration; use std::io; use std::fs::File; use std::io::Read; use tokio_core::reactor::Interval; use tokio_core::reactor::Handle; use futures::Stream; use types::*; pub trait Sensor { fn stream(handle: &Handle) -> Box<Stream<Item=Readings, Error=io::Error>>; } pub struct OneWireSensor { } impl OneWireSensor { fn new() -> OneWireSensor { OneWireSensor {} // todo } fn step(&mut self) -> Readings { let mut r = Readings::new(); r.add("ambient", Some(31.2)); r.add("wort_todo", Some(8.0)); debug!("sensor step {:?}", r); r } } impl Sensor for OneWireSensor { fn stream(handle: &Handle) -> Box<Stream<Item=Readings, Error=io::Error>> { let mut s = OneWireSensor::new(); let dur = Duration::from_millis(600); Interval::new(dur, handle).unwrap().map(move |()| { s.step() }).boxed() } } pub struct TestSensor { } impl TestSensor { fn step(&mut self) -> Readings { let mut r = Readings::new(); r.add("ambient", Some(31.2)); r.add("wort", Some(Self::try_read("test_wort.txt").unwrap_or_else(|_| 18.0))); r.add("fridge", Some(Self::try_read("test_fridge.txt").unwrap_or_else(|_| 20.0))); r } fn try_read(filename: &str) -> Result<f32, String> { File::open(filename) .map_err(|e| e.to_string()) .and_then(|mut f| { let mut s = String::new(); f.read_to_string(&mut s) .map_err(|e| e.to_string()) .map(|_| s) }) .and_then(|s| { s.trim().parse::<f32>() .map_err(|e| e.to_string()) }) } } impl Sensor for TestSensor { fn stream(handle: &Handle) -> Box<Stream<Item=Readings, Error=io::Error>> { let mut s = TestSensor {}; let dur = Duration::new(1,0); Interval::new(dur, handle).unwrap().map(move |()| { s.step() }).boxed() } }