view rust/src/main.rs @ 588:038734052b20 rust

fiddling with futures-rs instead
author Matt Johnston <matt@ucc.asn.au>
date Fri, 16 Dec 2016 01:10:57 +0800
parents 646f03870762
children f2508125adf1
line wrap: on
line source

#![feature(conservative_impl_trait)]
extern crate tokio_core;
extern crate futures;

use std::time::Duration;
use std::cell::RefCell;

use tokio_core::reactor::Interval;
use tokio_core::reactor::Core;
use tokio_core::reactor::Handle;
use futures::Stream;
use futures::Future;
use futures::IntoFuture;

pub struct Reading {
    name: String,
    value: Option<f32>,
}

pub type Readings = Vec<Reading>;

pub struct Sensor {
    current: f32,
}

impl Sensor {

    fn step(&mut self) -> Readings {
        let mut r = Vec::new();
        self.current = self.current + 0.1;
        r.push(Reading { name: "aaa".to_string(), value: Some(self.current) });
        r
    }

    pub fn new() -> Sensor {
        Sensor { current: 22.0 }
    }

    pub fn run(handle: &Handle) -> impl Stream<Item=Readings> {
        let mut s = Sensor::new();

        let dur = Duration::from_millis(400);
        Interval::new(dur, handle).unwrap().map(move |()| {
            println!("each one");
            // TODO read the sensor here
            s.step()
        }   )
    }
}

fn main() {
    println!("Wort Templog");

    let mut core = Core::new().unwrap();
    let handle = core.handle();

    let s = Sensor::run(&handle);

    let mut re = Readings::new();

    let h = s.for_each(|r| {
        re = r;
        for rx in &re {
            match rx.value {
                Some(x) => println!("re is {} {}", rx.name, x),
                None => println!("re is {} broken", rx.name),
            }
        };
        Ok(())
    });

    core.run(h);
}