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
use hal::blocking::i2c;
use mutex;
#[cfg(feature = "std")]
use std::cell;
#[cfg(not(feature = "std"))]
use core::cell;
#[cfg(feature = "std")]
use std::marker;
#[cfg(not(feature = "std"))]
use core::marker;
pub struct BusManager<M: mutex::BusMutex<cell::RefCell<T>>, T>(M, marker::PhantomData<T>);
impl<M: mutex::BusMutex<cell::RefCell<T>>, T> BusManager<M, T> {
pub fn new(d: T) -> BusManager<M, T> {
let mutex = M::create(cell::RefCell::new(d));
BusManager(mutex, marker::PhantomData)
}
pub fn acquire<'a>(&'a self) -> BusProxy<'a, M, T> {
BusProxy(&self.0, marker::PhantomData)
}
}
pub struct BusProxy<'a, M: 'a + mutex::BusMutex<cell::RefCell<T>>, T>(
&'a M,
marker::PhantomData<T>
);
impl<'a, M: 'a + mutex::BusMutex<cell::RefCell<T>>, T: i2c::Write> i2c::Write
for BusProxy<'a, M, T> {
type Error = T::Error;
fn write(&mut self, addr: u8, bytes: &[u8]) -> Result<(), Self::Error> {
self.0.lock(|lock| {
let mut i = lock.borrow_mut();
i.write(addr, bytes)
})
}
}
impl<'a, M: 'a + mutex::BusMutex<cell::RefCell<T>>, T: i2c::Read> i2c::Read for BusProxy<'a, M, T> {
type Error = T::Error;
fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Self::Error> {
self.0.lock(|lock| {
let mut i = lock.borrow_mut();
i.read(address, buffer)
})
}
}
impl<'a, M: 'a + mutex::BusMutex<cell::RefCell<T>>, T: i2c::WriteRead> i2c::WriteRead
for BusProxy<'a, M, T> {
type Error = T::Error;
fn write_read(
&mut self,
address: u8,
bytes: &[u8],
buffer: &mut [u8],
) -> Result<(), Self::Error> {
self.0.lock(|lock| {
let mut i = lock.borrow_mut();
i.write_read(address, bytes, buffer)
})
}
}