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
#![no_std]
use core::sync::atomic::{AtomicBool, Ordering};
use embedded_hal::blocking::{i2c, spi};
pub type SharedBus<T> = &'static CommonBus<T>;
pub struct CommonBus<BUS> {
bus: core::cell::UnsafeCell<BUS>,
busy: AtomicBool,
}
impl<BUS> CommonBus<BUS> {
pub fn new(bus: BUS) -> Self {
CommonBus {
bus: core::cell::UnsafeCell::new(bus),
busy: AtomicBool::from(false),
}
}
fn lock<R, F: FnOnce(&mut BUS) -> R>(&self, f: F) -> R {
self.busy
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
.expect("Bus conflict");
let result = f(unsafe { &mut *self.bus.get() });
self.busy.store(false, Ordering::SeqCst);
result
}
pub fn acquire(&self) -> &Self {
self
}
}
unsafe impl<BUS> Sync for CommonBus<BUS> {}
impl<BUS: i2c::Read> i2c::Read for &CommonBus<BUS> {
type Error = BUS::Error;
fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Self::Error> {
self.lock(|bus| bus.read(address, buffer))
}
}
impl<BUS: i2c::Write> i2c::Write for &CommonBus<BUS> {
type Error = BUS::Error;
fn write(&mut self, address: u8, buffer: &[u8]) -> Result<(), Self::Error> {
self.lock(|bus| bus.write(address, buffer))
}
}
impl<BUS: i2c::WriteRead> i2c::WriteRead for &CommonBus<BUS> {
type Error = BUS::Error;
fn write_read(
&mut self,
address: u8,
bytes: &[u8],
buffer: &mut [u8],
) -> Result<(), Self::Error> {
self.lock(|bus| bus.write_read(address, bytes, buffer))
}
}
impl<BUS: spi::Transfer<u8>> spi::Transfer<u8> for &CommonBus<BUS> {
type Error = BUS::Error;
fn transfer<'w>(&mut self, words: &'w mut [u8]) -> Result<&'w [u8], Self::Error> {
self.lock(move |bus| bus.transfer(words))
}
}
impl<BUS: spi::Write<u8>> spi::Write<u8> for &CommonBus<BUS> {
type Error = BUS::Error;
fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
self.lock(|bus| bus.write(words))
}
}
#[macro_export]
macro_rules! new {
($bus:ident, $T:ty) => {
unsafe {
static mut _MANAGER: core::mem::MaybeUninit<shared_bus_rtic::CommonBus<$T>> =
core::mem::MaybeUninit::uninit();
_MANAGER = core::mem::MaybeUninit::new(shared_bus_rtic::CommonBus::new($bus));
&*_MANAGER.as_ptr()
};
};
}