view rust/src/sensor.rs @ 599:f71cf1ad745f rust

updated toml serde works OK
author Matt Johnston <matt@ucc.asn.au>
date Tue, 07 Feb 2017 22:35:29 +0800
parents ca8102feaca6
children 8c21df3711e2
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::*;
use config::Config;

pub trait Sensor {
    fn stream(handle: &Handle, config: &Config)
        -> Box<Stream<Item=Readings, Error=io::Error>>;
}

pub struct OneWireSensor {
    config: Config,
}

impl OneWireSensor {
    fn new(config: &Config) -> OneWireSensor {
        OneWireSensor {
            config: config.clone(),
        }
    }

    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, config: &Config)
        -> Box<Stream<Item=Readings, Error=io::Error>> {
        let mut s = OneWireSensor::new(config);

        let dur = Duration::new(s.config.SENSOR_SLEEP,0);
        Interval::new(dur, handle).unwrap().map(move |()| {
            s.step()
        }).boxed()
    }
}

pub struct TestSensor {
    config: Config,
}

impl TestSensor {
    pub fn new(config: &Config) -> Self {
        TestSensor {
            config: config.clone(),
        }
    }

    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, config: &Config)
        -> Box<Stream<Item=Readings, Error=io::Error>> {
        let mut s = TestSensor::new(config);

        let dur = Duration::new(s.config.SENSOR_SLEEP,0);
        Interval::new(dur, handle).unwrap().map(move |()| {
            s.step()
        }).boxed()
    }
}