view rust/src/sensor.rs @ 633:490e9e15b98c rust

move some bits to riker
author Matt Johnston <matt@ucc.asn.au>
date Wed, 04 Sep 2019 23:24:13 +0800
parents bde302def78e
children a5721c02d3ee
line wrap: on
line source

use riker::actors::*;

use std::time::Duration;
use std::io;
use std::fs::File;
use std::io::{Read,BufReader,BufRead};
use std::path::PathBuf;

use std::str::FromStr;

use super::types::*;
use super::config::Config;

pub struct OneWireSensor {
    config: Config,
    chan: ChannelRef<Readings>,
}

struct SendReading;

trait Sensor {
}

impl Actor for dyn Sensor {
    type Msg = SendReading;

    fn recv(&mut self,
            ctx: &Context<Self::Msg>,
            msg: Self::Msg,
            sender: Sender) {
        self.chan.tell(Publish{msg: self.get_readings(), topic: "readings".into()}, None);
    }

    fn post_start(&mut self, ctx: &Context<Self::Msg>) {
        self.chan = channel("readings", &ctx.system).unwrap();
        let dur = Duration::new(self.config.SENSOR_SLEEP,0);
        ctx.schedule(Duration::from_millis(0), dur, self, None, SendReading);
    }
}

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

    fn get_readings(&self) -> Readings {
        let mut r = Readings::new();

        if let Ok(names) = self.sensor_names() {
            for n in &names {
                match self.read_sensor(n) {
                    Ok(s) => r.add(n, s),
                    Err(e) => debug!("Error reading sensors {}: {}", n, e)
                }
            }
        }

        debug!("sensor step {:?}", r);
        r
    }

    fn read_sensor(&self, n: &str) -> Result<f32, TemplogError> {
        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 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>, TemplogError> {
        // TODO: needs to handle multiple busses.
        let mut path = PathBuf::from(&self.config.SENSOR_BASE_DIR);
        path.push("w1_master_slaves");

        let f = BufReader::new(File::open(path)?);
        let s = f.lines().collect::<Result<Vec<String>, io::Error>>()?;
        Ok(s)
    }
}

impl Sensor for OneWireSensor {
}

#[derive(Clone)]
pub struct TestSensor {
    config: Config,
}

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

    fn test_step() -> Readings {
        let mut r = Readings::new();
        r.add("ambient", 31.2);
        r.add("wort", Self::try_read("test_wort.txt").unwrap_or_else(|_| 18.0));
        r.add("fridge", Self::try_read("test_fridge.txt").unwrap_or_else(|_| 20.0));
        r
    }

    fn try_read(filename: &str) -> Result<f32, TemplogError> {
        let mut s = String::new();
        File::open(filename)?.read_to_string(&mut s)?;
        Ok(s.trim().parse::<f32>()?)
    }
}

impl Sensor for TestSensor {
}