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
use crate::reading::{Message, Reading, Type};
use crate::services::Service;
use crate::threading;
use crate::value::Value;
use crate::Result;
use bus::Bus;
use chrono::Local;
use crossbeam_channel::Sender;
use serde::Deserialize;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
pub struct Db {
service_id: String,
interval: Duration,
}
#[derive(Deserialize, Debug, Clone)]
pub struct Settings {
pub interval_ms: Option<u64>,
}
impl Db {
pub fn new(service_id: &str, settings: &Settings) -> Db {
Db {
service_id: service_id.into(),
interval: Duration::from_millis(settings.interval_ms.unwrap_or(1000)),
}
}
}
impl Service for Db {
fn spawn(
self: Box<Self>,
db: Arc<Mutex<crate::db::Db>>,
tx: &Sender<Message>,
_rx: &mut Bus<Message>,
) -> Result<()> {
let tx = tx.clone();
let sensor = format!("{}::size", &self.service_id);
threading::spawn(format!("my-iot::db:{}", &self.service_id), move || loop {
let size = { db.lock().unwrap().select_size().unwrap() };
tx.try_send(Message {
type_: Type::Actual,
reading: Reading {
sensor: sensor.clone(),
value: Value::Size(size),
timestamp: Local::now(),
},
})
.unwrap();
thread::sleep(self.interval);
})?;
Ok(())
}
}