-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathbus.rs
86 lines (72 loc) · 1.85 KB
/
bus.rs
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
use core::cell::RefCell;
use embedded_hal::{
delay::DelayNs,
i2c::{self, ErrorType, I2c},
};
/// Nearly-verbatim copy of the trait specified by the shared_bus crate
pub trait BusMutex {
/// The actual bus that is wrapped inside this mutex.
type Bus;
/// Create a new mutex of this type.
fn create(v: Self::Bus) -> Self;
/// Lock the mutex and give a closure access to the bus inside.
fn lock<R, F: FnOnce(&mut Self::Bus) -> R>(&self, f: F) -> R;
}
#[derive(Debug)]
pub struct RefCellBus<T>(RefCell<T>);
impl<T> BusMutex for RefCellBus<T> {
type Bus = T;
fn create(v: Self::Bus) -> Self {
Self(RefCell::new(v))
}
fn lock<R, F: FnOnce(&mut Self::Bus) -> R>(&self, f: F) -> R {
let bus = &mut *self.0.borrow_mut();
f(bus)
}
}
#[cfg(feature = "std")]
impl<T> BusMutex for std::sync::Mutex<T> {
type Bus = T;
fn create(v: Self::Bus) -> Self {
std::sync::Mutex::new(v)
}
fn lock<R, F: FnOnce(&mut Self::Bus) -> R>(&self, f: F) -> R {
let mut v = self.lock().unwrap();
f(&mut v)
}
}
#[derive(Debug)]
pub struct Bus<'a, M>(pub(crate) &'a M);
// Delay implementation
impl<DELAY, I2C, M> DelayNs for Bus<'_, M>
where
DELAY: DelayNs,
I2C: I2c,
M: BusMutex<Bus = (DELAY, I2C)>,
{
fn delay_ns(&mut self, ns: u32) {
self.0.lock(|bus| bus.0.delay_ns(ns))
}
}
impl<DELAY, I2C, M> ErrorType for Bus<'_, M>
where
DELAY: DelayNs,
I2C: I2c,
M: BusMutex<Bus = (DELAY, I2C)>,
{
type Error = I2C::Error;
}
impl<DELAY, I2C, M> I2c for Bus<'_, M>
where
DELAY: DelayNs,
I2C: I2c,
M: BusMutex<Bus = (DELAY, I2C)>,
{
fn transaction(
&mut self,
address: u8,
operations: &mut [i2c::Operation<'_>],
) -> Result<(), Self::Error> {
self.0.lock(|bus| bus.1.transaction(address, operations))
}
}