aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorThomas Giesel <[email protected]>2025-06-25 21:10:25 +0200
committerGitHub <[email protected]>2025-06-25 21:10:25 +0200
commitef4faffcb55a141848e47c24178396a688eb1563 (patch)
tree7c2aec759bd3466c0b076de53827fdf6b0b46482
parentca14f5452959bb23499f057ca78cf21e0e69dccd (diff)
parentb5ab3276dce7322e33946e974770fa91b98124a4 (diff)
Merge branch 'main' into generate_all_opamp_pins
-rw-r--r--docs/index.adoc1
-rw-r--r--docs/pages/overview.adoc2
-rw-r--r--embassy-executor-macros/src/macros/task.rs34
-rw-r--r--embassy-executor/Cargo.toml1
-rw-r--r--embassy-executor/src/lib.rs51
-rw-r--r--embassy-executor/tests/test.rs36
-rw-r--r--embassy-executor/tests/ui.rs9
-rw-r--r--embassy-executor/tests/ui/bad_return_impl_future.rs9
-rw-r--r--embassy-executor/tests/ui/bad_return_impl_future.stderr120
-rw-r--r--embassy-executor/tests/ui/bad_return_impl_future_nightly.rs9
-rw-r--r--embassy-executor/tests/ui/bad_return_impl_future_nightly.stderr10
-rw-r--r--embassy-executor/tests/ui/return_impl_send.rs6
-rw-r--r--embassy-executor/tests/ui/return_impl_send.stderr137
-rw-r--r--embassy-executor/tests/ui/return_impl_send_nightly.rs6
-rw-r--r--embassy-executor/tests/ui/return_impl_send_nightly.stderr10
-rw-r--r--embassy-rp/src/rom_data/mod.rs36
-rw-r--r--embassy-stm32/src/can/bxcan/mod.rs327
-rw-r--r--embassy-stm32/src/can/common.rs111
-rw-r--r--embassy-stm32/src/can/enums.rs2
-rw-r--r--embassy-stm32/src/can/fdcan.rs194
-rw-r--r--embassy-stm32/src/hsem/mod.rs6
-rw-r--r--embassy-stm32/src/lib.rs4
-rw-r--r--embassy-stm32/src/sdmmc/mod.rs5
-rw-r--r--examples/boot/application/rp/src/bin/a.rs2
-rw-r--r--examples/stm32c0/Cargo.toml3
-rw-r--r--examples/stm32c0/src/bin/rtc.rs35
26 files changed, 803 insertions, 363 deletions
diff --git a/docs/index.adoc b/docs/index.adoc
index 9c6150196..80754d5a4 100644
--- a/docs/index.adoc
+++ b/docs/index.adoc
@@ -5,6 +5,7 @@
5:toc-placement: left 5:toc-placement: left
6:toclevels: 2 6:toclevels: 2
7:imagesdir: images 7:imagesdir: images
8:source-highlighter: rouge
8 9
9# Embassy Book 10# Embassy Book
10 11
diff --git a/docs/pages/overview.adoc b/docs/pages/overview.adoc
index acd757795..18eaaeb75 100644
--- a/docs/pages/overview.adoc
+++ b/docs/pages/overview.adoc
@@ -30,7 +30,7 @@ The Embassy project maintains HALs for select hardware, but you can still use HA
30* link:https://docs.embassy.dev/embassy-nrf/[embassy-nrf], for the Nordic Semiconductor nRF52, nRF53, nRF91 series. 30* link:https://docs.embassy.dev/embassy-nrf/[embassy-nrf], for the Nordic Semiconductor nRF52, nRF53, nRF91 series.
31* link:https://docs.embassy.dev/embassy-rp/[embassy-rp], for the Raspberry Pi RP2040 as well as RP235x microcontroller. 31* link:https://docs.embassy.dev/embassy-rp/[embassy-rp], for the Raspberry Pi RP2040 as well as RP235x microcontroller.
32* link:https://docs.embassy.dev/embassy-mspm0/[embassy-mspm0], for the Texas Instruments MSPM0 microcontrollers. 32* link:https://docs.embassy.dev/embassy-mspm0/[embassy-mspm0], for the Texas Instruments MSPM0 microcontrollers.
33* link:https://github.com/esp-rs[esp-rs], for the Espressif Systems ESP32 series of chips. 33* link:https://github.com/esp-rs/esp-hal[esp-hal], for the Espressif Systems ESP32 series of chips.
34* link:https://github.com/ch32-rs/ch32-hal[ch32-hal], for the WCH 32-bit RISC-V(CH32V) series of chips. 34* link:https://github.com/ch32-rs/ch32-hal[ch32-hal], for the WCH 32-bit RISC-V(CH32V) series of chips.
35* link:https://github.com/AlexCharlton/mpfs-hal[mpfs-hal], for the Microchip PolarFire SoC. 35* link:https://github.com/AlexCharlton/mpfs-hal[mpfs-hal], for the Microchip PolarFire SoC.
36* link:https://github.com/py32-rs/py32-hal[py32-hal], for the Puya Semiconductor PY32 series of chips. 36* link:https://github.com/py32-rs/py32-hal[py32-hal], for the Puya Semiconductor PY32 series of chips.
diff --git a/embassy-executor-macros/src/macros/task.rs b/embassy-executor-macros/src/macros/task.rs
index 91d6beee8..91bf8e940 100644
--- a/embassy-executor-macros/src/macros/task.rs
+++ b/embassy-executor-macros/src/macros/task.rs
@@ -51,7 +51,11 @@ pub fn run(args: TokenStream, item: TokenStream) -> TokenStream {
51 .embassy_executor 51 .embassy_executor
52 .unwrap_or(Expr::Verbatim(TokenStream::from_str("::embassy_executor").unwrap())); 52 .unwrap_or(Expr::Verbatim(TokenStream::from_str("::embassy_executor").unwrap()));
53 53
54 if f.sig.asyncness.is_none() { 54 let returns_impl_trait = match &f.sig.output {
55 ReturnType::Type(_, ty) => matches!(**ty, Type::ImplTrait(_)),
56 _ => false,
57 };
58 if f.sig.asyncness.is_none() && !returns_impl_trait {
55 error(&mut errors, &f.sig, "task functions must be async"); 59 error(&mut errors, &f.sig, "task functions must be async");
56 } 60 }
57 if !f.sig.generics.params.is_empty() { 61 if !f.sig.generics.params.is_empty() {
@@ -66,17 +70,19 @@ pub fn run(args: TokenStream, item: TokenStream) -> TokenStream {
66 if !f.sig.variadic.is_none() { 70 if !f.sig.variadic.is_none() {
67 error(&mut errors, &f.sig, "task functions must not be variadic"); 71 error(&mut errors, &f.sig, "task functions must not be variadic");
68 } 72 }
69 match &f.sig.output { 73 if f.sig.asyncness.is_some() {
70 ReturnType::Default => {} 74 match &f.sig.output {
71 ReturnType::Type(_, ty) => match &**ty { 75 ReturnType::Default => {}
72 Type::Tuple(tuple) if tuple.elems.is_empty() => {} 76 ReturnType::Type(_, ty) => match &**ty {
73 Type::Never(_) => {} 77 Type::Tuple(tuple) if tuple.elems.is_empty() => {}
74 _ => error( 78 Type::Never(_) => {}
75 &mut errors, 79 _ => error(
76 &f.sig, 80 &mut errors,
77 "task functions must either not return a value, return `()` or return `!`", 81 &f.sig,
78 ), 82 "task functions must either not return a value, return `()` or return `!`",
79 }, 83 ),
84 },
85 }
80 } 86 }
81 87
82 let mut args = Vec::new(); 88 let mut args = Vec::new();
@@ -128,12 +134,12 @@ pub fn run(args: TokenStream, item: TokenStream) -> TokenStream {
128 #[cfg(feature = "nightly")] 134 #[cfg(feature = "nightly")]
129 let mut task_outer_body = quote! { 135 let mut task_outer_body = quote! {
130 trait _EmbassyInternalTaskTrait { 136 trait _EmbassyInternalTaskTrait {
131 type Fut: ::core::future::Future + 'static; 137 type Fut: ::core::future::Future<Output: #embassy_executor::_export::TaskReturnValue> + 'static;
132 fn construct(#fargs) -> Self::Fut; 138 fn construct(#fargs) -> Self::Fut;
133 } 139 }
134 140
135 impl _EmbassyInternalTaskTrait for () { 141 impl _EmbassyInternalTaskTrait for () {
136 type Fut = impl core::future::Future + 'static; 142 type Fut = impl core::future::Future<Output: #embassy_executor::_export::TaskReturnValue> + 'static;
137 fn construct(#fargs) -> Self::Fut { 143 fn construct(#fargs) -> Self::Fut {
138 #task_inner_ident(#(#full_args,)*) 144 #task_inner_ident(#(#full_args,)*)
139 } 145 }
diff --git a/embassy-executor/Cargo.toml b/embassy-executor/Cargo.toml
index f014ccf30..2dbf2c29a 100644
--- a/embassy-executor/Cargo.toml
+++ b/embassy-executor/Cargo.toml
@@ -59,6 +59,7 @@ avr-device = { version = "0.7.0", optional = true }
59critical-section = { version = "1.1", features = ["std"] } 59critical-section = { version = "1.1", features = ["std"] }
60trybuild = "1.0" 60trybuild = "1.0"
61embassy-sync = { path = "../embassy-sync" } 61embassy-sync = { path = "../embassy-sync" }
62rustversion = "1.0.21"
62 63
63[features] 64[features]
64 65
diff --git a/embassy-executor/src/lib.rs b/embassy-executor/src/lib.rs
index dfe420bab..e174a0594 100644
--- a/embassy-executor/src/lib.rs
+++ b/embassy-executor/src/lib.rs
@@ -65,8 +65,17 @@ pub mod _export {
65 65
66 use crate::raw::TaskPool; 66 use crate::raw::TaskPool;
67 67
68 trait TaskReturnValue {}
69 impl TaskReturnValue for () {}
70 impl TaskReturnValue for Never {}
71
72 #[diagnostic::on_unimplemented(
73 message = "task futures must resolve to `()` or `!`",
74 note = "use `async fn` or change the return type to `impl Future<Output = ()>`"
75 )]
76 #[allow(private_bounds)]
68 pub trait TaskFn<Args>: Copy { 77 pub trait TaskFn<Args>: Copy {
69 type Fut: Future + 'static; 78 type Fut: Future<Output: TaskReturnValue> + 'static;
70 } 79 }
71 80
72 macro_rules! task_fn_impl { 81 macro_rules! task_fn_impl {
@@ -74,7 +83,7 @@ pub mod _export {
74 impl<F, Fut, $($Tn,)*> TaskFn<($($Tn,)*)> for F 83 impl<F, Fut, $($Tn,)*> TaskFn<($($Tn,)*)> for F
75 where 84 where
76 F: Copy + FnOnce($($Tn,)*) -> Fut, 85 F: Copy + FnOnce($($Tn,)*) -> Fut,
77 Fut: Future + 'static, 86 Fut: Future<Output: TaskReturnValue> + 'static,
78 { 87 {
79 type Fut = Fut; 88 type Fut = Fut;
80 } 89 }
@@ -205,4 +214,42 @@ pub mod _export {
205 Align268435456: 268435456, 214 Align268435456: 268435456,
206 Align536870912: 536870912, 215 Align536870912: 536870912,
207 ); 216 );
217
218 #[allow(dead_code)]
219 trait HasOutput {
220 type Output;
221 }
222
223 impl<O> HasOutput for fn() -> O {
224 type Output = O;
225 }
226
227 #[allow(dead_code)]
228 type Never = <fn() -> ! as HasOutput>::Output;
229}
230
231/// Implementation details for embassy macros.
232/// Do not use. Used for macros and HALs only. Not covered by semver guarantees.
233#[doc(hidden)]
234#[cfg(feature = "nightly")]
235pub mod _export {
236 #[diagnostic::on_unimplemented(
237 message = "task futures must resolve to `()` or `!`",
238 note = "use `async fn` or change the return type to `impl Future<Output = ()>`"
239 )]
240 pub trait TaskReturnValue {}
241 impl TaskReturnValue for () {}
242 impl TaskReturnValue for Never {}
243
244 #[allow(dead_code)]
245 trait HasOutput {
246 type Output;
247 }
248
249 impl<O> HasOutput for fn() -> O {
250 type Output = O;
251 }
252
253 #[allow(dead_code)]
254 type Never = <fn() -> ! as HasOutput>::Output;
208} 255}
diff --git a/embassy-executor/tests/test.rs b/embassy-executor/tests/test.rs
index 78c49c071..c1e7ec5d7 100644
--- a/embassy-executor/tests/test.rs
+++ b/embassy-executor/tests/test.rs
@@ -1,7 +1,8 @@
1#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] 1#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))]
2#![cfg_attr(feature = "nightly", feature(never_type))]
2 3
3use std::boxed::Box; 4use std::boxed::Box;
4use std::future::poll_fn; 5use std::future::{poll_fn, Future};
5use std::sync::{Arc, Mutex}; 6use std::sync::{Arc, Mutex};
6use std::task::Poll; 7use std::task::Poll;
7 8
@@ -58,6 +59,39 @@ fn executor_task() {
58 trace.push("poll task1") 59 trace.push("poll task1")
59 } 60 }
60 61
62 #[task]
63 async fn task2() -> ! {
64 panic!()
65 }
66
67 let (executor, trace) = setup();
68 executor.spawner().spawn(task1(trace.clone())).unwrap();
69
70 unsafe { executor.poll() };
71 unsafe { executor.poll() };
72
73 assert_eq!(
74 trace.get(),
75 &[
76 "pend", // spawning a task pends the executor
77 "poll task1", // poll only once.
78 ]
79 )
80}
81
82#[test]
83fn executor_task_rpit() {
84 #[task]
85 fn task1(trace: Trace) -> impl Future<Output = ()> {
86 async move { trace.push("poll task1") }
87 }
88
89 #[cfg(feature = "nightly")]
90 #[task]
91 fn task2() -> impl Future<Output = !> {
92 async { panic!() }
93 }
94
61 let (executor, trace) = setup(); 95 let (executor, trace) = setup();
62 executor.spawner().spawn(task1(trace.clone())).unwrap(); 96 executor.spawner().spawn(task1(trace.clone())).unwrap();
63 97
diff --git a/embassy-executor/tests/ui.rs b/embassy-executor/tests/ui.rs
index 278a4b903..c4a1a601c 100644
--- a/embassy-executor/tests/ui.rs
+++ b/embassy-executor/tests/ui.rs
@@ -17,6 +17,15 @@ fn ui() {
17 t.compile_fail("tests/ui/nonstatic_struct_elided.rs"); 17 t.compile_fail("tests/ui/nonstatic_struct_elided.rs");
18 t.compile_fail("tests/ui/nonstatic_struct_generic.rs"); 18 t.compile_fail("tests/ui/nonstatic_struct_generic.rs");
19 t.compile_fail("tests/ui/not_async.rs"); 19 t.compile_fail("tests/ui/not_async.rs");
20 if rustversion::cfg!(stable) {
21 // output is slightly different on nightly
22 t.compile_fail("tests/ui/bad_return_impl_future.rs");
23 t.compile_fail("tests/ui/return_impl_send.rs");
24 }
25 if cfg!(feature = "nightly") {
26 t.compile_fail("tests/ui/bad_return_impl_future_nightly.rs");
27 t.compile_fail("tests/ui/return_impl_send_nightly.rs");
28 }
20 t.compile_fail("tests/ui/self_ref.rs"); 29 t.compile_fail("tests/ui/self_ref.rs");
21 t.compile_fail("tests/ui/self.rs"); 30 t.compile_fail("tests/ui/self.rs");
22 t.compile_fail("tests/ui/type_error.rs"); 31 t.compile_fail("tests/ui/type_error.rs");
diff --git a/embassy-executor/tests/ui/bad_return_impl_future.rs b/embassy-executor/tests/ui/bad_return_impl_future.rs
new file mode 100644
index 000000000..baaa7dc5a
--- /dev/null
+++ b/embassy-executor/tests/ui/bad_return_impl_future.rs
@@ -0,0 +1,9 @@
1#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))]
2use core::future::Future;
3
4#[embassy_executor::task]
5fn task() -> impl Future<Output = u32> {
6 async { 5 }
7}
8
9fn main() {}
diff --git a/embassy-executor/tests/ui/bad_return_impl_future.stderr b/embassy-executor/tests/ui/bad_return_impl_future.stderr
new file mode 100644
index 000000000..2980fd18b
--- /dev/null
+++ b/embassy-executor/tests/ui/bad_return_impl_future.stderr
@@ -0,0 +1,120 @@
1error[E0277]: task futures must resolve to `()` or `!`
2 --> tests/ui/bad_return_impl_future.rs:5:4
3 |
44 | #[embassy_executor::task]
5 | ------------------------- required by a bound introduced by this call
65 | fn task() -> impl Future<Output = u32> {
7 | ^^^^ the trait `TaskFn<_>` is not implemented for fn item `fn() -> impl Future<Output = u32> {__task_task}`
8 |
9 = note: use `async fn` or change the return type to `impl Future<Output = ()>`
10note: required by a bound in `task_pool_size`
11 --> src/lib.rs
12 |
13 | pub const fn task_pool_size<F, Args, Fut, const POOL_SIZE: usize>(_: F) -> usize
14 | -------------- required by a bound in this function
15 | where
16 | F: TaskFn<Args, Fut = Fut>,
17 | ^^^^^^^^^ required by this bound in `task_pool_size`
18
19error[E0277]: task futures must resolve to `()` or `!`
20 --> tests/ui/bad_return_impl_future.rs:4:1
21 |
224 | #[embassy_executor::task]
23 | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TaskFn<_>` is not implemented for fn item `fn() -> impl Future<Output = u32> {__task_task}`
24 |
25 = note: use `async fn` or change the return type to `impl Future<Output = ()>`
26note: required by a bound in `task_pool_size`
27 --> src/lib.rs
28 |
29 | pub const fn task_pool_size<F, Args, Fut, const POOL_SIZE: usize>(_: F) -> usize
30 | -------------- required by a bound in this function
31 | where
32 | F: TaskFn<Args, Fut = Fut>,
33 | ^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `task_pool_size`
34 = note: this error originates in the attribute macro `embassy_executor::task` (in Nightly builds, run with -Z macro-backtrace for more info)
35
36error[E0277]: task futures must resolve to `()` or `!`
37 --> tests/ui/bad_return_impl_future.rs:5:4
38 |
394 | #[embassy_executor::task]
40 | ------------------------- required by a bound introduced by this call
415 | fn task() -> impl Future<Output = u32> {
42 | ^^^^ the trait `TaskFn<_>` is not implemented for fn item `fn() -> impl Future<Output = u32> {__task_task}`
43 |
44 = note: use `async fn` or change the return type to `impl Future<Output = ()>`
45note: required by a bound in `task_pool_align`
46 --> src/lib.rs
47 |
48 | pub const fn task_pool_align<F, Args, Fut, const POOL_SIZE: usize>(_: F) -> usize
49 | --------------- required by a bound in this function
50 | where
51 | F: TaskFn<Args, Fut = Fut>,
52 | ^^^^^^^^^ required by this bound in `task_pool_align`
53
54error[E0277]: task futures must resolve to `()` or `!`
55 --> tests/ui/bad_return_impl_future.rs:4:1
56 |
574 | #[embassy_executor::task]
58 | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TaskFn<_>` is not implemented for fn item `fn() -> impl Future<Output = u32> {__task_task}`
59 |
60 = note: use `async fn` or change the return type to `impl Future<Output = ()>`
61note: required by a bound in `task_pool_align`
62 --> src/lib.rs
63 |
64 | pub const fn task_pool_align<F, Args, Fut, const POOL_SIZE: usize>(_: F) -> usize
65 | --------------- required by a bound in this function
66 | where
67 | F: TaskFn<Args, Fut = Fut>,
68 | ^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `task_pool_align`
69 = note: this error originates in the attribute macro `embassy_executor::task` (in Nightly builds, run with -Z macro-backtrace for more info)
70
71error[E0277]: task futures must resolve to `()` or `!`
72 --> tests/ui/bad_return_impl_future.rs:5:4
73 |
744 | #[embassy_executor::task]
75 | ------------------------- required by a bound introduced by this call
765 | fn task() -> impl Future<Output = u32> {
77 | ^^^^ the trait `TaskFn<_>` is not implemented for fn item `fn() -> impl Future<Output = u32> {__task_task}`
78 |
79 = note: use `async fn` or change the return type to `impl Future<Output = ()>`
80note: required by a bound in `task_pool_new`
81 --> src/lib.rs
82 |
83 | pub const fn task_pool_new<F, Args, Fut, const POOL_SIZE: usize>(_: F) -> TaskPool<Fut, POOL_SIZE>
84 | ------------- required by a bound in this function
85 | where
86 | F: TaskFn<Args, Fut = Fut>,
87 | ^^^^^^^^^ required by this bound in `task_pool_new`
88
89error[E0277]: task futures must resolve to `()` or `!`
90 --> tests/ui/bad_return_impl_future.rs:4:1
91 |
924 | #[embassy_executor::task]
93 | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TaskFn<_>` is not implemented for fn item `fn() -> impl Future<Output = u32> {__task_task}`
94 |
95 = note: use `async fn` or change the return type to `impl Future<Output = ()>`
96note: required by a bound in `task_pool_new`
97 --> src/lib.rs
98 |
99 | pub const fn task_pool_new<F, Args, Fut, const POOL_SIZE: usize>(_: F) -> TaskPool<Fut, POOL_SIZE>
100 | ------------- required by a bound in this function
101 | where
102 | F: TaskFn<Args, Fut = Fut>,
103 | ^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `task_pool_new`
104 = note: this error originates in the attribute macro `embassy_executor::task` (in Nightly builds, run with -Z macro-backtrace for more info)
105
106error[E0277]: task futures must resolve to `()` or `!`
107 --> tests/ui/bad_return_impl_future.rs:5:4
108 |
1094 | #[embassy_executor::task]
110 | ------------------------- required by a bound introduced by this call
1115 | fn task() -> impl Future<Output = u32> {
112 | ^^^^ the trait `TaskFn<_>` is not implemented for fn item `fn() -> impl Future<Output = u32> {__task_task}`
113 |
114 = note: use `async fn` or change the return type to `impl Future<Output = ()>`
115note: required by a bound in `__task_pool_get`
116 --> tests/ui/bad_return_impl_future.rs:4:1
117 |
1184 | #[embassy_executor::task]
119 | ^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `__task_pool_get`
120 = note: this error originates in the attribute macro `embassy_executor::task` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/embassy-executor/tests/ui/bad_return_impl_future_nightly.rs b/embassy-executor/tests/ui/bad_return_impl_future_nightly.rs
new file mode 100644
index 000000000..baaa7dc5a
--- /dev/null
+++ b/embassy-executor/tests/ui/bad_return_impl_future_nightly.rs
@@ -0,0 +1,9 @@
1#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))]
2use core::future::Future;
3
4#[embassy_executor::task]
5fn task() -> impl Future<Output = u32> {
6 async { 5 }
7}
8
9fn main() {}
diff --git a/embassy-executor/tests/ui/bad_return_impl_future_nightly.stderr b/embassy-executor/tests/ui/bad_return_impl_future_nightly.stderr
new file mode 100644
index 000000000..73ceb989d
--- /dev/null
+++ b/embassy-executor/tests/ui/bad_return_impl_future_nightly.stderr
@@ -0,0 +1,10 @@
1error[E0277]: task futures must resolve to `()` or `!`
2 --> tests/ui/bad_return_impl_future_nightly.rs:4:1
3 |
44 | #[embassy_executor::task]
5 | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TaskReturnValue` is not implemented for `u32`
6 |
7 = note: use `async fn` or change the return type to `impl Future<Output = ()>`
8 = help: the following other types implement trait `TaskReturnValue`:
9 ()
10 <fn() -> ! as _export::HasOutput>::Output
diff --git a/embassy-executor/tests/ui/return_impl_send.rs b/embassy-executor/tests/ui/return_impl_send.rs
new file mode 100644
index 000000000..6ddb0e722
--- /dev/null
+++ b/embassy-executor/tests/ui/return_impl_send.rs
@@ -0,0 +1,6 @@
1#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))]
2
3#[embassy_executor::task]
4fn task() -> impl Send {}
5
6fn main() {}
diff --git a/embassy-executor/tests/ui/return_impl_send.stderr b/embassy-executor/tests/ui/return_impl_send.stderr
new file mode 100644
index 000000000..7e3e468b8
--- /dev/null
+++ b/embassy-executor/tests/ui/return_impl_send.stderr
@@ -0,0 +1,137 @@
1error[E0277]: task futures must resolve to `()` or `!`
2 --> tests/ui/return_impl_send.rs:4:4
3 |
43 | #[embassy_executor::task]
5 | ------------------------- required by a bound introduced by this call
64 | fn task() -> impl Send {}
7 | ^^^^ the trait `TaskFn<_>` is not implemented for fn item `fn() -> impl Send {__task_task}`
8 |
9 = note: use `async fn` or change the return type to `impl Future<Output = ()>`
10note: required by a bound in `task_pool_size`
11 --> src/lib.rs
12 |
13 | pub const fn task_pool_size<F, Args, Fut, const POOL_SIZE: usize>(_: F) -> usize
14 | -------------- required by a bound in this function
15 | where
16 | F: TaskFn<Args, Fut = Fut>,
17 | ^^^^^^^^^ required by this bound in `task_pool_size`
18
19error[E0277]: task futures must resolve to `()` or `!`
20 --> tests/ui/return_impl_send.rs:3:1
21 |
223 | #[embassy_executor::task]
23 | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TaskFn<_>` is not implemented for fn item `fn() -> impl Send {__task_task}`
24 |
25 = note: use `async fn` or change the return type to `impl Future<Output = ()>`
26note: required by a bound in `task_pool_size`
27 --> src/lib.rs
28 |
29 | pub const fn task_pool_size<F, Args, Fut, const POOL_SIZE: usize>(_: F) -> usize
30 | -------------- required by a bound in this function
31 | where
32 | F: TaskFn<Args, Fut = Fut>,
33 | ^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `task_pool_size`
34 = note: this error originates in the attribute macro `embassy_executor::task` (in Nightly builds, run with -Z macro-backtrace for more info)
35
36error[E0277]: task futures must resolve to `()` or `!`
37 --> tests/ui/return_impl_send.rs:4:4
38 |
393 | #[embassy_executor::task]
40 | ------------------------- required by a bound introduced by this call
414 | fn task() -> impl Send {}
42 | ^^^^ the trait `TaskFn<_>` is not implemented for fn item `fn() -> impl Send {__task_task}`
43 |
44 = note: use `async fn` or change the return type to `impl Future<Output = ()>`
45note: required by a bound in `task_pool_align`
46 --> src/lib.rs
47 |
48 | pub const fn task_pool_align<F, Args, Fut, const POOL_SIZE: usize>(_: F) -> usize
49 | --------------- required by a bound in this function
50 | where
51 | F: TaskFn<Args, Fut = Fut>,
52 | ^^^^^^^^^ required by this bound in `task_pool_align`
53
54error[E0277]: task futures must resolve to `()` or `!`
55 --> tests/ui/return_impl_send.rs:3:1
56 |
573 | #[embassy_executor::task]
58 | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TaskFn<_>` is not implemented for fn item `fn() -> impl Send {__task_task}`
59 |
60 = note: use `async fn` or change the return type to `impl Future<Output = ()>`
61note: required by a bound in `task_pool_align`
62 --> src/lib.rs
63 |
64 | pub const fn task_pool_align<F, Args, Fut, const POOL_SIZE: usize>(_: F) -> usize
65 | --------------- required by a bound in this function
66 | where
67 | F: TaskFn<Args, Fut = Fut>,
68 | ^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `task_pool_align`
69 = note: this error originates in the attribute macro `embassy_executor::task` (in Nightly builds, run with -Z macro-backtrace for more info)
70
71error[E0277]: task futures must resolve to `()` or `!`
72 --> tests/ui/return_impl_send.rs:4:4
73 |
743 | #[embassy_executor::task]
75 | ------------------------- required by a bound introduced by this call
764 | fn task() -> impl Send {}
77 | ^^^^ the trait `TaskFn<_>` is not implemented for fn item `fn() -> impl Send {__task_task}`
78 |
79 = note: use `async fn` or change the return type to `impl Future<Output = ()>`
80note: required by a bound in `task_pool_new`
81 --> src/lib.rs
82 |
83 | pub const fn task_pool_new<F, Args, Fut, const POOL_SIZE: usize>(_: F) -> TaskPool<Fut, POOL_SIZE>
84 | ------------- required by a bound in this function
85 | where
86 | F: TaskFn<Args, Fut = Fut>,
87 | ^^^^^^^^^ required by this bound in `task_pool_new`
88
89error[E0277]: task futures must resolve to `()` or `!`
90 --> tests/ui/return_impl_send.rs:3:1
91 |
923 | #[embassy_executor::task]
93 | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TaskFn<_>` is not implemented for fn item `fn() -> impl Send {__task_task}`
94 |
95 = note: use `async fn` or change the return type to `impl Future<Output = ()>`
96note: required by a bound in `task_pool_new`
97 --> src/lib.rs
98 |
99 | pub const fn task_pool_new<F, Args, Fut, const POOL_SIZE: usize>(_: F) -> TaskPool<Fut, POOL_SIZE>
100 | ------------- required by a bound in this function
101 | where
102 | F: TaskFn<Args, Fut = Fut>,
103 | ^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `task_pool_new`
104 = note: this error originates in the attribute macro `embassy_executor::task` (in Nightly builds, run with -Z macro-backtrace for more info)
105
106error[E0277]: task futures must resolve to `()` or `!`
107 --> tests/ui/return_impl_send.rs:4:4
108 |
1093 | #[embassy_executor::task]
110 | ------------------------- required by a bound introduced by this call
1114 | fn task() -> impl Send {}
112 | ^^^^ the trait `TaskFn<_>` is not implemented for fn item `fn() -> impl Send {__task_task}`
113 |
114 = note: use `async fn` or change the return type to `impl Future<Output = ()>`
115note: required by a bound in `__task_pool_get`
116 --> tests/ui/return_impl_send.rs:3:1
117 |
1183 | #[embassy_executor::task]
119 | ^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `__task_pool_get`
120 = note: this error originates in the attribute macro `embassy_executor::task` (in Nightly builds, run with -Z macro-backtrace for more info)
121
122error[E0277]: `impl Send` is not a future
123 --> tests/ui/return_impl_send.rs:3:1
124 |
1253 | #[embassy_executor::task]
126 | ^^^^^^^^^^^^^^^^^^^^^^^^^ `impl Send` is not a future
127 |
128 = help: the trait `Future` is not implemented for `impl Send`
129note: required by a bound in `TaskPool::<F, N>::_spawn_async_fn`
130 --> src/raw/mod.rs
131 |
132 | impl<F: Future + 'static, const N: usize> TaskPool<F, N> {
133 | ^^^^^^ required by this bound in `TaskPool::<F, N>::_spawn_async_fn`
134...
135 | pub unsafe fn _spawn_async_fn<FutFn>(&'static self, future: FutFn) -> SpawnToken<impl Sized>
136 | --------------- required by a bound in this associated function
137 = note: this error originates in the attribute macro `embassy_executor::task` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/embassy-executor/tests/ui/return_impl_send_nightly.rs b/embassy-executor/tests/ui/return_impl_send_nightly.rs
new file mode 100644
index 000000000..6ddb0e722
--- /dev/null
+++ b/embassy-executor/tests/ui/return_impl_send_nightly.rs
@@ -0,0 +1,6 @@
1#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))]
2
3#[embassy_executor::task]
4fn task() -> impl Send {}
5
6fn main() {}
diff --git a/embassy-executor/tests/ui/return_impl_send_nightly.stderr b/embassy-executor/tests/ui/return_impl_send_nightly.stderr
new file mode 100644
index 000000000..de9ba6243
--- /dev/null
+++ b/embassy-executor/tests/ui/return_impl_send_nightly.stderr
@@ -0,0 +1,10 @@
1error[E0277]: `impl Send` is not a future
2 --> tests/ui/return_impl_send_nightly.rs:3:1
3 |
43 | #[embassy_executor::task]
5 | ^^^^^^^^^^^^^^^^^^^^^^^^^
6 | |
7 | `impl Send` is not a future
8 | return type was inferred to be `impl Send` here
9 |
10 = help: the trait `Future` is not implemented for `impl Send`
diff --git a/embassy-rp/src/rom_data/mod.rs b/embassy-rp/src/rom_data/mod.rs
index e5fcf8e3c..a4aba5737 100644
--- a/embassy-rp/src/rom_data/mod.rs
+++ b/embassy-rp/src/rom_data/mod.rs
@@ -1,29 +1,29 @@
1#![cfg_attr( 1#![cfg_attr(
2 feature = "rp2040", 2 feature = "rp2040",
3 doc = r" 3 doc = r"
4//! Functions and data from the RPI Bootrom. 4Functions and data from the RPI Bootrom.
5//! 5
6//! From the [RP2040 datasheet](https://datasheets.raspberrypi.org/rp2040/rp2040-datasheet.pdf), Section 2.8.2.1: 6From the [RP2040 datasheet](https://datasheets.raspberrypi.org/rp2040/rp2040-datasheet.pdf), Section 2.8.2.1:
7//! 7
8//! > The Bootrom contains a number of public functions that provide useful 8> The Bootrom contains a number of public functions that provide useful
9//! > RP2040 functionality that might be needed in the absence of any other code 9> RP2040 functionality that might be needed in the absence of any other code
10//! > on the device, as well as highly optimized versions of certain key 10> on the device, as well as highly optimized versions of certain key
11//! > functionality that would otherwise have to take up space in most user 11> functionality that would otherwise have to take up space in most user
12//! > binaries. 12> binaries.
13" 13"
14)] 14)]
15#![cfg_attr( 15#![cfg_attr(
16 feature = "_rp235x", 16 feature = "_rp235x",
17 doc = r" 17 doc = r"
18//! Functions and data from the RPI Bootrom. 18Functions and data from the RPI Bootrom.
19//! 19
20//! From [Section 5.4](https://rptl.io/rp2350-datasheet#section_bootrom) of the 20From [Section 5.4](https://rptl.io/rp2350-datasheet#section_bootrom) of the
21//! RP2350 datasheet: 21RP2350 datasheet:
22//! 22
23//! > Whilst some ROM space is dedicated to the implementation of the boot 23> Whilst some ROM space is dedicated to the implementation of the boot
24//! > sequence and USB/UART boot interfaces, the bootrom also contains public 24> sequence and USB/UART boot interfaces, the bootrom also contains public
25//! > functions that provide useful RP2350 functionality that may be useful for 25> functions that provide useful RP2350 functionality that may be useful for
26//! > any code or runtime running on the device 26> any code or runtime running on the device
27" 27"
28)] 28)]
29 29
diff --git a/embassy-stm32/src/can/bxcan/mod.rs b/embassy-stm32/src/can/bxcan/mod.rs
index 305666d5b..4c0795a2a 100644
--- a/embassy-stm32/src/can/bxcan/mod.rs
+++ b/embassy-stm32/src/can/bxcan/mod.rs
@@ -15,9 +15,10 @@ pub use embedded_can::{ExtendedId, Id, StandardId};
15use self::filter::MasterFilters; 15use self::filter::MasterFilters;
16use self::registers::{Registers, RxFifo}; 16use self::registers::{Registers, RxFifo};
17pub use super::common::{BufferedCanReceiver, BufferedCanSender}; 17pub use super::common::{BufferedCanReceiver, BufferedCanSender};
18use super::common::{InfoRef, RxInfoRef, TxInfoRef};
18use super::frame::{Envelope, Frame}; 19use super::frame::{Envelope, Frame};
19use super::util; 20use super::util;
20use crate::can::enums::{BusError, InternalOperation, TryReadError}; 21use crate::can::enums::{BusError, RefCountOp, TryReadError};
21use crate::gpio::{AfType, OutputType, Pull, Speed}; 22use crate::gpio::{AfType, OutputType, Pull, Speed};
22use crate::interrupt::typelevel::Interrupt; 23use crate::interrupt::typelevel::Interrupt;
23use crate::rcc::{self, RccPeripheral}; 24use crate::rcc::{self, RccPeripheral};
@@ -35,7 +36,9 @@ impl<T: Instance> interrupt::typelevel::Handler<T::TXInterrupt> for TxInterruptH
35 v.set_rqcp(1, true); 36 v.set_rqcp(1, true);
36 v.set_rqcp(2, true); 37 v.set_rqcp(2, true);
37 }); 38 });
38 T::state().tx_mode.on_interrupt::<T>(); 39 T::info().state.lock(|state| {
40 state.borrow().tx_mode.on_interrupt::<T>();
41 });
39 } 42 }
40} 43}
41 44
@@ -46,7 +49,9 @@ pub struct Rx0InterruptHandler<T: Instance> {
46 49
47impl<T: Instance> interrupt::typelevel::Handler<T::RX0Interrupt> for Rx0InterruptHandler<T> { 50impl<T: Instance> interrupt::typelevel::Handler<T::RX0Interrupt> for Rx0InterruptHandler<T> {
48 unsafe fn on_interrupt() { 51 unsafe fn on_interrupt() {
49 T::state().rx_mode.on_interrupt::<T>(RxFifo::Fifo0); 52 T::info().state.lock(|state| {
53 state.borrow().rx_mode.on_interrupt::<T>(RxFifo::Fifo0);
54 });
50 } 55 }
51} 56}
52 57
@@ -57,7 +62,9 @@ pub struct Rx1InterruptHandler<T: Instance> {
57 62
58impl<T: Instance> interrupt::typelevel::Handler<T::RX1Interrupt> for Rx1InterruptHandler<T> { 63impl<T: Instance> interrupt::typelevel::Handler<T::RX1Interrupt> for Rx1InterruptHandler<T> {
59 unsafe fn on_interrupt() { 64 unsafe fn on_interrupt() {
60 T::state().rx_mode.on_interrupt::<T>(RxFifo::Fifo1); 65 T::info().state.lock(|state| {
66 state.borrow().rx_mode.on_interrupt::<T>(RxFifo::Fifo1);
67 });
61 } 68 }
62} 69}
63 70
@@ -73,7 +80,9 @@ impl<T: Instance> interrupt::typelevel::Handler<T::SCEInterrupt> for SceInterrup
73 80
74 if msr_val.slaki() { 81 if msr_val.slaki() {
75 msr.modify(|m| m.set_slaki(true)); 82 msr.modify(|m| m.set_slaki(true));
76 T::state().err_waker.wake(); 83 T::info().state.lock(|state| {
84 state.borrow().err_waker.wake();
85 });
77 } else if msr_val.erri() { 86 } else if msr_val.erri() {
78 // Disable the interrupt, but don't acknowledge the error, so that it can be 87 // Disable the interrupt, but don't acknowledge the error, so that it can be
79 // forwarded off the bus message consumer. If we don't provide some way for 88 // forwarded off the bus message consumer. If we don't provide some way for
@@ -82,8 +91,9 @@ impl<T: Instance> interrupt::typelevel::Handler<T::SCEInterrupt> for SceInterrup
82 // an indefinite amount of time. 91 // an indefinite amount of time.
83 let ier = T::regs().ier(); 92 let ier = T::regs().ier();
84 ier.modify(|i| i.set_errie(false)); 93 ier.modify(|i| i.set_errie(false));
85 94 T::info().state.lock(|state| {
86 T::state().err_waker.wake(); 95 state.borrow().err_waker.wake();
96 });
87 } 97 }
88 } 98 }
89} 99}
@@ -91,7 +101,7 @@ impl<T: Instance> interrupt::typelevel::Handler<T::SCEInterrupt> for SceInterrup
91/// Configuration proxy returned by [`Can::modify_config`]. 101/// Configuration proxy returned by [`Can::modify_config`].
92pub struct CanConfig<'a> { 102pub struct CanConfig<'a> {
93 phantom: PhantomData<&'a ()>, 103 phantom: PhantomData<&'a ()>,
94 info: &'static Info, 104 info: InfoRef,
95 periph_clock: crate::time::Hertz, 105 periph_clock: crate::time::Hertz,
96} 106}
97 107
@@ -156,8 +166,7 @@ impl Drop for CanConfig<'_> {
156/// CAN driver 166/// CAN driver
157pub struct Can<'d> { 167pub struct Can<'d> {
158 phantom: PhantomData<&'d ()>, 168 phantom: PhantomData<&'d ()>,
159 info: &'static Info, 169 info: InfoRef,
160 state: &'static State,
161 periph_clock: crate::time::Hertz, 170 periph_clock: crate::time::Hertz,
162} 171}
163 172
@@ -227,8 +236,7 @@ impl<'d> Can<'d> {
227 236
228 Self { 237 Self {
229 phantom: PhantomData, 238 phantom: PhantomData,
230 info: T::info(), 239 info: InfoRef::new(T::info()),
231 state: T::state(),
232 periph_clock: T::frequency(), 240 periph_clock: T::frequency(),
233 } 241 }
234 } 242 }
@@ -248,7 +256,7 @@ impl<'d> Can<'d> {
248 256
249 CanConfig { 257 CanConfig {
250 phantom: self.phantom, 258 phantom: self.phantom,
251 info: self.info, 259 info: InfoRef::new(&self.info),
252 periph_clock: self.periph_clock, 260 periph_clock: self.periph_clock,
253 } 261 }
254 } 262 }
@@ -297,7 +305,9 @@ impl<'d> Can<'d> {
297 self.info.regs.0.mcr().modify(|m| m.set_sleep(true)); 305 self.info.regs.0.mcr().modify(|m| m.set_sleep(true));
298 306
299 poll_fn(|cx| { 307 poll_fn(|cx| {
300 self.state.err_waker.register(cx.waker()); 308 self.info.state.lock(|s| {
309 s.borrow().err_waker.register(cx.waker());
310 });
301 if self.is_sleeping() { 311 if self.is_sleeping() {
302 Poll::Ready(()) 312 Poll::Ready(())
303 } else { 313 } else {
@@ -350,8 +360,7 @@ impl<'d> Can<'d> {
350 pub async fn flush(&self, mb: Mailbox) { 360 pub async fn flush(&self, mb: Mailbox) {
351 CanTx { 361 CanTx {
352 _phantom: PhantomData, 362 _phantom: PhantomData,
353 info: self.info, 363 info: TxInfoRef::new(&self.info),
354 state: self.state,
355 } 364 }
356 .flush_inner(mb) 365 .flush_inner(mb)
357 .await; 366 .await;
@@ -366,8 +375,7 @@ impl<'d> Can<'d> {
366 pub async fn flush_any(&self) { 375 pub async fn flush_any(&self) {
367 CanTx { 376 CanTx {
368 _phantom: PhantomData, 377 _phantom: PhantomData,
369 info: self.info, 378 info: TxInfoRef::new(&self.info),
370 state: self.state,
371 } 379 }
372 .flush_any_inner() 380 .flush_any_inner()
373 .await 381 .await
@@ -377,8 +385,7 @@ impl<'d> Can<'d> {
377 pub async fn flush_all(&self) { 385 pub async fn flush_all(&self) {
378 CanTx { 386 CanTx {
379 _phantom: PhantomData, 387 _phantom: PhantomData,
380 info: self.info, 388 info: TxInfoRef::new(&self.info),
381 state: self.state,
382 } 389 }
383 .flush_all_inner() 390 .flush_all_inner()
384 .await 391 .await
@@ -406,19 +413,19 @@ impl<'d> Can<'d> {
406 /// 413 ///
407 /// Returns a tuple of the time the message was received and the message frame 414 /// Returns a tuple of the time the message was received and the message frame
408 pub async fn read(&mut self) -> Result<Envelope, BusError> { 415 pub async fn read(&mut self) -> Result<Envelope, BusError> {
409 self.state.rx_mode.read(self.info, self.state).await 416 RxMode::read(&self.info).await
410 } 417 }
411 418
412 /// Attempts to read a CAN frame without blocking. 419 /// Attempts to read a CAN frame without blocking.
413 /// 420 ///
414 /// Returns [Err(TryReadError::Empty)] if there are no frames in the rx queue. 421 /// Returns [Err(TryReadError::Empty)] if there are no frames in the rx queue.
415 pub fn try_read(&mut self) -> Result<Envelope, TryReadError> { 422 pub fn try_read(&mut self) -> Result<Envelope, TryReadError> {
416 self.state.rx_mode.try_read(self.info) 423 RxMode::try_read(&self.info)
417 } 424 }
418 425
419 /// Waits while receive queue is empty. 426 /// Waits while receive queue is empty.
420 pub async fn wait_not_empty(&mut self) { 427 pub async fn wait_not_empty(&mut self) {
421 self.state.rx_mode.wait_not_empty(self.info, self.state).await 428 RxMode::wait_not_empty(&self.info).await
422 } 429 }
423 430
424 /// Split the CAN driver into transmit and receive halves. 431 /// Split the CAN driver into transmit and receive halves.
@@ -428,13 +435,11 @@ impl<'d> Can<'d> {
428 ( 435 (
429 CanTx { 436 CanTx {
430 _phantom: PhantomData, 437 _phantom: PhantomData,
431 info: self.info, 438 info: TxInfoRef::new(&self.info),
432 state: self.state,
433 }, 439 },
434 CanRx { 440 CanRx {
435 _phantom: PhantomData, 441 _phantom: PhantomData,
436 info: self.info, 442 info: RxInfoRef::new(&self.info),
437 state: self.state,
438 }, 443 },
439 ) 444 )
440 } 445 }
@@ -459,7 +464,7 @@ impl<'d> Can<'d> {
459 /// To modify filters of a slave peripheral, `modify_filters` has to be called on the master 464 /// To modify filters of a slave peripheral, `modify_filters` has to be called on the master
460 /// peripheral instead. 465 /// peripheral instead.
461 pub fn modify_filters(&mut self) -> MasterFilters<'_> { 466 pub fn modify_filters(&mut self) -> MasterFilters<'_> {
462 unsafe { MasterFilters::new(self.info) } 467 unsafe { MasterFilters::new(&self.info) }
463 } 468 }
464} 469}
465 470
@@ -514,8 +519,7 @@ impl<'d, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> BufferedCan<'d, TX_
514/// CAN driver, transmit half. 519/// CAN driver, transmit half.
515pub struct CanTx<'d> { 520pub struct CanTx<'d> {
516 _phantom: PhantomData<&'d ()>, 521 _phantom: PhantomData<&'d ()>,
517 info: &'static Info, 522 info: TxInfoRef,
518 state: &'static State,
519} 523}
520 524
521impl<'d> CanTx<'d> { 525impl<'d> CanTx<'d> {
@@ -524,7 +528,9 @@ impl<'d> CanTx<'d> {
524 /// If the TX queue is full, this will wait until there is space, therefore exerting backpressure. 528 /// If the TX queue is full, this will wait until there is space, therefore exerting backpressure.
525 pub async fn write(&mut self, frame: &Frame) -> TransmitStatus { 529 pub async fn write(&mut self, frame: &Frame) -> TransmitStatus {
526 poll_fn(|cx| { 530 poll_fn(|cx| {
527 self.state.tx_mode.register(cx.waker()); 531 self.info.state.lock(|s| {
532 s.borrow().tx_mode.register(cx.waker());
533 });
528 if let Ok(status) = self.info.regs.transmit(frame) { 534 if let Ok(status) = self.info.regs.transmit(frame) {
529 return Poll::Ready(status); 535 return Poll::Ready(status);
530 } 536 }
@@ -549,7 +555,9 @@ impl<'d> CanTx<'d> {
549 555
550 async fn flush_inner(&self, mb: Mailbox) { 556 async fn flush_inner(&self, mb: Mailbox) {
551 poll_fn(|cx| { 557 poll_fn(|cx| {
552 self.state.tx_mode.register(cx.waker()); 558 self.info.state.lock(|s| {
559 s.borrow().tx_mode.register(cx.waker());
560 });
553 if self.info.regs.0.tsr().read().tme(mb.index()) { 561 if self.info.regs.0.tsr().read().tme(mb.index()) {
554 return Poll::Ready(()); 562 return Poll::Ready(());
555 } 563 }
@@ -566,7 +574,9 @@ impl<'d> CanTx<'d> {
566 574
567 async fn flush_any_inner(&self) { 575 async fn flush_any_inner(&self) {
568 poll_fn(|cx| { 576 poll_fn(|cx| {
569 self.state.tx_mode.register(cx.waker()); 577 self.info.state.lock(|s| {
578 s.borrow().tx_mode.register(cx.waker());
579 });
570 580
571 let tsr = self.info.regs.0.tsr().read(); 581 let tsr = self.info.regs.0.tsr().read();
572 if tsr.tme(Mailbox::Mailbox0.index()) 582 if tsr.tme(Mailbox::Mailbox0.index())
@@ -593,7 +603,9 @@ impl<'d> CanTx<'d> {
593 603
594 async fn flush_all_inner(&self) { 604 async fn flush_all_inner(&self) {
595 poll_fn(|cx| { 605 poll_fn(|cx| {
596 self.state.tx_mode.register(cx.waker()); 606 self.info.state.lock(|s| {
607 s.borrow().tx_mode.register(cx.waker());
608 });
597 609
598 let tsr = self.info.regs.0.tsr().read(); 610 let tsr = self.info.regs.0.tsr().read();
599 if tsr.tme(Mailbox::Mailbox0.index()) 611 if tsr.tme(Mailbox::Mailbox0.index())
@@ -634,7 +646,7 @@ impl<'d> CanTx<'d> {
634 self, 646 self,
635 txb: &'static mut TxBuf<TX_BUF_SIZE>, 647 txb: &'static mut TxBuf<TX_BUF_SIZE>,
636 ) -> BufferedCanTx<'d, TX_BUF_SIZE> { 648 ) -> BufferedCanTx<'d, TX_BUF_SIZE> {
637 BufferedCanTx::new(self.info, self.state, self, txb) 649 BufferedCanTx::new(&self.info, self, txb)
638 } 650 }
639} 651}
640 652
@@ -643,17 +655,15 @@ pub type TxBuf<const BUF_SIZE: usize> = Channel<CriticalSectionRawMutex, Frame,
643 655
644/// Buffered CAN driver, transmit half. 656/// Buffered CAN driver, transmit half.
645pub struct BufferedCanTx<'d, const TX_BUF_SIZE: usize> { 657pub struct BufferedCanTx<'d, const TX_BUF_SIZE: usize> {
646 info: &'static Info, 658 info: TxInfoRef,
647 state: &'static State,
648 _tx: CanTx<'d>, 659 _tx: CanTx<'d>,
649 tx_buf: &'static TxBuf<TX_BUF_SIZE>, 660 tx_buf: &'static TxBuf<TX_BUF_SIZE>,
650} 661}
651 662
652impl<'d, const TX_BUF_SIZE: usize> BufferedCanTx<'d, TX_BUF_SIZE> { 663impl<'d, const TX_BUF_SIZE: usize> BufferedCanTx<'d, TX_BUF_SIZE> {
653 fn new(info: &'static Info, state: &'static State, _tx: CanTx<'d>, tx_buf: &'static TxBuf<TX_BUF_SIZE>) -> Self { 664 fn new(info: &'static Info, _tx: CanTx<'d>, tx_buf: &'static TxBuf<TX_BUF_SIZE>) -> Self {
654 Self { 665 Self {
655 info, 666 info: TxInfoRef::new(info),
656 state,
657 _tx, 667 _tx,
658 tx_buf, 668 tx_buf,
659 } 669 }
@@ -666,11 +676,9 @@ impl<'d, const TX_BUF_SIZE: usize> BufferedCanTx<'d, TX_BUF_SIZE> {
666 let tx_inner = super::common::ClassicBufferedTxInner { 676 let tx_inner = super::common::ClassicBufferedTxInner {
667 tx_receiver: self.tx_buf.receiver().into(), 677 tx_receiver: self.tx_buf.receiver().into(),
668 }; 678 };
669 let state = self.state as *const State; 679 self.info.state.lock(|s| {
670 unsafe { 680 s.borrow_mut().tx_mode = TxMode::Buffered(tx_inner);
671 let mut_state = state as *mut State; 681 });
672 (*mut_state).tx_mode = TxMode::Buffered(tx_inner);
673 }
674 }); 682 });
675 self 683 self
676 } 684 }
@@ -684,27 +692,18 @@ impl<'d, const TX_BUF_SIZE: usize> BufferedCanTx<'d, TX_BUF_SIZE> {
684 692
685 /// Returns a sender that can be used for sending CAN frames. 693 /// Returns a sender that can be used for sending CAN frames.
686 pub fn writer(&self) -> BufferedCanSender { 694 pub fn writer(&self) -> BufferedCanSender {
687 (self.info.internal_operation)(InternalOperation::NotifySenderCreated);
688 BufferedCanSender { 695 BufferedCanSender {
689 tx_buf: self.tx_buf.sender().into(), 696 tx_buf: self.tx_buf.sender().into(),
690 waker: self.info.tx_waker, 697 info: TxInfoRef::new(&self.info),
691 internal_operation: self.info.internal_operation,
692 } 698 }
693 } 699 }
694} 700}
695 701
696impl<'d, const TX_BUF_SIZE: usize> Drop for BufferedCanTx<'d, TX_BUF_SIZE> {
697 fn drop(&mut self) {
698 (self.info.internal_operation)(InternalOperation::NotifySenderDestroyed);
699 }
700}
701
702/// CAN driver, receive half. 702/// CAN driver, receive half.
703#[allow(dead_code)] 703#[allow(dead_code)]
704pub struct CanRx<'d> { 704pub struct CanRx<'d> {
705 _phantom: PhantomData<&'d ()>, 705 _phantom: PhantomData<&'d ()>,
706 info: &'static Info, 706 info: RxInfoRef,
707 state: &'static State,
708} 707}
709 708
710impl<'d> CanRx<'d> { 709impl<'d> CanRx<'d> {
@@ -714,19 +713,19 @@ impl<'d> CanRx<'d> {
714 /// 713 ///
715 /// Returns a tuple of the time the message was received and the message frame 714 /// Returns a tuple of the time the message was received and the message frame
716 pub async fn read(&mut self) -> Result<Envelope, BusError> { 715 pub async fn read(&mut self) -> Result<Envelope, BusError> {
717 self.state.rx_mode.read(self.info, self.state).await 716 RxMode::read(&self.info).await
718 } 717 }
719 718
720 /// Attempts to read a CAN frame without blocking. 719 /// Attempts to read a CAN frame without blocking.
721 /// 720 ///
722 /// Returns [Err(TryReadError::Empty)] if there are no frames in the rx queue. 721 /// Returns [Err(TryReadError::Empty)] if there are no frames in the rx queue.
723 pub fn try_read(&mut self) -> Result<Envelope, TryReadError> { 722 pub fn try_read(&mut self) -> Result<Envelope, TryReadError> {
724 self.state.rx_mode.try_read(self.info) 723 RxMode::try_read(&self.info)
725 } 724 }
726 725
727 /// Waits while receive queue is empty. 726 /// Waits while receive queue is empty.
728 pub async fn wait_not_empty(&mut self) { 727 pub async fn wait_not_empty(&mut self) {
729 self.state.rx_mode.wait_not_empty(self.info, self.state).await 728 RxMode::wait_not_empty(&self.info).await
730 } 729 }
731 730
732 /// Return a buffered instance of driver. User must supply Buffers 731 /// Return a buffered instance of driver. User must supply Buffers
@@ -734,7 +733,7 @@ impl<'d> CanRx<'d> {
734 self, 733 self,
735 rxb: &'static mut RxBuf<RX_BUF_SIZE>, 734 rxb: &'static mut RxBuf<RX_BUF_SIZE>,
736 ) -> BufferedCanRx<'d, RX_BUF_SIZE> { 735 ) -> BufferedCanRx<'d, RX_BUF_SIZE> {
737 BufferedCanRx::new(self.info, self.state, self, rxb) 736 BufferedCanRx::new(&self.info, self, rxb)
738 } 737 }
739 738
740 /// Accesses the filter banks owned by this CAN peripheral. 739 /// Accesses the filter banks owned by this CAN peripheral.
@@ -742,7 +741,7 @@ impl<'d> CanRx<'d> {
742 /// To modify filters of a slave peripheral, `modify_filters` has to be called on the master 741 /// To modify filters of a slave peripheral, `modify_filters` has to be called on the master
743 /// peripheral instead. 742 /// peripheral instead.
744 pub fn modify_filters(&mut self) -> MasterFilters<'_> { 743 pub fn modify_filters(&mut self) -> MasterFilters<'_> {
745 unsafe { MasterFilters::new(self.info) } 744 unsafe { MasterFilters::new(&self.info) }
746 } 745 }
747} 746}
748 747
@@ -751,17 +750,15 @@ pub type RxBuf<const BUF_SIZE: usize> = Channel<CriticalSectionRawMutex, Result<
751 750
752/// CAN driver, receive half in Buffered mode. 751/// CAN driver, receive half in Buffered mode.
753pub struct BufferedCanRx<'d, const RX_BUF_SIZE: usize> { 752pub struct BufferedCanRx<'d, const RX_BUF_SIZE: usize> {
754 info: &'static Info, 753 info: RxInfoRef,
755 state: &'static State,
756 rx: CanRx<'d>, 754 rx: CanRx<'d>,
757 rx_buf: &'static RxBuf<RX_BUF_SIZE>, 755 rx_buf: &'static RxBuf<RX_BUF_SIZE>,
758} 756}
759 757
760impl<'d, const RX_BUF_SIZE: usize> BufferedCanRx<'d, RX_BUF_SIZE> { 758impl<'d, const RX_BUF_SIZE: usize> BufferedCanRx<'d, RX_BUF_SIZE> {
761 fn new(info: &'static Info, state: &'static State, rx: CanRx<'d>, rx_buf: &'static RxBuf<RX_BUF_SIZE>) -> Self { 759 fn new(info: &'static Info, rx: CanRx<'d>, rx_buf: &'static RxBuf<RX_BUF_SIZE>) -> Self {
762 BufferedCanRx { 760 BufferedCanRx {
763 info, 761 info: RxInfoRef::new(info),
764 state,
765 rx, 762 rx,
766 rx_buf, 763 rx_buf,
767 } 764 }
@@ -774,11 +771,9 @@ impl<'d, const RX_BUF_SIZE: usize> BufferedCanRx<'d, RX_BUF_SIZE> {
774 let rx_inner = super::common::ClassicBufferedRxInner { 771 let rx_inner = super::common::ClassicBufferedRxInner {
775 rx_sender: self.rx_buf.sender().into(), 772 rx_sender: self.rx_buf.sender().into(),
776 }; 773 };
777 let state = self.state as *const State; 774 self.info.state.lock(|s| {
778 unsafe { 775 s.borrow_mut().rx_mode = RxMode::Buffered(rx_inner);
779 let mut_state = state as *mut State; 776 });
780 (*mut_state).rx_mode = RxMode::Buffered(rx_inner);
781 }
782 }); 777 });
783 self 778 self
784 } 779 }
@@ -792,7 +787,7 @@ impl<'d, const RX_BUF_SIZE: usize> BufferedCanRx<'d, RX_BUF_SIZE> {
792 /// 787 ///
793 /// Returns [Err(TryReadError::Empty)] if there are no frames in the rx queue. 788 /// Returns [Err(TryReadError::Empty)] if there are no frames in the rx queue.
794 pub fn try_read(&mut self) -> Result<Envelope, TryReadError> { 789 pub fn try_read(&mut self) -> Result<Envelope, TryReadError> {
795 match &self.state.rx_mode { 790 self.info.state.lock(|s| match &s.borrow().rx_mode {
796 RxMode::Buffered(_) => { 791 RxMode::Buffered(_) => {
797 if let Ok(result) = self.rx_buf.try_receive() { 792 if let Ok(result) = self.rx_buf.try_receive() {
798 match result { 793 match result {
@@ -810,7 +805,7 @@ impl<'d, const RX_BUF_SIZE: usize> BufferedCanRx<'d, RX_BUF_SIZE> {
810 _ => { 805 _ => {
811 panic!("Bad Mode") 806 panic!("Bad Mode")
812 } 807 }
813 } 808 })
814 } 809 }
815 810
816 /// Waits while receive queue is empty. 811 /// Waits while receive queue is empty.
@@ -820,10 +815,9 @@ impl<'d, const RX_BUF_SIZE: usize> BufferedCanRx<'d, RX_BUF_SIZE> {
820 815
821 /// Returns a receiver that can be used for receiving CAN frames. Note, each CAN frame will only be received by one receiver. 816 /// Returns a receiver that can be used for receiving CAN frames. Note, each CAN frame will only be received by one receiver.
822 pub fn reader(&self) -> BufferedCanReceiver { 817 pub fn reader(&self) -> BufferedCanReceiver {
823 (self.info.internal_operation)(InternalOperation::NotifyReceiverCreated);
824 BufferedCanReceiver { 818 BufferedCanReceiver {
825 rx_buf: self.rx_buf.receiver().into(), 819 rx_buf: self.rx_buf.receiver().into(),
826 internal_operation: self.info.internal_operation, 820 info: RxInfoRef::new(&self.info),
827 } 821 }
828 } 822 }
829 823
@@ -836,12 +830,6 @@ impl<'d, const RX_BUF_SIZE: usize> BufferedCanRx<'d, RX_BUF_SIZE> {
836 } 830 }
837} 831}
838 832
839impl<'d, const RX_BUF_SIZE: usize> Drop for BufferedCanRx<'d, RX_BUF_SIZE> {
840 fn drop(&mut self) {
841 (self.info.internal_operation)(InternalOperation::NotifyReceiverDestroyed);
842 }
843}
844
845impl Drop for Can<'_> { 833impl Drop for Can<'_> {
846 fn drop(&mut self) { 834 fn drop(&mut self) {
847 // Cannot call `free()` because it moves the instance. 835 // Cannot call `free()` because it moves the instance.
@@ -929,27 +917,30 @@ impl RxMode {
929 } 917 }
930 } 918 }
931 919
932 pub(crate) async fn read(&self, info: &Info, state: &State) -> Result<Envelope, BusError> { 920 pub(crate) async fn read(info: &Info) -> Result<Envelope, BusError> {
933 match self { 921 poll_fn(|cx| {
934 Self::NonBuffered(waker) => { 922 info.state.lock(|state| {
935 poll_fn(|cx| { 923 let state = state.borrow();
936 state.err_waker.register(cx.waker()); 924 state.err_waker.register(cx.waker());
937 waker.register(cx.waker()); 925 match &state.rx_mode {
938 match self.try_read(info) { 926 Self::NonBuffered(waker) => {
939 Ok(result) => Poll::Ready(Ok(result)), 927 waker.register(cx.waker());
940 Err(TryReadError::Empty) => Poll::Pending,
941 Err(TryReadError::BusError(be)) => Poll::Ready(Err(be)),
942 } 928 }
943 }) 929 _ => {
944 .await 930 panic!("Bad Mode")
945 } 931 }
946 _ => { 932 }
947 panic!("Bad Mode") 933 });
934 match RxMode::try_read(info) {
935 Ok(result) => Poll::Ready(Ok(result)),
936 Err(TryReadError::Empty) => Poll::Pending,
937 Err(TryReadError::BusError(be)) => Poll::Ready(Err(be)),
948 } 938 }
949 } 939 })
940 .await
950 } 941 }
951 pub(crate) fn try_read(&self, info: &Info) -> Result<Envelope, TryReadError> { 942 pub(crate) fn try_read(info: &Info) -> Result<Envelope, TryReadError> {
952 match self { 943 info.state.lock(|state| match state.borrow().rx_mode {
953 Self::NonBuffered(_) => { 944 Self::NonBuffered(_) => {
954 let registers = &info.regs; 945 let registers = &info.regs;
955 if let Some(msg) = registers.receive_fifo(RxFifo::Fifo0) { 946 if let Some(msg) = registers.receive_fifo(RxFifo::Fifo0) {
@@ -975,25 +966,28 @@ impl RxMode {
975 _ => { 966 _ => {
976 panic!("Bad Mode") 967 panic!("Bad Mode")
977 } 968 }
978 } 969 })
979 } 970 }
980 pub(crate) async fn wait_not_empty(&self, info: &Info, state: &State) { 971 pub(crate) async fn wait_not_empty(info: &Info) {
981 match &state.rx_mode { 972 poll_fn(|cx| {
982 Self::NonBuffered(waker) => { 973 info.state.lock(|s| {
983 poll_fn(|cx| { 974 let state = s.borrow();
984 waker.register(cx.waker()); 975 match &state.rx_mode {
985 if info.regs.receive_frame_available() { 976 Self::NonBuffered(waker) => {
986 Poll::Ready(()) 977 waker.register(cx.waker());
987 } else {
988 Poll::Pending
989 } 978 }
990 }) 979 _ => {
991 .await 980 panic!("Bad Mode")
992 } 981 }
993 _ => { 982 }
994 panic!("Bad Mode") 983 });
984 if info.regs.receive_frame_available() {
985 Poll::Ready(())
986 } else {
987 Poll::Pending
995 } 988 }
996 } 989 })
990 .await
997 } 991 }
998} 992}
999 993
@@ -1008,21 +1002,25 @@ impl TxMode {
1008 tsr.tme(Mailbox::Mailbox0.index()) || tsr.tme(Mailbox::Mailbox1.index()) || tsr.tme(Mailbox::Mailbox2.index()) 1002 tsr.tme(Mailbox::Mailbox0.index()) || tsr.tme(Mailbox::Mailbox1.index()) || tsr.tme(Mailbox::Mailbox2.index())
1009 } 1003 }
1010 pub fn on_interrupt<T: Instance>(&self) { 1004 pub fn on_interrupt<T: Instance>(&self) {
1011 match &T::state().tx_mode { 1005 T::info().state.lock(|state| {
1012 TxMode::NonBuffered(waker) => waker.wake(), 1006 let tx_mode = &state.borrow().tx_mode;
1013 TxMode::Buffered(buf) => { 1007
1014 while self.buffer_free::<T>() { 1008 match tx_mode {
1015 match buf.tx_receiver.try_receive() { 1009 TxMode::NonBuffered(waker) => waker.wake(),
1016 Ok(frame) => { 1010 TxMode::Buffered(buf) => {
1017 _ = Registers(T::regs()).transmit(&frame); 1011 while self.buffer_free::<T>() {
1018 } 1012 match buf.tx_receiver.try_receive() {
1019 Err(_) => { 1013 Ok(frame) => {
1020 break; 1014 _ = Registers(T::regs()).transmit(&frame);
1015 }
1016 Err(_) => {
1017 break;
1018 }
1021 } 1019 }
1022 } 1020 }
1023 } 1021 }
1024 } 1022 }
1025 } 1023 });
1026 } 1024 }
1027 1025
1028 fn register(&self, arg: &core::task::Waker) { 1026 fn register(&self, arg: &core::task::Waker) {
@@ -1057,14 +1055,15 @@ impl State {
1057 } 1055 }
1058} 1056}
1059 1057
1058type SharedState = embassy_sync::blocking_mutex::Mutex<CriticalSectionRawMutex, core::cell::RefCell<State>>;
1060pub(crate) struct Info { 1059pub(crate) struct Info {
1061 regs: Registers, 1060 regs: Registers,
1062 tx_interrupt: crate::interrupt::Interrupt, 1061 tx_interrupt: crate::interrupt::Interrupt,
1063 rx0_interrupt: crate::interrupt::Interrupt, 1062 rx0_interrupt: crate::interrupt::Interrupt,
1064 rx1_interrupt: crate::interrupt::Interrupt, 1063 rx1_interrupt: crate::interrupt::Interrupt,
1065 sce_interrupt: crate::interrupt::Interrupt, 1064 sce_interrupt: crate::interrupt::Interrupt,
1066 tx_waker: fn(), 1065 pub(crate) tx_waker: fn(),
1067 internal_operation: fn(InternalOperation), 1066 state: SharedState,
1068 1067
1069 /// The total number of filter banks available to the instance. 1068 /// The total number of filter banks available to the instance.
1070 /// 1069 ///
@@ -1072,12 +1071,37 @@ pub(crate) struct Info {
1072 num_filter_banks: u8, 1071 num_filter_banks: u8,
1073} 1072}
1074 1073
1074impl Info {
1075 pub(crate) fn adjust_reference_counter(&self, val: RefCountOp) {
1076 self.state.lock(|s| {
1077 let mut mut_state = s.borrow_mut();
1078 match val {
1079 RefCountOp::NotifySenderCreated => {
1080 mut_state.sender_instance_count += 1;
1081 }
1082 RefCountOp::NotifySenderDestroyed => {
1083 mut_state.sender_instance_count -= 1;
1084 if 0 == mut_state.sender_instance_count {
1085 (*mut_state).tx_mode = TxMode::NonBuffered(embassy_sync::waitqueue::AtomicWaker::new());
1086 }
1087 }
1088 RefCountOp::NotifyReceiverCreated => {
1089 mut_state.receiver_instance_count += 1;
1090 }
1091 RefCountOp::NotifyReceiverDestroyed => {
1092 mut_state.receiver_instance_count -= 1;
1093 if 0 == mut_state.receiver_instance_count {
1094 (*mut_state).rx_mode = RxMode::NonBuffered(embassy_sync::waitqueue::AtomicWaker::new());
1095 }
1096 }
1097 }
1098 });
1099 }
1100}
1101
1075trait SealedInstance { 1102trait SealedInstance {
1076 fn info() -> &'static Info; 1103 fn info() -> &'static Info;
1077 fn regs() -> crate::pac::can::Can; 1104 fn regs() -> crate::pac::can::Can;
1078 fn state() -> &'static State;
1079 unsafe fn mut_state() -> &'static mut State;
1080 fn internal_operation(val: InternalOperation);
1081} 1105}
1082 1106
1083/// CAN instance trait. 1107/// CAN instance trait.
@@ -1135,53 +1159,14 @@ foreach_peripheral!(
1135 rx1_interrupt: crate::_generated::peripheral_interrupts::$inst::RX1::IRQ, 1159 rx1_interrupt: crate::_generated::peripheral_interrupts::$inst::RX1::IRQ,
1136 sce_interrupt: crate::_generated::peripheral_interrupts::$inst::SCE::IRQ, 1160 sce_interrupt: crate::_generated::peripheral_interrupts::$inst::SCE::IRQ,
1137 tx_waker: crate::_generated::peripheral_interrupts::$inst::TX::pend, 1161 tx_waker: crate::_generated::peripheral_interrupts::$inst::TX::pend,
1138 internal_operation: peripherals::$inst::internal_operation,
1139 num_filter_banks: peripherals::$inst::NUM_FILTER_BANKS, 1162 num_filter_banks: peripherals::$inst::NUM_FILTER_BANKS,
1163 state: embassy_sync::blocking_mutex::Mutex::new(core::cell::RefCell::new(State::new())),
1140 }; 1164 };
1141 &INFO 1165 &INFO
1142 } 1166 }
1143 fn regs() -> crate::pac::can::Can { 1167 fn regs() -> crate::pac::can::Can {
1144 crate::pac::$inst 1168 crate::pac::$inst
1145 } 1169 }
1146
1147 unsafe fn mut_state() -> & 'static mut State {
1148 static mut STATE: State = State::new();
1149 &mut *core::ptr::addr_of_mut!(STATE)
1150 }
1151 fn state() -> &'static State {
1152 unsafe { peripherals::$inst::mut_state() }
1153 }
1154
1155
1156 fn internal_operation(val: InternalOperation) {
1157 critical_section::with(|_| {
1158 //let state = self.state as *const State;
1159 unsafe {
1160 //let mut_state = state as *mut State;
1161 let mut_state = peripherals::$inst::mut_state();
1162 match val {
1163 InternalOperation::NotifySenderCreated => {
1164 mut_state.sender_instance_count += 1;
1165 }
1166 InternalOperation::NotifySenderDestroyed => {
1167 mut_state.sender_instance_count -= 1;
1168 if ( 0 == mut_state.sender_instance_count) {
1169 (*mut_state).tx_mode = TxMode::NonBuffered(embassy_sync::waitqueue::AtomicWaker::new());
1170 }
1171 }
1172 InternalOperation::NotifyReceiverCreated => {
1173 mut_state.receiver_instance_count += 1;
1174 }
1175 InternalOperation::NotifyReceiverDestroyed => {
1176 mut_state.receiver_instance_count -= 1;
1177 if ( 0 == mut_state.receiver_instance_count) {
1178 (*mut_state).rx_mode = RxMode::NonBuffered(embassy_sync::waitqueue::AtomicWaker::new());
1179 }
1180 }
1181 }
1182 }
1183 });
1184 }
1185 } 1170 }
1186 1171
1187 impl Instance for peripherals::$inst { 1172 impl Instance for peripherals::$inst {
diff --git a/embassy-stm32/src/can/common.rs b/embassy-stm32/src/can/common.rs
index 386d4467c..980f33a04 100644
--- a/embassy-stm32/src/can/common.rs
+++ b/embassy-stm32/src/can/common.rs
@@ -24,22 +24,21 @@ pub(crate) struct FdBufferedTxInner {
24/// Sender that can be used for sending CAN frames. 24/// Sender that can be used for sending CAN frames.
25pub struct BufferedSender<'ch, FRAME> { 25pub struct BufferedSender<'ch, FRAME> {
26 pub(crate) tx_buf: embassy_sync::channel::SendDynamicSender<'ch, FRAME>, 26 pub(crate) tx_buf: embassy_sync::channel::SendDynamicSender<'ch, FRAME>,
27 pub(crate) waker: fn(), 27 pub(crate) info: TxInfoRef,
28 pub(crate) internal_operation: fn(InternalOperation),
29} 28}
30 29
31impl<'ch, FRAME> BufferedSender<'ch, FRAME> { 30impl<'ch, FRAME> BufferedSender<'ch, FRAME> {
32 /// Async write frame to TX buffer. 31 /// Async write frame to TX buffer.
33 pub fn try_write(&mut self, frame: FRAME) -> Result<(), embassy_sync::channel::TrySendError<FRAME>> { 32 pub fn try_write(&mut self, frame: FRAME) -> Result<(), embassy_sync::channel::TrySendError<FRAME>> {
34 self.tx_buf.try_send(frame)?; 33 self.tx_buf.try_send(frame)?;
35 (self.waker)(); 34 (self.info.tx_waker)();
36 Ok(()) 35 Ok(())
37 } 36 }
38 37
39 /// Async write frame to TX buffer. 38 /// Async write frame to TX buffer.
40 pub async fn write(&mut self, frame: FRAME) { 39 pub async fn write(&mut self, frame: FRAME) {
41 self.tx_buf.send(frame).await; 40 self.tx_buf.send(frame).await;
42 (self.waker)(); 41 (self.info.tx_waker)();
43 } 42 }
44 43
45 /// Allows a poll_fn to poll until the channel is ready to write 44 /// Allows a poll_fn to poll until the channel is ready to write
@@ -50,28 +49,20 @@ impl<'ch, FRAME> BufferedSender<'ch, FRAME> {
50 49
51impl<'ch, FRAME> Clone for BufferedSender<'ch, FRAME> { 50impl<'ch, FRAME> Clone for BufferedSender<'ch, FRAME> {
52 fn clone(&self) -> Self { 51 fn clone(&self) -> Self {
53 (self.internal_operation)(InternalOperation::NotifySenderCreated);
54 Self { 52 Self {
55 tx_buf: self.tx_buf, 53 tx_buf: self.tx_buf,
56 waker: self.waker, 54 info: TxInfoRef::new(&self.info),
57 internal_operation: self.internal_operation,
58 } 55 }
59 } 56 }
60} 57}
61 58
62impl<'ch, FRAME> Drop for BufferedSender<'ch, FRAME> {
63 fn drop(&mut self) {
64 (self.internal_operation)(InternalOperation::NotifySenderDestroyed);
65 }
66}
67
68/// Sender that can be used for sending Classic CAN frames. 59/// Sender that can be used for sending Classic CAN frames.
69pub type BufferedCanSender = BufferedSender<'static, Frame>; 60pub type BufferedCanSender = BufferedSender<'static, Frame>;
70 61
71/// Receiver that can be used for receiving CAN frames. Note, each CAN frame will only be received by one receiver. 62/// Receiver that can be used for receiving CAN frames. Note, each CAN frame will only be received by one receiver.
72pub struct BufferedReceiver<'ch, ENVELOPE> { 63pub struct BufferedReceiver<'ch, ENVELOPE> {
73 pub(crate) rx_buf: embassy_sync::channel::SendDynamicReceiver<'ch, Result<ENVELOPE, BusError>>, 64 pub(crate) rx_buf: embassy_sync::channel::SendDynamicReceiver<'ch, Result<ENVELOPE, BusError>>,
74 pub(crate) internal_operation: fn(InternalOperation), 65 pub(crate) info: RxInfoRef,
75} 66}
76 67
77impl<'ch, ENVELOPE> BufferedReceiver<'ch, ENVELOPE> { 68impl<'ch, ENVELOPE> BufferedReceiver<'ch, ENVELOPE> {
@@ -106,19 +97,99 @@ impl<'ch, ENVELOPE> BufferedReceiver<'ch, ENVELOPE> {
106 97
107impl<'ch, ENVELOPE> Clone for BufferedReceiver<'ch, ENVELOPE> { 98impl<'ch, ENVELOPE> Clone for BufferedReceiver<'ch, ENVELOPE> {
108 fn clone(&self) -> Self { 99 fn clone(&self) -> Self {
109 (self.internal_operation)(InternalOperation::NotifyReceiverCreated);
110 Self { 100 Self {
111 rx_buf: self.rx_buf, 101 rx_buf: self.rx_buf,
112 internal_operation: self.internal_operation, 102 info: RxInfoRef::new(&self.info),
113 } 103 }
114 } 104 }
115} 105}
116 106
117impl<'ch, ENVELOPE> Drop for BufferedReceiver<'ch, ENVELOPE> { 107/// A BufferedCanReceiver for Classic CAN frames.
108pub type BufferedCanReceiver = BufferedReceiver<'static, Envelope>;
109
110/// Provides a reference to the driver internals and implements RAII for the internal reference
111/// counting. Each type that can operate on the driver should contain either InfoRef
112/// or the similar TxInfoRef or RxInfoRef. The new method and the Drop impl will automatically
113/// call the reference counting function. Like this, the reference counting function does not
114/// need to be called manually for each type.
115pub(crate) struct InfoRef {
116 info: &'static super::Info,
117}
118impl InfoRef {
119 pub(crate) fn new(info: &'static super::Info) -> Self {
120 info.adjust_reference_counter(RefCountOp::NotifyReceiverCreated);
121 info.adjust_reference_counter(RefCountOp::NotifySenderCreated);
122 Self { info }
123 }
124}
125
126impl Drop for InfoRef {
118 fn drop(&mut self) { 127 fn drop(&mut self) {
119 (self.internal_operation)(InternalOperation::NotifyReceiverDestroyed); 128 self.info.adjust_reference_counter(RefCountOp::NotifyReceiverDestroyed);
129 self.info.adjust_reference_counter(RefCountOp::NotifySenderDestroyed);
120 } 130 }
121} 131}
122 132
123/// A BufferedCanReceiver for Classic CAN frames. 133impl core::ops::Deref for InfoRef {
124pub type BufferedCanReceiver = BufferedReceiver<'static, Envelope>; 134 type Target = &'static super::Info;
135
136 fn deref(&self) -> &Self::Target {
137 &self.info
138 }
139}
140
141/// Provides a reference to the driver internals and implements RAII for the internal reference
142/// counting for Tx only types.
143/// See InfoRef for further doc.
144pub(crate) struct TxInfoRef {
145 info: &'static super::Info,
146}
147
148impl TxInfoRef {
149 pub(crate) fn new(info: &'static super::Info) -> Self {
150 info.adjust_reference_counter(RefCountOp::NotifySenderCreated);
151 Self { info }
152 }
153}
154
155impl Drop for TxInfoRef {
156 fn drop(&mut self) {
157 self.info.adjust_reference_counter(RefCountOp::NotifySenderDestroyed);
158 }
159}
160
161impl core::ops::Deref for TxInfoRef {
162 type Target = &'static super::Info;
163
164 fn deref(&self) -> &Self::Target {
165 &self.info
166 }
167}
168
169/// Provides a reference to the driver internals and implements RAII for the internal reference
170/// counting for Rx only types.
171/// See InfoRef for further doc.
172pub(crate) struct RxInfoRef {
173 info: &'static super::Info,
174}
175
176impl RxInfoRef {
177 pub(crate) fn new(info: &'static super::Info) -> Self {
178 info.adjust_reference_counter(RefCountOp::NotifyReceiverCreated);
179 Self { info }
180 }
181}
182
183impl Drop for RxInfoRef {
184 fn drop(&mut self) {
185 self.info.adjust_reference_counter(RefCountOp::NotifyReceiverDestroyed);
186 }
187}
188
189impl core::ops::Deref for RxInfoRef {
190 type Target = &'static super::Info;
191
192 fn deref(&self) -> &Self::Target {
193 &self.info
194 }
195}
diff --git a/embassy-stm32/src/can/enums.rs b/embassy-stm32/src/can/enums.rs
index 97cb47640..6d91020fc 100644
--- a/embassy-stm32/src/can/enums.rs
+++ b/embassy-stm32/src/can/enums.rs
@@ -72,7 +72,7 @@ pub enum TryReadError {
72/// Internal Operation 72/// Internal Operation
73#[derive(Debug)] 73#[derive(Debug)]
74#[cfg_attr(feature = "defmt", derive(defmt::Format))] 74#[cfg_attr(feature = "defmt", derive(defmt::Format))]
75pub enum InternalOperation { 75pub enum RefCountOp {
76 /// Notify receiver created 76 /// Notify receiver created
77 NotifyReceiverCreated, 77 NotifyReceiverCreated,
78 /// Notify receiver destroyed 78 /// Notify receiver destroyed
diff --git a/embassy-stm32/src/can/fdcan.rs b/embassy-stm32/src/can/fdcan.rs
index 97d22315a..99e40ba62 100644
--- a/embassy-stm32/src/can/fdcan.rs
+++ b/embassy-stm32/src/can/fdcan.rs
@@ -21,6 +21,7 @@ use self::fd::config::*;
21use self::fd::filter::*; 21use self::fd::filter::*;
22pub use self::fd::{config, filter}; 22pub use self::fd::{config, filter};
23pub use super::common::{BufferedCanReceiver, BufferedCanSender}; 23pub use super::common::{BufferedCanReceiver, BufferedCanSender};
24use super::common::{InfoRef, RxInfoRef, TxInfoRef};
24use super::enums::*; 25use super::enums::*;
25use super::frame::*; 26use super::frame::*;
26use super::util; 27use super::util;
@@ -167,10 +168,10 @@ fn calc_ns_per_timer_tick(
167pub struct CanConfigurator<'d> { 168pub struct CanConfigurator<'d> {
168 _phantom: PhantomData<&'d ()>, 169 _phantom: PhantomData<&'d ()>,
169 config: crate::can::fd::config::FdCanConfig, 170 config: crate::can::fd::config::FdCanConfig,
170 info: &'static Info,
171 /// Reference to internals. 171 /// Reference to internals.
172 properties: Properties, 172 properties: Properties,
173 periph_clock: crate::time::Hertz, 173 periph_clock: crate::time::Hertz,
174 info: InfoRef,
174} 175}
175 176
176impl<'d> CanConfigurator<'d> { 177impl<'d> CanConfigurator<'d> {
@@ -194,8 +195,6 @@ impl<'d> CanConfigurator<'d> {
194 s.borrow_mut().tx_pin_port = Some(tx.pin_port()); 195 s.borrow_mut().tx_pin_port = Some(tx.pin_port());
195 s.borrow_mut().rx_pin_port = Some(rx.pin_port()); 196 s.borrow_mut().rx_pin_port = Some(rx.pin_port());
196 }); 197 });
197 (info.internal_operation)(InternalOperation::NotifySenderCreated);
198 (info.internal_operation)(InternalOperation::NotifyReceiverCreated);
199 198
200 let mut config = crate::can::fd::config::FdCanConfig::default(); 199 let mut config = crate::can::fd::config::FdCanConfig::default();
201 config.timestamp_source = TimestampSource::Prescaler(TimestampPrescaler::_1); 200 config.timestamp_source = TimestampSource::Prescaler(TimestampPrescaler::_1);
@@ -211,9 +210,9 @@ impl<'d> CanConfigurator<'d> {
211 Self { 210 Self {
212 _phantom: PhantomData, 211 _phantom: PhantomData,
213 config, 212 config,
214 info,
215 properties: Properties::new(T::info()), 213 properties: Properties::new(T::info()),
216 periph_clock: T::frequency(), 214 periph_clock: T::frequency(),
215 info: InfoRef::new(info),
217 } 216 }
218 } 217 }
219 218
@@ -262,19 +261,17 @@ impl<'d> CanConfigurator<'d> {
262 261
263 /// Start in mode. 262 /// Start in mode.
264 pub fn start(self, mode: OperatingMode) -> Can<'d> { 263 pub fn start(self, mode: OperatingMode) -> Can<'d> {
265 let ns_per_timer_tick = calc_ns_per_timer_tick(self.info, self.periph_clock, self.config.frame_transmit); 264 let ns_per_timer_tick = calc_ns_per_timer_tick(&self.info, self.periph_clock, self.config.frame_transmit);
266 self.info.state.lock(|s| { 265 self.info.state.lock(|s| {
267 s.borrow_mut().ns_per_timer_tick = ns_per_timer_tick; 266 s.borrow_mut().ns_per_timer_tick = ns_per_timer_tick;
268 }); 267 });
269 self.info.regs.into_mode(self.config, mode); 268 self.info.regs.into_mode(self.config, mode);
270 (self.info.internal_operation)(InternalOperation::NotifySenderCreated);
271 (self.info.internal_operation)(InternalOperation::NotifyReceiverCreated);
272 Can { 269 Can {
273 _phantom: PhantomData, 270 _phantom: PhantomData,
274 config: self.config, 271 config: self.config,
275 info: self.info,
276 _mode: mode, 272 _mode: mode,
277 properties: Properties::new(self.info), 273 properties: Properties::new(&self.info),
274 info: InfoRef::new(&self.info),
278 } 275 }
279 } 276 }
280 277
@@ -294,20 +291,13 @@ impl<'d> CanConfigurator<'d> {
294 } 291 }
295} 292}
296 293
297impl<'d> Drop for CanConfigurator<'d> {
298 fn drop(&mut self) {
299 (self.info.internal_operation)(InternalOperation::NotifySenderDestroyed);
300 (self.info.internal_operation)(InternalOperation::NotifyReceiverDestroyed);
301 }
302}
303
304/// FDCAN Instance 294/// FDCAN Instance
305pub struct Can<'d> { 295pub struct Can<'d> {
306 _phantom: PhantomData<&'d ()>, 296 _phantom: PhantomData<&'d ()>,
307 config: crate::can::fd::config::FdCanConfig, 297 config: crate::can::fd::config::FdCanConfig,
308 info: &'static Info,
309 _mode: OperatingMode, 298 _mode: OperatingMode,
310 properties: Properties, 299 properties: Properties,
300 info: InfoRef,
311} 301}
312 302
313impl<'d> Can<'d> { 303impl<'d> Can<'d> {
@@ -341,12 +331,12 @@ impl<'d> Can<'d> {
341 /// can be replaced, this call asynchronously waits for a frame to be successfully 331 /// can be replaced, this call asynchronously waits for a frame to be successfully
342 /// transmitted, then tries again. 332 /// transmitted, then tries again.
343 pub async fn write(&mut self, frame: &Frame) -> Option<Frame> { 333 pub async fn write(&mut self, frame: &Frame) -> Option<Frame> {
344 TxMode::write(self.info, frame).await 334 TxMode::write(&self.info, frame).await
345 } 335 }
346 336
347 /// Returns the next received message frame 337 /// Returns the next received message frame
348 pub async fn read(&mut self) -> Result<Envelope, BusError> { 338 pub async fn read(&mut self) -> Result<Envelope, BusError> {
349 RxMode::read_classic(self.info).await 339 RxMode::read_classic(&self.info).await
350 } 340 }
351 341
352 /// Queues the message to be sent but exerts backpressure. If a lower-priority 342 /// Queues the message to be sent but exerts backpressure. If a lower-priority
@@ -354,29 +344,27 @@ impl<'d> Can<'d> {
354 /// can be replaced, this call asynchronously waits for a frame to be successfully 344 /// can be replaced, this call asynchronously waits for a frame to be successfully
355 /// transmitted, then tries again. 345 /// transmitted, then tries again.
356 pub async fn write_fd(&mut self, frame: &FdFrame) -> Option<FdFrame> { 346 pub async fn write_fd(&mut self, frame: &FdFrame) -> Option<FdFrame> {
357 TxMode::write_fd(self.info, frame).await 347 TxMode::write_fd(&self.info, frame).await
358 } 348 }
359 349
360 /// Returns the next received message frame 350 /// Returns the next received message frame
361 pub async fn read_fd(&mut self) -> Result<FdEnvelope, BusError> { 351 pub async fn read_fd(&mut self) -> Result<FdEnvelope, BusError> {
362 RxMode::read_fd(self.info).await 352 RxMode::read_fd(&self.info).await
363 } 353 }
364 354
365 /// Split instance into separate portions: Tx(write), Rx(read), common properties 355 /// Split instance into separate portions: Tx(write), Rx(read), common properties
366 pub fn split(self) -> (CanTx<'d>, CanRx<'d>, Properties) { 356 pub fn split(self) -> (CanTx<'d>, CanRx<'d>, Properties) {
367 (self.info.internal_operation)(InternalOperation::NotifySenderCreated);
368 (self.info.internal_operation)(InternalOperation::NotifyReceiverCreated);
369 ( 357 (
370 CanTx { 358 CanTx {
371 _phantom: PhantomData, 359 _phantom: PhantomData,
372 info: self.info,
373 config: self.config, 360 config: self.config,
374 _mode: self._mode, 361 _mode: self._mode,
362 info: TxInfoRef::new(&self.info),
375 }, 363 },
376 CanRx { 364 CanRx {
377 _phantom: PhantomData, 365 _phantom: PhantomData,
378 info: self.info,
379 _mode: self._mode, 366 _mode: self._mode,
367 info: RxInfoRef::new(&self.info),
380 }, 368 },
381 Properties { 369 Properties {
382 info: self.properties.info, 370 info: self.properties.info,
@@ -385,14 +373,12 @@ impl<'d> Can<'d> {
385 } 373 }
386 /// Join split rx and tx portions back together 374 /// Join split rx and tx portions back together
387 pub fn join(tx: CanTx<'d>, rx: CanRx<'d>) -> Self { 375 pub fn join(tx: CanTx<'d>, rx: CanRx<'d>) -> Self {
388 (tx.info.internal_operation)(InternalOperation::NotifySenderCreated);
389 (tx.info.internal_operation)(InternalOperation::NotifyReceiverCreated);
390 Can { 376 Can {
391 _phantom: PhantomData, 377 _phantom: PhantomData,
392 config: tx.config, 378 config: tx.config,
393 info: tx.info,
394 _mode: rx._mode, 379 _mode: rx._mode,
395 properties: Properties::new(tx.info), 380 properties: Properties::new(&tx.info),
381 info: InfoRef::new(&tx.info),
396 } 382 }
397 } 383 }
398 384
@@ -402,7 +388,7 @@ impl<'d> Can<'d> {
402 tx_buf: &'static mut TxBuf<TX_BUF_SIZE>, 388 tx_buf: &'static mut TxBuf<TX_BUF_SIZE>,
403 rxb: &'static mut RxBuf<RX_BUF_SIZE>, 389 rxb: &'static mut RxBuf<RX_BUF_SIZE>,
404 ) -> BufferedCan<'d, TX_BUF_SIZE, RX_BUF_SIZE> { 390 ) -> BufferedCan<'d, TX_BUF_SIZE, RX_BUF_SIZE> {
405 BufferedCan::new(self.info, self._mode, tx_buf, rxb) 391 BufferedCan::new(&self.info, self._mode, tx_buf, rxb)
406 } 392 }
407 393
408 /// Return a buffered instance of driver with CAN FD support. User must supply Buffers 394 /// Return a buffered instance of driver with CAN FD support. User must supply Buffers
@@ -411,14 +397,7 @@ impl<'d> Can<'d> {
411 tx_buf: &'static mut TxFdBuf<TX_BUF_SIZE>, 397 tx_buf: &'static mut TxFdBuf<TX_BUF_SIZE>,
412 rxb: &'static mut RxFdBuf<RX_BUF_SIZE>, 398 rxb: &'static mut RxFdBuf<RX_BUF_SIZE>,
413 ) -> BufferedCanFd<'d, TX_BUF_SIZE, RX_BUF_SIZE> { 399 ) -> BufferedCanFd<'d, TX_BUF_SIZE, RX_BUF_SIZE> {
414 BufferedCanFd::new(self.info, self._mode, tx_buf, rxb) 400 BufferedCanFd::new(&self.info, self._mode, tx_buf, rxb)
415 }
416}
417
418impl<'d> Drop for Can<'d> {
419 fn drop(&mut self) {
420 (self.info.internal_operation)(InternalOperation::NotifySenderDestroyed);
421 (self.info.internal_operation)(InternalOperation::NotifyReceiverDestroyed);
422 } 401 }
423} 402}
424 403
@@ -431,11 +410,11 @@ pub type TxBuf<const BUF_SIZE: usize> = Channel<CriticalSectionRawMutex, Frame,
431/// Buffered FDCAN Instance 410/// Buffered FDCAN Instance
432pub struct BufferedCan<'d, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> { 411pub struct BufferedCan<'d, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> {
433 _phantom: PhantomData<&'d ()>, 412 _phantom: PhantomData<&'d ()>,
434 info: &'static Info,
435 _mode: OperatingMode, 413 _mode: OperatingMode,
436 tx_buf: &'static TxBuf<TX_BUF_SIZE>, 414 tx_buf: &'static TxBuf<TX_BUF_SIZE>,
437 rx_buf: &'static RxBuf<RX_BUF_SIZE>, 415 rx_buf: &'static RxBuf<RX_BUF_SIZE>,
438 properties: Properties, 416 properties: Properties,
417 info: InfoRef,
439} 418}
440 419
441impl<'c, 'd, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> BufferedCan<'d, TX_BUF_SIZE, RX_BUF_SIZE> { 420impl<'c, 'd, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> BufferedCan<'d, TX_BUF_SIZE, RX_BUF_SIZE> {
@@ -445,15 +424,13 @@ impl<'c, 'd, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> BufferedCan<'d,
445 tx_buf: &'static TxBuf<TX_BUF_SIZE>, 424 tx_buf: &'static TxBuf<TX_BUF_SIZE>,
446 rx_buf: &'static RxBuf<RX_BUF_SIZE>, 425 rx_buf: &'static RxBuf<RX_BUF_SIZE>,
447 ) -> Self { 426 ) -> Self {
448 (info.internal_operation)(InternalOperation::NotifySenderCreated);
449 (info.internal_operation)(InternalOperation::NotifyReceiverCreated);
450 BufferedCan { 427 BufferedCan {
451 _phantom: PhantomData, 428 _phantom: PhantomData,
452 info,
453 _mode, 429 _mode,
454 tx_buf, 430 tx_buf,
455 rx_buf, 431 rx_buf,
456 properties: Properties::new(info), 432 properties: Properties::new(info),
433 info: InfoRef::new(info),
457 } 434 }
458 .setup() 435 .setup()
459 } 436 }
@@ -492,31 +469,21 @@ impl<'c, 'd, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> BufferedCan<'d,
492 469
493 /// Returns a sender that can be used for sending CAN frames. 470 /// Returns a sender that can be used for sending CAN frames.
494 pub fn writer(&self) -> BufferedCanSender { 471 pub fn writer(&self) -> BufferedCanSender {
495 (self.info.internal_operation)(InternalOperation::NotifySenderCreated);
496 BufferedCanSender { 472 BufferedCanSender {
497 tx_buf: self.tx_buf.sender().into(), 473 tx_buf: self.tx_buf.sender().into(),
498 waker: self.info.tx_waker, 474 info: TxInfoRef::new(&self.info),
499 internal_operation: self.info.internal_operation,
500 } 475 }
501 } 476 }
502 477
503 /// Returns a receiver that can be used for receiving CAN frames. Note, each CAN frame will only be received by one receiver. 478 /// Returns a receiver that can be used for receiving CAN frames. Note, each CAN frame will only be received by one receiver.
504 pub fn reader(&self) -> BufferedCanReceiver { 479 pub fn reader(&self) -> BufferedCanReceiver {
505 (self.info.internal_operation)(InternalOperation::NotifyReceiverCreated);
506 BufferedCanReceiver { 480 BufferedCanReceiver {
507 rx_buf: self.rx_buf.receiver().into(), 481 rx_buf: self.rx_buf.receiver().into(),
508 internal_operation: self.info.internal_operation, 482 info: RxInfoRef::new(&self.info),
509 } 483 }
510 } 484 }
511} 485}
512 486
513impl<'c, 'd, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> Drop for BufferedCan<'d, TX_BUF_SIZE, RX_BUF_SIZE> {
514 fn drop(&mut self) {
515 (self.info.internal_operation)(InternalOperation::NotifySenderDestroyed);
516 (self.info.internal_operation)(InternalOperation::NotifyReceiverDestroyed);
517 }
518}
519
520/// User supplied buffer for RX Buffering 487/// User supplied buffer for RX Buffering
521pub type RxFdBuf<const BUF_SIZE: usize> = Channel<CriticalSectionRawMutex, Result<FdEnvelope, BusError>, BUF_SIZE>; 488pub type RxFdBuf<const BUF_SIZE: usize> = Channel<CriticalSectionRawMutex, Result<FdEnvelope, BusError>, BUF_SIZE>;
522 489
@@ -532,11 +499,11 @@ pub type BufferedFdCanReceiver = super::common::BufferedReceiver<'static, FdEnve
532/// Buffered FDCAN Instance 499/// Buffered FDCAN Instance
533pub struct BufferedCanFd<'d, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> { 500pub struct BufferedCanFd<'d, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> {
534 _phantom: PhantomData<&'d ()>, 501 _phantom: PhantomData<&'d ()>,
535 info: &'static Info,
536 _mode: OperatingMode, 502 _mode: OperatingMode,
537 tx_buf: &'static TxFdBuf<TX_BUF_SIZE>, 503 tx_buf: &'static TxFdBuf<TX_BUF_SIZE>,
538 rx_buf: &'static RxFdBuf<RX_BUF_SIZE>, 504 rx_buf: &'static RxFdBuf<RX_BUF_SIZE>,
539 properties: Properties, 505 properties: Properties,
506 info: InfoRef,
540} 507}
541 508
542impl<'c, 'd, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> BufferedCanFd<'d, TX_BUF_SIZE, RX_BUF_SIZE> { 509impl<'c, 'd, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> BufferedCanFd<'d, TX_BUF_SIZE, RX_BUF_SIZE> {
@@ -546,15 +513,13 @@ impl<'c, 'd, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> BufferedCanFd<'
546 tx_buf: &'static TxFdBuf<TX_BUF_SIZE>, 513 tx_buf: &'static TxFdBuf<TX_BUF_SIZE>,
547 rx_buf: &'static RxFdBuf<RX_BUF_SIZE>, 514 rx_buf: &'static RxFdBuf<RX_BUF_SIZE>,
548 ) -> Self { 515 ) -> Self {
549 (info.internal_operation)(InternalOperation::NotifySenderCreated);
550 (info.internal_operation)(InternalOperation::NotifyReceiverCreated);
551 BufferedCanFd { 516 BufferedCanFd {
552 _phantom: PhantomData, 517 _phantom: PhantomData,
553 info,
554 _mode, 518 _mode,
555 tx_buf, 519 tx_buf,
556 rx_buf, 520 rx_buf,
557 properties: Properties::new(info), 521 properties: Properties::new(info),
522 info: InfoRef::new(info),
558 } 523 }
559 .setup() 524 .setup()
560 } 525 }
@@ -593,36 +558,26 @@ impl<'c, 'd, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> BufferedCanFd<'
593 558
594 /// Returns a sender that can be used for sending CAN frames. 559 /// Returns a sender that can be used for sending CAN frames.
595 pub fn writer(&self) -> BufferedFdCanSender { 560 pub fn writer(&self) -> BufferedFdCanSender {
596 (self.info.internal_operation)(InternalOperation::NotifySenderCreated);
597 BufferedFdCanSender { 561 BufferedFdCanSender {
598 tx_buf: self.tx_buf.sender().into(), 562 tx_buf: self.tx_buf.sender().into(),
599 waker: self.info.tx_waker, 563 info: TxInfoRef::new(&self.info),
600 internal_operation: self.info.internal_operation,
601 } 564 }
602 } 565 }
603 566
604 /// Returns a receiver that can be used for receiving CAN frames. Note, each CAN frame will only be received by one receiver. 567 /// Returns a receiver that can be used for receiving CAN frames. Note, each CAN frame will only be received by one receiver.
605 pub fn reader(&self) -> BufferedFdCanReceiver { 568 pub fn reader(&self) -> BufferedFdCanReceiver {
606 (self.info.internal_operation)(InternalOperation::NotifyReceiverCreated);
607 BufferedFdCanReceiver { 569 BufferedFdCanReceiver {
608 rx_buf: self.rx_buf.receiver().into(), 570 rx_buf: self.rx_buf.receiver().into(),
609 internal_operation: self.info.internal_operation, 571 info: RxInfoRef::new(&self.info),
610 } 572 }
611 } 573 }
612} 574}
613 575
614impl<'c, 'd, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> Drop for BufferedCanFd<'d, TX_BUF_SIZE, RX_BUF_SIZE> {
615 fn drop(&mut self) {
616 (self.info.internal_operation)(InternalOperation::NotifySenderDestroyed);
617 (self.info.internal_operation)(InternalOperation::NotifyReceiverDestroyed);
618 }
619}
620
621/// FDCAN Rx only Instance 576/// FDCAN Rx only Instance
622pub struct CanRx<'d> { 577pub struct CanRx<'d> {
623 _phantom: PhantomData<&'d ()>, 578 _phantom: PhantomData<&'d ()>,
624 info: &'static Info,
625 _mode: OperatingMode, 579 _mode: OperatingMode,
580 info: RxInfoRef,
626} 581}
627 582
628impl<'d> CanRx<'d> { 583impl<'d> CanRx<'d> {
@@ -637,18 +592,12 @@ impl<'d> CanRx<'d> {
637 } 592 }
638} 593}
639 594
640impl<'d> Drop for CanRx<'d> {
641 fn drop(&mut self) {
642 (self.info.internal_operation)(InternalOperation::NotifyReceiverDestroyed);
643 }
644}
645
646/// FDCAN Tx only Instance 595/// FDCAN Tx only Instance
647pub struct CanTx<'d> { 596pub struct CanTx<'d> {
648 _phantom: PhantomData<&'d ()>, 597 _phantom: PhantomData<&'d ()>,
649 info: &'static Info,
650 config: crate::can::fd::config::FdCanConfig, 598 config: crate::can::fd::config::FdCanConfig,
651 _mode: OperatingMode, 599 _mode: OperatingMode,
600 info: TxInfoRef,
652} 601}
653 602
654impl<'c, 'd> CanTx<'d> { 603impl<'c, 'd> CanTx<'d> {
@@ -657,7 +606,7 @@ impl<'c, 'd> CanTx<'d> {
657 /// can be replaced, this call asynchronously waits for a frame to be successfully 606 /// can be replaced, this call asynchronously waits for a frame to be successfully
658 /// transmitted, then tries again. 607 /// transmitted, then tries again.
659 pub async fn write(&mut self, frame: &Frame) -> Option<Frame> { 608 pub async fn write(&mut self, frame: &Frame) -> Option<Frame> {
660 TxMode::write(self.info, frame).await 609 TxMode::write(&self.info, frame).await
661 } 610 }
662 611
663 /// Queues the message to be sent but exerts backpressure. If a lower-priority 612 /// Queues the message to be sent but exerts backpressure. If a lower-priority
@@ -665,13 +614,7 @@ impl<'c, 'd> CanTx<'d> {
665 /// can be replaced, this call asynchronously waits for a frame to be successfully 614 /// can be replaced, this call asynchronously waits for a frame to be successfully
666 /// transmitted, then tries again. 615 /// transmitted, then tries again.
667 pub async fn write_fd(&mut self, frame: &FdFrame) -> Option<FdFrame> { 616 pub async fn write_fd(&mut self, frame: &FdFrame) -> Option<FdFrame> {
668 TxMode::write_fd(self.info, frame).await 617 TxMode::write_fd(&self.info, frame).await
669 }
670}
671
672impl<'d> Drop for CanTx<'d> {
673 fn drop(&mut self) {
674 (self.info.internal_operation)(InternalOperation::NotifySenderDestroyed);
675 } 618 }
676} 619}
677 620
@@ -938,21 +881,56 @@ impl State {
938} 881}
939 882
940type SharedState = embassy_sync::blocking_mutex::Mutex<CriticalSectionRawMutex, core::cell::RefCell<State>>; 883type SharedState = embassy_sync::blocking_mutex::Mutex<CriticalSectionRawMutex, core::cell::RefCell<State>>;
941struct Info { 884pub(crate) struct Info {
942 regs: Registers, 885 regs: Registers,
943 interrupt0: crate::interrupt::Interrupt, 886 interrupt0: crate::interrupt::Interrupt,
944 _interrupt1: crate::interrupt::Interrupt, 887 _interrupt1: crate::interrupt::Interrupt,
945 tx_waker: fn(), 888 pub(crate) tx_waker: fn(),
946 internal_operation: fn(InternalOperation),
947 state: SharedState, 889 state: SharedState,
948} 890}
949 891
892impl Info {
893 pub(crate) fn adjust_reference_counter(&self, val: RefCountOp) {
894 self.state.lock(|s| {
895 let mut mut_state = s.borrow_mut();
896 match val {
897 RefCountOp::NotifySenderCreated => {
898 mut_state.sender_instance_count += 1;
899 }
900 RefCountOp::NotifySenderDestroyed => {
901 mut_state.sender_instance_count -= 1;
902 if 0 == mut_state.sender_instance_count {
903 (*mut_state).tx_mode = TxMode::NonBuffered(embassy_sync::waitqueue::AtomicWaker::new());
904 }
905 }
906 RefCountOp::NotifyReceiverCreated => {
907 mut_state.receiver_instance_count += 1;
908 }
909 RefCountOp::NotifyReceiverDestroyed => {
910 mut_state.receiver_instance_count -= 1;
911 if 0 == mut_state.receiver_instance_count {
912 (*mut_state).rx_mode = RxMode::NonBuffered(embassy_sync::waitqueue::AtomicWaker::new());
913 }
914 }
915 }
916 if mut_state.sender_instance_count == 0 && mut_state.receiver_instance_count == 0 {
917 unsafe {
918 let tx_pin = crate::gpio::AnyPin::steal(mut_state.tx_pin_port.unwrap());
919 tx_pin.set_as_disconnected();
920 let rx_pin = crate::gpio::AnyPin::steal(mut_state.rx_pin_port.unwrap());
921 rx_pin.set_as_disconnected();
922 self.interrupt0.disable();
923 }
924 }
925 });
926 }
927}
928
950trait SealedInstance { 929trait SealedInstance {
951 const MSG_RAM_OFFSET: usize; 930 const MSG_RAM_OFFSET: usize;
952 931
953 fn info() -> &'static Info; 932 fn info() -> &'static Info;
954 fn registers() -> crate::can::fd::peripheral::Registers; 933 fn registers() -> crate::can::fd::peripheral::Registers;
955 fn internal_operation(val: InternalOperation);
956} 934}
957 935
958/// Instance trait 936/// Instance trait
@@ -974,41 +952,6 @@ macro_rules! impl_fdcan {
974 impl SealedInstance for peripherals::$inst { 952 impl SealedInstance for peripherals::$inst {
975 const MSG_RAM_OFFSET: usize = $msg_ram_offset; 953 const MSG_RAM_OFFSET: usize = $msg_ram_offset;
976 954
977 fn internal_operation(val: InternalOperation) {
978 peripherals::$inst::info().state.lock(|s| {
979 let mut mut_state = s.borrow_mut();
980 match val {
981 InternalOperation::NotifySenderCreated => {
982 mut_state.sender_instance_count += 1;
983 }
984 InternalOperation::NotifySenderDestroyed => {
985 mut_state.sender_instance_count -= 1;
986 if ( 0 == mut_state.sender_instance_count) {
987 (*mut_state).tx_mode = TxMode::NonBuffered(embassy_sync::waitqueue::AtomicWaker::new());
988 }
989 }
990 InternalOperation::NotifyReceiverCreated => {
991 mut_state.receiver_instance_count += 1;
992 }
993 InternalOperation::NotifyReceiverDestroyed => {
994 mut_state.receiver_instance_count -= 1;
995 if ( 0 == mut_state.receiver_instance_count) {
996 (*mut_state).rx_mode = RxMode::NonBuffered(embassy_sync::waitqueue::AtomicWaker::new());
997 }
998 }
999 }
1000 if mut_state.sender_instance_count == 0 && mut_state.receiver_instance_count == 0 {
1001 unsafe {
1002 let tx_pin = crate::gpio::AnyPin::steal(mut_state.tx_pin_port.unwrap());
1003 tx_pin.set_as_disconnected();
1004 let rx_pin = crate::gpio::AnyPin::steal(mut_state.rx_pin_port.unwrap());
1005 rx_pin.set_as_disconnected();
1006 rcc::disable::<peripherals::$inst>();
1007 }
1008 }
1009 });
1010 }
1011
1012 fn info() -> &'static Info { 955 fn info() -> &'static Info {
1013 956
1014 static INFO: Info = Info { 957 static INFO: Info = Info {
@@ -1016,7 +959,6 @@ macro_rules! impl_fdcan {
1016 interrupt0: crate::_generated::peripheral_interrupts::$inst::IT0::IRQ, 959 interrupt0: crate::_generated::peripheral_interrupts::$inst::IT0::IRQ,
1017 _interrupt1: crate::_generated::peripheral_interrupts::$inst::IT1::IRQ, 960 _interrupt1: crate::_generated::peripheral_interrupts::$inst::IT1::IRQ,
1018 tx_waker: crate::_generated::peripheral_interrupts::$inst::IT0::pend, 961 tx_waker: crate::_generated::peripheral_interrupts::$inst::IT0::pend,
1019 internal_operation: peripherals::$inst::internal_operation,
1020 state: embassy_sync::blocking_mutex::Mutex::new(core::cell::RefCell::new(State::new())), 962 state: embassy_sync::blocking_mutex::Mutex::new(core::cell::RefCell::new(State::new())),
1021 }; 963 };
1022 &INFO 964 &INFO
diff --git a/embassy-stm32/src/hsem/mod.rs b/embassy-stm32/src/hsem/mod.rs
index 31527bcdb..573a1851d 100644
--- a/embassy-stm32/src/hsem/mod.rs
+++ b/embassy-stm32/src/hsem/mod.rs
@@ -3,7 +3,7 @@
3use embassy_hal_internal::PeripheralType; 3use embassy_hal_internal::PeripheralType;
4 4
5use crate::pac; 5use crate::pac;
6use crate::rcc::RccPeripheral; 6use crate::rcc::{self, RccPeripheral};
7// TODO: This code works for all HSEM implemenations except for the STM32WBA52/4/5xx MCUs. 7// TODO: This code works for all HSEM implemenations except for the STM32WBA52/4/5xx MCUs.
8// Those MCUs have a different HSEM implementation (Secure semaphore lock support, 8// Those MCUs have a different HSEM implementation (Secure semaphore lock support,
9// Privileged / unprivileged semaphore lock support, Semaphore lock protection via semaphore attribute), 9// Privileged / unprivileged semaphore lock support, Semaphore lock protection via semaphore attribute),
@@ -46,7 +46,7 @@ pub enum CoreId {
46#[inline(always)] 46#[inline(always)]
47pub fn get_current_coreid() -> CoreId { 47pub fn get_current_coreid() -> CoreId {
48 let cpuid = unsafe { cortex_m::peripheral::CPUID::PTR.read_volatile().base.read() }; 48 let cpuid = unsafe { cortex_m::peripheral::CPUID::PTR.read_volatile().base.read() };
49 match cpuid & 0x000000F0 { 49 match (cpuid & 0x000000F0) >> 4 {
50 #[cfg(any(stm32wb, stm32wl))] 50 #[cfg(any(stm32wb, stm32wl))]
51 0x0 => CoreId::Core1, 51 0x0 => CoreId::Core1,
52 52
@@ -80,6 +80,8 @@ pub struct HardwareSemaphore<'d, T: Instance> {
80impl<'d, T: Instance> HardwareSemaphore<'d, T> { 80impl<'d, T: Instance> HardwareSemaphore<'d, T> {
81 /// Creates a new HardwareSemaphore instance. 81 /// Creates a new HardwareSemaphore instance.
82 pub fn new(peripheral: Peri<'d, T>) -> Self { 82 pub fn new(peripheral: Peri<'d, T>) -> Self {
83 rcc::enable_and_reset::<T>();
84
83 HardwareSemaphore { _peri: peripheral } 85 HardwareSemaphore { _peri: peripheral }
84 } 86 }
85 87
diff --git a/embassy-stm32/src/lib.rs b/embassy-stm32/src/lib.rs
index 973acc9bb..06c91ef97 100644
--- a/embassy-stm32/src/lib.rs
+++ b/embassy-stm32/src/lib.rs
@@ -178,7 +178,7 @@ pub use crate::_generated::interrupt;
178macro_rules! bind_interrupts { 178macro_rules! bind_interrupts {
179 ($(#[$outer:meta])* $vis:vis struct $name:ident { 179 ($(#[$outer:meta])* $vis:vis struct $name:ident {
180 $( 180 $(
181 $(#[$inner:meta])* 181 $(#[doc = $doc:literal])*
182 $(#[cfg($cond_irq:meta)])? 182 $(#[cfg($cond_irq:meta)])?
183 $irq:ident => $( 183 $irq:ident => $(
184 $(#[cfg($cond_handler:meta)])? 184 $(#[cfg($cond_handler:meta)])?
@@ -194,7 +194,7 @@ macro_rules! bind_interrupts {
194 #[allow(non_snake_case)] 194 #[allow(non_snake_case)]
195 #[no_mangle] 195 #[no_mangle]
196 $(#[cfg($cond_irq)])? 196 $(#[cfg($cond_irq)])?
197 $(#[$inner])* 197 $(#[doc = $doc])*
198 unsafe extern "C" fn $irq() { 198 unsafe extern "C" fn $irq() {
199 $( 199 $(
200 $(#[cfg($cond_handler)])? 200 $(#[cfg($cond_handler)])?
diff --git a/embassy-stm32/src/sdmmc/mod.rs b/embassy-stm32/src/sdmmc/mod.rs
index 6a02aae70..675d1813b 100644
--- a/embassy-stm32/src/sdmmc/mod.rs
+++ b/embassy-stm32/src/sdmmc/mod.rs
@@ -751,7 +751,6 @@ impl<'d, T: Instance> Sdmmc<'d, T> {
751 Self::wait_idle(); 751 Self::wait_idle();
752 Self::clear_interrupt_flags(); 752 Self::clear_interrupt_flags();
753 753
754 regs.dtimer().write(|w| w.set_datatime(config.data_transfer_timeout));
755 regs.dlenr().write(|w| w.set_datalength(length_bytes)); 754 regs.dlenr().write(|w| w.set_datalength(length_bytes));
756 755
757 #[cfg(sdmmc_v1)] 756 #[cfg(sdmmc_v1)]
@@ -789,8 +788,6 @@ impl<'d, T: Instance> Sdmmc<'d, T> {
789 Self::wait_idle(); 788 Self::wait_idle();
790 Self::clear_interrupt_flags(); 789 Self::clear_interrupt_flags();
791 790
792 regs.dtimer()
793 .write(|w| w.set_datatime(self.config.data_transfer_timeout));
794 regs.dlenr().write(|w| w.set_datalength(length_bytes)); 791 regs.dlenr().write(|w| w.set_datalength(length_bytes));
795 792
796 #[cfg(sdmmc_v1)] 793 #[cfg(sdmmc_v1)]
@@ -1349,6 +1346,8 @@ impl<'d, T: Instance> Sdmmc<'d, T> {
1349 #[cfg(sdmmc_v1)] 1346 #[cfg(sdmmc_v1)]
1350 w.set_bypass(_bypass); 1347 w.set_bypass(_bypass);
1351 }); 1348 });
1349 regs.dtimer()
1350 .write(|w| w.set_datatime(self.config.data_transfer_timeout));
1352 1351
1353 regs.power().modify(|w| w.set_pwrctrl(PowerCtrl::On as u8)); 1352 regs.power().modify(|w| w.set_pwrctrl(PowerCtrl::On as u8));
1354 Self::cmd(common_cmd::idle(), false)?; 1353 Self::cmd(common_cmd::idle(), false)?;
diff --git a/examples/boot/application/rp/src/bin/a.rs b/examples/boot/application/rp/src/bin/a.rs
index ede0c07da..e6d7b3d4f 100644
--- a/examples/boot/application/rp/src/bin/a.rs
+++ b/examples/boot/application/rp/src/bin/a.rs
@@ -54,7 +54,7 @@ async fn main(_s: Spawner) {
54 for chunk in APP_B.chunks(4096) { 54 for chunk in APP_B.chunks(4096) {
55 buf.0[..chunk.len()].copy_from_slice(chunk); 55 buf.0[..chunk.len()].copy_from_slice(chunk);
56 defmt::info!("writing block at offset {}", offset); 56 defmt::info!("writing block at offset {}", offset);
57 writer.write(offset, &buf.0[..]).unwrap(); 57 writer.write(offset, &buf.0[..chunk.len()]).unwrap();
58 offset += chunk.len() as u32; 58 offset += chunk.len() as u32;
59 } 59 }
60 watchdog.feed(); 60 watchdog.feed();
diff --git a/examples/stm32c0/Cargo.toml b/examples/stm32c0/Cargo.toml
index 4cf07cef4..70a7b0895 100644
--- a/examples/stm32c0/Cargo.toml
+++ b/examples/stm32c0/Cargo.toml
@@ -6,7 +6,7 @@ license = "MIT OR Apache-2.0"
6 6
7[dependencies] 7[dependencies]
8# Change stm32c031c6 to your chip name, if necessary. 8# Change stm32c031c6 to your chip name, if necessary.
9embassy-stm32 = { version = "0.2.0", path = "../../embassy-stm32", features = [ "defmt", "time-driver-any", "stm32c031c6", "memory-x", "unstable-pac", "exti"] } 9embassy-stm32 = { version = "0.2.0", path = "../../embassy-stm32", features = [ "defmt", "time-driver-any", "stm32c031c6", "memory-x", "unstable-pac", "exti", "chrono"] }
10embassy-sync = { version = "0.7.0", path = "../../embassy-sync", features = ["defmt"] } 10embassy-sync = { version = "0.7.0", path = "../../embassy-sync", features = ["defmt"] }
11embassy-executor = { version = "0.7.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt"] } 11embassy-executor = { version = "0.7.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt"] }
12embassy-time = { version = "0.4.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } 12embassy-time = { version = "0.4.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] }
@@ -19,6 +19,7 @@ cortex-m-rt = "0.7.0"
19embedded-hal = "0.2.6" 19embedded-hal = "0.2.6"
20panic-probe = { version = "1.0.0", features = ["print-defmt"] } 20panic-probe = { version = "1.0.0", features = ["print-defmt"] }
21heapless = { version = "0.8", default-features = false } 21heapless = { version = "0.8", default-features = false }
22chrono = { version = "^0.4", default-features = false}
22 23
23[profile.release] 24[profile.release]
24debug = 2 25debug = 2
diff --git a/examples/stm32c0/src/bin/rtc.rs b/examples/stm32c0/src/bin/rtc.rs
new file mode 100644
index 000000000..82d8a37ba
--- /dev/null
+++ b/examples/stm32c0/src/bin/rtc.rs
@@ -0,0 +1,35 @@
1#![no_std]
2#![no_main]
3
4use chrono::{NaiveDate, NaiveDateTime};
5use defmt::*;
6use embassy_executor::Spawner;
7use embassy_stm32::rtc::{Rtc, RtcConfig};
8use embassy_stm32::Config;
9use embassy_time::Timer;
10use {defmt_rtt as _, panic_probe as _};
11
12#[embassy_executor::main]
13async fn main(_spawner: Spawner) {
14 let config = Config::default();
15 let p = embassy_stm32::init(config);
16
17 info!("Hello World!");
18
19 let now = NaiveDate::from_ymd_opt(2020, 5, 15)
20 .unwrap()
21 .and_hms_opt(10, 30, 15)
22 .unwrap();
23
24 let mut rtc = Rtc::new(p.RTC, RtcConfig::default());
25
26 rtc.set_datetime(now.into()).expect("datetime not set");
27
28 loop {
29 let now: NaiveDateTime = rtc.now().unwrap().into();
30
31 info!("{}", now.and_utc().timestamp());
32
33 Timer::after_millis(1000).await;
34 }
35}