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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
use crate::{
types::{device, Error},
Result,
};
use tokio::sync::{mpsc, oneshot};
#[derive(Debug, PartialEq, Eq)]
pub struct DevInfoReply {
pub name: device::Name,
pub units: Option<String>,
pub settable: bool,
pub driver: String,
}
pub enum Request {
QueryDeviceInfo {
pattern: Option<String>,
rpy_chan: oneshot::Sender<Result<Vec<DevInfoReply>>>,
},
SetDevice {
name: device::Name,
value: device::Value,
rpy_chan: oneshot::Sender<Result<device::Value>>,
},
MonitorDevice {
name: device::Name,
rpy_chan: oneshot::Sender<Result<device::DataStream<device::Reading>>>,
},
}
#[derive(Clone)]
pub struct RequestChan {
req_chan: mpsc::Sender<Request>,
}
impl RequestChan {
pub fn new(req_chan: mpsc::Sender<Request>) -> Self {
RequestChan { req_chan }
}
pub async fn monitor_device(
&self, name: device::Name,
) -> Result<device::DataStream<device::Reading>> {
let (tx, rx) = oneshot::channel();
let msg = Request::MonitorDevice { name, rpy_chan: tx };
self.req_chan.send(msg).await?;
rx.await?
}
pub async fn set_device<
T: Into<device::Value> + TryFrom<device::Value, Error = Error>,
>(
&self, name: device::Name, value: T,
) -> Result<T> {
let (tx, rx) = oneshot::channel();
let msg = Request::SetDevice {
name,
value: value.into(),
rpy_chan: tx,
};
self.req_chan.send(msg).await?;
rx.await?.and_then(T::try_from)
}
pub async fn get_device_info(
&self, pattern: Option<String>,
) -> Result<Vec<DevInfoReply>> {
let (rpy_chan, rx) = oneshot::channel();
self.req_chan
.send(Request::QueryDeviceInfo { pattern, rpy_chan })
.await?;
rx.await.map_err(|e| e.into()).and_then(|v| v)
}
}