view rust/src/sensor.rs @ 591:4a944663fa8d rust

more skeleton
author Matt Johnston <matt@ucc.asn.au>
date Fri, 23 Dec 2016 00:33:19 +0800
parents dccd8504aa38
children 03b48ec0bb03
line wrap: on
line source

extern crate tokio_core;
extern crate futures;

use std::time::Duration;
use std::io;

use tokio_core::reactor::Interval;
use tokio_core::reactor::Handle;
use futures::Stream;

#[derive(Debug)]
pub struct Reading {
    name: String,
    value: Option<f32>,
}

pub struct Sensor {
    current: f32,
    suf: String,
}

impl Sensor {
    fn step(&mut self) -> Vec<Reading> {
        let mut r = Vec::new();
        self.current = self.current + 0.1;
        r.push(Reading { name: "aaa".to_string() + &self.suf, value: Some(self.current) });
        r.push(Reading { name: "b".to_string() + &self.suf, value: Some(self.current/3.0) });
        r
    }

    fn new(suffix: String) -> Self {
        Sensor { current: 22.0, suf: suffix }
    }

    pub fn run(handle: &Handle, rate: u64, suffix: String) -> Box<Stream<Item=Vec<Reading>, Error=io::Error>> {
        let mut s = Sensor::new(suffix);

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