Compare commits
51 Commits
executor-0
...
stable
Author | SHA1 | Date | |
---|---|---|---|
996c3c1f7e | |||
171cdb94c7 | |||
1fbc150fd6 | |||
259cf6192b | |||
e8ff5a2baf | |||
4f8c79c911 | |||
738971938a | |||
dec7c1a28b | |||
e0727fe1f6 | |||
ba9cc102e2 | |||
32b59148a8 | |||
bd2e6b0422 | |||
85059f693b | |||
c211d51c06 | |||
7f1fd199bb | |||
5ddd2cf9a6 | |||
88f893da45 | |||
aedd41eac4 | |||
19ba7da3fd | |||
06a83c0f89 | |||
766ec77ec5 | |||
d1af696605 | |||
2386619f1f | |||
382949e1ff | |||
454828accb | |||
cf82fa687c | |||
7f258cd3c4 | |||
3a939fb511 | |||
b8e9e00b44 | |||
ff2f1049b1 | |||
be17e1b363 | |||
f3c77e59c4 | |||
30424d83ff | |||
e3be0b957a | |||
5221705495 | |||
814e096d22 | |||
5a60024af7 | |||
f482a105b8 | |||
7589b5e13e | |||
2efa73f431 | |||
270ec324b0 | |||
ca0d02933b | |||
5bc7557826 | |||
4947b13615 | |||
006260fedd | |||
e3ee24017d | |||
467b53076c | |||
27e6634c9d | |||
0f2208c0af | |||
6c42885d4a | |||
3b33cc4691 |
10
.github/ci/build-stable.sh
vendored
10
.github/ci/build-stable.sh
vendored
@ -12,9 +12,19 @@ export CARGO_TARGET_DIR=/ci/cache/target
|
||||
# used when pointing stm32-metapac to a CI-built one.
|
||||
export CARGO_NET_GIT_FETCH_WITH_CLI=true
|
||||
|
||||
# Restore lockfiles
|
||||
if [ -f /ci/cache/lockfiles.tar ]; then
|
||||
echo Restoring lockfiles...
|
||||
tar xf /ci/cache/lockfiles.tar
|
||||
fi
|
||||
|
||||
hashtime restore /ci/cache/filetime.json || true
|
||||
hashtime save /ci/cache/filetime.json
|
||||
|
||||
sed -i 's/channel.*/channel = "stable"/g' rust-toolchain.toml
|
||||
|
||||
./ci_stable.sh
|
||||
|
||||
# Save lockfiles
|
||||
echo Saving lockfiles...
|
||||
find . -type f -name Cargo.lock -exec tar -cf /ci/cache/lockfiles.tar '{}' \+
|
10
.github/ci/build.sh
vendored
10
.github/ci/build.sh
vendored
@ -18,7 +18,17 @@ fi
|
||||
# used when pointing stm32-metapac to a CI-built one.
|
||||
export CARGO_NET_GIT_FETCH_WITH_CLI=true
|
||||
|
||||
# Restore lockfiles
|
||||
if [ -f /ci/cache/lockfiles.tar ]; then
|
||||
echo Restoring lockfiles...
|
||||
tar xf /ci/cache/lockfiles.tar
|
||||
fi
|
||||
|
||||
hashtime restore /ci/cache/filetime.json || true
|
||||
hashtime save /ci/cache/filetime.json
|
||||
|
||||
./ci.sh
|
||||
|
||||
# Save lockfiles
|
||||
echo Saving lockfiles...
|
||||
find . -type f -name Cargo.lock -exec tar -cf /ci/cache/lockfiles.tar '{}' \+
|
3
.github/ci/test.sh
vendored
3
.github/ci/test.sh
vendored
@ -15,6 +15,9 @@ export CARGO_NET_GIT_FETCH_WITH_CLI=true
|
||||
hashtime restore /ci/cache/filetime.json || true
|
||||
hashtime save /ci/cache/filetime.json
|
||||
|
||||
MIRIFLAGS=-Zmiri-ignore-leaks cargo miri test --manifest-path ./embassy-executor/Cargo.toml
|
||||
MIRIFLAGS=-Zmiri-ignore-leaks cargo miri test --manifest-path ./embassy-executor/Cargo.toml --features nightly
|
||||
|
||||
cargo test --manifest-path ./embassy-sync/Cargo.toml
|
||||
cargo test --manifest-path ./embassy-embedded-hal/Cargo.toml
|
||||
cargo test --manifest-path ./embassy-hal-internal/Cargo.toml
|
||||
|
2
ci.sh
2
ci.sh
@ -38,6 +38,7 @@ cargo batch \
|
||||
--- build --release --manifest-path embassy-sync/Cargo.toml --target thumbv6m-none-eabi --features nightly,defmt \
|
||||
--- build --release --manifest-path embassy-time/Cargo.toml --target thumbv6m-none-eabi --features nightly,defmt,defmt-timestamp-uptime,tick-hz-32_768,generic-queue-8 \
|
||||
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,medium-ethernet \
|
||||
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,igmp,medium-ethernet \
|
||||
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet \
|
||||
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet,nightly,dhcpv4-hostname \
|
||||
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv6,medium-ethernet \
|
||||
@ -110,6 +111,7 @@ cargo batch \
|
||||
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32h753zi,defmt,exti,time-driver-any,unstable-traits,time \
|
||||
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32h735zg,defmt,exti,time-driver-any,unstable-traits,time \
|
||||
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32h755zi-cm7,defmt,exti,time-driver-any,unstable-traits,time \
|
||||
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32h725re,defmt,exti,time-driver-any,unstable-traits,time \
|
||||
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32h7b3ai,defmt,exti,time-driver-any,unstable-traits,time \
|
||||
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32l476vg,defmt,exti,time-driver-any,unstable-traits,time \
|
||||
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32l422cb,defmt,exti,time-driver-any,unstable-traits,time \
|
||||
|
@ -1,4 +1,5 @@
|
||||
use core::cmp::{max, min};
|
||||
use core::iter::zip;
|
||||
|
||||
use embassy_net_driver_channel as ch;
|
||||
use embassy_net_driver_channel::driver::{HardwareAddress, LinkState};
|
||||
@ -16,6 +17,12 @@ pub struct Error {
|
||||
pub status: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AddMulticastAddressError {
|
||||
NotMulticast,
|
||||
NoFreeSlots,
|
||||
}
|
||||
|
||||
pub struct Control<'a> {
|
||||
state_ch: ch::StateRunner<'a>,
|
||||
events: &'a Events,
|
||||
@ -316,6 +323,54 @@ impl<'a> Control<'a> {
|
||||
self.set_iovar_u32x2("bss", 0, 1).await; // bss = BSS_UP
|
||||
}
|
||||
|
||||
/// Add specified address to the list of hardware addresses the device
|
||||
/// listens on. The address must be a Group address (I/G bit set). Up
|
||||
/// to 10 addresses are supported by the firmware. Returns the number of
|
||||
/// address slots filled after adding, or an error.
|
||||
pub async fn add_multicast_address(&mut self, address: [u8; 6]) -> Result<usize, AddMulticastAddressError> {
|
||||
// The firmware seems to ignore non-multicast addresses, so let's
|
||||
// prevent the user from adding them and wasting space.
|
||||
if address[0] & 0x01 != 1 {
|
||||
return Err(AddMulticastAddressError::NotMulticast);
|
||||
}
|
||||
|
||||
let mut buf = [0; 64];
|
||||
self.get_iovar("mcast_list", &mut buf).await;
|
||||
|
||||
let n = u32::from_le_bytes(buf[..4].try_into().unwrap()) as usize;
|
||||
let (used, free) = buf[4..].split_at_mut(n * 6);
|
||||
|
||||
if used.chunks(6).any(|a| a == address) {
|
||||
return Ok(n);
|
||||
}
|
||||
|
||||
if free.len() < 6 {
|
||||
return Err(AddMulticastAddressError::NoFreeSlots);
|
||||
}
|
||||
|
||||
free[..6].copy_from_slice(&address);
|
||||
let n = n + 1;
|
||||
buf[..4].copy_from_slice(&(n as u32).to_le_bytes());
|
||||
|
||||
self.set_iovar_v::<80>("mcast_list", &buf).await;
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Retrieve the list of configured multicast hardware addresses.
|
||||
pub async fn list_mulistcast_addresses(&mut self, result: &mut [[u8; 6]; 10]) -> usize {
|
||||
let mut buf = [0; 64];
|
||||
self.get_iovar("mcast_list", &mut buf).await;
|
||||
|
||||
let n = u32::from_le_bytes(buf[..4].try_into().unwrap()) as usize;
|
||||
let used = &buf[4..][..n * 6];
|
||||
|
||||
for (addr, output) in zip(used.chunks(6), result.iter_mut()) {
|
||||
output.copy_from_slice(addr)
|
||||
}
|
||||
|
||||
n
|
||||
}
|
||||
|
||||
async fn set_iovar_u32x2(&mut self, name: &str, val1: u32, val2: u32) {
|
||||
let mut buf = [0; 8];
|
||||
buf[0..4].copy_from_slice(&val1.to_le_bytes());
|
||||
|
@ -27,7 +27,7 @@ use ioctl::IoctlState;
|
||||
|
||||
use crate::bus::Bus;
|
||||
pub use crate::bus::SpiBusCyw43;
|
||||
pub use crate::control::{Control, Error as ControlError, Scanner};
|
||||
pub use crate::control::{AddMulticastAddressError, Control, Error as ControlError, Scanner};
|
||||
pub use crate::runner::Runner;
|
||||
pub use crate::structs::BssInfo;
|
||||
|
||||
|
@ -10,3 +10,4 @@
|
||||
* xref:examples.adoc[Examples]
|
||||
* xref:developer.adoc[Developer]
|
||||
** xref:developer_stm32.adoc[Developer: STM32]
|
||||
* xref:faq.adoc[Frequently Asked Questions]
|
||||
|
38
docs/modules/ROOT/pages/faq.adoc
Normal file
38
docs/modules/ROOT/pages/faq.adoc
Normal file
@ -0,0 +1,38 @@
|
||||
= Frequently Asked Questions
|
||||
|
||||
These are a list of unsorted, commonly asked questions and answers.
|
||||
|
||||
Please feel free to add items to link:https://github.com/embassy-rs/embassy/edit/main/docs/modules/ROOT/pages/faq.adoc[this page], especially if someone in the chat answered a question for you!
|
||||
|
||||
== How to deploy to RP2040 without a debugging probe.
|
||||
|
||||
Install link:https://github.com/JoNil/elf2uf2-rs[elf2uf2-rs] for converting the generated elf binary into a uf2 file.
|
||||
|
||||
Configure the runner to use this tool, add this to `.cargo/config.toml`:
|
||||
[source,toml]
|
||||
----
|
||||
[target.'cfg(all(target_arch = "arm", target_os = "none"))']
|
||||
runner = "elf2uf2-rs --deploy --serial --verbose"
|
||||
----
|
||||
|
||||
The command-line parameters `--deploy` will detect your device and upload the binary, `--serial` starts a serial connection. See the documentation for more info.
|
||||
|
||||
== Missing main macro
|
||||
|
||||
If you see an error like this:
|
||||
|
||||
[source,rust]
|
||||
----
|
||||
#[embassy_executor::main]
|
||||
| ^^^^ could not find `main` in `embassy_executor`
|
||||
----
|
||||
|
||||
You are likely missing some features of the `embassy-executor` crate.
|
||||
|
||||
For Cortex-M targets, consider making sure that ALL of the following features are active in your `Cargo.toml` for the `embassy-executor` crate:
|
||||
|
||||
* `arch-cortex-m`
|
||||
* `executor-thread`
|
||||
* `nightly`
|
||||
|
||||
For Xtensa ESP32, consider using the executors and `#[main]` macro provided by your appropriate link:https://crates.io/crates/esp-hal-common[HAL crate].
|
@ -27,31 +27,6 @@ default-target = "thumbv7em-none-eabi"
|
||||
targets = ["thumbv7em-none-eabi"]
|
||||
features = ["nightly", "defmt", "arch-cortex-m", "executor-thread", "executor-interrupt"]
|
||||
|
||||
[features]
|
||||
|
||||
# Architecture
|
||||
_arch = [] # some arch was picked
|
||||
arch-std = ["_arch", "critical-section/std"]
|
||||
arch-cortex-m = ["_arch", "dep:cortex-m"]
|
||||
arch-xtensa = ["_arch"]
|
||||
arch-riscv32 = ["_arch", "dep:portable-atomic"]
|
||||
arch-wasm = ["_arch", "dep:wasm-bindgen", "dep:js-sys"]
|
||||
|
||||
# Enable the thread-mode executor (using WFE/SEV in Cortex-M, WFI in other embedded archs)
|
||||
executor-thread = []
|
||||
# Enable the interrupt-mode executor (available in Cortex-M only)
|
||||
executor-interrupt = []
|
||||
|
||||
# Enable nightly-only features
|
||||
nightly = []
|
||||
|
||||
turbowakers = []
|
||||
|
||||
integrated-timers = ["dep:embassy-time"]
|
||||
|
||||
# Trace interrupt invocations with rtos-trace.
|
||||
rtos-trace-interrupt = ["rtos-trace", "embassy-macros/rtos-trace-interrupt"]
|
||||
|
||||
[dependencies]
|
||||
defmt = { version = "0.3", optional = true }
|
||||
log = { version = "0.4.14", optional = true }
|
||||
@ -71,3 +46,74 @@ cortex-m = { version = "0.7.6", optional = true }
|
||||
# arch-wasm dependencies
|
||||
wasm-bindgen = { version = "0.2.82", optional = true }
|
||||
js-sys = { version = "0.3", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
critical-section = { version = "1.1", features = ["std"] }
|
||||
|
||||
|
||||
[features]
|
||||
|
||||
# Architecture
|
||||
_arch = [] # some arch was picked
|
||||
arch-std = ["_arch", "critical-section/std"]
|
||||
arch-cortex-m = ["_arch", "dep:cortex-m"]
|
||||
arch-xtensa = ["_arch"]
|
||||
arch-riscv32 = ["_arch", "dep:portable-atomic"]
|
||||
arch-wasm = ["_arch", "dep:wasm-bindgen", "dep:js-sys"]
|
||||
|
||||
# Enable the thread-mode executor (using WFE/SEV in Cortex-M, WFI in other embedded archs)
|
||||
executor-thread = []
|
||||
# Enable the interrupt-mode executor (available in Cortex-M only)
|
||||
executor-interrupt = []
|
||||
|
||||
# Enable nightly-only features
|
||||
nightly = ["embassy-macros/nightly"]
|
||||
|
||||
turbowakers = []
|
||||
|
||||
integrated-timers = ["dep:embassy-time"]
|
||||
|
||||
# BEGIN AUTOGENERATED CONFIG FEATURES
|
||||
# Generated by gen_config.py. DO NOT EDIT.
|
||||
task-arena-size-64 = []
|
||||
task-arena-size-128 = []
|
||||
task-arena-size-192 = []
|
||||
task-arena-size-256 = []
|
||||
task-arena-size-320 = []
|
||||
task-arena-size-384 = []
|
||||
task-arena-size-512 = []
|
||||
task-arena-size-640 = []
|
||||
task-arena-size-768 = []
|
||||
task-arena-size-1024 = []
|
||||
task-arena-size-1280 = []
|
||||
task-arena-size-1536 = []
|
||||
task-arena-size-2048 = []
|
||||
task-arena-size-2560 = []
|
||||
task-arena-size-3072 = []
|
||||
task-arena-size-4096 = [] # Default
|
||||
task-arena-size-5120 = []
|
||||
task-arena-size-6144 = []
|
||||
task-arena-size-8192 = []
|
||||
task-arena-size-10240 = []
|
||||
task-arena-size-12288 = []
|
||||
task-arena-size-16384 = []
|
||||
task-arena-size-20480 = []
|
||||
task-arena-size-24576 = []
|
||||
task-arena-size-32768 = []
|
||||
task-arena-size-40960 = []
|
||||
task-arena-size-49152 = []
|
||||
task-arena-size-65536 = []
|
||||
task-arena-size-81920 = []
|
||||
task-arena-size-98304 = []
|
||||
task-arena-size-131072 = []
|
||||
task-arena-size-163840 = []
|
||||
task-arena-size-196608 = []
|
||||
task-arena-size-262144 = []
|
||||
task-arena-size-327680 = []
|
||||
task-arena-size-393216 = []
|
||||
task-arena-size-524288 = []
|
||||
task-arena-size-655360 = []
|
||||
task-arena-size-786432 = []
|
||||
task-arena-size-1048576 = []
|
||||
|
||||
# END AUTOGENERATED CONFIG FEATURES
|
||||
|
@ -2,10 +2,36 @@
|
||||
|
||||
An async/await executor designed for embedded usage.
|
||||
|
||||
- No `alloc`, no heap needed. Task futures are statically allocated.
|
||||
- No `alloc`, no heap needed.
|
||||
- With nightly Rust, task futures can be fully statically allocated.
|
||||
- No "fixed capacity" data structures, executor works with 1 or 1000 tasks without needing config/tuning.
|
||||
- Integrated timer queue: sleeping is easy, just do `Timer::after_secs(1).await;`.
|
||||
- No busy-loop polling: CPU sleeps when there's no work to do, using interrupts or `WFE/SEV`.
|
||||
- Efficient polling: a wake will only poll the woken task, not all of them.
|
||||
- Fair: a task can't monopolize CPU time even if it's constantly being woken. All other tasks get a chance to run before a given task gets polled for the second time.
|
||||
- Creating multiple executor instances is supported, to run tasks with multiple priority levels. This allows higher-priority tasks to preempt lower-priority tasks.
|
||||
|
||||
## Task arena
|
||||
|
||||
When the `nightly` Cargo feature is not enabled, `embassy-executor` allocates tasks out of an arena (a very simple bump allocator).
|
||||
|
||||
If the task arena gets full, the program will panic at runtime. To guarantee this doesn't happen, you must set the size to the sum of sizes of all tasks.
|
||||
|
||||
Tasks are allocated from the arena when spawned for the first time. If the task exists, the allocation is not released to the arena, but can be reused to spawn the task again. For multiple-instance tasks (like `#[embassy_executor::task(pool_size = 4)]`), the first spawn will allocate memory for all instances. This is done for performance and to increase predictability (for example, spawning at least 1 instance of every task at boot guarantees an immediate panic if the arena is too small, while allocating instances on-demand could delay the panic to only when the program is under load).
|
||||
|
||||
The arena size can be configured in two ways:
|
||||
|
||||
- Via Cargo features: enable a Cargo feature like `task-arena-size-8192`. Only a selection of values
|
||||
is available, check `Cargo.toml` for the list.
|
||||
- Via environment variables at build time: set the variable named `EMBASSY_EXECUTOR_TASK_ARENA_SIZE`. For example
|
||||
`EMBASSY_EXECUTOR_TASK_ARENA_SIZE=4321 cargo build`. You can also set them in the `[env]` section of `.cargo/config.toml`.
|
||||
Any value can be set, unlike with Cargo features.
|
||||
|
||||
Environment variables take precedence over Cargo features. If two Cargo features are enabled for the same setting
|
||||
with different values, compilation fails.
|
||||
|
||||
## Statically allocating tasks
|
||||
|
||||
When using nightly Rust, enable the `nightly` Cargo feature. This will make `embassy-executor` use the `type_alias_impl_trait` feature to allocate all tasks in `static`s. Each task gets its own `static`, with the exact size to hold the task (or multiple instances of it, if using `pool_size`) calculated automatically at compile time. If tasks don't fit in RAM, this is detected at compile time by the linker. Runtime panics due to running out of memory are not possible.
|
||||
|
||||
The configured arena size is ignored, no arena is used at all.
|
||||
|
@ -1,6 +1,97 @@
|
||||
use std::env;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::{env, fs};
|
||||
|
||||
static CONFIGS: &[(&str, usize)] = &[
|
||||
// BEGIN AUTOGENERATED CONFIG FEATURES
|
||||
// Generated by gen_config.py. DO NOT EDIT.
|
||||
("TASK_ARENA_SIZE", 4096),
|
||||
// END AUTOGENERATED CONFIG FEATURES
|
||||
];
|
||||
|
||||
struct ConfigState {
|
||||
value: usize,
|
||||
seen_feature: bool,
|
||||
seen_env: bool,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let crate_name = env::var("CARGO_PKG_NAME")
|
||||
.unwrap()
|
||||
.to_ascii_uppercase()
|
||||
.replace('-', "_");
|
||||
|
||||
// only rebuild if build.rs changed. Otherwise Cargo will rebuild if any
|
||||
// other file changed.
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
|
||||
// Rebuild if config envvar changed.
|
||||
for (name, _) in CONFIGS {
|
||||
println!("cargo:rerun-if-env-changed={crate_name}_{name}");
|
||||
}
|
||||
|
||||
let mut configs = HashMap::new();
|
||||
for (name, default) in CONFIGS {
|
||||
configs.insert(
|
||||
*name,
|
||||
ConfigState {
|
||||
value: *default,
|
||||
seen_env: false,
|
||||
seen_feature: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let prefix = format!("{crate_name}_");
|
||||
for (var, value) in env::vars() {
|
||||
if let Some(name) = var.strip_prefix(&prefix) {
|
||||
let Some(cfg) = configs.get_mut(name) else {
|
||||
panic!("Unknown env var {name}")
|
||||
};
|
||||
|
||||
let Ok(value) = value.parse::<usize>() else {
|
||||
panic!("Invalid value for env var {name}: {value}")
|
||||
};
|
||||
|
||||
cfg.value = value;
|
||||
cfg.seen_env = true;
|
||||
}
|
||||
|
||||
if let Some(feature) = var.strip_prefix("CARGO_FEATURE_") {
|
||||
if let Some(i) = feature.rfind('_') {
|
||||
let name = &feature[..i];
|
||||
let value = &feature[i + 1..];
|
||||
if let Some(cfg) = configs.get_mut(name) {
|
||||
let Ok(value) = value.parse::<usize>() else {
|
||||
panic!("Invalid value for feature {name}: {value}")
|
||||
};
|
||||
|
||||
// envvars take priority.
|
||||
if !cfg.seen_env {
|
||||
if cfg.seen_feature {
|
||||
panic!("multiple values set for feature {}: {} and {}", name, cfg.value, value);
|
||||
}
|
||||
|
||||
cfg.value = value;
|
||||
cfg.seen_feature = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut data = String::new();
|
||||
|
||||
for (name, cfg) in &configs {
|
||||
writeln!(&mut data, "pub const {}: usize = {};", name, cfg.value).unwrap();
|
||||
}
|
||||
|
||||
let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
|
||||
let out_file = out_dir.join("config.rs").to_string_lossy().to_string();
|
||||
fs::write(out_file, data).unwrap();
|
||||
|
||||
// cortex-m targets
|
||||
let target = env::var("TARGET").unwrap();
|
||||
|
||||
if target.starts_with("thumbv6m-") {
|
||||
|
82
embassy-executor/gen_config.py
Normal file
82
embassy-executor/gen_config.py
Normal file
@ -0,0 +1,82 @@
|
||||
import os
|
||||
|
||||
abspath = os.path.abspath(__file__)
|
||||
dname = os.path.dirname(abspath)
|
||||
os.chdir(dname)
|
||||
|
||||
features = []
|
||||
|
||||
|
||||
def feature(name, default, min=None, max=None, pow2=None, vals=None, factors=[]):
|
||||
if vals is None:
|
||||
assert min is not None
|
||||
assert max is not None
|
||||
|
||||
vals = set()
|
||||
val = min
|
||||
while val <= max:
|
||||
vals.add(val)
|
||||
for f in factors:
|
||||
if val * f <= max:
|
||||
vals.add(val * f)
|
||||
if (pow2 == True or (isinstance(pow2, int) and val >= pow2)) and val > 0:
|
||||
val *= 2
|
||||
else:
|
||||
val += 1
|
||||
vals.add(default)
|
||||
vals = sorted(list(vals))
|
||||
|
||||
features.append(
|
||||
{
|
||||
"name": name,
|
||||
"default": default,
|
||||
"vals": vals,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
feature(
|
||||
"task_arena_size", default=4096, min=64, max=1024 * 1024, pow2=True, factors=[3, 5]
|
||||
)
|
||||
|
||||
# ========= Update Cargo.toml
|
||||
|
||||
things = ""
|
||||
for f in features:
|
||||
name = f["name"].replace("_", "-")
|
||||
for val in f["vals"]:
|
||||
things += f"{name}-{val} = []"
|
||||
if val == f["default"]:
|
||||
things += " # Default"
|
||||
things += "\n"
|
||||
things += "\n"
|
||||
|
||||
SEPARATOR_START = "# BEGIN AUTOGENERATED CONFIG FEATURES\n"
|
||||
SEPARATOR_END = "# END AUTOGENERATED CONFIG FEATURES\n"
|
||||
HELP = "# Generated by gen_config.py. DO NOT EDIT.\n"
|
||||
with open("Cargo.toml", "r") as f:
|
||||
data = f.read()
|
||||
before, data = data.split(SEPARATOR_START, maxsplit=1)
|
||||
_, after = data.split(SEPARATOR_END, maxsplit=1)
|
||||
data = before + SEPARATOR_START + HELP + things + SEPARATOR_END + after
|
||||
with open("Cargo.toml", "w") as f:
|
||||
f.write(data)
|
||||
|
||||
|
||||
# ========= Update build.rs
|
||||
|
||||
things = ""
|
||||
for f in features:
|
||||
name = f["name"].upper()
|
||||
things += f' ("{name}", {f["default"]}),\n'
|
||||
|
||||
SEPARATOR_START = "// BEGIN AUTOGENERATED CONFIG FEATURES\n"
|
||||
SEPARATOR_END = "// END AUTOGENERATED CONFIG FEATURES\n"
|
||||
HELP = " // Generated by gen_config.py. DO NOT EDIT.\n"
|
||||
with open("build.rs", "r") as f:
|
||||
data = f.read()
|
||||
before, data = data.split(SEPARATOR_START, maxsplit=1)
|
||||
_, after = data.split(SEPARATOR_END, maxsplit=1)
|
||||
data = before + SEPARATOR_START + HELP + things + " " + SEPARATOR_END + after
|
||||
with open("build.rs", "w") as f:
|
||||
f.write(data)
|
@ -51,7 +51,6 @@ mod thread {
|
||||
use core::arch::asm;
|
||||
use core::marker::PhantomData;
|
||||
|
||||
#[cfg(feature = "nightly")]
|
||||
pub use embassy_macros::main_cortex_m as main;
|
||||
|
||||
use crate::{raw, Spawner};
|
||||
|
@ -7,7 +7,6 @@ pub use thread::*;
|
||||
mod thread {
|
||||
use core::marker::PhantomData;
|
||||
|
||||
#[cfg(feature = "nightly")]
|
||||
pub use embassy_macros::main_riscv as main;
|
||||
use portable_atomic::{AtomicBool, Ordering};
|
||||
|
||||
|
@ -8,7 +8,6 @@ mod thread {
|
||||
use std::marker::PhantomData;
|
||||
use std::sync::{Condvar, Mutex};
|
||||
|
||||
#[cfg(feature = "nightly")]
|
||||
pub use embassy_macros::main_std as main;
|
||||
|
||||
use crate::{raw, Spawner};
|
||||
|
@ -8,7 +8,6 @@ mod thread {
|
||||
|
||||
use core::marker::PhantomData;
|
||||
|
||||
#[cfg(feature = "nightly")]
|
||||
pub use embassy_macros::main_wasm as main;
|
||||
use js_sys::Promise;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
@ -8,7 +8,6 @@ mod thread {
|
||||
use core::marker::PhantomData;
|
||||
use core::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
#[cfg(feature = "nightly")]
|
||||
pub use embassy_macros::main_riscv as main;
|
||||
|
||||
use crate::{raw, Spawner};
|
||||
|
@ -1,5 +1,5 @@
|
||||
#![cfg_attr(not(any(feature = "arch-std", feature = "arch-wasm")), no_std)]
|
||||
#![cfg_attr(all(feature = "nightly", feature = "arch-xtensa"), feature(asm_experimental_arch))]
|
||||
#![cfg_attr(feature = "arch-xtensa", feature(asm_experimental_arch))]
|
||||
#![allow(clippy::new_without_default)]
|
||||
#![doc = include_str!("../README.md")]
|
||||
#![warn(missing_docs)]
|
||||
@ -7,7 +7,6 @@
|
||||
// This mod MUST go first, so that the others see its macros.
|
||||
pub(crate) mod fmt;
|
||||
|
||||
#[cfg(feature = "nightly")]
|
||||
pub use embassy_macros::task;
|
||||
|
||||
macro_rules! check_at_most_one {
|
||||
@ -41,28 +40,101 @@ pub mod raw;
|
||||
mod spawner;
|
||||
pub use spawner::*;
|
||||
|
||||
mod config {
|
||||
#![allow(unused)]
|
||||
include!(concat!(env!("OUT_DIR"), "/config.rs"));
|
||||
}
|
||||
|
||||
/// Implementation details for embassy macros.
|
||||
/// Do not use. Used for macros and HALs only. Not covered by semver guarantees.
|
||||
#[doc(hidden)]
|
||||
#[cfg(not(feature = "nightly"))]
|
||||
pub mod _export {
|
||||
#[cfg(feature = "rtos-trace")]
|
||||
pub use rtos_trace::trace;
|
||||
use core::alloc::Layout;
|
||||
use core::cell::{Cell, UnsafeCell};
|
||||
use core::future::Future;
|
||||
use core::mem::MaybeUninit;
|
||||
use core::ptr::null_mut;
|
||||
|
||||
/// Expands the given block of code when `embassy-executor` is compiled with
|
||||
/// the `rtos-trace-interrupt` feature.
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
#[cfg(feature = "rtos-trace-interrupt")]
|
||||
macro_rules! rtos_trace_interrupt {
|
||||
($($tt:tt)*) => { $($tt)* };
|
||||
use critical_section::{CriticalSection, Mutex};
|
||||
|
||||
use crate::raw::TaskPool;
|
||||
|
||||
struct Arena<const N: usize> {
|
||||
buf: UnsafeCell<MaybeUninit<[u8; N]>>,
|
||||
ptr: Mutex<Cell<*mut u8>>,
|
||||
}
|
||||
|
||||
/// Does not expand the given block of code when `embassy-executor` is
|
||||
/// compiled without the `rtos-trace-interrupt` feature.
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
#[cfg(not(feature = "rtos-trace-interrupt"))]
|
||||
macro_rules! rtos_trace_interrupt {
|
||||
($($tt:tt)*) => {};
|
||||
unsafe impl<const N: usize> Sync for Arena<N> {}
|
||||
unsafe impl<const N: usize> Send for Arena<N> {}
|
||||
|
||||
impl<const N: usize> Arena<N> {
|
||||
const fn new() -> Self {
|
||||
Self {
|
||||
buf: UnsafeCell::new(MaybeUninit::uninit()),
|
||||
ptr: Mutex::new(Cell::new(null_mut())),
|
||||
}
|
||||
}
|
||||
|
||||
fn alloc<T>(&'static self, cs: CriticalSection) -> &'static mut MaybeUninit<T> {
|
||||
let layout = Layout::new::<T>();
|
||||
|
||||
let start = self.buf.get().cast::<u8>();
|
||||
let end = unsafe { start.add(N) };
|
||||
|
||||
let mut ptr = self.ptr.borrow(cs).get();
|
||||
if ptr.is_null() {
|
||||
ptr = self.buf.get().cast::<u8>();
|
||||
}
|
||||
|
||||
let bytes_left = (end as usize) - (ptr as usize);
|
||||
let align_offset = (ptr as usize).next_multiple_of(layout.align()) - (ptr as usize);
|
||||
|
||||
if align_offset + layout.size() > bytes_left {
|
||||
panic!("embassy-executor: task arena is full. You must increase the arena size, see the documentation for details: https://docs.embassy.dev/embassy-executor/");
|
||||
}
|
||||
|
||||
let res = unsafe { ptr.add(align_offset) };
|
||||
let ptr = unsafe { ptr.add(align_offset + layout.size()) };
|
||||
|
||||
self.ptr.borrow(cs).set(ptr);
|
||||
|
||||
unsafe { &mut *(res as *mut MaybeUninit<T>) }
|
||||
}
|
||||
}
|
||||
|
||||
static ARENA: Arena<{ crate::config::TASK_ARENA_SIZE }> = Arena::new();
|
||||
|
||||
pub struct TaskPoolRef {
|
||||
// type-erased `&'static mut TaskPool<F, N>`
|
||||
// Needed because statics can't have generics.
|
||||
ptr: Mutex<Cell<*mut ()>>,
|
||||
}
|
||||
unsafe impl Sync for TaskPoolRef {}
|
||||
unsafe impl Send for TaskPoolRef {}
|
||||
|
||||
impl TaskPoolRef {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
ptr: Mutex::new(Cell::new(null_mut())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the pool for this ref, allocating it from the arena the first time.
|
||||
///
|
||||
/// safety: for a given TaskPoolRef instance, must always call with the exact
|
||||
/// same generic params.
|
||||
pub unsafe fn get<F: Future, const N: usize>(&'static self) -> &'static TaskPool<F, N> {
|
||||
critical_section::with(|cs| {
|
||||
let ptr = self.ptr.borrow(cs);
|
||||
if ptr.get().is_null() {
|
||||
let pool = ARENA.alloc::<TaskPool<F, N>>(cs);
|
||||
pool.write(TaskPool::new());
|
||||
ptr.set(pool as *mut _ as _);
|
||||
}
|
||||
|
||||
unsafe { &*(ptr.get() as *const _) }
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -11,7 +11,8 @@
|
||||
#[cfg_attr(not(target_has_atomic = "ptr"), path = "run_queue_critical_section.rs")]
|
||||
mod run_queue;
|
||||
|
||||
#[cfg_attr(target_has_atomic = "8", path = "state_atomics.rs")]
|
||||
#[cfg_attr(all(cortex_m, target_has_atomic = "8"), path = "state_atomics_arm.rs")]
|
||||
#[cfg_attr(all(not(cortex_m), target_has_atomic = "8"), path = "state_atomics.rs")]
|
||||
#[cfg_attr(not(target_has_atomic = "8"), path = "state_critical_section.rs")]
|
||||
mod state;
|
||||
|
||||
|
103
embassy-executor/src/raw/state_atomics_arm.rs
Normal file
103
embassy-executor/src/raw/state_atomics_arm.rs
Normal file
@ -0,0 +1,103 @@
|
||||
use core::arch::asm;
|
||||
use core::sync::atomic::{compiler_fence, AtomicBool, AtomicU32, Ordering};
|
||||
|
||||
// Must be kept in sync with the layout of `State`!
|
||||
pub(crate) const STATE_SPAWNED: u32 = 1 << 0;
|
||||
pub(crate) const STATE_RUN_QUEUED: u32 = 1 << 8;
|
||||
|
||||
#[repr(C, align(4))]
|
||||
pub(crate) struct State {
|
||||
/// Task is spawned (has a future)
|
||||
spawned: AtomicBool,
|
||||
/// Task is in the executor run queue
|
||||
run_queued: AtomicBool,
|
||||
/// Task is in the executor timer queue
|
||||
timer_queued: AtomicBool,
|
||||
pad: AtomicBool,
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub const fn new() -> State {
|
||||
Self {
|
||||
spawned: AtomicBool::new(false),
|
||||
run_queued: AtomicBool::new(false),
|
||||
timer_queued: AtomicBool::new(false),
|
||||
pad: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
fn as_u32(&self) -> &AtomicU32 {
|
||||
unsafe { &*(self as *const _ as *const AtomicU32) }
|
||||
}
|
||||
|
||||
/// If task is idle, mark it as spawned + run_queued and return true.
|
||||
#[inline(always)]
|
||||
pub fn spawn(&self) -> bool {
|
||||
compiler_fence(Ordering::Release);
|
||||
let r = self
|
||||
.as_u32()
|
||||
.compare_exchange(
|
||||
0,
|
||||
STATE_SPAWNED | STATE_RUN_QUEUED,
|
||||
Ordering::Relaxed,
|
||||
Ordering::Relaxed,
|
||||
)
|
||||
.is_ok();
|
||||
compiler_fence(Ordering::Acquire);
|
||||
r
|
||||
}
|
||||
|
||||
/// Unmark the task as spawned.
|
||||
#[inline(always)]
|
||||
pub fn despawn(&self) {
|
||||
compiler_fence(Ordering::Release);
|
||||
self.spawned.store(false, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Mark the task as run-queued if it's spawned and isn't already run-queued. Return true on success.
|
||||
#[inline(always)]
|
||||
pub fn run_enqueue(&self) -> bool {
|
||||
unsafe {
|
||||
loop {
|
||||
let state: u32;
|
||||
asm!("ldrex {}, [{}]", out(reg) state, in(reg) self, options(nostack));
|
||||
|
||||
if (state & STATE_RUN_QUEUED != 0) || (state & STATE_SPAWNED == 0) {
|
||||
asm!("clrex", options(nomem, nostack));
|
||||
return false;
|
||||
}
|
||||
|
||||
let outcome: usize;
|
||||
let new_state = state | STATE_RUN_QUEUED;
|
||||
asm!("strex {}, {}, [{}]", out(reg) outcome, in(reg) new_state, in(reg) self, options(nostack));
|
||||
if outcome == 0 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Unmark the task as run-queued. Return whether the task is spawned.
|
||||
#[inline(always)]
|
||||
pub fn run_dequeue(&self) -> bool {
|
||||
compiler_fence(Ordering::Release);
|
||||
|
||||
let r = self.spawned.load(Ordering::Relaxed);
|
||||
self.run_queued.store(false, Ordering::Relaxed);
|
||||
r
|
||||
}
|
||||
|
||||
/// Mark the task as timer-queued. Return whether it was newly queued (i.e. not queued before)
|
||||
#[cfg(feature = "integrated-timers")]
|
||||
#[inline(always)]
|
||||
pub fn timer_enqueue(&self) -> bool {
|
||||
!self.timer_queued.swap(true, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Unmark the task as timer-queued.
|
||||
#[cfg(feature = "integrated-timers")]
|
||||
#[inline(always)]
|
||||
pub fn timer_dequeue(&self) {
|
||||
self.timer_queued.store(false, Ordering::Relaxed);
|
||||
}
|
||||
}
|
137
embassy-executor/tests/test.rs
Normal file
137
embassy-executor/tests/test.rs
Normal file
@ -0,0 +1,137 @@
|
||||
#![cfg_attr(feature = "nightly", feature(type_alias_impl_trait))]
|
||||
|
||||
use std::boxed::Box;
|
||||
use std::future::poll_fn;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::Poll;
|
||||
|
||||
use embassy_executor::raw::Executor;
|
||||
use embassy_executor::task;
|
||||
|
||||
#[export_name = "__pender"]
|
||||
fn __pender(context: *mut ()) {
|
||||
unsafe {
|
||||
let trace = &*(context as *const Trace);
|
||||
trace.push("pend");
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Trace {
|
||||
trace: Arc<Mutex<Vec<&'static str>>>,
|
||||
}
|
||||
|
||||
impl Trace {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
trace: Arc::new(Mutex::new(Vec::new())),
|
||||
}
|
||||
}
|
||||
fn push(&self, value: &'static str) {
|
||||
self.trace.lock().unwrap().push(value)
|
||||
}
|
||||
|
||||
fn get(&self) -> Vec<&'static str> {
|
||||
self.trace.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn setup() -> (&'static Executor, Trace) {
|
||||
let trace = Trace::new();
|
||||
let context = Box::leak(Box::new(trace.clone())) as *mut _ as *mut ();
|
||||
let executor = &*Box::leak(Box::new(Executor::new(context)));
|
||||
(executor, trace)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executor_noop() {
|
||||
let (executor, trace) = setup();
|
||||
unsafe { executor.poll() };
|
||||
assert!(trace.get().is_empty())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executor_task() {
|
||||
#[task]
|
||||
async fn task1(trace: Trace) {
|
||||
trace.push("poll task1")
|
||||
}
|
||||
|
||||
let (executor, trace) = setup();
|
||||
executor.spawner().spawn(task1(trace.clone())).unwrap();
|
||||
|
||||
unsafe { executor.poll() };
|
||||
unsafe { executor.poll() };
|
||||
|
||||
assert_eq!(
|
||||
trace.get(),
|
||||
&[
|
||||
"pend", // spawning a task pends the executor
|
||||
"poll task1", // poll only once.
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executor_task_self_wake() {
|
||||
#[task]
|
||||
async fn task1(trace: Trace) {
|
||||
poll_fn(|cx| {
|
||||
trace.push("poll task1");
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
let (executor, trace) = setup();
|
||||
executor.spawner().spawn(task1(trace.clone())).unwrap();
|
||||
|
||||
unsafe { executor.poll() };
|
||||
unsafe { executor.poll() };
|
||||
|
||||
assert_eq!(
|
||||
trace.get(),
|
||||
&[
|
||||
"pend", // spawning a task pends the executor
|
||||
"poll task1", //
|
||||
"pend", // task self-wakes
|
||||
"poll task1", //
|
||||
"pend", // task self-wakes
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executor_task_self_wake_twice() {
|
||||
#[task]
|
||||
async fn task1(trace: Trace) {
|
||||
poll_fn(|cx| {
|
||||
trace.push("poll task1");
|
||||
cx.waker().wake_by_ref();
|
||||
trace.push("poll task1 wake 2");
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
let (executor, trace) = setup();
|
||||
executor.spawner().spawn(task1(trace.clone())).unwrap();
|
||||
|
||||
unsafe { executor.poll() };
|
||||
unsafe { executor.poll() };
|
||||
|
||||
assert_eq!(
|
||||
trace.get(),
|
||||
&[
|
||||
"pend", // spawning a task pends the executor
|
||||
"poll task1", //
|
||||
"pend", // task self-wakes
|
||||
"poll task1 wake 2", // task self-wakes again, shouldn't pend
|
||||
"poll task1", //
|
||||
"pend", // task self-wakes
|
||||
"poll task1 wake 2", // task self-wakes again, shouldn't pend
|
||||
]
|
||||
)
|
||||
}
|
@ -21,5 +21,4 @@ proc-macro2 = "1.0.29"
|
||||
proc-macro = true
|
||||
|
||||
[features]
|
||||
# Enabling this cause interrupt::take! to require embassy-executor
|
||||
rtos-trace-interrupt = []
|
||||
nightly = []
|
@ -79,6 +79,7 @@ pub fn run(args: &[NestedMeta], f: syn::ItemFn) -> Result<TokenStream, TokenStre
|
||||
task_inner.vis = syn::Visibility::Inherited;
|
||||
task_inner.sig.ident = task_inner_ident.clone();
|
||||
|
||||
#[cfg(feature = "nightly")]
|
||||
let mut task_outer: ItemFn = parse_quote! {
|
||||
#visibility fn #task_ident(#fargs) -> ::embassy_executor::SpawnToken<impl Sized> {
|
||||
type Fut = impl ::core::future::Future + 'static;
|
||||
@ -87,6 +88,14 @@ pub fn run(args: &[NestedMeta], f: syn::ItemFn) -> Result<TokenStream, TokenStre
|
||||
unsafe { POOL._spawn_async_fn(move || #task_inner_ident(#(#arg_names,)*)) }
|
||||
}
|
||||
};
|
||||
#[cfg(not(feature = "nightly"))]
|
||||
let mut task_outer: ItemFn = parse_quote! {
|
||||
#visibility fn #task_ident(#fargs) -> ::embassy_executor::SpawnToken<impl Sized> {
|
||||
const POOL_SIZE: usize = #pool_size;
|
||||
static POOL: ::embassy_executor::_export::TaskPoolRef = ::embassy_executor::_export::TaskPoolRef::new();
|
||||
unsafe { POOL.get::<_, POOL_SIZE>()._spawn_async_fn(move || #task_inner_ident(#(#arg_names,)*)) }
|
||||
}
|
||||
};
|
||||
|
||||
task_outer.attrs.append(&mut task_inner.attrs.clone());
|
||||
|
||||
|
@ -616,9 +616,11 @@ impl<D: Driver> Stack<D> {
|
||||
let addr = addr.into();
|
||||
|
||||
self.with_mut(|s, i| {
|
||||
let (_hardware_addr, medium) = to_smoltcp_hardware_address(i.device.hardware_address());
|
||||
let mut smoldev = DriverAdapter {
|
||||
cx: Some(cx),
|
||||
inner: &mut i.device,
|
||||
medium,
|
||||
};
|
||||
|
||||
match s
|
||||
@ -653,9 +655,11 @@ impl<D: Driver> Stack<D> {
|
||||
let addr = addr.into();
|
||||
|
||||
self.with_mut(|s, i| {
|
||||
let (_hardware_addr, medium) = to_smoltcp_hardware_address(i.device.hardware_address());
|
||||
let mut smoldev = DriverAdapter {
|
||||
cx: Some(cx),
|
||||
inner: &mut i.device,
|
||||
medium,
|
||||
};
|
||||
|
||||
match s
|
||||
|
@ -61,6 +61,7 @@ fn main() {
|
||||
let mut singletons: Vec<String> = Vec::new();
|
||||
for p in METADATA.peripherals {
|
||||
if let Some(r) = &p.registers {
|
||||
println!("cargo:rustc-cfg=peri_{}", p.name.to_ascii_lowercase());
|
||||
match r.kind {
|
||||
// Generate singletons per pin, not per port
|
||||
"gpio" => {
|
||||
|
@ -1,4 +1,3 @@
|
||||
use core::cell::{RefCell, RefMut};
|
||||
use core::future::poll_fn;
|
||||
use core::marker::PhantomData;
|
||||
use core::ops::{Deref, DerefMut};
|
||||
@ -84,7 +83,7 @@ impl<T: Instance> interrupt::typelevel::Handler<T::SCEInterrupt> for SceInterrup
|
||||
}
|
||||
|
||||
pub struct Can<'d, T: Instance> {
|
||||
pub can: RefCell<bxcan::Can<BxcanInstance<'d, T>>>,
|
||||
pub can: bxcan::Can<BxcanInstance<'d, T>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@ -175,17 +174,12 @@ impl<'d, T: Instance> Can<'d, T> {
|
||||
tx.set_as_af(tx.af_num(), AFType::OutputPushPull);
|
||||
|
||||
let can = bxcan::Can::builder(BxcanInstance(peri)).leave_disabled();
|
||||
let can_ref_cell = RefCell::new(can);
|
||||
Self { can: can_ref_cell }
|
||||
Self { can }
|
||||
}
|
||||
|
||||
pub fn set_bitrate(&mut self, bitrate: u32) {
|
||||
let bit_timing = Self::calc_bxcan_timings(T::frequency(), bitrate).unwrap();
|
||||
self.can
|
||||
.borrow_mut()
|
||||
.modify_config()
|
||||
.set_bit_timing(bit_timing)
|
||||
.leave_disabled();
|
||||
self.can.modify_config().set_bit_timing(bit_timing).leave_disabled();
|
||||
}
|
||||
|
||||
/// Enables the peripheral and synchronizes with the bus.
|
||||
@ -193,7 +187,7 @@ impl<'d, T: Instance> Can<'d, T> {
|
||||
/// This will wait for 11 consecutive recessive bits (bus idle state).
|
||||
/// Contrary to enable method from bxcan library, this will not freeze the executor while waiting.
|
||||
pub async fn enable(&mut self) {
|
||||
while self.borrow_mut().enable_non_blocking().is_err() {
|
||||
while self.enable_non_blocking().is_err() {
|
||||
// SCE interrupt is only generated for entering sleep mode, but not leaving.
|
||||
// Yield to allow other tasks to execute while can bus is initializing.
|
||||
embassy_futures::yield_now().await;
|
||||
@ -202,46 +196,46 @@ impl<'d, T: Instance> Can<'d, T> {
|
||||
|
||||
/// Queues the message to be sent but exerts backpressure
|
||||
pub async fn write(&mut self, frame: &Frame) -> bxcan::TransmitStatus {
|
||||
CanTx { can: &self.can }.write(frame).await
|
||||
self.split().0.write(frame).await
|
||||
}
|
||||
|
||||
/// Attempts to transmit a frame without blocking.
|
||||
///
|
||||
/// Returns [Err(TryWriteError::Full)] if all transmit mailboxes are full.
|
||||
pub fn try_write(&mut self, frame: &Frame) -> Result<bxcan::TransmitStatus, TryWriteError> {
|
||||
CanTx { can: &self.can }.try_write(frame)
|
||||
self.split().0.try_write(frame)
|
||||
}
|
||||
|
||||
/// Waits for a specific transmit mailbox to become empty
|
||||
pub async fn flush(&self, mb: bxcan::Mailbox) {
|
||||
CanTx { can: &self.can }.flush(mb).await
|
||||
CanTx::<T>::flush_inner(mb).await
|
||||
}
|
||||
|
||||
/// Waits until any of the transmit mailboxes become empty
|
||||
pub async fn flush_any(&self) {
|
||||
CanTx { can: &self.can }.flush_any().await
|
||||
CanTx::<T>::flush_any_inner().await
|
||||
}
|
||||
|
||||
/// Waits until all of the transmit mailboxes become empty
|
||||
pub async fn flush_all(&self) {
|
||||
CanTx { can: &self.can }.flush_all().await
|
||||
CanTx::<T>::flush_all_inner().await
|
||||
}
|
||||
|
||||
/// Returns a tuple of the time the message was received and the message frame
|
||||
pub async fn read(&mut self) -> Result<Envelope, BusError> {
|
||||
CanRx { can: &self.can }.read().await
|
||||
self.split().1.read().await
|
||||
}
|
||||
|
||||
/// Attempts to read a can frame without blocking.
|
||||
///
|
||||
/// Returns [Err(TryReadError::Empty)] if there are no frames in the rx queue.
|
||||
pub fn try_read(&mut self) -> Result<Envelope, TryReadError> {
|
||||
CanRx { can: &self.can }.try_read()
|
||||
self.split().1.try_read()
|
||||
}
|
||||
|
||||
/// Waits while receive queue is empty.
|
||||
pub async fn wait_not_empty(&mut self) {
|
||||
CanRx { can: &self.can }.wait_not_empty().await
|
||||
self.split().1.wait_not_empty().await
|
||||
}
|
||||
|
||||
unsafe fn receive_fifo(fifo: RxFifo) {
|
||||
@ -385,24 +379,25 @@ impl<'d, T: Instance> Can<'d, T> {
|
||||
Some((sjw - 1) << 24 | (bs1 as u32 - 1) << 16 | (bs2 as u32 - 1) << 20 | (prescaler - 1))
|
||||
}
|
||||
|
||||
pub fn split<'c>(&'c self) -> (CanTx<'c, 'd, T>, CanRx<'c, 'd, T>) {
|
||||
(CanTx { can: &self.can }, CanRx { can: &self.can })
|
||||
pub fn split<'c>(&'c mut self) -> (CanTx<'c, 'd, T>, CanRx<'c, 'd, T>) {
|
||||
let (tx, rx0, rx1) = self.can.split_by_ref();
|
||||
(CanTx { tx }, CanRx { rx0, rx1 })
|
||||
}
|
||||
|
||||
pub fn as_mut(&self) -> RefMut<'_, bxcan::Can<BxcanInstance<'d, T>>> {
|
||||
self.can.borrow_mut()
|
||||
pub fn as_mut(&mut self) -> &mut bxcan::Can<BxcanInstance<'d, T>> {
|
||||
&mut self.can
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CanTx<'c, 'd, T: Instance> {
|
||||
can: &'c RefCell<bxcan::Can<BxcanInstance<'d, T>>>,
|
||||
tx: &'c mut bxcan::Tx<BxcanInstance<'d, T>>,
|
||||
}
|
||||
|
||||
impl<'c, 'd, T: Instance> CanTx<'c, 'd, T> {
|
||||
pub async fn write(&mut self, frame: &Frame) -> bxcan::TransmitStatus {
|
||||
poll_fn(|cx| {
|
||||
T::state().tx_waker.register(cx.waker());
|
||||
if let Ok(status) = self.can.borrow_mut().transmit(frame) {
|
||||
if let Ok(status) = self.tx.transmit(frame) {
|
||||
return Poll::Ready(status);
|
||||
}
|
||||
|
||||
@ -415,11 +410,10 @@ impl<'c, 'd, T: Instance> CanTx<'c, 'd, T> {
|
||||
///
|
||||
/// Returns [Err(TryWriteError::Full)] if all transmit mailboxes are full.
|
||||
pub fn try_write(&mut self, frame: &Frame) -> Result<bxcan::TransmitStatus, TryWriteError> {
|
||||
self.can.borrow_mut().transmit(frame).map_err(|_| TryWriteError::Full)
|
||||
self.tx.transmit(frame).map_err(|_| TryWriteError::Full)
|
||||
}
|
||||
|
||||
/// Waits for a specific transmit mailbox to become empty
|
||||
pub async fn flush(&self, mb: bxcan::Mailbox) {
|
||||
async fn flush_inner(mb: bxcan::Mailbox) {
|
||||
poll_fn(|cx| {
|
||||
T::state().tx_waker.register(cx.waker());
|
||||
if T::regs().tsr().read().tme(mb.index()) {
|
||||
@ -431,8 +425,12 @@ impl<'c, 'd, T: Instance> CanTx<'c, 'd, T> {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Waits until any of the transmit mailboxes become empty
|
||||
pub async fn flush_any(&self) {
|
||||
/// Waits for a specific transmit mailbox to become empty
|
||||
pub async fn flush(&self, mb: bxcan::Mailbox) {
|
||||
Self::flush_inner(mb).await
|
||||
}
|
||||
|
||||
async fn flush_any_inner() {
|
||||
poll_fn(|cx| {
|
||||
T::state().tx_waker.register(cx.waker());
|
||||
|
||||
@ -449,8 +447,12 @@ impl<'c, 'd, T: Instance> CanTx<'c, 'd, T> {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Waits until all of the transmit mailboxes become empty
|
||||
pub async fn flush_all(&self) {
|
||||
/// Waits until any of the transmit mailboxes become empty
|
||||
pub async fn flush_any(&self) {
|
||||
Self::flush_any_inner().await
|
||||
}
|
||||
|
||||
async fn flush_all_inner() {
|
||||
poll_fn(|cx| {
|
||||
T::state().tx_waker.register(cx.waker());
|
||||
|
||||
@ -466,11 +468,17 @@ impl<'c, 'd, T: Instance> CanTx<'c, 'd, T> {
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Waits until all of the transmit mailboxes become empty
|
||||
pub async fn flush_all(&self) {
|
||||
Self::flush_all_inner().await
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub struct CanRx<'c, 'd, T: Instance> {
|
||||
can: &'c RefCell<bxcan::Can<BxcanInstance<'d, T>>>,
|
||||
rx0: &'c mut bxcan::Rx0<BxcanInstance<'d, T>>,
|
||||
rx1: &'c mut bxcan::Rx1<BxcanInstance<'d, T>>,
|
||||
}
|
||||
|
||||
impl<'c, 'd, T: Instance> CanRx<'c, 'd, T> {
|
||||
@ -538,7 +546,7 @@ impl<'d, T: Instance> Drop for Can<'d, T> {
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> Deref for Can<'d, T> {
|
||||
type Target = RefCell<bxcan::Can<BxcanInstance<'d, T>>>;
|
||||
type Target = bxcan::Can<BxcanInstance<'d, T>>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.can
|
||||
|
@ -1,21 +1,16 @@
|
||||
use core::cmp;
|
||||
#[cfg(feature = "time")]
|
||||
use core::future::poll_fn;
|
||||
use core::marker::PhantomData;
|
||||
#[cfg(feature = "time")]
|
||||
use core::task::Poll;
|
||||
|
||||
use embassy_embedded_hal::SetConfig;
|
||||
#[cfg(feature = "time")]
|
||||
use embassy_hal_internal::drop::OnDrop;
|
||||
use embassy_hal_internal::{into_ref, PeripheralRef};
|
||||
use embassy_sync::waitqueue::AtomicWaker;
|
||||
#[cfg(feature = "time")]
|
||||
use embassy_time::{Duration, Instant};
|
||||
|
||||
use crate::dma::NoDma;
|
||||
#[cfg(feature = "time")]
|
||||
use crate::dma::Transfer;
|
||||
use crate::dma::{NoDma, Transfer};
|
||||
use crate::gpio::sealed::AFType;
|
||||
use crate::gpio::Pull;
|
||||
use crate::i2c::{Error, Instance, SclPin, SdaPin};
|
||||
@ -24,6 +19,23 @@ use crate::pac::i2c;
|
||||
use crate::time::Hertz;
|
||||
use crate::{interrupt, Peripheral};
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
fn timeout_fn(timeout: Duration) -> impl Fn() -> Result<(), Error> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
move || {
|
||||
if Instant::now() > deadline {
|
||||
Err(Error::Timeout)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "time"))]
|
||||
pub fn no_timeout_fn() -> impl Fn() -> Result<(), Error> {
|
||||
move || Ok(())
|
||||
}
|
||||
|
||||
/// Interrupt handler.
|
||||
pub struct InterruptHandler<T: Instance> {
|
||||
_phantom: PhantomData<T>,
|
||||
@ -260,21 +272,12 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> {
|
||||
}
|
||||
|
||||
fn flush_txdr(&self) {
|
||||
//if $i2c.isr.read().txis().bit_is_set() {
|
||||
//$i2c.txdr.write(|w| w.txdata().bits(0));
|
||||
//}
|
||||
|
||||
if T::regs().isr().read().txis() {
|
||||
T::regs().txdr().write(|w| w.set_txdata(0));
|
||||
}
|
||||
if !T::regs().isr().read().txe() {
|
||||
T::regs().isr().modify(|w| w.set_txe(true))
|
||||
}
|
||||
|
||||
// If TXDR is not flagged as empty, write 1 to flush it
|
||||
//if $i2c.isr.read().txe().is_not_empty() {
|
||||
//$i2c.isr.write(|w| w.txe().set_bit());
|
||||
//}
|
||||
}
|
||||
|
||||
fn wait_txe(&self, check_timeout: impl Fn() -> Result<(), Error>) -> Result<(), Error> {
|
||||
@ -437,7 +440,6 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> {
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
async fn write_dma_internal(
|
||||
&mut self,
|
||||
address: u8,
|
||||
@ -528,7 +530,6 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
async fn read_dma_internal(
|
||||
&mut self,
|
||||
address: u8,
|
||||
@ -610,42 +611,38 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> {
|
||||
|
||||
// =========================
|
||||
// Async public API
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
pub async fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Error>
|
||||
where
|
||||
TXDMA: crate::i2c::TxDma<T>,
|
||||
{
|
||||
self.write_timeout(address, write, self.timeout).await
|
||||
}
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
pub async fn write_timeout(&mut self, address: u8, write: &[u8], timeout: Duration) -> Result<(), Error>
|
||||
where
|
||||
TXDMA: crate::i2c::TxDma<T>,
|
||||
{
|
||||
if write.is_empty() {
|
||||
self.write_internal(address, write, true, timeout_fn(timeout))
|
||||
self.write_internal(address, write, true, timeout_fn(self.timeout))
|
||||
} else {
|
||||
embassy_time::with_timeout(
|
||||
timeout,
|
||||
self.write_dma_internal(address, write, true, true, timeout_fn(timeout)),
|
||||
self.timeout,
|
||||
self.write_dma_internal(address, write, true, true, timeout_fn(self.timeout)),
|
||||
)
|
||||
.await
|
||||
.unwrap_or(Err(Error::Timeout))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
pub async fn write_vectored(&mut self, address: u8, write: &[&[u8]]) -> Result<(), Error>
|
||||
#[cfg(not(feature = "time"))]
|
||||
pub async fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Error>
|
||||
where
|
||||
TXDMA: crate::i2c::TxDma<T>,
|
||||
{
|
||||
self.write_vectored_timeout(address, write, self.timeout).await
|
||||
if write.is_empty() {
|
||||
self.write_internal(address, write, true, no_timeout_fn())
|
||||
} else {
|
||||
self.write_dma_internal(address, write, true, true, no_timeout_fn())
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
pub async fn write_vectored_timeout(&mut self, address: u8, write: &[&[u8]], timeout: Duration) -> Result<(), Error>
|
||||
pub async fn write_vectored(&mut self, address: u8, write: &[&[u8]]) -> Result<(), Error>
|
||||
where
|
||||
TXDMA: crate::i2c::TxDma<T>,
|
||||
{
|
||||
@ -661,8 +658,8 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> {
|
||||
let is_last = next.is_none();
|
||||
|
||||
embassy_time::with_timeout(
|
||||
timeout,
|
||||
self.write_dma_internal(address, c, first, is_last, timeout_fn(timeout)),
|
||||
self.timeout,
|
||||
self.write_dma_internal(address, c, first, is_last, timeout_fn(self.timeout)),
|
||||
)
|
||||
.await
|
||||
.unwrap_or(Err(Error::Timeout))?;
|
||||
@ -672,66 +669,79 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "time"))]
|
||||
pub async fn write_vectored(&mut self, address: u8, write: &[&[u8]]) -> Result<(), Error>
|
||||
where
|
||||
TXDMA: crate::i2c::TxDma<T>,
|
||||
{
|
||||
if write.is_empty() {
|
||||
return Err(Error::ZeroLengthTransfer);
|
||||
}
|
||||
let mut iter = write.iter();
|
||||
|
||||
let mut first = true;
|
||||
let mut current = iter.next();
|
||||
while let Some(c) = current {
|
||||
let next = iter.next();
|
||||
let is_last = next.is_none();
|
||||
|
||||
self.write_dma_internal(address, c, first, is_last, no_timeout_fn())
|
||||
.await?;
|
||||
first = false;
|
||||
current = next;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
pub async fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Error>
|
||||
where
|
||||
RXDMA: crate::i2c::RxDma<T>,
|
||||
{
|
||||
self.read_timeout(address, buffer, self.timeout).await
|
||||
if buffer.is_empty() {
|
||||
self.read_internal(address, buffer, false, timeout_fn(self.timeout))
|
||||
} else {
|
||||
embassy_time::with_timeout(
|
||||
self.timeout,
|
||||
self.read_dma_internal(address, buffer, false, timeout_fn(self.timeout)),
|
||||
)
|
||||
.await
|
||||
.unwrap_or(Err(Error::Timeout))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
pub async fn read_timeout(&mut self, address: u8, buffer: &mut [u8], timeout: Duration) -> Result<(), Error>
|
||||
#[cfg(not(feature = "time"))]
|
||||
pub async fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Error>
|
||||
where
|
||||
RXDMA: crate::i2c::RxDma<T>,
|
||||
{
|
||||
if buffer.is_empty() {
|
||||
self.read_internal(address, buffer, false, timeout_fn(timeout))
|
||||
self.read_internal(address, buffer, false, no_timeout_fn())
|
||||
} else {
|
||||
embassy_time::with_timeout(
|
||||
timeout,
|
||||
self.read_dma_internal(address, buffer, false, timeout_fn(timeout)),
|
||||
)
|
||||
.await
|
||||
.unwrap_or(Err(Error::Timeout))
|
||||
self.read_dma_internal(address, buffer, false, no_timeout_fn()).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
pub async fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error>
|
||||
where
|
||||
TXDMA: super::TxDma<T>,
|
||||
RXDMA: super::RxDma<T>,
|
||||
{
|
||||
self.write_read_timeout(address, write, read, self.timeout).await
|
||||
}
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
pub async fn write_read_timeout(
|
||||
&mut self,
|
||||
address: u8,
|
||||
write: &[u8],
|
||||
read: &mut [u8],
|
||||
timeout: Duration,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
TXDMA: super::TxDma<T>,
|
||||
RXDMA: super::RxDma<T>,
|
||||
{
|
||||
let start_instant = Instant::now();
|
||||
let check_timeout = timeout_fn(timeout);
|
||||
let check_timeout = timeout_fn(self.timeout);
|
||||
if write.is_empty() {
|
||||
self.write_internal(address, write, false, &check_timeout)?;
|
||||
} else {
|
||||
embassy_time::with_timeout(
|
||||
timeout,
|
||||
self.timeout,
|
||||
self.write_dma_internal(address, write, true, true, &check_timeout),
|
||||
)
|
||||
.await
|
||||
.unwrap_or(Err(Error::Timeout))?;
|
||||
}
|
||||
|
||||
let time_left_until_timeout = timeout - Instant::now().duration_since(start_instant);
|
||||
let time_left_until_timeout = self.timeout - Instant::now().duration_since(start_instant);
|
||||
|
||||
if read.is_empty() {
|
||||
self.read_internal(address, read, true, &check_timeout)?;
|
||||
@ -747,6 +757,28 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "time"))]
|
||||
pub async fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error>
|
||||
where
|
||||
TXDMA: super::TxDma<T>,
|
||||
RXDMA: super::RxDma<T>,
|
||||
{
|
||||
let no_timeout = no_timeout_fn();
|
||||
if write.is_empty() {
|
||||
self.write_internal(address, write, false, &no_timeout)?;
|
||||
} else {
|
||||
self.write_dma_internal(address, write, true, true, &no_timeout).await?;
|
||||
}
|
||||
|
||||
if read.is_empty() {
|
||||
self.read_internal(address, read, true, &no_timeout)?;
|
||||
} else {
|
||||
self.read_dma_internal(address, read, true, &no_timeout).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Blocking public API
|
||||
|
||||
@ -1155,7 +1187,7 @@ mod eh1 {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "unstable-traits", feature = "nightly", feature = "time"))]
|
||||
#[cfg(all(feature = "unstable-traits", feature = "nightly"))]
|
||||
mod eha {
|
||||
use super::super::{RxDma, TxDma};
|
||||
use super::*;
|
||||
@ -1201,15 +1233,3 @@ impl<'d, T: Instance> SetConfig for I2c<'d, T> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
fn timeout_fn(timeout: Duration) -> impl Fn() -> Result<(), Error> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
move || {
|
||||
if Instant::now() > deadline {
|
||||
Err(Error::Timeout)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -31,12 +31,9 @@ impl From<OpAmpSpeed> for crate::pac::opamp::vals::OpampCsrOpahsm {
|
||||
|
||||
/// OpAmp external outputs, wired to a GPIO pad.
|
||||
///
|
||||
/// The GPIO output pad is held by this struct to ensure it cannot be used elsewhere.
|
||||
///
|
||||
/// This struct can also be used as an ADC input.
|
||||
pub struct OpAmpOutput<'d, 'p, T: Instance, P: OutputPin<T>> {
|
||||
pub struct OpAmpOutput<'d, T: Instance> {
|
||||
_inner: &'d OpAmp<'d, T>,
|
||||
_output: &'p mut P,
|
||||
}
|
||||
|
||||
/// OpAmp internal outputs, wired directly to ADC inputs.
|
||||
@ -54,19 +51,12 @@ pub struct OpAmp<'d, T: Instance> {
|
||||
impl<'d, T: Instance> OpAmp<'d, T> {
|
||||
/// Create a new driver instance.
|
||||
///
|
||||
/// Enables the OpAmp and configures the speed, but
|
||||
/// does not set any other configuration.
|
||||
/// Does not enable the opamp, but does set the speed mode on some families.
|
||||
pub fn new(opamp: impl Peripheral<P = T> + 'd, #[cfg(opamp_g4)] speed: OpAmpSpeed) -> Self {
|
||||
into_ref!(opamp);
|
||||
|
||||
#[cfg(opamp_f3)]
|
||||
T::regs().opampcsr().modify(|w| {
|
||||
w.set_opampen(true);
|
||||
});
|
||||
|
||||
#[cfg(opamp_g4)]
|
||||
T::regs().opamp_csr().modify(|w| {
|
||||
w.set_opaen(true);
|
||||
w.set_opahsm(speed.into());
|
||||
});
|
||||
|
||||
@ -74,24 +64,23 @@ impl<'d, T: Instance> OpAmp<'d, T> {
|
||||
}
|
||||
|
||||
/// Configure the OpAmp as a buffer for the provided input pin,
|
||||
/// outputting to the provided output pin.
|
||||
/// outputting to the provided output pin, and enable the opamp.
|
||||
///
|
||||
/// The input pin is configured for analogue mode but not consumed,
|
||||
/// so it may subsequently be used for ADC or comparator inputs.
|
||||
///
|
||||
/// The output pin is held within the returned [`OpAmpOutput`] struct,
|
||||
/// preventing it being used elsewhere. The `OpAmpOutput` can then be
|
||||
/// directly used as an ADC input.
|
||||
pub fn buffer_ext<'a, 'b, IP, OP>(
|
||||
&'a mut self,
|
||||
in_pin: &IP,
|
||||
out_pin: &'b mut OP,
|
||||
/// directly used as an ADC input. The opamp will be disabled when the
|
||||
/// [`OpAmpOutput`] is dropped.
|
||||
pub fn buffer_ext(
|
||||
&'d mut self,
|
||||
in_pin: impl Peripheral<P = impl NonInvertingPin<T> + crate::gpio::sealed::Pin>,
|
||||
out_pin: impl Peripheral<P = impl OutputPin<T> + crate::gpio::sealed::Pin> + 'd,
|
||||
gain: OpAmpGain,
|
||||
) -> OpAmpOutput<'a, 'b, T, OP>
|
||||
where
|
||||
IP: NonInvertingPin<T> + crate::gpio::sealed::Pin,
|
||||
OP: OutputPin<T> + crate::gpio::sealed::Pin,
|
||||
{
|
||||
) -> OpAmpOutput<'d, T> {
|
||||
into_ref!(in_pin);
|
||||
into_ref!(out_pin);
|
||||
in_pin.set_as_analog();
|
||||
out_pin.set_as_analog();
|
||||
|
||||
@ -122,24 +111,24 @@ impl<'d, T: Instance> OpAmp<'d, T> {
|
||||
w.set_opaen(true);
|
||||
});
|
||||
|
||||
OpAmpOutput {
|
||||
_inner: self,
|
||||
_output: out_pin,
|
||||
}
|
||||
OpAmpOutput { _inner: self }
|
||||
}
|
||||
|
||||
/// Configure the OpAmp as a buffer for the provided input pin,
|
||||
/// with the output only used internally.
|
||||
/// with the output only used internally, and enable the opamp.
|
||||
///
|
||||
/// The input pin is configured for analogue mode but not consumed,
|
||||
/// so it may be subsequently used for ADC or comparator inputs.
|
||||
///
|
||||
/// The returned `OpAmpInternalOutput` struct may be used as an ADC input.
|
||||
/// The opamp output will be disabled when it is dropped.
|
||||
#[cfg(opamp_g4)]
|
||||
pub fn buffer_int<'a, P>(&'a mut self, pin: &P, gain: OpAmpGain) -> OpAmpInternalOutput<'a, T>
|
||||
where
|
||||
P: NonInvertingPin<T> + crate::gpio::sealed::Pin,
|
||||
{
|
||||
pub fn buffer_int(
|
||||
&'d mut self,
|
||||
pin: impl Peripheral<P = impl NonInvertingPin<T> + crate::gpio::sealed::Pin>,
|
||||
gain: OpAmpGain,
|
||||
) -> OpAmpInternalOutput<'d, T> {
|
||||
into_ref!(pin);
|
||||
pin.set_as_analog();
|
||||
|
||||
let (vm_sel, pga_gain) = match gain {
|
||||
@ -163,7 +152,21 @@ impl<'d, T: Instance> OpAmp<'d, T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> Drop for OpAmp<'d, T> {
|
||||
impl<'d, T: Instance> Drop for OpAmpOutput<'d, T> {
|
||||
fn drop(&mut self) {
|
||||
#[cfg(opamp_f3)]
|
||||
T::regs().opampcsr().modify(|w| {
|
||||
w.set_opampen(false);
|
||||
});
|
||||
|
||||
#[cfg(opamp_g4)]
|
||||
T::regs().opamp_csr().modify(|w| {
|
||||
w.set_opaen(false);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> Drop for OpAmpInternalOutput<'d, T> {
|
||||
fn drop(&mut self) {
|
||||
#[cfg(opamp_f3)]
|
||||
T::regs().opampcsr().modify(|w| {
|
||||
@ -203,16 +206,16 @@ macro_rules! impl_opamp_external_output {
|
||||
($inst:ident, $adc:ident, $ch:expr) => {
|
||||
foreach_adc!(
|
||||
($adc, $common_inst:ident, $adc_clock:ident) => {
|
||||
impl<'d, 'p, P: OutputPin<crate::peripherals::$inst>> crate::adc::sealed::AdcPin<crate::peripherals::$adc>
|
||||
for OpAmpOutput<'d, 'p, crate::peripherals::$inst, P>
|
||||
impl<'d> crate::adc::sealed::AdcPin<crate::peripherals::$adc>
|
||||
for OpAmpOutput<'d, crate::peripherals::$inst>
|
||||
{
|
||||
fn channel(&self) -> u8 {
|
||||
$ch
|
||||
}
|
||||
}
|
||||
|
||||
impl<'d, 'p, P: OutputPin<crate::peripherals::$inst>> crate::adc::AdcPin<crate::peripherals::$adc>
|
||||
for OpAmpOutput<'d, 'p, crate::peripherals::$inst, P>
|
||||
impl<'d> crate::adc::AdcPin<crate::peripherals::$adc>
|
||||
for OpAmpOutput<'d, crate::peripherals::$inst>
|
||||
{
|
||||
}
|
||||
};
|
||||
|
@ -168,7 +168,12 @@ impl Default for Config {
|
||||
apb4_pre: APBPrescaler::DIV1,
|
||||
|
||||
per_clock_source: PerClockSource::HSI,
|
||||
adc_clock_source: AdcClockSource::from_bits(0), // PLL2_P on H7, HCLK on H5
|
||||
|
||||
#[cfg(stm32h5)]
|
||||
adc_clock_source: AdcClockSource::HCLK1,
|
||||
#[cfg(stm32h7)]
|
||||
adc_clock_source: AdcClockSource::PER,
|
||||
|
||||
timer_prescaler: TimerPrescaler::DefaultX2,
|
||||
voltage_scale: VoltageScale::Scale0,
|
||||
ls: Default::default(),
|
||||
|
@ -207,27 +207,40 @@ impl Protocol {
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq)]
|
||||
pub enum SyncEnable {
|
||||
Asynchronous,
|
||||
pub enum SyncInput {
|
||||
/// Not synced to any other SAI unit.
|
||||
None,
|
||||
/// Syncs with the other A/B sub-block within the SAI unit
|
||||
Internal,
|
||||
/// Syncs with a sub-block in the other SAI unit - use set_sync_output() and set_sync_input()
|
||||
#[cfg(any(sai_v4))]
|
||||
External,
|
||||
/// Syncs with a sub-block in the other SAI unit
|
||||
#[cfg(sai_v4)]
|
||||
External(SyncInputInstance),
|
||||
}
|
||||
|
||||
impl SyncEnable {
|
||||
#[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))]
|
||||
impl SyncInput {
|
||||
pub const fn syncen(&self) -> vals::Syncen {
|
||||
match self {
|
||||
SyncEnable::Asynchronous => vals::Syncen::ASYNCHRONOUS,
|
||||
SyncEnable::Internal => vals::Syncen::INTERNAL,
|
||||
SyncInput::None => vals::Syncen::ASYNCHRONOUS,
|
||||
SyncInput::Internal => vals::Syncen::INTERNAL,
|
||||
#[cfg(any(sai_v4))]
|
||||
SyncEnable::External => vals::Syncen::EXTERNAL,
|
||||
SyncInput::External(_) => vals::Syncen::EXTERNAL,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(sai_v4)]
|
||||
#[derive(Copy, Clone, PartialEq)]
|
||||
pub enum SyncInputInstance {
|
||||
#[cfg(peri_sai1)]
|
||||
Sai1 = 0,
|
||||
#[cfg(peri_sai2)]
|
||||
Sai2 = 1,
|
||||
#[cfg(peri_sai3)]
|
||||
Sai3 = 2,
|
||||
#[cfg(peri_sai4)]
|
||||
Sai4 = 3,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq)]
|
||||
pub enum StereoMono {
|
||||
Stereo,
|
||||
@ -428,8 +441,8 @@ impl MasterClockDivider {
|
||||
pub struct Config {
|
||||
pub mode: Mode,
|
||||
pub tx_rx: TxRx,
|
||||
pub sync_enable: SyncEnable,
|
||||
pub is_sync_output: bool,
|
||||
pub sync_input: SyncInput,
|
||||
pub sync_output: bool,
|
||||
pub protocol: Protocol,
|
||||
pub slot_size: SlotSize,
|
||||
pub slot_count: word::U4,
|
||||
@ -459,8 +472,8 @@ impl Default for Config {
|
||||
Self {
|
||||
mode: Mode::Master,
|
||||
tx_rx: TxRx::Transmitter,
|
||||
is_sync_output: false,
|
||||
sync_enable: SyncEnable::Asynchronous,
|
||||
sync_output: false,
|
||||
sync_input: SyncInput::None,
|
||||
protocol: Protocol::Free,
|
||||
slot_size: SlotSize::DataSize,
|
||||
slot_count: word::U4(2),
|
||||
@ -608,18 +621,18 @@ impl<'d, T: Instance> Sai<'d, T> {
|
||||
|
||||
fn update_synchronous_config(config: &mut Config) {
|
||||
config.mode = Mode::Slave;
|
||||
config.is_sync_output = false;
|
||||
config.sync_output = false;
|
||||
|
||||
#[cfg(any(sai_v1, sai_v2, sai_v3))]
|
||||
{
|
||||
config.sync_enable = SyncEnable::Internal;
|
||||
config.sync_input = SyncInput::Internal;
|
||||
}
|
||||
|
||||
#[cfg(any(sai_v4))]
|
||||
{
|
||||
//this must either be Internal or External
|
||||
//The asynchronous sub-block on the same SAI needs to enable is_sync_output
|
||||
assert!(config.sync_enable != SyncEnable::Asynchronous);
|
||||
//The asynchronous sub-block on the same SAI needs to enable sync_output
|
||||
assert!(config.sync_input != SyncInput::None);
|
||||
}
|
||||
}
|
||||
|
||||
@ -866,20 +879,13 @@ impl<'d, T: Instance, C: Channel, W: word::Word> SubBlock<'d, T, C, W> {
|
||||
|
||||
#[cfg(any(sai_v4))]
|
||||
{
|
||||
// Not totally clear from the datasheet if this is right
|
||||
// This is only used if using SyncEnable::External on the other SAI unit
|
||||
// Syncing from SAIX subblock A to subblock B does not require this
|
||||
// Only syncing from SAI1 subblock A/B to SAI2 subblock A/B
|
||||
let value: u8 = if T::REGS.as_ptr() == stm32_metapac::SAI1.as_ptr() {
|
||||
1 //this is SAI1, so sync with SAI2
|
||||
} else {
|
||||
0 //this is SAI2, so sync with SAI1
|
||||
};
|
||||
T::REGS.gcr().modify(|w| {
|
||||
w.set_syncin(value);
|
||||
});
|
||||
if let SyncInput::External(i) = config.sync_input {
|
||||
T::REGS.gcr().modify(|w| {
|
||||
w.set_syncin(i as u8);
|
||||
});
|
||||
}
|
||||
|
||||
if config.is_sync_output {
|
||||
if config.sync_output {
|
||||
let syncout: u8 = match sub_block {
|
||||
WhichSubBlock::A => 0b01,
|
||||
WhichSubBlock::B => 0b10,
|
||||
@ -903,7 +909,7 @@ impl<'d, T: Instance, C: Channel, W: word::Word> SubBlock<'d, T, C, W> {
|
||||
w.set_ds(config.data_size.ds());
|
||||
w.set_lsbfirst(config.bit_order.lsbfirst());
|
||||
w.set_ckstr(config.clock_strobe.ckstr());
|
||||
w.set_syncen(config.sync_enable.syncen());
|
||||
w.set_syncen(config.sync_input.syncen());
|
||||
w.set_mono(config.stereo_mono.mono());
|
||||
w.set_outdriv(config.output_drive.outdriv());
|
||||
w.set_mckdiv(config.master_clock_divider.mckdiv());
|
||||
|
@ -5,6 +5,7 @@ An [Embassy](https://embassy.dev) project.
|
||||
Synchronization primitives and data structures with async support:
|
||||
|
||||
- [`Channel`](channel::Channel) - A Multiple Producer Multiple Consumer (MPMC) channel. Each message is only received by a single consumer.
|
||||
- [`PriorityChannel`](channel::priority::PriorityChannel) - A Multiple Producer Multiple Consumer (MPMC) channel. Each message is only received by a single consumer. Higher priority items are sifted to the front of the channel.
|
||||
- [`PubSubChannel`](pubsub::PubSubChannel) - A broadcast channel (publish-subscribe) channel. Each message is received by all consumers.
|
||||
- [`Signal`](signal::Signal) - Signalling latest value to a single consumer.
|
||||
- [`Mutex`](mutex::Mutex) - Mutex for synchronizing state between asynchronous tasks.
|
||||
|
@ -76,7 +76,7 @@ where
|
||||
|
||||
/// Send-only access to a [`Channel`] without knowing channel size.
|
||||
pub struct DynamicSender<'ch, T> {
|
||||
channel: &'ch dyn DynamicChannel<T>,
|
||||
pub(crate) channel: &'ch dyn DynamicChannel<T>,
|
||||
}
|
||||
|
||||
impl<'ch, T> Clone for DynamicSender<'ch, T> {
|
||||
@ -176,7 +176,7 @@ where
|
||||
|
||||
/// Receive-only access to a [`Channel`] without knowing channel size.
|
||||
pub struct DynamicReceiver<'ch, T> {
|
||||
channel: &'ch dyn DynamicChannel<T>,
|
||||
pub(crate) channel: &'ch dyn DynamicChannel<T>,
|
||||
}
|
||||
|
||||
impl<'ch, T> Clone for DynamicReceiver<'ch, T> {
|
||||
@ -321,7 +321,7 @@ impl<'ch, T> Future for DynamicSendFuture<'ch, T> {
|
||||
|
||||
impl<'ch, T> Unpin for DynamicSendFuture<'ch, T> {}
|
||||
|
||||
trait DynamicChannel<T> {
|
||||
pub(crate) trait DynamicChannel<T> {
|
||||
fn try_send_with_context(&self, message: T, cx: Option<&mut Context<'_>>) -> Result<(), TrySendError<T>>;
|
||||
|
||||
fn try_receive_with_context(&self, cx: Option<&mut Context<'_>>) -> Result<T, TryReceiveError>;
|
||||
|
@ -15,6 +15,7 @@ pub mod blocking_mutex;
|
||||
pub mod channel;
|
||||
pub mod mutex;
|
||||
pub mod pipe;
|
||||
pub mod priority_channel;
|
||||
pub mod pubsub;
|
||||
pub mod signal;
|
||||
pub mod waitqueue;
|
||||
|
613
embassy-sync/src/priority_channel.rs
Normal file
613
embassy-sync/src/priority_channel.rs
Normal file
@ -0,0 +1,613 @@
|
||||
//! A queue for sending values between asynchronous tasks.
|
||||
//!
|
||||
//! Similar to a [`Channel`](crate::channel::Channel), however [`PriorityChannel`] sifts higher priority items to the front of the queue.
|
||||
//! Priority is determined by the `Ord` trait. Priority behavior is determined by the [`Kind`](heapless::binary_heap::Kind) parameter of the channel.
|
||||
|
||||
use core::cell::RefCell;
|
||||
use core::future::Future;
|
||||
use core::pin::Pin;
|
||||
use core::task::{Context, Poll};
|
||||
|
||||
pub use heapless::binary_heap::{Kind, Max, Min};
|
||||
use heapless::BinaryHeap;
|
||||
|
||||
use crate::blocking_mutex::raw::RawMutex;
|
||||
use crate::blocking_mutex::Mutex;
|
||||
use crate::channel::{DynamicChannel, DynamicReceiver, DynamicSender, TryReceiveError, TrySendError};
|
||||
use crate::waitqueue::WakerRegistration;
|
||||
|
||||
/// Send-only access to a [`PriorityChannel`].
|
||||
pub struct Sender<'ch, M, T, K, const N: usize>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
channel: &'ch PriorityChannel<M, T, K, N>,
|
||||
}
|
||||
|
||||
impl<'ch, M, T, K, const N: usize> Clone for Sender<'ch, M, T, K, N>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Sender { channel: self.channel }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ch, M, T, K, const N: usize> Copy for Sender<'ch, M, T, K, N>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
}
|
||||
|
||||
impl<'ch, M, T, K, const N: usize> Sender<'ch, M, T, K, N>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
/// Sends a value.
|
||||
///
|
||||
/// See [`PriorityChannel::send()`]
|
||||
pub fn send(&self, message: T) -> SendFuture<'ch, M, T, K, N> {
|
||||
self.channel.send(message)
|
||||
}
|
||||
|
||||
/// Attempt to immediately send a message.
|
||||
///
|
||||
/// See [`PriorityChannel::send()`]
|
||||
pub fn try_send(&self, message: T) -> Result<(), TrySendError<T>> {
|
||||
self.channel.try_send(message)
|
||||
}
|
||||
|
||||
/// Allows a poll_fn to poll until the channel is ready to send
|
||||
///
|
||||
/// See [`PriorityChannel::poll_ready_to_send()`]
|
||||
pub fn poll_ready_to_send(&self, cx: &mut Context<'_>) -> Poll<()> {
|
||||
self.channel.poll_ready_to_send(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ch, M, T, K, const N: usize> From<Sender<'ch, M, T, K, N>> for DynamicSender<'ch, T>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
fn from(s: Sender<'ch, M, T, K, N>) -> Self {
|
||||
Self { channel: s.channel }
|
||||
}
|
||||
}
|
||||
|
||||
/// Receive-only access to a [`PriorityChannel`].
|
||||
pub struct Receiver<'ch, M, T, K, const N: usize>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
channel: &'ch PriorityChannel<M, T, K, N>,
|
||||
}
|
||||
|
||||
impl<'ch, M, T, K, const N: usize> Clone for Receiver<'ch, M, T, K, N>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Receiver { channel: self.channel }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ch, M, T, K, const N: usize> Copy for Receiver<'ch, M, T, K, N>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
}
|
||||
|
||||
impl<'ch, M, T, K, const N: usize> Receiver<'ch, M, T, K, N>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
/// Receive the next value.
|
||||
///
|
||||
/// See [`PriorityChannel::receive()`].
|
||||
pub fn receive(&self) -> ReceiveFuture<'_, M, T, K, N> {
|
||||
self.channel.receive()
|
||||
}
|
||||
|
||||
/// Attempt to immediately receive the next value.
|
||||
///
|
||||
/// See [`PriorityChannel::try_receive()`]
|
||||
pub fn try_receive(&self) -> Result<T, TryReceiveError> {
|
||||
self.channel.try_receive()
|
||||
}
|
||||
|
||||
/// Allows a poll_fn to poll until the channel is ready to receive
|
||||
///
|
||||
/// See [`PriorityChannel::poll_ready_to_receive()`]
|
||||
pub fn poll_ready_to_receive(&self, cx: &mut Context<'_>) -> Poll<()> {
|
||||
self.channel.poll_ready_to_receive(cx)
|
||||
}
|
||||
|
||||
/// Poll the channel for the next item
|
||||
///
|
||||
/// See [`PriorityChannel::poll_receive()`]
|
||||
pub fn poll_receive(&self, cx: &mut Context<'_>) -> Poll<T> {
|
||||
self.channel.poll_receive(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ch, M, T, K, const N: usize> From<Receiver<'ch, M, T, K, N>> for DynamicReceiver<'ch, T>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
fn from(s: Receiver<'ch, M, T, K, N>) -> Self {
|
||||
Self { channel: s.channel }
|
||||
}
|
||||
}
|
||||
|
||||
/// Future returned by [`PriorityChannel::receive`] and [`Receiver::receive`].
|
||||
#[must_use = "futures do nothing unless you `.await` or poll them"]
|
||||
pub struct ReceiveFuture<'ch, M, T, K, const N: usize>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
channel: &'ch PriorityChannel<M, T, K, N>,
|
||||
}
|
||||
|
||||
impl<'ch, M, T, K, const N: usize> Future for ReceiveFuture<'ch, M, T, K, N>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
type Output = T;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
|
||||
self.channel.poll_receive(cx)
|
||||
}
|
||||
}
|
||||
|
||||
/// Future returned by [`PriorityChannel::send`] and [`Sender::send`].
|
||||
#[must_use = "futures do nothing unless you `.await` or poll them"]
|
||||
pub struct SendFuture<'ch, M, T, K, const N: usize>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
channel: &'ch PriorityChannel<M, T, K, N>,
|
||||
message: Option<T>,
|
||||
}
|
||||
|
||||
impl<'ch, M, T, K, const N: usize> Future for SendFuture<'ch, M, T, K, N>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
type Output = ();
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
match self.message.take() {
|
||||
Some(m) => match self.channel.try_send_with_context(m, Some(cx)) {
|
||||
Ok(..) => Poll::Ready(()),
|
||||
Err(TrySendError::Full(m)) => {
|
||||
self.message = Some(m);
|
||||
Poll::Pending
|
||||
}
|
||||
},
|
||||
None => panic!("Message cannot be None"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ch, M, T, K, const N: usize> Unpin for SendFuture<'ch, M, T, K, N>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
}
|
||||
|
||||
struct ChannelState<T, K, const N: usize> {
|
||||
queue: BinaryHeap<T, K, N>,
|
||||
receiver_waker: WakerRegistration,
|
||||
senders_waker: WakerRegistration,
|
||||
}
|
||||
|
||||
impl<T, K, const N: usize> ChannelState<T, K, N>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
{
|
||||
const fn new() -> Self {
|
||||
ChannelState {
|
||||
queue: BinaryHeap::new(),
|
||||
receiver_waker: WakerRegistration::new(),
|
||||
senders_waker: WakerRegistration::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn try_receive(&mut self) -> Result<T, TryReceiveError> {
|
||||
self.try_receive_with_context(None)
|
||||
}
|
||||
|
||||
fn try_receive_with_context(&mut self, cx: Option<&mut Context<'_>>) -> Result<T, TryReceiveError> {
|
||||
if self.queue.len() == self.queue.capacity() {
|
||||
self.senders_waker.wake();
|
||||
}
|
||||
|
||||
if let Some(message) = self.queue.pop() {
|
||||
Ok(message)
|
||||
} else {
|
||||
if let Some(cx) = cx {
|
||||
self.receiver_waker.register(cx.waker());
|
||||
}
|
||||
Err(TryReceiveError::Empty)
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_receive(&mut self, cx: &mut Context<'_>) -> Poll<T> {
|
||||
if self.queue.len() == self.queue.capacity() {
|
||||
self.senders_waker.wake();
|
||||
}
|
||||
|
||||
if let Some(message) = self.queue.pop() {
|
||||
Poll::Ready(message)
|
||||
} else {
|
||||
self.receiver_waker.register(cx.waker());
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_ready_to_receive(&mut self, cx: &mut Context<'_>) -> Poll<()> {
|
||||
self.receiver_waker.register(cx.waker());
|
||||
|
||||
if !self.queue.is_empty() {
|
||||
Poll::Ready(())
|
||||
} else {
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
fn try_send(&mut self, message: T) -> Result<(), TrySendError<T>> {
|
||||
self.try_send_with_context(message, None)
|
||||
}
|
||||
|
||||
fn try_send_with_context(&mut self, message: T, cx: Option<&mut Context<'_>>) -> Result<(), TrySendError<T>> {
|
||||
match self.queue.push(message) {
|
||||
Ok(()) => {
|
||||
self.receiver_waker.wake();
|
||||
Ok(())
|
||||
}
|
||||
Err(message) => {
|
||||
if let Some(cx) = cx {
|
||||
self.senders_waker.register(cx.waker());
|
||||
}
|
||||
Err(TrySendError::Full(message))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_ready_to_send(&mut self, cx: &mut Context<'_>) -> Poll<()> {
|
||||
self.senders_waker.register(cx.waker());
|
||||
|
||||
if !self.queue.len() == self.queue.capacity() {
|
||||
Poll::Ready(())
|
||||
} else {
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A bounded channel for communicating between asynchronous tasks
|
||||
/// with backpressure.
|
||||
///
|
||||
/// The channel will buffer up to the provided number of messages. Once the
|
||||
/// buffer is full, attempts to `send` new messages will wait until a message is
|
||||
/// received from the channel.
|
||||
///
|
||||
/// Sent data may be reordered based on their priorty within the channel.
|
||||
/// For example, in a [`Max`](heapless::binary_heap::Max) [`PriorityChannel`]
|
||||
/// containing `u32`'s, data sent in the following order `[1, 2, 3]` will be recieved as `[3, 2, 1]`.
|
||||
pub struct PriorityChannel<M, T, K, const N: usize>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
inner: Mutex<M, RefCell<ChannelState<T, K, N>>>,
|
||||
}
|
||||
|
||||
impl<M, T, K, const N: usize> PriorityChannel<M, T, K, N>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
/// Establish a new bounded channel. For example, to create one with a NoopMutex:
|
||||
///
|
||||
/// ```
|
||||
/// use embassy_sync::priority_channel::{PriorityChannel, Max};
|
||||
/// use embassy_sync::blocking_mutex::raw::NoopRawMutex;
|
||||
///
|
||||
/// // Declare a bounded channel of 3 u32s.
|
||||
/// let mut channel = PriorityChannel::<NoopRawMutex, u32, Max, 3>::new();
|
||||
/// ```
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
inner: Mutex::new(RefCell::new(ChannelState::new())),
|
||||
}
|
||||
}
|
||||
|
||||
fn lock<R>(&self, f: impl FnOnce(&mut ChannelState<T, K, N>) -> R) -> R {
|
||||
self.inner.lock(|rc| f(&mut *unwrap!(rc.try_borrow_mut())))
|
||||
}
|
||||
|
||||
fn try_receive_with_context(&self, cx: Option<&mut Context<'_>>) -> Result<T, TryReceiveError> {
|
||||
self.lock(|c| c.try_receive_with_context(cx))
|
||||
}
|
||||
|
||||
/// Poll the channel for the next message
|
||||
pub fn poll_receive(&self, cx: &mut Context<'_>) -> Poll<T> {
|
||||
self.lock(|c| c.poll_receive(cx))
|
||||
}
|
||||
|
||||
fn try_send_with_context(&self, m: T, cx: Option<&mut Context<'_>>) -> Result<(), TrySendError<T>> {
|
||||
self.lock(|c| c.try_send_with_context(m, cx))
|
||||
}
|
||||
|
||||
/// Allows a poll_fn to poll until the channel is ready to receive
|
||||
pub fn poll_ready_to_receive(&self, cx: &mut Context<'_>) -> Poll<()> {
|
||||
self.lock(|c| c.poll_ready_to_receive(cx))
|
||||
}
|
||||
|
||||
/// Allows a poll_fn to poll until the channel is ready to send
|
||||
pub fn poll_ready_to_send(&self, cx: &mut Context<'_>) -> Poll<()> {
|
||||
self.lock(|c| c.poll_ready_to_send(cx))
|
||||
}
|
||||
|
||||
/// Get a sender for this channel.
|
||||
pub fn sender(&self) -> Sender<'_, M, T, K, N> {
|
||||
Sender { channel: self }
|
||||
}
|
||||
|
||||
/// Get a receiver for this channel.
|
||||
pub fn receiver(&self) -> Receiver<'_, M, T, K, N> {
|
||||
Receiver { channel: self }
|
||||
}
|
||||
|
||||
/// Send a value, waiting until there is capacity.
|
||||
///
|
||||
/// Sending completes when the value has been pushed to the channel's queue.
|
||||
/// This doesn't mean the value has been received yet.
|
||||
pub fn send(&self, message: T) -> SendFuture<'_, M, T, K, N> {
|
||||
SendFuture {
|
||||
channel: self,
|
||||
message: Some(message),
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempt to immediately send a message.
|
||||
///
|
||||
/// This method differs from [`send`](PriorityChannel::send) by returning immediately if the channel's
|
||||
/// buffer is full, instead of waiting.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// If the channel capacity has been reached, i.e., the channel has `n`
|
||||
/// buffered values where `n` is the argument passed to [`PriorityChannel`], then an
|
||||
/// error is returned.
|
||||
pub fn try_send(&self, message: T) -> Result<(), TrySendError<T>> {
|
||||
self.lock(|c| c.try_send(message))
|
||||
}
|
||||
|
||||
/// Receive the next value.
|
||||
///
|
||||
/// If there are no messages in the channel's buffer, this method will
|
||||
/// wait until a message is sent.
|
||||
pub fn receive(&self) -> ReceiveFuture<'_, M, T, K, N> {
|
||||
ReceiveFuture { channel: self }
|
||||
}
|
||||
|
||||
/// Attempt to immediately receive a message.
|
||||
///
|
||||
/// This method will either receive a message from the channel immediately or return an error
|
||||
/// if the channel is empty.
|
||||
pub fn try_receive(&self) -> Result<T, TryReceiveError> {
|
||||
self.lock(|c| c.try_receive())
|
||||
}
|
||||
}
|
||||
|
||||
/// Implements the DynamicChannel to allow creating types that are unaware of the queue size with the
|
||||
/// tradeoff cost of dynamic dispatch.
|
||||
impl<M, T, K, const N: usize> DynamicChannel<T> for PriorityChannel<M, T, K, N>
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
M: RawMutex,
|
||||
{
|
||||
fn try_send_with_context(&self, m: T, cx: Option<&mut Context<'_>>) -> Result<(), TrySendError<T>> {
|
||||
PriorityChannel::try_send_with_context(self, m, cx)
|
||||
}
|
||||
|
||||
fn try_receive_with_context(&self, cx: Option<&mut Context<'_>>) -> Result<T, TryReceiveError> {
|
||||
PriorityChannel::try_receive_with_context(self, cx)
|
||||
}
|
||||
|
||||
fn poll_ready_to_send(&self, cx: &mut Context<'_>) -> Poll<()> {
|
||||
PriorityChannel::poll_ready_to_send(self, cx)
|
||||
}
|
||||
|
||||
fn poll_ready_to_receive(&self, cx: &mut Context<'_>) -> Poll<()> {
|
||||
PriorityChannel::poll_ready_to_receive(self, cx)
|
||||
}
|
||||
|
||||
fn poll_receive(&self, cx: &mut Context<'_>) -> Poll<T> {
|
||||
PriorityChannel::poll_receive(self, cx)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use core::time::Duration;
|
||||
|
||||
use futures_executor::ThreadPool;
|
||||
use futures_timer::Delay;
|
||||
use futures_util::task::SpawnExt;
|
||||
use heapless::binary_heap::{Kind, Max};
|
||||
use static_cell::StaticCell;
|
||||
|
||||
use super::*;
|
||||
use crate::blocking_mutex::raw::{CriticalSectionRawMutex, NoopRawMutex};
|
||||
|
||||
fn capacity<T, K, const N: usize>(c: &ChannelState<T, K, N>) -> usize
|
||||
where
|
||||
T: Ord,
|
||||
K: Kind,
|
||||
{
|
||||
c.queue.capacity() - c.queue.len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sending_once() {
|
||||
let mut c = ChannelState::<u32, Max, 3>::new();
|
||||
assert!(c.try_send(1).is_ok());
|
||||
assert_eq!(capacity(&c), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sending_when_full() {
|
||||
let mut c = ChannelState::<u32, Max, 3>::new();
|
||||
let _ = c.try_send(1);
|
||||
let _ = c.try_send(1);
|
||||
let _ = c.try_send(1);
|
||||
match c.try_send(2) {
|
||||
Err(TrySendError::Full(2)) => assert!(true),
|
||||
_ => assert!(false),
|
||||
}
|
||||
assert_eq!(capacity(&c), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_priority() {
|
||||
// Prio channel with kind `Max` sifts larger numbers to the front of the queue
|
||||
let mut c = ChannelState::<u32, Max, 3>::new();
|
||||
assert!(c.try_send(1).is_ok());
|
||||
assert!(c.try_send(2).is_ok());
|
||||
assert!(c.try_send(3).is_ok());
|
||||
assert_eq!(c.try_receive().unwrap(), 3);
|
||||
assert_eq!(c.try_receive().unwrap(), 2);
|
||||
assert_eq!(c.try_receive().unwrap(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receiving_once_with_one_send() {
|
||||
let mut c = ChannelState::<u32, Max, 3>::new();
|
||||
assert!(c.try_send(1).is_ok());
|
||||
assert_eq!(c.try_receive().unwrap(), 1);
|
||||
assert_eq!(capacity(&c), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receiving_when_empty() {
|
||||
let mut c = ChannelState::<u32, Max, 3>::new();
|
||||
match c.try_receive() {
|
||||
Err(TryReceiveError::Empty) => assert!(true),
|
||||
_ => assert!(false),
|
||||
}
|
||||
assert_eq!(capacity(&c), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simple_send_and_receive() {
|
||||
let c = PriorityChannel::<NoopRawMutex, u32, Max, 3>::new();
|
||||
assert!(c.try_send(1).is_ok());
|
||||
assert_eq!(c.try_receive().unwrap(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cloning() {
|
||||
let c = PriorityChannel::<NoopRawMutex, u32, Max, 3>::new();
|
||||
let r1 = c.receiver();
|
||||
let s1 = c.sender();
|
||||
|
||||
let _ = r1.clone();
|
||||
let _ = s1.clone();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_dispatch() {
|
||||
let c = PriorityChannel::<NoopRawMutex, u32, Max, 3>::new();
|
||||
let s: DynamicSender<'_, u32> = c.sender().into();
|
||||
let r: DynamicReceiver<'_, u32> = c.receiver().into();
|
||||
|
||||
assert!(s.try_send(1).is_ok());
|
||||
assert_eq!(r.try_receive().unwrap(), 1);
|
||||
}
|
||||
|
||||
#[futures_test::test]
|
||||
async fn receiver_receives_given_try_send_async() {
|
||||
let executor = ThreadPool::new().unwrap();
|
||||
|
||||
static CHANNEL: StaticCell<PriorityChannel<CriticalSectionRawMutex, u32, Max, 3>> = StaticCell::new();
|
||||
let c = &*CHANNEL.init(PriorityChannel::new());
|
||||
let c2 = c;
|
||||
assert!(executor
|
||||
.spawn(async move {
|
||||
assert!(c2.try_send(1).is_ok());
|
||||
})
|
||||
.is_ok());
|
||||
assert_eq!(c.receive().await, 1);
|
||||
}
|
||||
|
||||
#[futures_test::test]
|
||||
async fn sender_send_completes_if_capacity() {
|
||||
let c = PriorityChannel::<CriticalSectionRawMutex, u32, Max, 1>::new();
|
||||
c.send(1).await;
|
||||
assert_eq!(c.receive().await, 1);
|
||||
}
|
||||
|
||||
#[futures_test::test]
|
||||
async fn senders_sends_wait_until_capacity() {
|
||||
let executor = ThreadPool::new().unwrap();
|
||||
|
||||
static CHANNEL: StaticCell<PriorityChannel<CriticalSectionRawMutex, u32, Max, 1>> = StaticCell::new();
|
||||
let c = &*CHANNEL.init(PriorityChannel::new());
|
||||
assert!(c.try_send(1).is_ok());
|
||||
|
||||
let c2 = c;
|
||||
let send_task_1 = executor.spawn_with_handle(async move { c2.send(2).await });
|
||||
let c2 = c;
|
||||
let send_task_2 = executor.spawn_with_handle(async move { c2.send(3).await });
|
||||
// Wish I could think of a means of determining that the async send is waiting instead.
|
||||
// However, I've used the debugger to observe that the send does indeed wait.
|
||||
Delay::new(Duration::from_millis(500)).await;
|
||||
assert_eq!(c.receive().await, 1);
|
||||
assert!(executor
|
||||
.spawn(async move {
|
||||
loop {
|
||||
c.receive().await;
|
||||
}
|
||||
})
|
||||
.is_ok());
|
||||
send_task_1.unwrap().await;
|
||||
send_task_2.unwrap().await;
|
||||
}
|
||||
}
|
@ -5,7 +5,19 @@ MEMORY
|
||||
BOOTLOADER_STATE : ORIGIN = 0x10006000, LENGTH = 4K
|
||||
FLASH : ORIGIN = 0x10007000, LENGTH = 512K
|
||||
DFU : ORIGIN = 0x10087000, LENGTH = 516K
|
||||
RAM : ORIGIN = 0x20000000, LENGTH = 256K
|
||||
|
||||
/* Pick one of the two options for RAM layout */
|
||||
|
||||
/* OPTION A: Use all RAM banks as one big block */
|
||||
/* Reasonable, unless you are doing something */
|
||||
/* really particular with DMA or other concurrent */
|
||||
/* access that would benefit from striping */
|
||||
RAM : ORIGIN = 0x20000000, LENGTH = 264K
|
||||
|
||||
/* OPTION B: Keep the unstriped sections separate */
|
||||
/* RAM: ORIGIN = 0x20000000, LENGTH = 256K */
|
||||
/* SCRATCH_A: ORIGIN = 0x20040000, LENGTH = 4K */
|
||||
/* SCRATCH_B: ORIGIN = 0x20041000, LENGTH = 4K */
|
||||
}
|
||||
|
||||
__bootloader_state_start = ORIGIN(BOOTLOADER_STATE) - ORIGIN(BOOT2);
|
||||
|
@ -6,7 +6,19 @@ MEMORY
|
||||
BOOTLOADER_STATE : ORIGIN = 0x10006000, LENGTH = 4K
|
||||
ACTIVE : ORIGIN = 0x10007000, LENGTH = 512K
|
||||
DFU : ORIGIN = 0x10087000, LENGTH = 516K
|
||||
RAM : ORIGIN = 0x20000000, LENGTH = 256K
|
||||
|
||||
/* Pick one of the two options for RAM layout */
|
||||
|
||||
/* OPTION A: Use all RAM banks as one big block */
|
||||
/* Reasonable, unless you are doing something */
|
||||
/* really particular with DMA or other concurrent */
|
||||
/* access that would benefit from striping */
|
||||
RAM : ORIGIN = 0x20000000, LENGTH = 264K
|
||||
|
||||
/* OPTION B: Keep the unstriped sections separate */
|
||||
/* RAM: ORIGIN = 0x20000000, LENGTH = 256K */
|
||||
/* SCRATCH_A: ORIGIN = 0x20040000, LENGTH = 4K */
|
||||
/* SCRATCH_B: ORIGIN = 0x20041000, LENGTH = 4K */
|
||||
}
|
||||
|
||||
__bootloader_state_start = ORIGIN(BOOTLOADER_STATE) - ORIGIN(BOOT2);
|
||||
|
@ -17,7 +17,7 @@ log = [
|
||||
|
||||
[dependencies]
|
||||
embassy-sync = { version = "0.4.0", path = "../../embassy-sync" }
|
||||
embassy-executor = { version = "0.3.3", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "rtos-trace", "rtos-trace-interrupt", "integrated-timers"] }
|
||||
embassy-executor = { version = "0.3.3", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "rtos-trace", "integrated-timers"] }
|
||||
embassy-time = { version = "0.1.5", path = "../../embassy-time" }
|
||||
embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac"] }
|
||||
|
||||
|
@ -1,5 +1,17 @@
|
||||
MEMORY {
|
||||
BOOT2 : ORIGIN = 0x10000000, LENGTH = 0x100
|
||||
FLASH : ORIGIN = 0x10000100, LENGTH = 2048K - 0x100
|
||||
RAM : ORIGIN = 0x20000000, LENGTH = 256K
|
||||
}
|
||||
|
||||
/* Pick one of the two options for RAM layout */
|
||||
|
||||
/* OPTION A: Use all RAM banks as one big block */
|
||||
/* Reasonable, unless you are doing something */
|
||||
/* really particular with DMA or other concurrent */
|
||||
/* access that would benefit from striping */
|
||||
RAM : ORIGIN = 0x20000000, LENGTH = 264K
|
||||
|
||||
/* OPTION B: Keep the unstriped sections separate */
|
||||
/* RAM: ORIGIN = 0x20000000, LENGTH = 256K */
|
||||
/* SCRATCH_A: ORIGIN = 0x20040000, LENGTH = 4K */
|
||||
/* SCRATCH_B: ORIGIN = 0x20041000, LENGTH = 4K */
|
||||
}
|
||||
|
@ -39,7 +39,7 @@ async fn main(_spawner: Spawner) -> ! {
|
||||
|
||||
let mut vrefint = adc.enable_vref(&mut Delay);
|
||||
let mut temperature = adc.enable_temperature();
|
||||
let mut buffer = opamp.buffer_ext(&p.PA7, &mut p.PA6, OpAmpGain::Mul1);
|
||||
let mut buffer = opamp.buffer_ext(&mut p.PA7, &mut p.PA6, OpAmpGain::Mul1);
|
||||
|
||||
loop {
|
||||
let vref = adc.read(&mut vrefint).await;
|
||||
|
@ -2,7 +2,7 @@
|
||||
# https://rust-lang.github.io/rustup-components-history
|
||||
[toolchain]
|
||||
channel = "nightly-2023-11-01"
|
||||
components = [ "rust-src", "rustfmt", "llvm-tools" ]
|
||||
components = [ "rust-src", "rustfmt", "llvm-tools", "miri" ]
|
||||
targets = [
|
||||
"thumbv7em-none-eabi",
|
||||
"thumbv7m-none-eabi",
|
||||
|
Reference in New Issue
Block a user