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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use std::fmt::{Display, Formatter};
use std::sync::Arc;
use parking_lot::RwLock;
use crate::devices::input::{Input, InputEvent};
use crate::devices::Device;
use crate::errors::Error;
use crate::hardware::Hardware;
use crate::io::{IoProtocol, PinIdOrName, PinModeId};
use crate::pause;
use crate::utils::{task, EventHandler, EventManager, State, TaskHandler};
/// Represents a digital sensor of unspecified type: an [`Input`] [`Device`] that reads digital values
/// from an INPUT compatible pin.
/// <https://docs.arduino.cc/built-in-examples/digital/DigitalInput>
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug)]
pub struct DigitalInput {
// ########################################
// # Basics
/// The pin (id) of the [`Board`] used to read the digital value.
pin: u8,
/// The current digital state.
#[cfg_attr(feature = "serde", serde(with = "crate::devices::arc_rwlock_serde"))]
state: Arc<RwLock<bool>>,
// ########################################
// # Volatile utility data.
#[cfg_attr(feature = "serde", serde(skip))]
protocol: Box<dyn IoProtocol>,
/// Inner handler to the task running the button value check.
#[cfg_attr(feature = "serde", serde(skip))]
handler: Arc<RwLock<Option<TaskHandler>>>,
/// The event manager for the DigitalInput.
#[cfg_attr(feature = "serde", serde(skip))]
events: EventManager,
}
impl DigitalInput {
/// Creates an instance of a [`DigitalInput`] attached to a given board.
///
/// # Errors
/// * `UnknownPin`: this function will bail an error if the DigitalInput pin does not exist for this board.
/// * `IncompatiblePin`: this function will bail an error if the DigitalInput pin does not support ANALOG mode.
pub fn new<T: Into<PinIdOrName>>(board: &dyn Hardware, pin: T) -> Result<Self, Error> {
let pin = board.get_io().read().get_pin(pin)?.clone();
let mut sensor = Self {
pin: pin.id,
state: Arc::new(RwLock::new(pin.value != 0)),
protocol: board.get_protocol(),
handler: Arc::new(RwLock::new(None)),
events: Default::default(),
};
// Set pin mode to INPUT.
sensor.protocol.set_pin_mode(sensor.pin, PinModeId::INPUT)?;
// Set reporting for this pin.
sensor.protocol.report_digital(sensor.pin, true)?;
// Attaches the event handler.
sensor.attach();
Ok(sensor)
}
// ########################################
// Getters and Setters
/// Returns the pin (id) used by the device.
pub fn get_pin(&self) -> u8 {
self.pin
}
// ########################################
// Event related functions
/// Manually attaches the DigitalInput with the value change events.
/// This should never be needed unless you manually `detach()` the DigitalInput first for some reason
/// and want it to start being reactive to events again.
pub fn attach(&self) {
if self.handler.read().is_none() {
let self_clone = self.clone();
*self.handler.write() = Some(
task::run(async move {
loop {
let pin_value = self_clone
.protocol
.get_io()
.read()
.get_pin(self_clone.pin)?
.value
!= 0;
let state_value = *self_clone.state.read();
if pin_value != state_value {
*self_clone.state.write() = pin_value;
self_clone.events.emit(InputEvent::OnChange, pin_value);
match pin_value {
true => self_clone.events.emit(InputEvent::OnHigh, ()),
false => self_clone.events.emit(InputEvent::OnLow, ()),
}
}
// Change can only be done 10x a sec. to avoid bouncing.
pause!(100);
}
#[allow(unreachable_code)]
Ok(())
})
.unwrap(),
);
}
}
/// Detaches the interval associated with the DigitalInput.
/// This means the DigitalInput won't react anymore to value changes.
pub fn detach(&self) {
if let Some(handler) = self.handler.read().as_ref() {
handler.abort();
}
*self.handler.write() = None
}
/// Registers a callback to be executed on a given event on the DigitalInput.
///
/// Available events for a button are:
/// - **`InputEvent::OnChange` | `change`:** Triggered when the input value changes.
/// _The callback must receive the following parameter: `|value: bool| { ... }`_
/// - **`InputEvent::OnHigh` | `high`:** Triggered when the input value changes.
/// _The callback must receive the void parameter: `|_:()| { ... }`_
///- **`InputEvent::OnLow` | `low`:** Triggered when the input value changes.
/// _The callback must receive the void parameter: `|_:()| { ... }`_
///
/// # Example
///
/// ```
/// use hermes_five::devices::{DigitalInput, InputEvent};
/// use hermes_five::hardware::{Board, BoardEvent};
///
/// #[hermes_five::runtime]
/// async fn main() {
/// let board = Board::run();
/// board.on(BoardEvent::OnReady, |board: Board| async move {
///
/// // Register a sensor on pin 7.
/// let sensor = DigitalInput::new(&board, 7)?;
/// // Triggered function when the sensor state changes.
/// sensor.on(InputEvent::OnChange, |value: bool| async move {
/// println!("Sensor value changed: {}", value);
/// Ok(())
/// });
///
/// // The above code will run forever.
/// // <do something useful>
///
/// // The above code will run forever runs a listener on the pin state under-the-hood.
/// // It means the program will run forever listening to the InputEvent,
/// // until we detach the device and close the board.
/// sensor.detach();
/// board.close();
///
/// Ok(())
/// });
/// }
/// ```
pub fn on<S, F, T, Fut>(&self, event: S, callback: F) -> EventHandler
where
S: Into<String>,
T: 'static + Send + Sync + Clone,
F: FnMut(T) -> Fut + Send + 'static,
Fut: std::future::Future<Output = Result<(), Error>> + Send + 'static,
{
self.events.on(event, callback)
}
}
impl Display for DigitalInput {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"DigitalInput (pin={}) [state={}]",
self.pin,
self.state.read(),
)
}
}
#[cfg_attr(feature = "serde", typetag::serde)]
impl Device for DigitalInput {}
#[cfg_attr(feature = "serde", typetag::serde)]
impl Input for DigitalInput {
fn get_state(&self) -> State {
State::from(*self.state.read())
}
}
#[cfg(test)]
mod tests {
use crate::devices::input::digital::DigitalInput;
use crate::devices::input::Input;
use crate::devices::input::InputEvent;
use crate::hardware::Board;
use crate::mocks::plugin_io::MockIoProtocol;
use crate::pause;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
#[hermes_five_macros::test]
fn test_new_digital_input() {
let board = Board::new(MockIoProtocol::default());
let sensor = DigitalInput::new(&board, 2).unwrap();
assert_eq!(sensor.get_pin(), 2);
assert!(sensor.get_state().as_bool());
sensor.detach();
let sensor = DigitalInput::new(&board, "D3").unwrap();
assert_eq!(sensor.get_pin(), 3);
assert!(sensor.get_state().as_bool());
sensor.detach();
board.close();
}
#[hermes_five_macros::test]
fn test_digital_display() {
let board = Board::new(MockIoProtocol::default());
let sensor = DigitalInput::new(&board, "D5").unwrap();
assert!(!sensor.get_state().as_bool());
assert_eq!(
format!("{}", sensor),
String::from("DigitalInput (pin=5) [state=false]")
);
sensor.detach();
board.close();
}
#[hermes_five_macros::test]
fn test_digital_events() {
let board = Board::new(MockIoProtocol::default());
let button = DigitalInput::new(&board, 5).unwrap();
// CHANGE
let change_flag = Arc::new(AtomicBool::new(false));
let moved_change_flag = change_flag.clone();
button.on(InputEvent::OnChange, move |new_state: bool| {
let captured_flag = moved_change_flag.clone();
async move {
captured_flag.store(new_state, Ordering::SeqCst);
Ok(())
}
});
// HIGH
let high_flag = Arc::new(AtomicBool::new(false));
let moved_high_flag = high_flag.clone();
button.on(InputEvent::OnHigh, move |_: ()| {
let captured_flag = moved_high_flag.clone();
async move {
captured_flag.store(true, Ordering::SeqCst);
Ok(())
}
});
// LOW
let low_flag = Arc::new(AtomicBool::new(false));
let moved_low_flag = low_flag.clone();
button.on(InputEvent::OnLow, move |_: ()| {
let captured_flag = moved_low_flag.clone();
async move {
captured_flag.store(true, Ordering::SeqCst);
Ok(())
}
});
assert!(!change_flag.load(Ordering::SeqCst));
assert!(!high_flag.load(Ordering::SeqCst));
assert!(!low_flag.load(Ordering::SeqCst));
// Simulate pin state change in the protocol => take value 0xFF
button
.protocol
.get_io()
.write()
.get_pin_mut(5)
.unwrap()
.value = 0xFF;
pause!(500);
assert!(change_flag.load(Ordering::SeqCst));
assert!(high_flag.load(Ordering::SeqCst));
assert!(!low_flag.load(Ordering::SeqCst));
// Simulate pin state change in the protocol => takes value 0
button
.protocol
.get_io()
.write()
.get_pin_mut(5)
.unwrap()
.value = 0;
pause!(500);
assert!(!change_flag.load(Ordering::SeqCst)); // change switched back to 0
assert!(low_flag.load(Ordering::SeqCst));
button.detach();
board.close();
}
}