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
extern crate futures;
use futures::{Poll, Stream};
#[derive(Copy,Clone,Debug,Eq,PartialEq)]
pub enum Direction {
CW,
CCW,
}
impl Direction {
pub fn from(old: (u8, u8), new: (u8, u8)) -> Option<Self> {
use Direction::*;
match (old, new) {
((0, 0), (0, 1)) => Some(CW),
((0, 1), (1, 1)) => Some(CW),
((1, 1), (1, 0)) => Some(CW),
((1, 0), (0, 0)) => Some(CW),
((1, 0), (1, 1)) => Some(CCW),
((1, 1), (0, 1)) => Some(CCW),
((0, 1), (0, 0)) => Some(CCW),
((0, 0), (1, 0)) => Some(CCW),
_ => None,
}
}
}
#[derive(Copy,Clone,Debug,Eq,PartialEq)]
enum Pin {
A,
B,
}
type InternalStream<S> where S: Stream<Item = u8> + 'static =
Box<Stream<Item = Direction, Error = S::Error> + 'static>;
pub struct RotaryEncoder<S>(InternalStream<S>) where S: Stream<Item = u8> + 'static;
impl<S> RotaryEncoder<S>
where S: Stream<Item = u8>
{
pub fn new(a: S, b: S) -> Self {
let mut values = (2, 2);
RotaryEncoder(Box::new(a.map(|v| (Pin::A, v))
.select(b.map(|v| (Pin::B, v)))
.filter_map(move |(p, val)| {
let previous = values;
match p {
Pin::A => values.0 = val,
Pin::B => values.1 = val,
}
Direction::from(previous, values)
})))
}
}
impl<S> Stream for RotaryEncoder<S>
where S: Stream<Item = u8> + 'static
{
type Item = Direction;
type Error = S::Error;
fn poll(&mut self) -> Poll<Option<Direction>, S::Error> {
self.0.poll()
}
}