aboutsummaryrefslogtreecommitdiff
path: root/embassy-extras/src
diff options
context:
space:
mode:
authorThales Fragoso <[email protected]>2021-03-07 20:15:40 -0300
committerThales Fragoso <[email protected]>2021-03-07 20:15:40 -0300
commit15c3e78408a2835003b9d7dee0b7fbae544d10ba (patch)
tree2f511983d6efa69c5055e9aad888ce0899624cd0 /embassy-extras/src
parentf922cf1609c9baebf8dead87161df215f35df449 (diff)
Move nRF's util into a separate crate
Diffstat (limited to 'embassy-extras/src')
-rw-r--r--embassy-extras/src/fmt.rs119
-rw-r--r--embassy-extras/src/lib.rs17
-rw-r--r--embassy-extras/src/peripheral.rs119
-rw-r--r--embassy-extras/src/ring_buffer.rs80
4 files changed, 335 insertions, 0 deletions
diff --git a/embassy-extras/src/fmt.rs b/embassy-extras/src/fmt.rs
new file mode 100644
index 000000000..1be1057a7
--- /dev/null
+++ b/embassy-extras/src/fmt.rs
@@ -0,0 +1,119 @@
1#![macro_use]
2#![allow(clippy::module_inception)]
3
4#[cfg(all(feature = "defmt", feature = "log"))]
5compile_error!("You may not enable both `defmt` and `log` features.");
6
7pub use fmt::*;
8
9#[cfg(feature = "defmt")]
10mod fmt {
11 pub use defmt::{
12 assert, assert_eq, assert_ne, debug, debug_assert, debug_assert_eq, debug_assert_ne, error,
13 info, panic, todo, trace, unreachable, unwrap, warn,
14 };
15}
16
17#[cfg(feature = "log")]
18mod fmt {
19 pub use core::{
20 assert, assert_eq, assert_ne, debug_assert, debug_assert_eq, debug_assert_ne, panic, todo,
21 unreachable,
22 };
23 pub use log::{debug, error, info, trace, warn};
24}
25
26#[cfg(not(any(feature = "defmt", feature = "log")))]
27mod fmt {
28 #![macro_use]
29
30 pub use core::{
31 assert, assert_eq, assert_ne, debug_assert, debug_assert_eq, debug_assert_ne, panic, todo,
32 unreachable,
33 };
34
35 #[macro_export]
36 macro_rules! trace {
37 ($($msg:expr),+ $(,)?) => {
38 ()
39 };
40 }
41
42 #[macro_export]
43 macro_rules! debug {
44 ($($msg:expr),+ $(,)?) => {
45 ()
46 };
47 }
48
49 #[macro_export]
50 macro_rules! info {
51 ($($msg:expr),+ $(,)?) => {
52 ()
53 };
54 }
55
56 #[macro_export]
57 macro_rules! warn {
58 ($($msg:expr),+ $(,)?) => {
59 ()
60 };
61 }
62
63 #[macro_export]
64 macro_rules! error {
65 ($($msg:expr),+ $(,)?) => {
66 ()
67 };
68 }
69}
70
71#[cfg(not(feature = "defmt"))]
72#[macro_export]
73macro_rules! unwrap {
74 ($arg:expr) => {
75 match $crate::fmt::Try::into_result($arg) {
76 ::core::result::Result::Ok(t) => t,
77 ::core::result::Result::Err(e) => {
78 ::core::panic!("unwrap of `{}` failed: {:?}", ::core::stringify!($arg), e);
79 }
80 }
81 };
82 ($arg:expr, $($msg:expr),+ $(,)? ) => {
83 match $crate::fmt::Try::into_result($arg) {
84 ::core::result::Result::Ok(t) => t,
85 ::core::result::Result::Err(e) => {
86 ::core::panic!("unwrap of `{}` failed: {}: {:?}", ::core::stringify!($arg), ::core::format_args!($($msg,)*), e);
87 }
88 }
89 }
90}
91
92#[derive(Debug, Copy, Clone, Eq, PartialEq)]
93pub struct NoneError;
94
95pub trait Try {
96 type Ok;
97 type Error;
98 fn into_result(self) -> Result<Self::Ok, Self::Error>;
99}
100
101impl<T> Try for Option<T> {
102 type Ok = T;
103 type Error = NoneError;
104
105 #[inline]
106 fn into_result(self) -> Result<T, NoneError> {
107 self.ok_or(NoneError)
108 }
109}
110
111impl<T, E> Try for Result<T, E> {
112 type Ok = T;
113 type Error = E;
114
115 #[inline]
116 fn into_result(self) -> Self {
117 self
118 }
119}
diff --git a/embassy-extras/src/lib.rs b/embassy-extras/src/lib.rs
new file mode 100644
index 000000000..4a95173cf
--- /dev/null
+++ b/embassy-extras/src/lib.rs
@@ -0,0 +1,17 @@
1#![no_std]
2
3// This mod MUST go first, so that the others see its macros.
4pub(crate) mod fmt;
5
6pub mod peripheral;
7pub mod ring_buffer;
8
9/// Low power blocking wait loop using WFE/SEV.
10pub fn low_power_wait_until(mut condition: impl FnMut() -> bool) {
11 while !condition() {
12 // WFE might "eat" an event that would have otherwise woken the executor.
13 cortex_m::asm::wfe();
14 }
15 // Retrigger an event to be transparent to the executor.
16 cortex_m::asm::sev();
17}
diff --git a/embassy-extras/src/peripheral.rs b/embassy-extras/src/peripheral.rs
new file mode 100644
index 000000000..e9357969d
--- /dev/null
+++ b/embassy-extras/src/peripheral.rs
@@ -0,0 +1,119 @@
1use core::cell::UnsafeCell;
2use core::marker::{PhantomData, PhantomPinned};
3use core::mem::MaybeUninit;
4use core::pin::Pin;
5use core::sync::atomic::{compiler_fence, Ordering};
6
7use embassy::interrupt::{Interrupt, InterruptExt};
8
9use crate::fmt::assert;
10
11pub trait PeripheralState {
12 type Interrupt: Interrupt;
13 fn on_interrupt(&mut self);
14}
15
16#[derive(Clone, Copy, PartialEq, Eq, Debug)]
17enum Life {
18 Ready,
19 Created,
20 Freed,
21}
22
23pub struct PeripheralMutex<S: PeripheralState> {
24 life: Life,
25
26 state: MaybeUninit<UnsafeCell<S>>, // Init if life != Freed
27 irq: MaybeUninit<S::Interrupt>, // Init if life != Freed
28
29 _not_send: PhantomData<*mut ()>,
30 _pinned: PhantomPinned,
31}
32
33impl<S: PeripheralState> PeripheralMutex<S> {
34 pub fn new(state: S, irq: S::Interrupt) -> Self {
35 Self {
36 life: Life::Created,
37 state: MaybeUninit::new(UnsafeCell::new(state)),
38 irq: MaybeUninit::new(irq),
39 _not_send: PhantomData,
40 _pinned: PhantomPinned,
41 }
42 }
43
44 /// safety: self must be pinned.
45 unsafe fn setup(&mut self) {
46 assert!(self.life == Life::Created);
47
48 let irq = &mut *self.irq.as_mut_ptr();
49 irq.disable();
50 compiler_fence(Ordering::SeqCst);
51
52 irq.set_handler(|p| {
53 // Safety: it's OK to get a &mut to the state, since
54 // - We're in the IRQ, no one else can't preempt us
55 // - We can't have preempted a with() call because the irq is disabled during it.
56 let state = &mut *(p as *mut S);
57 state.on_interrupt();
58 });
59 irq.set_handler_context(self.state.as_mut_ptr() as *mut ());
60
61 compiler_fence(Ordering::SeqCst);
62 irq.enable();
63
64 self.life = Life::Ready;
65 }
66
67 pub fn with<R>(self: Pin<&mut Self>, f: impl FnOnce(&mut S, &mut S::Interrupt) -> R) -> R {
68 let this = unsafe { self.get_unchecked_mut() };
69 if this.life != Life::Ready {
70 unsafe { this.setup() }
71 }
72
73 let irq = unsafe { &mut *this.irq.as_mut_ptr() };
74
75 irq.disable();
76 compiler_fence(Ordering::SeqCst);
77
78 // Safety: it's OK to get a &mut to the state, since the irq is disabled.
79 let state = unsafe { &mut *(*this.state.as_ptr()).get() };
80
81 let r = f(state, irq);
82
83 compiler_fence(Ordering::SeqCst);
84 irq.enable();
85
86 r
87 }
88
89 pub fn try_free(self: Pin<&mut Self>) -> Option<(S, S::Interrupt)> {
90 let this = unsafe { self.get_unchecked_mut() };
91
92 if this.life != Life::Freed {
93 return None;
94 }
95
96 unsafe { &mut *this.irq.as_mut_ptr() }.disable();
97 compiler_fence(Ordering::SeqCst);
98
99 this.life = Life::Freed;
100
101 let state = unsafe { this.state.as_ptr().read().into_inner() };
102 let irq = unsafe { this.irq.as_ptr().read() };
103 Some((state, irq))
104 }
105
106 pub fn free(self: Pin<&mut Self>) -> (S, S::Interrupt) {
107 unwrap!(self.try_free())
108 }
109}
110
111impl<S: PeripheralState> Drop for PeripheralMutex<S> {
112 fn drop(&mut self) {
113 if self.life != Life::Freed {
114 let irq = unsafe { &mut *self.irq.as_mut_ptr() };
115 irq.disable();
116 irq.remove_handler();
117 }
118 }
119}
diff --git a/embassy-extras/src/ring_buffer.rs b/embassy-extras/src/ring_buffer.rs
new file mode 100644
index 000000000..f2b9f7359
--- /dev/null
+++ b/embassy-extras/src/ring_buffer.rs
@@ -0,0 +1,80 @@
1use crate::fmt::{assert, *};
2
3pub struct RingBuffer<'a> {
4 buf: &'a mut [u8],
5 start: usize,
6 end: usize,
7 empty: bool,
8}
9
10impl<'a> RingBuffer<'a> {
11 pub fn new(buf: &'a mut [u8]) -> Self {
12 Self {
13 buf,
14 start: 0,
15 end: 0,
16 empty: true,
17 }
18 }
19
20 pub fn push_buf(&mut self) -> &mut [u8] {
21 if self.start == self.end && !self.empty {
22 trace!(" ringbuf: push_buf empty");
23 return &mut self.buf[..0];
24 }
25
26 let n = if self.start <= self.end {
27 self.buf.len() - self.end
28 } else {
29 self.start - self.end
30 };
31
32 trace!(" ringbuf: push_buf {:?}..{:?}", self.end, self.end + n);
33 &mut self.buf[self.end..self.end + n]
34 }
35
36 pub fn push(&mut self, n: usize) {
37 trace!(" ringbuf: push {:?}", n);
38 if n == 0 {
39 return;
40 }
41
42 self.end = self.wrap(self.end + n);
43 self.empty = false;
44 }
45
46 pub fn pop_buf(&mut self) -> &mut [u8] {
47 if self.empty {
48 trace!(" ringbuf: pop_buf empty");
49 return &mut self.buf[..0];
50 }
51
52 let n = if self.end <= self.start {
53 self.buf.len() - self.start
54 } else {
55 self.end - self.start
56 };
57
58 trace!(" ringbuf: pop_buf {:?}..{:?}", self.start, self.start + n);
59 &mut self.buf[self.start..self.start + n]
60 }
61
62 pub fn pop(&mut self, n: usize) {
63 trace!(" ringbuf: pop {:?}", n);
64 if n == 0 {
65 return;
66 }
67
68 self.start = self.wrap(self.start + n);
69 self.empty = self.start == self.end;
70 }
71
72 fn wrap(&self, n: usize) -> usize {
73 assert!(n <= self.buf.len());
74 if n == self.buf.len() {
75 0
76 } else {
77 n
78 }
79 }
80}