view rust/src/sensor.rs @ 595:e87655ed8429 rust

add config
author Matt Johnston <matt@ucc.asn.au>
date Thu, 05 Jan 2017 23:26:00 +0800
parents aff50ee77252
children ca8102feaca6
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 {
    master_dir: String,
}

impl OneWireSensor {
    fn new() -> OneWireSensor {
        OneWireSensor {
            master_dir: String::new(), // XXX
            
        }
        // 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
    }

    fn sensor_names(self) -> Vec<String> {
        let mut names = vec![];
        names
    }
}

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()
    }
}