1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use config;
use measurement::{self, Measurement};
use futures::{Future, Stream};
use hyper::Client;
use hyper::client::{FutureResponse, HttpConnector};
use std::str;
use tokio_core::reactor::Core;

error_chain! {
    errors {

    }
    links {
        ReadingMeasurementFailed(measurement::Error, measurement::ErrorKind);
    }
    foreign_links {
        Fmt(::std::str::Utf8Error);
        Io(::std::io::Error);
        Hyper(::hyper::Error);
    }
}

#[derive(Debug, Deserialize, Serialize)]
#[derive(PartialEq)]
pub struct Sensor {
    pub name: String,
    pub id: String,
    pub ui_uri: String,
    pub data_uri: String,
    pub threshold_pm10: Option<f32>,
    pub threshold_pm2: Option<f32>,
    pub e_mail_addr: Option<String>,
    pub e_mail_subject: Option<String>,
    pub e_mail_condition: Option<config::EmailCondition>,
}

impl Sensor {
    pub fn new<T: Into<String>>(name: T, id: T, ui_uri: T, data_uri: T) -> Sensor {
        Sensor {
            name: name.into(),
            id: id.into(),
            ui_uri: ui_uri.into(),
            data_uri: data_uri.into(),
            threshold_pm10: None,
            threshold_pm2: None,
            e_mail_addr: None,
            e_mail_subject: None,
            e_mail_condition: None,
        }
    }

    pub fn read_measurement(
        self: Self,
        response: FutureResponse,
    ) -> Box<Future<Item = Measurement, Error = Error>> {
        let m = response
            .and_then(|res| res.body().concat2())
            .map(|body| {
                let json = str::from_utf8(&body)?;
                Measurement::from_json(self, json).map_err(|e| e.into())
            })
            .map_err(|e| e.into())
            .and_then(|x| x);
        Box::new(m)
    }
}

pub fn create_sensor_reader(core: &mut Core) -> Client<HttpConnector> {
    Client::new(&core.handle())
}