Compare commits

..

1 Commits

Author SHA1 Message Date
eba55543be f0 blinky in 3084 bytes 2023-10-11 23:21:28 +02:00
459 changed files with 5812 additions and 7720 deletions

View File

@ -62,9 +62,9 @@ async fn blink(pin: AnyPin) {
loop { loop {
// Timekeeping is globally available, no need to mess with hardware timers. // Timekeeping is globally available, no need to mess with hardware timers.
led.set_high(); led.set_high();
Timer::after_millis(150).await; Timer::after(Duration::from_millis(150)).await;
led.set_low(); led.set_low();
Timer::after_millis(150).await; Timer::after(Duration::from_millis(150)).await;
} }
} }

118
ci.sh
View File

@ -69,69 +69,62 @@ cargo batch \
--- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly \ --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly \
--- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly,intrinsics \ --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly,intrinsics \
--- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly,qspi-as-gpio \ --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly,qspi-as-gpio \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti,time \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti,unstable-traits,time \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,time \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti,unstable-traits \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f401ve,defmt,exti,time-driver-any,unstable-traits \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f401ve,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f405zg,defmt,exti,time-driver-any,unstable-traits \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f405zg,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f407zg,defmt,exti,time-driver-any,unstable-traits \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f407zg,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f401ve,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f410tb,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f405zg,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f411ce,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f407zg,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f412zg,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f410tb,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f413vh,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f411ce,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f415zg,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f412zg,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f417zg,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f413vh,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f423zh,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f415zg,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f427zi,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f417zg,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f429zi,log,exti,time-driver-any,unstable-traits,embedded-sdmmc \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f423zh,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f437zi,log,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f427zi,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f439zi,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f429zi,log,exti,time-driver-any,unstable-traits,embedded-sdmmc,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f446ze,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f437zi,log,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f469zi,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f439zi,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f479zi,defmt,exti,time-driver-any,unstable-traits,embedded-sdmmc \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f446ze,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f730i8,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f469zi,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32h753zi,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f479zi,defmt,exti,time-driver-any,unstable-traits,embedded-sdmmc,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32h735zg,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f730i8,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 \
--- 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,stm32h7b3ai,defmt,exti,time-driver-any,unstable-traits \
--- 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,stm32l476vg,defmt,exti,time-driver-any,unstable-traits \
--- 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,stm32l422cb,defmt,exti,time-driver-any,unstable-traits \
--- 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,stm32wb15cc,defmt,exti,time-driver-any,unstable-traits \
--- 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 thumbv6m-none-eabi --features nightly,stm32l072cz,defmt,exti,time-driver-any,unstable-traits \
--- 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 thumbv6m-none-eabi --features nightly,stm32l041f6,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32l422cb,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32l073cz,defmt,exti,time-driver-any,unstable-traits,low-power \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32wb15cc,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32l151cb-a,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32l072cz,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f398ve,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32l041f6,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f378cc,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32l073cz,defmt,exti,time-driver-any,unstable-traits,low-power,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32g0c1ve,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32l151cb-a,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f217zg,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f398ve,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features nightly,stm32l552ze,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f378cc,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32wl54jc-cm0p,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32g0c1ve,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32wle5jb,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f217zg,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32g474pe,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features nightly,stm32l552ze,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f107vc,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32wl54jc-cm0p,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f103re,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32wle5jb,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f100c4,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32g474pe,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32h503rb,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f107vc,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32h562ag,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f103re,defmt,exti,time-driver-any,unstable-traits,time \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f100c4,defmt,exti,time-driver-any,unstable-traits,time \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32h503rb,defmt,exti,time-driver-any,unstable-traits,time \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32h562ag,defmt,exti,time-driver-any,unstable-traits,time \
--- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features ''\ --- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features ''\
--- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'log' \ --- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'log' \
--- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'defmt' \ --- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'defmt' \
@ -193,13 +186,9 @@ cargo batch \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32g071rb --out-dir out/tests/stm32g071rb \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32g071rb --out-dir out/tests/stm32g071rb \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32c031c6 --out-dir out/tests/stm32c031c6 \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32c031c6 --out-dir out/tests/stm32c031c6 \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h755zi --out-dir out/tests/stm32h755zi \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h755zi --out-dir out/tests/stm32h755zi \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h753zi --out-dir out/tests/stm32h753zi \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h7a3zi --out-dir out/tests/stm32h7a3zi \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wb55rg --out-dir out/tests/stm32wb55rg \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wb55rg --out-dir out/tests/stm32wb55rg \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h563zi --out-dir out/tests/stm32h563zi \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h563zi --out-dir out/tests/stm32h563zi \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32u585ai --out-dir out/tests/stm32u585ai \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32u585ai --out-dir out/tests/stm32u585ai \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32u5a5zj --out-dir out/tests/stm32u5a5zj \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wba52cg --out-dir out/tests/stm32wba52cg \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32l073rz --out-dir out/tests/stm32l073rz \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32l073rz --out-dir out/tests/stm32l073rz \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32l152re --out-dir out/tests/stm32l152re \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32l152re --out-dir out/tests/stm32l152re \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l4a6zg --out-dir out/tests/stm32l4a6zg \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l4a6zg --out-dir out/tests/stm32l4a6zg \
@ -209,7 +198,6 @@ cargo batch \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f207zg --out-dir out/tests/stm32f207zg \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f207zg --out-dir out/tests/stm32f207zg \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f303ze --out-dir out/tests/stm32f303ze \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f303ze --out-dir out/tests/stm32f303ze \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l496zg --out-dir out/tests/stm32l496zg \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l496zg --out-dir out/tests/stm32l496zg \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wl55jc --out-dir out/tests/stm32wl55jc \
--- build --release --manifest-path tests/rp/Cargo.toml --target thumbv6m-none-eabi --out-dir out/tests/rpi-pico \ --- build --release --manifest-path tests/rp/Cargo.toml --target thumbv6m-none-eabi --out-dir out/tests/rpi-pico \
--- build --release --manifest-path tests/nrf/Cargo.toml --target thumbv7em-none-eabi --out-dir out/tests/nrf52840-dk \ --- build --release --manifest-path tests/nrf/Cargo.toml --target thumbv7em-none-eabi --out-dir out/tests/nrf52840-dk \
--- build --release --manifest-path tests/riscv32/Cargo.toml --target riscv32imac-unknown-none-elf \ --- build --release --manifest-path tests/riscv32/Cargo.toml --target riscv32imac-unknown-none-elf \
@ -218,14 +206,8 @@ cargo batch \
rm out/tests/stm32wb55rg/wpan_mac rm out/tests/stm32wb55rg/wpan_mac
rm out/tests/stm32wb55rg/wpan_ble rm out/tests/stm32wb55rg/wpan_ble
# unstable, I think it's running out of RAM?
rm out/tests/stm32f207zg/eth rm out/tests/stm32f207zg/eth
# doesn't work, gives "noise error", no idea why. usart_dma does pass.
rm out/tests/stm32u5a5zj/usart
if [[ -z "${TELEPROBE_TOKEN-}" ]]; then if [[ -z "${TELEPROBE_TOKEN-}" ]]; then
echo No teleprobe token found, skipping running HIL tests echo No teleprobe token found, skipping running HIL tests
exit exit

View File

@ -40,38 +40,33 @@ cargo batch \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32u585zi,defmt,exti,time-driver-any,unstable-traits \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32u585zi,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wb55vy,defmt,exti,time-driver-any,unstable-traits \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wb55vy,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wl55cc-cm4,defmt,exti,time-driver-any,unstable-traits \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wl55cc-cm4,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32g473cc,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l4r9zi,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32g491re,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f303vc,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32u585zi,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f411ce,defmt,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wb55vy,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f411ce,defmt,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wl55cc-cm4,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f429zi,log,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l4r9zi,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f429zi,log,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f303vc,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h755zi-cm7,defmt,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f411ce,defmt,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h755zi-cm7,defmt,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f411ce,defmt,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l476vg,defmt,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f429zi,log,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l476vg,defmt,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f429zi,log,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32l072cz,defmt,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h755zi-cm7,defmt,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32l072cz,defmt,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h755zi-cm7,defmt,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32l151cb-a,defmt,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l476vg,defmt,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32l151cb-a,defmt,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l476vg,defmt,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f410tb,defmt,exti,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32l072cz,defmt,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f410tb,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32l072cz,defmt,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f429zi,log,exti,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32l151cb-a,defmt,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f429zi,log,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32l151cb-a,defmt,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h755zi-cm7,defmt,exti,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f410tb,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h755zi-cm7,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f410tb,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l476vg,defmt,exti,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f429zi,log,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l476vg,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f429zi,log,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32l072cz,defmt,exti,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h755zi-cm7,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32l072cz,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h755zi-cm7,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32l151cb-a,defmt,exti,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l476vg,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32l151cb-a,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l476vg,defmt,exti,time-driver-any,unstable-traits,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f217zg,defmt,exti,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32l072cz,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f217zg,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32l072cz,defmt,exti,time-driver-any,unstable-traits,time \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32l151cb-a,defmt,exti,time-driver-any,time \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32l151cb-a,defmt,exti,time-driver-any,unstable-traits,time \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f217zg,defmt,exti,time-driver-any,time \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f217zg,defmt,exti,time-driver-any,unstable-traits,time \
--- build --release --manifest-path examples/nrf52840/Cargo.toml --target thumbv7em-none-eabi --no-default-features --out-dir out/examples/nrf52840 --bin raw_spawn \ --- build --release --manifest-path examples/nrf52840/Cargo.toml --target thumbv7em-none-eabi --no-default-features --out-dir out/examples/nrf52840 --bin raw_spawn \
--- build --release --manifest-path examples/stm32l0/Cargo.toml --target thumbv6m-none-eabi --no-default-features --out-dir out/examples/stm32l0 --bin raw_spawn \ --- build --release --manifest-path examples/stm32l0/Cargo.toml --target thumbv6m-none-eabi --no-default-features --out-dir out/examples/stm32l0 --bin raw_spawn \

View File

@ -1,6 +1,6 @@
#![no_std] #![no_std]
#![allow(incomplete_features)]
#![feature(async_fn_in_trait)] #![feature(async_fn_in_trait)]
#![allow(stable_features, unknown_lints, async_fn_in_trait)]
use core::slice; use core::slice;

View File

@ -11,10 +11,11 @@ log = ["dep:log"]
firmware-logs = [] firmware-logs = []
[dependencies] [dependencies]
embassy-time = { version = "0.1.5", path = "../embassy-time"} embassy-time = { version = "0.1.3", path = "../embassy-time"}
embassy-sync = { version = "0.4.0", path = "../embassy-sync"} embassy-sync = { version = "0.3.0", path = "../embassy-sync"}
embassy-futures = { version = "0.1.0", path = "../embassy-futures"} embassy-futures = { version = "0.1.0", path = "../embassy-futures"}
embassy-net-driver-channel = { version = "0.2.0", path = "../embassy-net-driver-channel"} embassy-net-driver-channel = { version = "0.1.0", path = "../embassy-net-driver-channel"}
atomic-polyfill = "0.1.5"
defmt = { version = "0.3", optional = true } defmt = { version = "0.3", optional = true }
log = { version = "0.4.17", optional = true } log = { version = "0.4.17", optional = true }

View File

@ -1,5 +1,5 @@
use embassy_futures::yield_now; use embassy_futures::yield_now;
use embassy_time::Timer; use embassy_time::{Duration, Timer};
use embedded_hal_1::digital::OutputPin; use embedded_hal_1::digital::OutputPin;
use futures::FutureExt; use futures::FutureExt;
@ -51,9 +51,9 @@ where
pub async fn init(&mut self) { pub async fn init(&mut self) {
// Reset // Reset
self.pwr.set_low().unwrap(); self.pwr.set_low().unwrap();
Timer::after_millis(20).await; Timer::after(Duration::from_millis(20)).await;
self.pwr.set_high().unwrap(); self.pwr.set_high().unwrap();
Timer::after_millis(250).await; Timer::after(Duration::from_millis(250)).await;
while self while self
.read32_swapped(REG_BUS_TEST_RO) .read32_swapped(REG_BUS_TEST_RO)

View File

@ -1,10 +1,10 @@
use core::cmp::{max, min}; use core::cmp::{max, min};
use core::iter::zip;
use ch::driver::LinkState;
use embassy_net_driver_channel as ch; use embassy_net_driver_channel as ch;
use embassy_net_driver_channel::driver::{HardwareAddress, LinkState}; use embassy_time::{Duration, Timer};
use embassy_time::Timer;
pub use crate::bus::SpiBusCyw43;
use crate::consts::*; use crate::consts::*;
use crate::events::{Event, EventSubscriber, Events}; use crate::events::{Event, EventSubscriber, Events};
use crate::fmt::Bytes; use crate::fmt::Bytes;
@ -17,12 +17,6 @@ pub struct Error {
pub status: u32, pub status: u32,
} }
#[derive(Debug)]
pub enum AddMulticastAddressError {
NotMulticast,
NoFreeSlots,
}
pub struct Control<'a> { pub struct Control<'a> {
state_ch: ch::StateRunner<'a>, state_ch: ch::StateRunner<'a>,
events: &'a Events, events: &'a Events,
@ -93,22 +87,22 @@ impl<'a> Control<'a> {
self.set_iovar("country", &country_info.to_bytes()).await; self.set_iovar("country", &country_info.to_bytes()).await;
// set country takes some time, next ioctls fail if we don't wait. // set country takes some time, next ioctls fail if we don't wait.
Timer::after_millis(100).await; Timer::after(Duration::from_millis(100)).await;
// Set antenna to chip antenna // Set antenna to chip antenna
self.ioctl_set_u32(IOCTL_CMD_ANTDIV, 0, 0).await; self.ioctl_set_u32(IOCTL_CMD_ANTDIV, 0, 0).await;
self.set_iovar_u32("bus:txglom", 0).await; self.set_iovar_u32("bus:txglom", 0).await;
Timer::after_millis(100).await; Timer::after(Duration::from_millis(100)).await;
//self.set_iovar_u32("apsta", 1).await; // this crashes, also we already did it before...?? //self.set_iovar_u32("apsta", 1).await; // this crashes, also we already did it before...??
//Timer::after_millis(100).await; //Timer::after(Duration::from_millis(100)).await;
self.set_iovar_u32("ampdu_ba_wsize", 8).await; self.set_iovar_u32("ampdu_ba_wsize", 8).await;
Timer::after_millis(100).await; Timer::after(Duration::from_millis(100)).await;
self.set_iovar_u32("ampdu_mpdu", 4).await; self.set_iovar_u32("ampdu_mpdu", 4).await;
Timer::after_millis(100).await; Timer::after(Duration::from_millis(100)).await;
//self.set_iovar_u32("ampdu_rx_factor", 0).await; // this crashes //self.set_iovar_u32("ampdu_rx_factor", 0).await; // this crashes
//Timer::after_millis(100).await; //Timer::after(Duration::from_millis(100)).await;
// evts // evts
let mut evts = EventMask { let mut evts = EventMask {
@ -127,19 +121,19 @@ impl<'a> Control<'a> {
self.set_iovar("bsscfg:event_msgs", &evts.to_bytes()).await; self.set_iovar("bsscfg:event_msgs", &evts.to_bytes()).await;
Timer::after_millis(100).await; Timer::after(Duration::from_millis(100)).await;
// set wifi up // set wifi up
self.up().await; self.up().await;
Timer::after_millis(100).await; Timer::after(Duration::from_millis(100)).await;
self.ioctl_set_u32(110, 0, 1).await; // SET_GMODE = auto self.ioctl_set_u32(110, 0, 1).await; // SET_GMODE = auto
self.ioctl_set_u32(142, 0, 0).await; // SET_BAND = any self.ioctl_set_u32(142, 0, 0).await; // SET_BAND = any
Timer::after_millis(100).await; Timer::after(Duration::from_millis(100)).await;
self.state_ch.set_hardware_address(HardwareAddress::Ethernet(mac_addr)); self.state_ch.set_ethernet_address(mac_addr);
debug!("INIT DONE"); debug!("INIT DONE");
} }
@ -191,7 +185,7 @@ impl<'a> Control<'a> {
self.set_iovar_u32x2("bsscfg:sup_wpa2_eapver", 0, 0xFFFF_FFFF).await; self.set_iovar_u32x2("bsscfg:sup_wpa2_eapver", 0, 0xFFFF_FFFF).await;
self.set_iovar_u32x2("bsscfg:sup_wpa_tmo", 0, 2500).await; self.set_iovar_u32x2("bsscfg:sup_wpa_tmo", 0, 2500).await;
Timer::after_millis(100).await; Timer::after(Duration::from_millis(100)).await;
let mut pfi = PassphraseInfo { let mut pfi = PassphraseInfo {
len: passphrase.len() as _, len: passphrase.len() as _,
@ -303,7 +297,7 @@ impl<'a> Control<'a> {
if security != Security::OPEN { if security != Security::OPEN {
self.set_iovar_u32x2("bsscfg:wpa_auth", 0, 0x0084).await; // wpa_auth = WPA2_AUTH_PSK | WPA_AUTH_PSK self.set_iovar_u32x2("bsscfg:wpa_auth", 0, 0x0084).await; // wpa_auth = WPA2_AUTH_PSK | WPA_AUTH_PSK
Timer::after_millis(100).await; Timer::after(Duration::from_millis(100)).await;
// Set passphrase // Set passphrase
let mut pfi = PassphraseInfo { let mut pfi = PassphraseInfo {
@ -323,54 +317,6 @@ impl<'a> Control<'a> {
self.set_iovar_u32x2("bss", 0, 1).await; // bss = BSS_UP 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) { async fn set_iovar_u32x2(&mut self, name: &str, val1: u32, val2: u32) {
let mut buf = [0; 8]; let mut buf = [0; 8];
buf[0..4].copy_from_slice(&val1.to_le_bytes()); buf[0..4].copy_from_slice(&val1.to_le_bytes());

View File

@ -1,7 +1,7 @@
#![no_std] #![no_std]
#![no_main] #![no_main]
#![allow(incomplete_features)]
#![feature(async_fn_in_trait, type_alias_impl_trait, concat_bytes)] #![feature(async_fn_in_trait, type_alias_impl_trait, concat_bytes)]
#![allow(stable_features, unknown_lints, async_fn_in_trait)]
#![deny(unused_must_use)] #![deny(unused_must_use)]
// This mod MUST go first, so that the others see its macros. // This mod MUST go first, so that the others see its macros.
@ -27,7 +27,7 @@ use ioctl::IoctlState;
use crate::bus::Bus; use crate::bus::Bus;
pub use crate::bus::SpiBusCyw43; pub use crate::bus::SpiBusCyw43;
pub use crate::control::{AddMulticastAddressError, Control, Error as ControlError, Scanner}; pub use crate::control::{Control, Error as ControlError, Scanner};
pub use crate::runner::Runner; pub use crate::runner::Runner;
pub use crate::structs::BssInfo; pub use crate::structs::BssInfo;

View File

@ -555,14 +555,14 @@ where
self.bus.bp_write8(base + AI_RESETCTRL_OFFSET, 0).await; self.bus.bp_write8(base + AI_RESETCTRL_OFFSET, 0).await;
Timer::after_millis(1).await; Timer::after(Duration::from_millis(1)).await;
self.bus self.bus
.bp_write8(base + AI_IOCTRL_OFFSET, AI_IOCTRL_BIT_CLOCK_EN) .bp_write8(base + AI_IOCTRL_OFFSET, AI_IOCTRL_BIT_CLOCK_EN)
.await; .await;
let _ = self.bus.bp_read8(base + AI_IOCTRL_OFFSET).await; let _ = self.bus.bp_read8(base + AI_IOCTRL_OFFSET).await;
Timer::after_millis(1).await; Timer::after(Duration::from_millis(1)).await;
} }
async fn core_is_up(&mut self, core: Core) -> bool { async fn core_is_up(&mut self, core: Core) -> bool {

View File

@ -7,7 +7,7 @@ license = "MIT OR Apache-2.0"
[dependencies] [dependencies]
embassy-executor = { version = "0.3.0", path = "../../../../../embassy-executor", features = ["defmt", "nightly", "integrated-timers", "arch-cortex-m", "executor-thread"] } embassy-executor = { version = "0.3.0", path = "../../../../../embassy-executor", features = ["defmt", "nightly", "integrated-timers", "arch-cortex-m", "executor-thread"] }
embassy-time = { version = "0.1.4", path = "../../../../../embassy-time", features = ["defmt", "nightly"] } embassy-time = { version = "0.1.0", path = "../../../../../embassy-time", features = ["defmt", "nightly"] }
embassy-nrf = { version = "0.1.0", path = "../../../../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote", "nightly"] } embassy-nrf = { version = "0.1.0", path = "../../../../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote", "nightly"] }
defmt = "0.3" defmt = "0.3"

View File

@ -48,7 +48,7 @@ The `Spawner` is the way the main application spawns other tasks. The `Periphera
include::example$basic/src/main.rs[lines="22..-1"] include::example$basic/src/main.rs[lines="22..-1"]
---- ----
What happens when the `blinker` task has been spawned and main returns? Well, the main entry point is actually just like any other task, except that you can only have one and it takes some specific type arguments. The magic lies within the `#[embassy_executor::main]` macro. The macro does the following: What happens when the `blinker` task has been spawned and main returns? Well, the main entry point is actually just like any other task, except that you can only have one and it takes some specific type arguments. The magic lies within the `#[embassy::main]` macro. The macro does the following:
. Creates an Embassy Executor . Creates an Embassy Executor
. Initializes the microcontroller HAL to get the `Peripherals` . Initializes the microcontroller HAL to get the `Peripherals`

View File

@ -6,7 +6,7 @@ The Embassy executor is an async/await executor designed for embedded usage alon
* No `alloc`, no heap needed. Task are statically allocated. * No `alloc`, no heap needed. Task are statically allocated.
* No "fixed capacity" data structures, executor works with 1 or 1000 tasks without needing config/tuning. * 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;`. * Integrated timer queue: sleeping is easy, just do `Timer::after(Duration::from_secs(1)).await;`.
* No busy-loop polling: CPU sleeps when there's no work to do, using interrupts or `WFE/SEV`. * 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. * 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. * 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.

View File

@ -28,7 +28,7 @@ digest = "0.10"
log = { version = "0.4", optional = true } log = { version = "0.4", optional = true }
ed25519-dalek = { version = "1.0.1", default_features = false, features = ["u32_backend"], optional = true } ed25519-dalek = { version = "1.0.1", default_features = false, features = ["u32_backend"], optional = true }
embassy-embedded-hal = { version = "0.1.0", path = "../../embassy-embedded-hal" } embassy-embedded-hal = { version = "0.1.0", path = "../../embassy-embedded-hal" }
embassy-sync = { version = "0.4.0", path = "../../embassy-sync" } embassy-sync = { version = "0.3.0", path = "../../embassy-sync" }
embedded-storage = "0.3.0" embedded-storage = "0.3.0"
embedded-storage-async = { version = "0.4.0", optional = true } embedded-storage-async = { version = "0.4.0", optional = true }
salty = { git = "https://github.com/ycrypto/salty.git", rev = "a9f17911a5024698406b75c0fac56ab5ccf6a8c7", optional = true } salty = { git = "https://github.com/ycrypto/salty.git", rev = "a9f17911a5024698406b75c0fac56ab5ccf6a8c7", optional = true }

View File

@ -1,5 +1,4 @@
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait))] #![cfg_attr(feature = "nightly", feature(async_fn_in_trait))]
#![cfg_attr(feature = "nightly", allow(stable_features, unknown_lints, async_fn_in_trait))]
#![no_std] #![no_std]
#![warn(missing_docs)] #![warn(missing_docs)]
#![doc = include_str!("../README.md")] #![doc = include_str!("../README.md")]

View File

@ -16,7 +16,7 @@ target = "thumbv7em-none-eabi"
[dependencies] [dependencies]
defmt = { version = "0.3", optional = true } defmt = { version = "0.3", optional = true }
embassy-sync = { version = "0.4.0", path = "../../embassy-sync" } embassy-sync = { path = "../../embassy-sync" }
embassy-nrf = { path = "../../embassy-nrf" } embassy-nrf = { path = "../../embassy-nrf" }
embassy-boot = { path = "../boot", default-features = false } embassy-boot = { path = "../boot", default-features = false }
cortex-m = { version = "0.7.6" } cortex-m = { version = "0.7.6" }

View File

@ -17,7 +17,7 @@ defmt = { version = "0.3", optional = true }
defmt-rtt = { version = "0.4", optional = true } defmt-rtt = { version = "0.4", optional = true }
log = { version = "0.4", optional = true } log = { version = "0.4", optional = true }
embassy-sync = { version = "0.4.0", path = "../../embassy-sync" } embassy-sync = { path = "../../embassy-sync" }
embassy-rp = { path = "../../embassy-rp", default-features = false } embassy-rp = { path = "../../embassy-rp", default-features = false }
embassy-boot = { path = "../boot", default-features = false } embassy-boot = { path = "../boot", default-features = false }
embassy-time = { path = "../../embassy-time" } embassy-time = { path = "../../embassy-time" }

View File

@ -18,7 +18,7 @@ defmt = { version = "0.3", optional = true }
defmt-rtt = { version = "0.4", optional = true } defmt-rtt = { version = "0.4", optional = true }
log = { version = "0.4", optional = true } log = { version = "0.4", optional = true }
embassy-sync = { version = "0.4.0", path = "../../embassy-sync" } embassy-sync = { path = "../../embassy-sync" }
embassy-stm32 = { path = "../../embassy-stm32", default-features = false } embassy-stm32 = { path = "../../embassy-stm32", default-features = false }
embassy-boot = { path = "../boot", default-features = false } embassy-boot = { path = "../boot", default-features = false }
cortex-m = { version = "0.7.6" } cortex-m = { version = "0.7.6" }

View File

@ -20,8 +20,8 @@ default = ["time"]
[dependencies] [dependencies]
embassy-futures = { version = "0.1.0", path = "../embassy-futures", optional = true } embassy-futures = { version = "0.1.0", path = "../embassy-futures", optional = true }
embassy-sync = { version = "0.4.0", path = "../embassy-sync" } embassy-sync = { version = "0.3.0", path = "../embassy-sync" }
embassy-time = { version = "0.1.5", path = "../embassy-time", optional = true } embassy-time = { version = "0.1.3", path = "../embassy-time", optional = true }
embedded-hal-02 = { package = "embedded-hal", version = "0.2.6", features = [ embedded-hal-02 = { package = "embedded-hal", version = "0.2.6", features = [
"unproven", "unproven",
] } ] }

View File

@ -1,6 +1,5 @@
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait, impl_trait_projections, try_blocks))] #![cfg_attr(feature = "nightly", feature(async_fn_in_trait, try_blocks))]
#![cfg_attr(feature = "nightly", allow(stable_features, unknown_lints, async_fn_in_trait))]
#![warn(missing_docs)] #![warn(missing_docs)]
//! Utilities to use `embedded-hal` traits with Embassy. //! Utilities to use `embedded-hal` traits with Embassy.

View File

@ -76,7 +76,9 @@ where
#[cfg(not(feature = "time"))] #[cfg(not(feature = "time"))]
Operation::DelayUs(_) => return Err(SpiDeviceError::DelayUsNotSupported), Operation::DelayUs(_) => return Err(SpiDeviceError::DelayUsNotSupported),
#[cfg(feature = "time")] #[cfg(feature = "time")]
Operation::DelayUs(us) => embassy_time::Timer::after_micros(*us as _).await, Operation::DelayUs(us) => {
embassy_time::Timer::after(embassy_time::Duration::from_micros(*us as _)).await
}
} }
} }
}; };
@ -141,7 +143,9 @@ where
#[cfg(not(feature = "time"))] #[cfg(not(feature = "time"))]
Operation::DelayUs(_) => return Err(SpiDeviceError::DelayUsNotSupported), Operation::DelayUs(_) => return Err(SpiDeviceError::DelayUsNotSupported),
#[cfg(feature = "time")] #[cfg(feature = "time")]
Operation::DelayUs(us) => embassy_time::Timer::after_micros(*us as _).await, Operation::DelayUs(us) => {
embassy_time::Timer::after(embassy_time::Duration::from_micros(*us as _)).await
}
} }
} }
}; };

View File

@ -5,20 +5,6 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## 0.3.3 - 2023-11-15
- Add `main` macro reexport for Xtensa arch.
- Remove use of `atomic-polyfill`. The executor now has multiple implementations of its internal data structures for cases where the target supports atomics or doesn't.
## 0.3.2 - 2023-11-06
- Use `atomic-polyfill` for `riscv32`
- Removed unused dependencies (static_cell, futures-util)
## 0.3.1 - 2023-11-01
- Fix spurious "Found waker not created by the Embassy executor" error in recent nightlies.
## 0.3.0 - 2023-08-25 ## 0.3.0 - 2023-08-25
- Replaced Pender. Implementations now must define an extern function called `__pender`. - Replaced Pender. Implementations now must define an extern function called `__pender`.

View File

@ -1,6 +1,6 @@
[package] [package]
name = "embassy-executor" name = "embassy-executor"
version = "0.3.3" version = "0.3.0"
edition = "2021" edition = "2021"
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
description = "async/await executor designed for embedded usage" description = "async/await executor designed for embedded usage"
@ -34,7 +34,7 @@ _arch = [] # some arch was picked
arch-std = ["_arch", "critical-section/std"] arch-std = ["_arch", "critical-section/std"]
arch-cortex-m = ["_arch", "dep:cortex-m"] arch-cortex-m = ["_arch", "dep:cortex-m"]
arch-xtensa = ["_arch"] arch-xtensa = ["_arch"]
arch-riscv32 = ["_arch", "dep:portable-atomic"] arch-riscv32 = ["_arch"]
arch-wasm = ["_arch", "dep:wasm-bindgen", "dep:js-sys"] 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) # Enable the thread-mode executor (using WFE/SEV in Cortex-M, WFI in other embedded archs)
@ -57,13 +57,12 @@ defmt = { version = "0.3", optional = true }
log = { version = "0.4.14", optional = true } log = { version = "0.4.14", optional = true }
rtos-trace = { version = "0.1.2", optional = true } rtos-trace = { version = "0.1.2", optional = true }
futures-util = { version = "0.3.17", default-features = false }
embassy-macros = { version = "0.2.1", path = "../embassy-macros" } embassy-macros = { version = "0.2.1", path = "../embassy-macros" }
embassy-time = { version = "0.1.5", path = "../embassy-time", optional = true} embassy-time = { version = "0.1.3", path = "../embassy-time", optional = true}
atomic-polyfill = "1.0.1"
critical-section = "1.1" critical-section = "1.1"
static_cell = "1.1"
# needed for riscv
# remove when https://github.com/rust-lang/rust/pull/114499 is merged
portable-atomic = { version = "1.5", optional = true }
# arch-cortex-m dependencies # arch-cortex-m dependencies
cortex-m = { version = "0.7.6", optional = true } cortex-m = { version = "0.7.6", optional = true }

View File

@ -4,7 +4,7 @@ An async/await executor designed for embedded usage.
- No `alloc`, no heap needed. Task futures are statically allocated. - No `alloc`, no heap needed. Task futures are statically allocated.
- No "fixed capacity" data structures, executor works with 1 or 1000 tasks without needing config/tuning. - 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;`. - Integrated timer queue: sleeping is easy, just do `Timer::after(Duration::from_secs(1)).await;`.
- No busy-loop polling: CPU sleeps when there's no work to do, using interrupts or `WFE/SEV`. - 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. - 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. - 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.

View File

@ -115,12 +115,12 @@ mod thread {
pub use interrupt::*; pub use interrupt::*;
#[cfg(feature = "executor-interrupt")] #[cfg(feature = "executor-interrupt")]
mod interrupt { mod interrupt {
use core::cell::{Cell, UnsafeCell}; use core::cell::UnsafeCell;
use core::mem::MaybeUninit; use core::mem::MaybeUninit;
use atomic_polyfill::{AtomicBool, Ordering};
use cortex_m::interrupt::InterruptNumber; use cortex_m::interrupt::InterruptNumber;
use cortex_m::peripheral::NVIC; use cortex_m::peripheral::NVIC;
use critical_section::Mutex;
use crate::raw; use crate::raw;
@ -146,7 +146,7 @@ mod interrupt {
/// It is somewhat more complex to use, it's recommended to use the thread-mode /// It is somewhat more complex to use, it's recommended to use the thread-mode
/// [`Executor`] instead, if it works for your use case. /// [`Executor`] instead, if it works for your use case.
pub struct InterruptExecutor { pub struct InterruptExecutor {
started: Mutex<Cell<bool>>, started: AtomicBool,
executor: UnsafeCell<MaybeUninit<raw::Executor>>, executor: UnsafeCell<MaybeUninit<raw::Executor>>,
} }
@ -158,7 +158,7 @@ mod interrupt {
#[inline] #[inline]
pub const fn new() -> Self { pub const fn new() -> Self {
Self { Self {
started: Mutex::new(Cell::new(false)), started: AtomicBool::new(false),
executor: UnsafeCell::new(MaybeUninit::uninit()), executor: UnsafeCell::new(MaybeUninit::uninit()),
} }
} }
@ -167,8 +167,7 @@ mod interrupt {
/// ///
/// # Safety /// # Safety
/// ///
/// - You MUST call this from the interrupt handler, and from nowhere else. /// You MUST call this from the interrupt handler, and from nowhere else.
/// - You must not call this before calling `start()`.
pub unsafe fn on_interrupt(&'static self) { pub unsafe fn on_interrupt(&'static self) {
let executor = unsafe { (&*self.executor.get()).assume_init_ref() }; let executor = unsafe { (&*self.executor.get()).assume_init_ref() };
executor.poll(); executor.poll();
@ -197,7 +196,11 @@ mod interrupt {
/// do it after. /// do it after.
/// ///
pub fn start(&'static self, irq: impl InterruptNumber) -> crate::SendSpawner { pub fn start(&'static self, irq: impl InterruptNumber) -> crate::SendSpawner {
if critical_section::with(|cs| self.started.borrow(cs).replace(true)) { if self
.started
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
panic!("InterruptExecutor::start() called multiple times on the same executor."); panic!("InterruptExecutor::start() called multiple times on the same executor.");
} }
@ -219,10 +222,10 @@ mod interrupt {
/// This returns a [`SendSpawner`] you can use to spawn tasks on this /// This returns a [`SendSpawner`] you can use to spawn tasks on this
/// executor. /// executor.
/// ///
/// This MUST only be called on an executor that has already been started. /// This MUST only be called on an executor that has already been spawned.
/// The function will panic otherwise. /// The function will panic otherwise.
pub fn spawner(&'static self) -> crate::SendSpawner { pub fn spawner(&'static self) -> crate::SendSpawner {
if !critical_section::with(|cs| self.started.borrow(cs).get()) { if !self.started.load(Ordering::Acquire) {
panic!("InterruptExecutor::spawner() called on uninitialized executor."); panic!("InterruptExecutor::spawner() called on uninitialized executor.");
} }
let executor = unsafe { (&*self.executor.get()).assume_init_ref() }; let executor = unsafe { (&*self.executor.get()).assume_init_ref() };

View File

@ -6,10 +6,10 @@ pub use thread::*;
#[cfg(feature = "executor-thread")] #[cfg(feature = "executor-thread")]
mod thread { mod thread {
use core::marker::PhantomData; use core::marker::PhantomData;
use core::sync::atomic::{AtomicBool, Ordering};
#[cfg(feature = "nightly")] #[cfg(feature = "nightly")]
pub use embassy_macros::main_riscv as main; pub use embassy_macros::main_riscv as main;
use portable_atomic::{AtomicBool, Ordering};
use crate::{raw, Spawner}; use crate::{raw, Spawner};

View File

@ -8,9 +8,6 @@ mod thread {
use core::marker::PhantomData; use core::marker::PhantomData;
use core::sync::atomic::{AtomicBool, Ordering}; use core::sync::atomic::{AtomicBool, Ordering};
#[cfg(feature = "nightly")]
pub use embassy_macros::main_riscv as main;
use crate::{raw, Spawner}; use crate::{raw, Spawner};
/// global atomic used to keep track of whether there is work to do since sev() is not available on Xtensa /// global atomic used to keep track of whether there is work to do since sev() is not available on Xtensa

View File

@ -33,7 +33,6 @@ check_at_most_one!("arch-cortex-m", "arch-riscv32", "arch-xtensa", "arch-std", "
mod arch; mod arch;
#[cfg(feature = "_arch")] #[cfg(feature = "_arch")]
#[allow(unused_imports)] // don't warn if the module is empty.
pub use arch::*; pub use arch::*;
pub mod raw; pub mod raw;
@ -47,6 +46,7 @@ pub use spawner::*;
pub mod _export { pub mod _export {
#[cfg(feature = "rtos-trace")] #[cfg(feature = "rtos-trace")]
pub use rtos_trace::trace; pub use rtos_trace::trace;
pub use static_cell::StaticCell;
/// Expands the given block of code when `embassy-executor` is compiled with /// Expands the given block of code when `embassy-executor` is compiled with
/// the `rtos-trace-interrupt` feature. /// the `rtos-trace-interrupt` feature.

View File

@ -7,15 +7,7 @@
//! Using this module requires respecting subtle safety contracts. If you can, prefer using the safe //! Using this module requires respecting subtle safety contracts. If you can, prefer using the safe
//! [executor wrappers](crate::Executor) and the [`embassy_executor::task`](embassy_macros::task) macro, which are fully safe. //! [executor wrappers](crate::Executor) and the [`embassy_executor::task`](embassy_macros::task) macro, which are fully safe.
#[cfg_attr(target_has_atomic = "ptr", path = "run_queue_atomics.rs")]
#[cfg_attr(not(target_has_atomic = "ptr"), path = "run_queue_critical_section.rs")]
mod run_queue; mod run_queue;
#[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;
#[cfg(feature = "integrated-timers")] #[cfg(feature = "integrated-timers")]
mod timer_queue; mod timer_queue;
pub(crate) mod util; pub(crate) mod util;
@ -29,6 +21,7 @@ use core::pin::Pin;
use core::ptr::NonNull; use core::ptr::NonNull;
use core::task::{Context, Poll}; use core::task::{Context, Poll};
use atomic_polyfill::{AtomicU32, Ordering};
#[cfg(feature = "integrated-timers")] #[cfg(feature = "integrated-timers")]
use embassy_time::driver::{self, AlarmHandle}; use embassy_time::driver::{self, AlarmHandle};
#[cfg(feature = "integrated-timers")] #[cfg(feature = "integrated-timers")]
@ -37,14 +30,21 @@ use embassy_time::Instant;
use rtos_trace::trace; use rtos_trace::trace;
use self::run_queue::{RunQueue, RunQueueItem}; use self::run_queue::{RunQueue, RunQueueItem};
use self::state::State;
use self::util::{SyncUnsafeCell, UninitCell}; use self::util::{SyncUnsafeCell, UninitCell};
pub use self::waker::task_from_waker; pub use self::waker::task_from_waker;
use super::SpawnToken; use super::SpawnToken;
/// Task is spawned (has a future)
pub(crate) const STATE_SPAWNED: u32 = 1 << 0;
/// Task is in the executor run queue
pub(crate) const STATE_RUN_QUEUED: u32 = 1 << 1;
/// Task is in the executor timer queue
#[cfg(feature = "integrated-timers")]
pub(crate) const STATE_TIMER_QUEUED: u32 = 1 << 2;
/// Raw task header for use in task pointers. /// Raw task header for use in task pointers.
pub(crate) struct TaskHeader { pub(crate) struct TaskHeader {
pub(crate) state: State, pub(crate) state: AtomicU32,
pub(crate) run_queue_item: RunQueueItem, pub(crate) run_queue_item: RunQueueItem,
pub(crate) executor: SyncUnsafeCell<Option<&'static SyncExecutor>>, pub(crate) executor: SyncUnsafeCell<Option<&'static SyncExecutor>>,
poll_fn: SyncUnsafeCell<Option<unsafe fn(TaskRef)>>, poll_fn: SyncUnsafeCell<Option<unsafe fn(TaskRef)>>,
@ -116,7 +116,7 @@ impl<F: Future + 'static> TaskStorage<F> {
pub const fn new() -> Self { pub const fn new() -> Self {
Self { Self {
raw: TaskHeader { raw: TaskHeader {
state: State::new(), state: AtomicU32::new(0),
run_queue_item: RunQueueItem::new(), run_queue_item: RunQueueItem::new(),
executor: SyncUnsafeCell::new(None), executor: SyncUnsafeCell::new(None),
// Note: this is lazily initialized so that a static `TaskStorage` will go in `.bss` // Note: this is lazily initialized so that a static `TaskStorage` will go in `.bss`
@ -161,7 +161,7 @@ impl<F: Future + 'static> TaskStorage<F> {
match future.poll(&mut cx) { match future.poll(&mut cx) {
Poll::Ready(_) => { Poll::Ready(_) => {
this.future.drop_in_place(); this.future.drop_in_place();
this.raw.state.despawn(); this.raw.state.fetch_and(!STATE_SPAWNED, Ordering::AcqRel);
#[cfg(feature = "integrated-timers")] #[cfg(feature = "integrated-timers")]
this.raw.expires_at.set(Instant::MAX); this.raw.expires_at.set(Instant::MAX);
@ -193,7 +193,11 @@ impl<F: Future + 'static> AvailableTask<F> {
/// ///
/// This function returns `None` if a task has already been spawned and has not finished running. /// This function returns `None` if a task has already been spawned and has not finished running.
pub fn claim(task: &'static TaskStorage<F>) -> Option<Self> { pub fn claim(task: &'static TaskStorage<F>) -> Option<Self> {
task.raw.state.spawn().then(|| Self { task }) task.raw
.state
.compare_exchange(0, STATE_SPAWNED | STATE_RUN_QUEUED, Ordering::AcqRel, Ordering::Acquire)
.ok()
.map(|_| Self { task })
} }
fn initialize_impl<S>(self, future: impl FnOnce() -> F) -> SpawnToken<S> { fn initialize_impl<S>(self, future: impl FnOnce() -> F) -> SpawnToken<S> {
@ -390,7 +394,8 @@ impl SyncExecutor {
#[cfg(feature = "integrated-timers")] #[cfg(feature = "integrated-timers")]
task.expires_at.set(Instant::MAX); task.expires_at.set(Instant::MAX);
if !task.state.run_dequeue() { let state = task.state.fetch_and(!STATE_RUN_QUEUED, Ordering::AcqRel);
if state & STATE_SPAWNED == 0 {
// If task is not running, ignore it. This can happen in the following scenario: // If task is not running, ignore it. This can happen in the following scenario:
// - Task gets dequeued, poll starts // - Task gets dequeued, poll starts
// - While task is being polled, it gets woken. It gets placed in the queue. // - While task is being polled, it gets woken. It gets placed in the queue.
@ -541,7 +546,18 @@ impl Executor {
/// You can obtain a `TaskRef` from a `Waker` using [`task_from_waker`]. /// You can obtain a `TaskRef` from a `Waker` using [`task_from_waker`].
pub fn wake_task(task: TaskRef) { pub fn wake_task(task: TaskRef) {
let header = task.header(); let header = task.header();
if header.state.run_enqueue() {
let res = header.state.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |state| {
// If already scheduled, or if not started,
if (state & STATE_RUN_QUEUED != 0) || (state & STATE_SPAWNED == 0) {
None
} else {
// Mark it as scheduled
Some(state | STATE_RUN_QUEUED)
}
});
if res.is_ok() {
// We have just marked the task as scheduled, so enqueue it. // We have just marked the task as scheduled, so enqueue it.
unsafe { unsafe {
let executor = header.executor.get().unwrap_unchecked(); let executor = header.executor.get().unwrap_unchecked();
@ -555,7 +571,18 @@ pub fn wake_task(task: TaskRef) {
/// You can obtain a `TaskRef` from a `Waker` using [`task_from_waker`]. /// You can obtain a `TaskRef` from a `Waker` using [`task_from_waker`].
pub fn wake_task_no_pend(task: TaskRef) { pub fn wake_task_no_pend(task: TaskRef) {
let header = task.header(); let header = task.header();
if header.state.run_enqueue() {
let res = header.state.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |state| {
// If already scheduled, or if not started,
if (state & STATE_RUN_QUEUED != 0) || (state & STATE_SPAWNED == 0) {
None
} else {
// Mark it as scheduled
Some(state | STATE_RUN_QUEUED)
}
});
if res.is_ok() {
// We have just marked the task as scheduled, so enqueue it. // We have just marked the task as scheduled, so enqueue it.
unsafe { unsafe {
let executor = header.executor.get().unwrap_unchecked(); let executor = header.executor.get().unwrap_unchecked();

View File

@ -1,6 +1,7 @@
use core::ptr; use core::ptr;
use core::ptr::NonNull; use core::ptr::NonNull;
use core::sync::atomic::{AtomicPtr, Ordering};
use atomic_polyfill::{AtomicPtr, Ordering};
use super::{TaskHeader, TaskRef}; use super::{TaskHeader, TaskRef};
use crate::raw::util::SyncUnsafeCell; use crate::raw::util::SyncUnsafeCell;

View File

@ -1,75 +0,0 @@
use core::cell::Cell;
use critical_section::{CriticalSection, Mutex};
use super::TaskRef;
pub(crate) struct RunQueueItem {
next: Mutex<Cell<Option<TaskRef>>>,
}
impl RunQueueItem {
pub const fn new() -> Self {
Self {
next: Mutex::new(Cell::new(None)),
}
}
}
/// Atomic task queue using a very, very simple lock-free linked-list queue:
///
/// To enqueue a task, task.next is set to the old head, and head is atomically set to task.
///
/// Dequeuing is done in batches: the queue is emptied by atomically replacing head with
/// null. Then the batch is iterated following the next pointers until null is reached.
///
/// Note that batches will be iterated in the reverse order as they were enqueued. This is OK
/// for our purposes: it can't create fairness problems since the next batch won't run until the
/// current batch is completely processed, so even if a task enqueues itself instantly (for example
/// by waking its own waker) can't prevent other tasks from running.
pub(crate) struct RunQueue {
head: Mutex<Cell<Option<TaskRef>>>,
}
impl RunQueue {
pub const fn new() -> Self {
Self {
head: Mutex::new(Cell::new(None)),
}
}
/// Enqueues an item. Returns true if the queue was empty.
///
/// # Safety
///
/// `item` must NOT be already enqueued in any queue.
#[inline(always)]
pub(crate) unsafe fn enqueue(&self, task: TaskRef) -> bool {
critical_section::with(|cs| {
let prev = self.head.borrow(cs).replace(Some(task));
task.header().run_queue_item.next.borrow(cs).set(prev);
prev.is_none()
})
}
/// Empty the queue, then call `on_task` for each task that was in the queue.
/// NOTE: It is OK for `on_task` to enqueue more tasks. In this case they're left in the queue
/// and will be processed by the *next* call to `dequeue_all`, *not* the current one.
pub(crate) fn dequeue_all(&self, on_task: impl Fn(TaskRef)) {
// Atomically empty the queue.
let mut next = critical_section::with(|cs| self.head.borrow(cs).take());
// Iterate the linked list of tasks that were previously in the queue.
while let Some(task) = next {
// If the task re-enqueues itself, the `next` pointer will get overwritten.
// Therefore, first read the next pointer, and only then process the task.
// safety: we know if the task is enqueued, no one else will touch the `next` pointer.
let cs = unsafe { CriticalSection::new() };
next = task.header().run_queue_item.next.borrow(cs).get();
on_task(task);
}
}
}

View File

@ -1,73 +0,0 @@
use core::sync::atomic::{AtomicU32, Ordering};
/// Task is spawned (has a future)
pub(crate) const STATE_SPAWNED: u32 = 1 << 0;
/// Task is in the executor run queue
pub(crate) const STATE_RUN_QUEUED: u32 = 1 << 1;
/// Task is in the executor timer queue
#[cfg(feature = "integrated-timers")]
pub(crate) const STATE_TIMER_QUEUED: u32 = 1 << 2;
pub(crate) struct State {
state: AtomicU32,
}
impl State {
pub const fn new() -> State {
Self {
state: AtomicU32::new(0),
}
}
/// If task is idle, mark it as spawned + run_queued and return true.
#[inline(always)]
pub fn spawn(&self) -> bool {
self.state
.compare_exchange(0, STATE_SPAWNED | STATE_RUN_QUEUED, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
}
/// Unmark the task as spawned.
#[inline(always)]
pub fn despawn(&self) {
self.state.fetch_and(!STATE_SPAWNED, Ordering::AcqRel);
}
/// 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 {
self.state
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |state| {
// If already scheduled, or if not started,
if (state & STATE_RUN_QUEUED != 0) || (state & STATE_SPAWNED == 0) {
None
} else {
// Mark it as scheduled
Some(state | STATE_RUN_QUEUED)
}
})
.is_ok()
}
/// Unmark the task as run-queued. Return whether the task is spawned.
#[inline(always)]
pub fn run_dequeue(&self) -> bool {
let state = self.state.fetch_and(!STATE_RUN_QUEUED, Ordering::AcqRel);
state & STATE_SPAWNED != 0
}
/// 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 {
let old_state = self.state.fetch_or(STATE_TIMER_QUEUED, Ordering::AcqRel);
old_state & STATE_TIMER_QUEUED == 0
}
/// Unmark the task as timer-queued.
#[cfg(feature = "integrated-timers")]
#[inline(always)]
pub fn timer_dequeue(&self) {
self.state.fetch_and(!STATE_TIMER_QUEUED, Ordering::AcqRel);
}
}

View File

@ -1,103 +0,0 @@
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);
}
}

View File

@ -1,93 +0,0 @@
use core::cell::Cell;
use critical_section::Mutex;
/// Task is spawned (has a future)
pub(crate) const STATE_SPAWNED: u32 = 1 << 0;
/// Task is in the executor run queue
pub(crate) const STATE_RUN_QUEUED: u32 = 1 << 1;
/// Task is in the executor timer queue
#[cfg(feature = "integrated-timers")]
pub(crate) const STATE_TIMER_QUEUED: u32 = 1 << 2;
pub(crate) struct State {
state: Mutex<Cell<u32>>,
}
impl State {
pub const fn new() -> State {
Self {
state: Mutex::new(Cell::new(0)),
}
}
fn update<R>(&self, f: impl FnOnce(&mut u32) -> R) -> R {
critical_section::with(|cs| {
let s = self.state.borrow(cs);
let mut val = s.get();
let r = f(&mut val);
s.set(val);
r
})
}
/// If task is idle, mark it as spawned + run_queued and return true.
#[inline(always)]
pub fn spawn(&self) -> bool {
self.update(|s| {
if *s == 0 {
*s = STATE_SPAWNED | STATE_RUN_QUEUED;
true
} else {
false
}
})
}
/// Unmark the task as spawned.
#[inline(always)]
pub fn despawn(&self) {
self.update(|s| *s &= !STATE_SPAWNED);
}
/// 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 {
self.update(|s| {
if (*s & STATE_RUN_QUEUED != 0) || (*s & STATE_SPAWNED == 0) {
false
} else {
*s |= STATE_RUN_QUEUED;
true
}
})
}
/// Unmark the task as run-queued. Return whether the task is spawned.
#[inline(always)]
pub fn run_dequeue(&self) -> bool {
self.update(|s| {
let ok = *s & STATE_SPAWNED != 0;
*s &= !STATE_RUN_QUEUED;
ok
})
}
/// 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.update(|s| {
let ok = *s & STATE_TIMER_QUEUED == 0;
*s |= STATE_TIMER_QUEUED;
ok
})
}
/// Unmark the task as timer-queued.
#[cfg(feature = "integrated-timers")]
#[inline(always)]
pub fn timer_dequeue(&self) {
self.update(|s| *s &= !STATE_TIMER_QUEUED);
}
}

View File

@ -1,8 +1,9 @@
use core::cmp::min; use core::cmp::min;
use atomic_polyfill::Ordering;
use embassy_time::Instant; use embassy_time::Instant;
use super::TaskRef; use super::{TaskRef, STATE_TIMER_QUEUED};
use crate::raw::util::SyncUnsafeCell; use crate::raw::util::SyncUnsafeCell;
pub(crate) struct TimerQueueItem { pub(crate) struct TimerQueueItem {
@ -31,7 +32,10 @@ impl TimerQueue {
pub(crate) unsafe fn update(&self, p: TaskRef) { pub(crate) unsafe fn update(&self, p: TaskRef) {
let task = p.header(); let task = p.header();
if task.expires_at.get() != Instant::MAX { if task.expires_at.get() != Instant::MAX {
if task.state.timer_enqueue() { let old_state = task.state.fetch_or(STATE_TIMER_QUEUED, Ordering::AcqRel);
let is_new = old_state & STATE_TIMER_QUEUED == 0;
if is_new {
task.timer_queue_item.next.set(self.head.get()); task.timer_queue_item.next.set(self.head.get());
self.head.set(Some(p)); self.head.set(Some(p));
} }
@ -71,7 +75,7 @@ impl TimerQueue {
} else { } else {
// Remove it // Remove it
prev.set(task.timer_queue_item.next.get()); prev.set(task.timer_queue_item.next.get());
task.state.timer_dequeue(); task.state.fetch_and(!STATE_TIMER_QUEUED, Ordering::AcqRel);
} }
} }
} }

View File

@ -3,7 +3,7 @@ use core::task::{RawWaker, RawWakerVTable, Waker};
use super::{wake_task, TaskHeader, TaskRef}; use super::{wake_task, TaskHeader, TaskRef};
static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake, drop); const VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake, drop);
unsafe fn clone(p: *const ()) -> RawWaker { unsafe fn clone(p: *const ()) -> RawWaker {
RawWaker::new(p, &VTABLE) RawWaker::new(p, &VTABLE)

View File

@ -1,6 +1,6 @@
[package] [package]
name = "embassy-futures" name = "embassy-futures"
version = "0.1.1" version = "0.1.0"
edition = "2021" edition = "2021"
description = "no-std, no-alloc utilities for working with futures" description = "no-std, no-alloc utilities for working with futures"
repository = "https://github.com/embassy-rs/embassy" repository = "https://github.com/embassy-rs/embassy"

View File

@ -1,4 +1,4 @@
# embassy-hal-internal # embassy-macros
An [Embassy](https://embassy.dev) project. An [Embassy](https://embassy.dev) project.

View File

@ -4,7 +4,6 @@ use core::sync::atomic::{compiler_fence, Ordering};
use cortex_m::interrupt::InterruptNumber; use cortex_m::interrupt::InterruptNumber;
use cortex_m::peripheral::NVIC; use cortex_m::peripheral::NVIC;
use critical_section::CriticalSection;
/// Generate a standard `mod interrupt` for a HAL. /// Generate a standard `mod interrupt` for a HAL.
#[macro_export] #[macro_export]
@ -92,12 +91,6 @@ macro_rules! interrupt_mod {
fn set_priority(prio: crate::interrupt::Priority) { fn set_priority(prio: crate::interrupt::Priority) {
Self::IRQ.set_priority(prio) Self::IRQ.set_priority(prio)
} }
/// Set the interrupt priority with an already-acquired critical section
#[inline]
fn set_priority_with_cs(cs: critical_section::CriticalSection, prio: crate::interrupt::Priority) {
Self::IRQ.set_priority_with_cs(cs, prio)
}
} }
$( $(
@ -202,29 +195,10 @@ pub unsafe trait InterruptExt: InterruptNumber + Copy {
/// Set the interrupt priority. /// Set the interrupt priority.
#[inline] #[inline]
fn set_priority(self, prio: Priority) { fn set_priority(self, prio: Priority) {
unsafe { critical_section::with(|_| unsafe {
let mut nvic: cortex_m::peripheral::NVIC = mem::transmute(()); let mut nvic: cortex_m::peripheral::NVIC = mem::transmute(());
nvic.set_priority(self, prio.into())
// On thumbv6, set_priority must do a RMW to change 8bit in a 32bit reg. })
#[cfg(armv6m)]
critical_section::with(|_| nvic.set_priority(self, prio.into()));
// On thumbv7+, set_priority does an atomic 8bit write, so no CS needed.
#[cfg(not(armv6m))]
nvic.set_priority(self, prio.into());
}
}
/// Set the interrupt priority with an already-acquired critical section
///
/// Equivalent to `set_priority`, except you pass a `CriticalSection` to prove
/// you've already acquired a critical section. This prevents acquiring another
/// one, which saves code size.
#[inline]
fn set_priority_with_cs(self, _cs: CriticalSection, prio: Priority) {
unsafe {
let mut nvic: cortex_m::peripheral::NVIC = mem::transmute(());
nvic.set_priority(self, prio.into());
}
} }
} }

View File

@ -10,6 +10,7 @@ pub mod drop;
mod macros; mod macros;
mod peripheral; mod peripheral;
pub mod ratio; pub mod ratio;
pub mod ring_buffer;
pub use peripheral::{Peripheral, PeripheralRef}; pub use peripheral::{Peripheral, PeripheralRef};
#[cfg(feature = "cortex-m")] #[cfg(feature = "cortex-m")]

View File

@ -48,23 +48,17 @@ macro_rules! peripherals_struct {
///Returns all the peripherals *once* ///Returns all the peripherals *once*
#[inline] #[inline]
pub(crate) fn take() -> Self { pub(crate) fn take() -> Self {
critical_section::with(Self::take_with_cs)
}
///Returns all the peripherals *once*
#[inline]
pub(crate) fn take_with_cs(_cs: critical_section::CriticalSection) -> Self {
#[no_mangle] #[no_mangle]
static mut _EMBASSY_DEVICE_PERIPHERALS: bool = false; static mut _EMBASSY_DEVICE_PERIPHERALS: bool = false;
// safety: OK because we're inside a CS. critical_section::with(|_| unsafe {
unsafe {
if _EMBASSY_DEVICE_PERIPHERALS { if _EMBASSY_DEVICE_PERIPHERALS {
panic!("init called more than once!") panic!("init called more than once!")
} }
_EMBASSY_DEVICE_PERIPHERALS = true; _EMBASSY_DEVICE_PERIPHERALS = true;
Self::steal() Self::steal()
} })
} }
} }

View File

@ -0,0 +1,136 @@
pub struct RingBuffer<'a> {
buf: &'a mut [u8],
start: usize,
end: usize,
empty: bool,
}
impl<'a> RingBuffer<'a> {
pub fn new(buf: &'a mut [u8]) -> Self {
Self {
buf,
start: 0,
end: 0,
empty: true,
}
}
pub fn push_buf(&mut self) -> &mut [u8] {
if self.start == self.end && !self.empty {
trace!(" ringbuf: push_buf empty");
return &mut self.buf[..0];
}
let n = if self.start <= self.end {
self.buf.len() - self.end
} else {
self.start - self.end
};
trace!(" ringbuf: push_buf {:?}..{:?}", self.end, self.end + n);
&mut self.buf[self.end..self.end + n]
}
pub fn push(&mut self, n: usize) {
trace!(" ringbuf: push {:?}", n);
if n == 0 {
return;
}
self.end = self.wrap(self.end + n);
self.empty = false;
}
pub fn pop_buf(&mut self) -> &mut [u8] {
if self.empty {
trace!(" ringbuf: pop_buf empty");
return &mut self.buf[..0];
}
let n = if self.end <= self.start {
self.buf.len() - self.start
} else {
self.end - self.start
};
trace!(" ringbuf: pop_buf {:?}..{:?}", self.start, self.start + n);
&mut self.buf[self.start..self.start + n]
}
pub fn pop(&mut self, n: usize) {
trace!(" ringbuf: pop {:?}", n);
if n == 0 {
return;
}
self.start = self.wrap(self.start + n);
self.empty = self.start == self.end;
}
pub fn is_full(&self) -> bool {
self.start == self.end && !self.empty
}
pub fn is_empty(&self) -> bool {
self.empty
}
pub fn clear(&mut self) {
self.start = 0;
self.end = 0;
self.empty = true;
}
fn wrap(&self, n: usize) -> usize {
assert!(n <= self.buf.len());
if n == self.buf.len() {
0
} else {
n
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn push_pop() {
let mut b = [0; 4];
let mut rb = RingBuffer::new(&mut b);
let buf = rb.push_buf();
assert_eq!(4, buf.len());
buf[0] = 1;
buf[1] = 2;
buf[2] = 3;
buf[3] = 4;
rb.push(4);
let buf = rb.pop_buf();
assert_eq!(4, buf.len());
assert_eq!(1, buf[0]);
rb.pop(1);
let buf = rb.pop_buf();
assert_eq!(3, buf.len());
assert_eq!(2, buf[0]);
rb.pop(1);
let buf = rb.pop_buf();
assert_eq!(2, buf.len());
assert_eq!(3, buf[0]);
rb.pop(1);
let buf = rb.pop_buf();
assert_eq!(1, buf.len());
assert_eq!(4, buf[0]);
rb.pop(1);
let buf = rb.pop_buf();
assert_eq!(0, buf.len());
let buf = rb.push_buf();
assert_eq!(4, buf.len());
}
}

View File

@ -20,8 +20,8 @@ defmt = ["dep:defmt", "lorawan-device/defmt"]
defmt = { version = "0.3", optional = true } defmt = { version = "0.3", optional = true }
log = { version = "0.4.14", optional = true } log = { version = "0.4.14", optional = true }
embassy-time = { version = "0.1.5", path = "../embassy-time", optional = true } embassy-time = { version = "0.1.3", path = "../embassy-time", optional = true }
embassy-sync = { version = "0.4.0", path = "../embassy-sync" } embassy-sync = { version = "0.3.0", path = "../embassy-sync" }
embassy-stm32 = { version = "0.1.0", path = "../embassy-stm32", default-features = false, optional = true } embassy-stm32 = { version = "0.1.0", path = "../embassy-stm32", default-features = false, optional = true }
embedded-hal-async = { version = "=1.0.0-rc.1" } embedded-hal-async = { version = "=1.0.0-rc.1" }
embedded-hal = { version = "0.2", features = ["unproven"] } embedded-hal = { version = "0.2", features = ["unproven"] }

View File

@ -1,6 +1,5 @@
#![no_std] #![no_std]
#![feature(async_fn_in_trait, impl_trait_projections)] #![feature(async_fn_in_trait)]
#![allow(stable_features, unknown_lints, async_fn_in_trait)]
//! embassy-lora holds LoRa-specific functionality. //! embassy-lora holds LoRa-specific functionality.
pub(crate) mod fmt; pub(crate) mod fmt;
@ -35,6 +34,6 @@ impl lorawan_device::async_device::radio::Timer for LoraTimer {
} }
async fn delay_ms(&mut self, millis: u64) { async fn delay_ms(&mut self, millis: u64) {
Timer::after_millis(millis).await Timer::after(Duration::from_millis(millis)).await
} }
} }

View File

@ -53,7 +53,8 @@ pub fn wasm() -> TokenStream {
quote! { quote! {
#[wasm_bindgen::prelude::wasm_bindgen(start)] #[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn main() -> Result<(), wasm_bindgen::JsValue> { pub fn main() -> Result<(), wasm_bindgen::JsValue> {
let executor = ::std::boxed::Box::leak(::std::boxed::Box::new(::embassy_executor::Executor::new())); static EXECUTOR: ::embassy_executor::_export::StaticCell<::embassy_executor::Executor> = ::embassy_executor::_export::StaticCell::new();
let executor = EXECUTOR.init(::embassy_executor::Executor::new());
executor.start(|spawner| { executor.start(|spawner| {
spawner.spawn(__embassy_main(spawner)).unwrap(); spawner.spawn(__embassy_main(spawner)).unwrap();

View File

@ -10,19 +10,21 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
heapless = "0.8" heapless = "0.7.16"
defmt = { version = "0.3", optional = true } defmt = { version = "0.3", optional = true }
log = { version = "0.4", default-features = false, optional = true } log = { version = "0.4", default-features = false, optional = true }
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.1" } embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.1" }
embedded-hal-async = { version = "=1.0.0-rc.1" } embedded-hal-async = { version = "=1.0.0-rc.1" }
embedded-hal-bus = { version = "=0.1.0-rc.1", features = ["async"] } embedded-hal-bus = { version = "=0.1.0-rc.1", features = ["async"] }
embassy-net-driver-channel = { version = "0.2.0", path = "../embassy-net-driver-channel" } embassy-net-driver-channel = { version = "0.1.0", path = "../embassy-net-driver-channel" }
embassy-time = { version = "0.1.5", path = "../embassy-time" } embassy-time = { version = "0.1.3" }
embassy-futures = { version = "0.1.0", path = "../embassy-futures" } embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
bitfield = "0.14.0" bitfield = "0.14.0"
[dev-dependencies] [dev-dependencies]
embedded-hal-mock = { version = "=0.10.0-rc.1", features = ["embedded-hal-async", "eh1"] } # reenable when https://github.com/dbrgn/embedded-hal-mock/pull/86 is merged.
#embedded-hal-mock = { git = "https://github.com/dbrgn/embedded-hal-mock", branch = "1-alpha", features = ["embedded-hal-async", "eh1"] }] }
embedded-hal-mock = { git = "https://github.com/newAM/embedded-hal-mock", branch = "eh1-rc.1", features = ["embedded-hal-async", "eh1"] }
crc = "3.0.1" crc = "3.0.1"
env_logger = "0.10" env_logger = "0.10"
critical-section = { version = "1.1.2", features = ["std"] } critical-section = { version = "1.1.2", features = ["std"] }

View File

@ -1,6 +1,5 @@
#![deny(clippy::pedantic)] #![deny(clippy::pedantic)]
#![feature(async_fn_in_trait)] #![feature(async_fn_in_trait)]
#![allow(stable_features, unknown_lints, async_fn_in_trait)]
#![cfg_attr(not(any(test, feature = "std")), no_std)] #![cfg_attr(not(any(test, feature = "std")), no_std)]
#![allow(clippy::module_name_repetitions)] #![allow(clippy::module_name_repetitions)]
#![allow(clippy::missing_errors_doc)] #![allow(clippy::missing_errors_doc)]
@ -21,7 +20,7 @@ pub use crc32::ETH_FCS;
use crc8::crc8; use crc8::crc8;
use embassy_futures::select::{select, Either}; use embassy_futures::select::{select, Either};
use embassy_net_driver_channel as ch; use embassy_net_driver_channel as ch;
use embassy_time::Timer; use embassy_time::{Duration, Timer};
use embedded_hal_1::digital::OutputPin; use embedded_hal_1::digital::OutputPin;
use embedded_hal_async::digital::Wait; use embedded_hal_async::digital::Wait;
use embedded_hal_async::spi::{Error, Operation, SpiDevice}; use embedded_hal_async::spi::{Error, Operation, SpiDevice};
@ -610,12 +609,12 @@ pub async fn new<const N_RX: usize, const N_TX: usize, SPI: SpiDevice, INT: Wait
reset.set_low().unwrap(); reset.set_low().unwrap();
// Wait t1: 20-43mS // Wait t1: 20-43mS
Timer::after_millis(30).await; Timer::after(Duration::from_millis(30)).await;
reset.set_high().unwrap(); reset.set_high().unwrap();
// Wait t3: 50mS // Wait t3: 50mS
Timer::after_millis(50).await; Timer::after(Duration::from_millis(50)).await;
// Create device // Create device
let mut mac = ADIN1110::new(spi_dev, spi_crc, append_fcs_on_tx); let mut mac = ADIN1110::new(spi_dev, spi_crc, append_fcs_on_tx);

View File

@ -1,16 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## 0.2.0 - 2023-10-18
- Update `embassy-net-driver` to v0.2
- `Runner::new` now takes an `embassy_net_driver::HardwareAddress` parameter.
- `Runner::set_ethernet_address` is now `set_hardware_address`.
## 0.1.0 - 2023-06-29
- First release

View File

@ -1,6 +1,6 @@
[package] [package]
name = "embassy-net-driver-channel" name = "embassy-net-driver-channel"
version = "0.2.0" version = "0.1.0"
edition = "2021" edition = "2021"
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
description = "High-level channel-based driver for the `embassy-net` async TCP/IP network stack." description = "High-level channel-based driver for the `embassy-net` async TCP/IP network stack."
@ -24,6 +24,6 @@ features = ["defmt"]
defmt = { version = "0.3", optional = true } defmt = { version = "0.3", optional = true }
log = { version = "0.4.14", optional = true } log = { version = "0.4.14", optional = true }
embassy-sync = { version = "0.4.0", path = "../embassy-sync" } embassy-sync = { version = "0.3.0", path = "../embassy-sync" }
embassy-futures = { version = "0.1.0", path = "../embassy-futures" } embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
embassy-net-driver = { version = "0.2.0", path = "../embassy-net-driver" } embassy-net-driver = { version = "0.1.0", path = "../embassy-net-driver" }

View File

@ -7,9 +7,7 @@ The `embassy-net-driver` trait is polling-based. To implement it, you must write
hand, and hook up the `Waker`s provided by `embassy-net` to the right interrupt handlers so that `embassy-net` hand, and hook up the `Waker`s provided by `embassy-net` to the right interrupt handlers so that `embassy-net`
knows when to poll your driver again to make more progress. knows when to poll your driver again to make more progress.
With `embassy-net-driver-channel` you get a "channel-like" interface instead, where you can send/receive packets With `embassy-net-driver-channel`
to/from embassy-net. The intended usage is to spawn a "driver task" in the background that does this, passing
packets between the hardware and the channel.
## A note about deadlocks ## A note about deadlocks
@ -20,19 +18,19 @@ loop {
// Wait for either.. // Wait for either..
match select( match select(
// ... the chip signaling an interrupt, indicating a packet is available to receive, or // ... the chip signaling an interrupt, indicating a packet is available to receive, or
irq_pin.wait_for_low(), irq_pin.wait_for_low(),
// ... a TX buffer becoming available, i.e. embassy-net wants to send a packet // ... a TX buffer becoming available, i.e. embassy-net wants to send a packet
tx_chan.tx_buf(), tx_chan.tx_buf(),
).await { ).await {
Either::First(_) => { Either::First(_) => {
// a packet is ready to be received! // a packet is ready to be received!
let buf = rx_chan.rx_buf().await; // allocate a rx buf from the packet queue let buf = rx_chan.rx_buf().await; // allocate a rx buf from the packet queue
let n = receive_packet_over_spi(buf).await; let n = receive_packet_over_spi(buf).await;
rx_chan.rx_done(n); rx_chan.rx_done(n);
} }
Either::Second(buf) => { Either::Second(buf) => {
// a packet is ready to be sent! // a packet is ready to be sent!
send_packet_over_spi(buf).await; send_packet_over_spi(buf).await;
tx_chan.tx_done(); tx_chan.tx_done();
} }
} }
@ -43,7 +41,7 @@ However, this code has a latent deadlock bug. The symptom is it can hang at `rx_
The reason is that, under load, both the TX and RX queues can get full at the same time. When this happens, the `embassy-net` task stalls trying to send because the TX queue is full, therefore it stops processing packets in the RX queue. Your driver task also stalls because the RX queue is full, therefore it stops processing packets in the TX queue. The reason is that, under load, both the TX and RX queues can get full at the same time. When this happens, the `embassy-net` task stalls trying to send because the TX queue is full, therefore it stops processing packets in the RX queue. Your driver task also stalls because the RX queue is full, therefore it stops processing packets in the TX queue.
The fix is to make sure to always service the TX queue while you're waiting for space to become available in the RX queue. For example, select on either "tx_chan.tx_buf() available" or "INT is low AND rx_chan.rx_buf() available": The fix is to make sure to always service the TX queue while you're waiting for space to become available in the TX queue. For example, select on either "tx_chan.tx_buf() available" or "INT is low AND rx_chan.rx_buf() available":
```rust,ignore ```rust,ignore
loop { loop {
@ -60,12 +58,12 @@ loop {
).await { ).await {
Either::First(buf) => { Either::First(buf) => {
// a packet is ready to be received! // a packet is ready to be received!
let n = receive_packet_over_spi(buf).await; let n = receive_packet_over_spi(buf).await;
rx_chan.rx_done(n); rx_chan.rx_done(n);
} }
Either::Second(buf) => { Either::Second(buf) => {
// a packet is ready to be sent! // a packet is ready to be sent!
send_packet_over_spi(buf).await; send_packet_over_spi(buf).await;
tx_chan.tx_done(); tx_chan.tx_done();
} }
} }
@ -81,10 +79,12 @@ These `embassy-net` drivers are implemented using this crate. You can look at th
- [`embassy-net-wiznet`](https://github.com/embassy-rs/embassy/tree/main/embassy-net-wiznet) for Wiznet SPI Ethernet MAC+PHY chips. - [`embassy-net-wiznet`](https://github.com/embassy-rs/embassy/tree/main/embassy-net-wiznet) for Wiznet SPI Ethernet MAC+PHY chips.
- [`embassy-net-esp-hosted`](https://github.com/embassy-rs/embassy/tree/main/embassy-net-esp-hosted) for using ESP32 chips with the [`esp-hosted`](https://github.com/espressif/esp-hosted) firmware as WiFi adapters for another non-ESP32 MCU. - [`embassy-net-esp-hosted`](https://github.com/embassy-rs/embassy/tree/main/embassy-net-esp-hosted) for using ESP32 chips with the [`esp-hosted`](https://github.com/espressif/esp-hosted) firmware as WiFi adapters for another non-ESP32 MCU.
## Interoperability ## Interoperability
This crate can run on any executor. This crate can run on any executor.
## License ## License
This work is licensed under either of This work is licensed under either of

View File

@ -8,8 +8,9 @@ use core::cell::RefCell;
use core::mem::MaybeUninit; use core::mem::MaybeUninit;
use core::task::{Context, Poll}; use core::task::{Context, Poll};
use driver::HardwareAddress;
pub use embassy_net_driver as driver; pub use embassy_net_driver as driver;
use embassy_net_driver::{Capabilities, LinkState}; use embassy_net_driver::{Capabilities, LinkState, Medium};
use embassy_sync::blocking_mutex::raw::NoopRawMutex; use embassy_sync::blocking_mutex::raw::NoopRawMutex;
use embassy_sync::blocking_mutex::Mutex; use embassy_sync::blocking_mutex::Mutex;
use embassy_sync::waitqueue::WakerRegistration; use embassy_sync::waitqueue::WakerRegistration;
@ -160,10 +161,18 @@ impl<'d> StateRunner<'d> {
}); });
} }
pub fn set_hardware_address(&self, address: driver::HardwareAddress) { pub fn set_ethernet_address(&self, address: [u8; 6]) {
self.shared.lock(|s| { self.shared.lock(|s| {
let s = &mut *s.borrow_mut(); let s = &mut *s.borrow_mut();
s.hardware_address = address; s.hardware_address = driver::HardwareAddress::Ethernet(address);
s.waker.wake();
});
}
pub fn set_ieee802154_address(&self, address: [u8; 8]) {
self.shared.lock(|s| {
let s = &mut *s.borrow_mut();
s.hardware_address = driver::HardwareAddress::Ieee802154(address);
s.waker.wake(); s.waker.wake();
}); });
} }
@ -223,6 +232,11 @@ pub fn new<'d, const MTU: usize, const N_RX: usize, const N_TX: usize>(
) -> (Runner<'d, MTU>, Device<'d, MTU>) { ) -> (Runner<'d, MTU>, Device<'d, MTU>) {
let mut caps = Capabilities::default(); let mut caps = Capabilities::default();
caps.max_transmission_unit = MTU; caps.max_transmission_unit = MTU;
caps.medium = match &hardware_address {
HardwareAddress::Ethernet(_) => Medium::Ethernet,
HardwareAddress::Ieee802154(_) => Medium::Ieee802154,
HardwareAddress::Ip => Medium::Ip,
};
// safety: this is a self-referential struct, however: // safety: this is a self-referential struct, however:
// - it can't move while the `'d` borrow is active. // - it can't move while the `'d` borrow is active.

View File

@ -1,17 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## 0.2.0 - 2023-10-18
- Added support for IEEE 802.15.4 mediums.
- Added `Driver::hardware_address()`, `HardwareAddress`.
- Removed `Medium` enum. The medium is deduced out of the hardware address.
- Removed `Driver::ethernet_address()`. Replacement is `hardware_address()`.
## 0.1.0 - 2023-06-29
- First release

View File

@ -1,6 +1,6 @@
[package] [package]
name = "embassy-net-driver" name = "embassy-net-driver"
version = "0.2.0" version = "0.1.0"
edition = "2021" edition = "2021"
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
description = "Driver trait for the `embassy-net` async TCP/IP network stack." description = "Driver trait for the `embassy-net` async TCP/IP network stack."

View File

@ -7,23 +7,12 @@ use core::task::Context;
/// Representation of an hardware address, such as an Ethernet address or an IEEE802.15.4 address. /// Representation of an hardware address, such as an Ethernet address or an IEEE802.15.4 address.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))] #[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum HardwareAddress { pub enum HardwareAddress {
/// Ethernet medium, with a A six-octet Ethernet address. /// A six-octet Ethernet address
///
/// Devices of this type send and receive Ethernet frames,
/// and interfaces using it must do neighbor discovery via ARP or NDISC.
///
/// Examples of devices of this type are Ethernet, WiFi (802.11), Linux `tap`, and VPNs in tap (layer 2) mode.
Ethernet([u8; 6]), Ethernet([u8; 6]),
/// 6LoWPAN over IEEE802.15.4, with an eight-octet address. /// An eight-octet IEEE802.15.4 address
Ieee802154([u8; 8]), Ieee802154([u8; 8]),
/// Indicates that a Driver is IP-native, and has no hardware address. /// Indicates that a Driver is IP-native, and has no hardware address
///
/// Devices of this type send and receive IP frames, without an
/// Ethernet header. MAC addresses are not used, and no neighbor discovery (ARP, NDISC) is done.
///
/// Examples of devices of this type are the Linux `tun`, PPP interfaces, VPNs in tun (layer 3) mode.
Ip, Ip,
} }
@ -75,10 +64,6 @@ pub trait Driver {
fn capabilities(&self) -> Capabilities; fn capabilities(&self) -> Capabilities;
/// Get the device's hardware address. /// Get the device's hardware address.
///
/// The returned hardware address also determines the "medium" of this driver. This indicates
/// what kind of packet the sent/received bytes are, and determines some behaviors of
/// the interface. For example, ARP/NDISC address resolution is only done for Ethernet mediums.
fn hardware_address(&self) -> HardwareAddress; fn hardware_address(&self) -> HardwareAddress;
} }
@ -139,6 +124,13 @@ pub trait TxToken {
#[cfg_attr(feature = "defmt", derive(defmt::Format))] #[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive] #[non_exhaustive]
pub struct Capabilities { pub struct Capabilities {
/// Medium of the device.
///
/// This indicates what kind of packet the sent/received bytes are, and determines
/// some behaviors of Interface. For example, ARP/NDISC address resolution is only done
/// for Ethernet mediums.
pub medium: Medium,
/// Maximum transmission unit. /// Maximum transmission unit.
/// ///
/// The network device is unable to send or receive frames larger than the value returned /// The network device is unable to send or receive frames larger than the value returned
@ -169,6 +161,32 @@ pub struct Capabilities {
pub checksum: ChecksumCapabilities, pub checksum: ChecksumCapabilities,
} }
/// Type of medium of a device.
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Medium {
/// Ethernet medium. Devices of this type send and receive Ethernet frames,
/// and interfaces using it must do neighbor discovery via ARP or NDISC.
///
/// Examples of devices of this type are Ethernet, WiFi (802.11), Linux `tap`, and VPNs in tap (layer 2) mode.
Ethernet,
/// IP medium. Devices of this type send and receive IP frames, without an
/// Ethernet header. MAC addresses are not used, and no neighbor discovery (ARP, NDISC) is done.
///
/// Examples of devices of this type are the Linux `tun`, PPP interfaces, VPNs in tun (layer 3) mode.
Ip,
/// IEEE 802_15_4 medium
Ieee802154,
}
impl Default for Medium {
fn default() -> Medium {
Medium::Ethernet
}
}
/// A description of checksum behavior for every supported protocol. /// A description of checksum behavior for every supported protocol.
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))] #[cfg_attr(feature = "defmt", derive(defmt::Format))]

View File

@ -10,8 +10,8 @@ edition = "2021"
[dependencies] [dependencies]
embedded-hal = { version = "1.0.0-rc.1" } embedded-hal = { version = "1.0.0-rc.1" }
embedded-hal-async = { version = "=1.0.0-rc.1" } embedded-hal-async = { version = "=1.0.0-rc.1" }
embassy-net-driver = { version = "0.2.0", path = "../embassy-net-driver" } embassy-net-driver = { version = "0.1.0", path = "../embassy-net-driver" }
embassy-time = { version = "0.1.5", path = "../embassy-time" } embassy-time = { version = "0.1.3", path = "../embassy-time" }
embassy-futures = { version = "0.1.0", path = "../embassy-futures" } embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
defmt = { version = "0.3", optional = true } defmt = { version = "0.3", optional = true }

View File

@ -19,7 +19,7 @@ mod traits;
use core::cmp; use core::cmp;
use core::convert::TryInto; use core::convert::TryInto;
use embassy_net_driver::{Capabilities, HardwareAddress, LinkState}; use embassy_net_driver::{Capabilities, HardwareAddress, LinkState, Medium};
use embassy_time::Duration; use embassy_time::Duration;
use embedded_hal::digital::OutputPin; use embedded_hal::digital::OutputPin;
use embedded_hal::spi::{Operation, SpiDevice}; use embedded_hal::spi::{Operation, SpiDevice};
@ -671,6 +671,7 @@ where
fn capabilities(&self) -> Capabilities { fn capabilities(&self) -> Capabilities {
let mut caps = Capabilities::default(); let mut caps = Capabilities::default();
caps.max_transmission_unit = MTU; caps.max_transmission_unit = MTU;
caps.medium = Medium::Ethernet;
caps caps
} }

View File

@ -7,17 +7,17 @@ edition = "2021"
defmt = { version = "0.3", optional = true } defmt = { version = "0.3", optional = true }
log = { version = "0.4.14", optional = true } log = { version = "0.4.14", optional = true }
embassy-time = { version = "0.1.5", path = "../embassy-time" } embassy-time = { version = "0.1.3", path = "../embassy-time" }
embassy-sync = { version = "0.4.0", path = "../embassy-sync"} embassy-sync = { version = "0.3.0", path = "../embassy-sync"}
embassy-futures = { version = "0.1.0", path = "../embassy-futures"} embassy-futures = { version = "0.1.0", path = "../embassy-futures"}
embassy-net-driver-channel = { version = "0.2.0", path = "../embassy-net-driver-channel"} embassy-net-driver-channel = { version = "0.1.0", path = "../embassy-net-driver-channel"}
embedded-hal = { version = "1.0.0-rc.1" } embedded-hal = { version = "1.0.0-rc.1" }
embedded-hal-async = { version = "=1.0.0-rc.1" } embedded-hal-async = { version = "=1.0.0-rc.1" }
noproto = { git="https://github.com/embassy-rs/noproto", rev = "f5e6d1f325b6ad4e344f60452b09576e24671f62", default-features = false, features = ["derive"] } noproto = { git="https://github.com/embassy-rs/noproto", default-features = false, features = ["derive"] }
#noproto = { version = "0.1", path = "/home/dirbaio/noproto", default-features = false, features = ["derive"] } #noproto = { version = "0.1", path = "/home/dirbaio/noproto", default-features = false, features = ["derive"] }
heapless = "0.8" heapless = "0.7.16"
[package.metadata.embassy_docs] [package.metadata.embassy_docs]
src_base = "https://github.com/embassy-rs/embassy/blob/embassy-net-esp-hosted-v$VERSION/embassy-net-esp-hosted/src/" src_base = "https://github.com/embassy-rs/embassy/blob/embassy-net-esp-hosted-v$VERSION/embassy-net-esp-hosted/src/"

View File

@ -1,5 +1,5 @@
use ch::driver::LinkState;
use embassy_net_driver_channel as ch; use embassy_net_driver_channel as ch;
use embassy_net_driver_channel::driver::{HardwareAddress, LinkState};
use heapless::String; use heapless::String;
use crate::ioctl::Shared; use crate::ioctl::Shared;
@ -77,7 +77,7 @@ impl<'a> Control<'a> {
let mac_addr = self.get_mac_addr().await?; let mac_addr = self.get_mac_addr().await?;
debug!("mac addr: {:02x}", mac_addr); debug!("mac addr: {:02x}", mac_addr);
self.state_ch.set_hardware_address(HardwareAddress::Ethernet(mac_addr)); self.state_ch.set_ethernet_address(mac_addr);
Ok(()) Ok(())
} }
@ -97,8 +97,8 @@ impl<'a> Control<'a> {
pub async fn connect(&mut self, ssid: &str, password: &str) -> Result<(), Error> { pub async fn connect(&mut self, ssid: &str, password: &str) -> Result<(), Error> {
let req = proto::CtrlMsgReqConnectAp { let req = proto::CtrlMsgReqConnectAp {
ssid: unwrap!(String::try_from(ssid)), ssid: String::from(ssid),
pwd: unwrap!(String::try_from(password)), pwd: String::from(password),
bssid: String::new(), bssid: String::new(),
listen_interval: 3, listen_interval: 3,
is_wpa3_supported: false, is_wpa3_supported: false,

View File

@ -169,9 +169,9 @@ where
pub async fn run(mut self) -> ! { pub async fn run(mut self) -> ! {
debug!("resetting..."); debug!("resetting...");
self.reset.set_low().unwrap(); self.reset.set_low().unwrap();
Timer::after_millis(100).await; Timer::after(Duration::from_millis(100)).await;
self.reset.set_high().unwrap(); self.reset.set_high().unwrap();
Timer::after_millis(1000).await; Timer::after(Duration::from_millis(1000)).await;
let mut tx_buf = [0u8; MAX_SPI_BUFFER_SIZE]; let mut tx_buf = [0u8; MAX_SPI_BUFFER_SIZE];
let mut rx_buf = [0u8; MAX_SPI_BUFFER_SIZE]; let mut rx_buf = [0u8; MAX_SPI_BUFFER_SIZE];

View File

@ -16,10 +16,10 @@ defmt = { version = "0.3", optional = true }
log = { version = "0.4.14", optional = true } log = { version = "0.4.14", optional = true }
embedded-io-async = { version = "0.6.0" } embedded-io-async = { version = "0.6.0" }
embassy-net-driver-channel = { version = "0.2.0", path = "../embassy-net-driver-channel" } embassy-net-driver-channel = { version = "0.1.0", path = "../embassy-net-driver-channel" }
embassy-futures = { version = "0.1.0", path = "../embassy-futures" } embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
ppproto = { version = "0.1.2"} ppproto = { version = "0.1.2"}
embassy-sync = { version = "0.4.0", path = "../embassy-sync" } embassy-sync = { version = "0.3.0", path = "../embassy-sync" }
[package.metadata.embassy_docs] [package.metadata.embassy_docs]
src_base = "https://github.com/embassy-rs/embassy/blob/embassy-net-ppp-v$VERSION/embassy-net-ppp/src/" src_base = "https://github.com/embassy-rs/embassy/blob/embassy-net-ppp-v$VERSION/embassy-net-ppp/src/"

View File

@ -8,7 +8,7 @@ license = "MIT OR Apache-2.0"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
embassy-net-driver = { version = "0.2.0", path = "../embassy-net-driver" } embassy-net-driver = { version = "0.1.0", path = "../embassy-net-driver" }
async-io = "1.6.0" async-io = "1.6.0"
log = "0.4.14" log = "0.4.14"
libc = "0.2.101" libc = "0.2.101"

View File

@ -10,8 +10,8 @@ edition = "2021"
[dependencies] [dependencies]
embedded-hal = { version = "1.0.0-rc.1" } embedded-hal = { version = "1.0.0-rc.1" }
embedded-hal-async = { version = "=1.0.0-rc.1" } embedded-hal-async = { version = "=1.0.0-rc.1" }
embassy-net-driver-channel = { version = "0.2.0", path = "../embassy-net-driver-channel" } embassy-net-driver-channel = { version = "0.1.0", path = "../embassy-net-driver-channel" }
embassy-time = { version = "0.1.5", path = "../embassy-time" } embassy-time = { version = "0.1.3", path = "../embassy-time" }
embassy-futures = { version = "0.1.0", path = "../embassy-futures" } embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
defmt = { version = "0.3", optional = true } defmt = { version = "0.3", optional = true }

View File

@ -1,15 +1,14 @@
//! [`embassy-net`](https://crates.io/crates/embassy-net) driver for WIZnet ethernet chips.
#![no_std] #![no_std]
#![feature(async_fn_in_trait)] #![feature(async_fn_in_trait)]
#![allow(stable_features, unknown_lints, async_fn_in_trait)]
#![doc = include_str!("../README.md")]
pub mod chip; pub mod chip;
mod device; mod device;
use embassy_futures::select::{select3, Either3}; use embassy_futures::select::{select, Either};
use embassy_net_driver_channel as ch; use embassy_net_driver_channel as ch;
use embassy_net_driver_channel::driver::LinkState; use embassy_net_driver_channel::driver::LinkState;
use embassy_time::{Duration, Ticker, Timer}; use embassy_time::{Duration, Timer};
use embedded_hal::digital::OutputPin; use embedded_hal::digital::OutputPin;
use embedded_hal_async::digital::Wait; use embedded_hal_async::digital::Wait;
use embedded_hal_async::spi::SpiDevice; use embedded_hal_async::spi::SpiDevice;
@ -50,34 +49,32 @@ pub struct Runner<'d, C: Chip, SPI: SpiDevice, INT: Wait, RST: OutputPin> {
impl<'d, C: Chip, SPI: SpiDevice, INT: Wait, RST: OutputPin> Runner<'d, C, SPI, INT, RST> { impl<'d, C: Chip, SPI: SpiDevice, INT: Wait, RST: OutputPin> Runner<'d, C, SPI, INT, RST> {
pub async fn run(mut self) -> ! { pub async fn run(mut self) -> ! {
let (state_chan, mut rx_chan, mut tx_chan) = self.ch.split(); let (state_chan, mut rx_chan, mut tx_chan) = self.ch.split();
let mut tick = Ticker::every(Duration::from_millis(500));
loop { loop {
match select3( if self.mac.is_link_up().await {
async { state_chan.set_link_state(LinkState::Up);
self.int.wait_for_low().await.ok(); loop {
rx_chan.rx_buf().await match select(
}, async {
tx_chan.tx_buf(), self.int.wait_for_low().await.ok();
tick.next(), rx_chan.rx_buf().await
) },
.await tx_chan.tx_buf(),
{ )
Either3::First(p) => { .await
if let Ok(n) = self.mac.read_frame(p).await { {
rx_chan.rx_done(n); Either::First(p) => {
} if let Ok(n) = self.mac.read_frame(p).await {
} rx_chan.rx_done(n);
Either3::Second(p) => { }
self.mac.write_frame(p).await.ok(); }
tx_chan.tx_done(); Either::Second(p) => {
} self.mac.write_frame(p).await.ok();
Either3::Third(()) => { tx_chan.tx_done();
if self.mac.is_link_up().await { }
state_chan.set_link_state(LinkState::Up);
} else {
state_chan.set_link_state(LinkState::Down);
} }
} }
} else {
state_chan.set_link_state(LinkState::Down);
} }
} }
} }
@ -98,12 +95,12 @@ pub async fn new<'a, const N_RX: usize, const N_TX: usize, C: Chip, SPI: SpiDevi
// Reset the chip. // Reset the chip.
reset.set_low().ok(); reset.set_low().ok();
// Ensure the reset is registered. // Ensure the reset is registered.
Timer::after_millis(1).await; Timer::after(Duration::from_millis(1)).await;
reset.set_high().ok(); reset.set_high().ok();
// Wait for PLL lock. Some chips are slower than others. // Wait for PLL lock. Some chips are slower than others.
// Slowest is w5100s which is 100ms, so let's just wait that. // Slowest is w5100s which is 100ms, so let's just wait that.
Timer::after_millis(100).await; Timer::after(Duration::from_millis(100)).await;
let mac = WiznetDevice::new(spi_dev, mac_addr).await.unwrap(); let mac = WiznetDevice::new(spi_dev, mac_addr).await.unwrap();

View File

@ -1,40 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Unreleased
- Avoid never resolving `TcpIo::read` when the output buffer is empty.
- Update to `smoltcp` git.
- Forward constants from `smoltcp` in DNS query results so changing DNS result size in `smoltcp` properly propagates.
## 0.2.1 - 2023-10-31
- Re-add impl_trait_projections
- Fix: Reset DHCP socket when the link up is detected
## 0.2.0 - 2023-10-18
- Re-export `smoltcp::wire::IpEndpoint`
- Add poll functions on UdpSocket
- Make dual-stack work in embassy-net
- Fix multicast support
- Allow ethernet and 802.15.4 to coexist
- Add IEEE802.15.4 address to embassy net Stack
- Use HardwareAddress in Driver
- Add async versions of smoltcp's `send` and `recv` closure based API
- add error translation to tcp errors
- Forward TCP/UDP socket capacity impls
- allow changing IP config at runtime
- allow non-'static drivers
- Remove impl_trait_projections
- update embedded-io, embedded-nal-async
- add support for dhcp hostname option
- Wake stack's task after queueing a DNS query
## 0.1.0 - 2023-06-29
- First release

View File

@ -1,6 +1,6 @@
[package] [package]
name = "embassy-net" name = "embassy-net"
version = "0.2.1" version = "0.1.0"
edition = "2021" edition = "2021"
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
description = "Async TCP/IP network stack for embedded systems" description = "Async TCP/IP network stack for embedded systems"
@ -25,7 +25,7 @@ features = ["nightly", "defmt", "tcp", "udp", "dns", "dhcpv4", "proto-ipv6", "me
default = [] default = []
std = [] std = []
defmt = ["dep:defmt", "smoltcp/defmt", "embassy-net-driver/defmt", "heapless/defmt-03"] defmt = ["dep:defmt", "smoltcp/defmt", "embassy-net-driver/defmt"]
nightly = ["dep:embedded-io-async", "dep:embedded-nal-async"] nightly = ["dep:embedded-io-async", "dep:embedded-nal-async"]
@ -46,21 +46,22 @@ igmp = ["smoltcp/proto-igmp"]
defmt = { version = "0.3", optional = true } defmt = { version = "0.3", optional = true }
log = { version = "0.4.14", optional = true } log = { version = "0.4.14", optional = true }
smoltcp = { git = "https://github.com/smoltcp-rs/smoltcp.git", rev = "b57e2f9e70e82a13f31d5ea17e55232c11cc2b2d", default-features = false, features = [ smoltcp = { version = "0.10.0", default-features = false, features = [
"socket", "socket",
"async", "async",
] } ] }
embassy-net-driver = { version = "0.2.0", path = "../embassy-net-driver" } embassy-net-driver = { version = "0.1.0", path = "../embassy-net-driver" }
embassy-time = { version = "0.1.5", path = "../embassy-time" } embassy-time = { version = "0.1.3", path = "../embassy-time" }
embassy-sync = { version = "0.4.0", path = "../embassy-sync" } embassy-sync = { version = "0.3.0", path = "../embassy-sync" }
embedded-io-async = { version = "0.6.0", optional = true } embedded-io-async = { version = "0.6.0", optional = true }
managed = { version = "0.8.0", default-features = false, features = [ "map" ] } managed = { version = "0.8.0", default-features = false, features = [ "map" ] }
heapless = { version = "0.8", default-features = false } heapless = { version = "0.7.5", default-features = false }
as-slice = "0.2.1" as-slice = "0.2.1"
generic-array = { version = "0.14.4", default-features = false } generic-array = { version = "0.14.4", default-features = false }
stable_deref_trait = { version = "1.2.0", default-features = false } stable_deref_trait = { version = "1.2.0", default-features = false }
futures = { version = "0.3.17", default-features = false, features = [ "async-await" ] } futures = { version = "0.3.17", default-features = false, features = [ "async-await" ] }
atomic-pool = "1.0" atomic-pool = "1.0"
embedded-nal-async = { version = "0.7", optional = true } embedded-nal-async = { version = "0.6.0", optional = true }
atomic-polyfill = { version = "1.0" }

View File

@ -4,7 +4,7 @@
It builds on [`smoltcp`](https://github.com/smoltcp-rs/smoltcp). It provides a higher-level and more opinionated It builds on [`smoltcp`](https://github.com/smoltcp-rs/smoltcp). It provides a higher-level and more opinionated
API. It glues together the components provided by `smoltcp`, handling the low-level details with defaults and API. It glues together the components provided by `smoltcp`, handling the low-level details with defaults and
memory management designed to work well for embedded systems, aiming for a more "Just Works" experience. memory management designed to work well for embedded systems, aiiming for a more "Just Works" experience.
## Features ## Features

View File

@ -1,7 +1,7 @@
use core::task::Context; use core::task::Context;
use embassy_net_driver::{Capabilities, Checksum, Driver, RxToken, TxToken}; use embassy_net_driver::{Capabilities, Checksum, Driver, Medium, RxToken, TxToken};
use smoltcp::phy::{self, Medium}; use smoltcp::phy;
use smoltcp::time::Instant; use smoltcp::time::Instant;
pub(crate) struct DriverAdapter<'d, 'c, T> pub(crate) struct DriverAdapter<'d, 'c, T>
@ -11,7 +11,6 @@ where
// must be Some when actually using this to rx/tx // must be Some when actually using this to rx/tx
pub cx: Option<&'d mut Context<'c>>, pub cx: Option<&'d mut Context<'c>>,
pub inner: &'d mut T, pub inner: &'d mut T,
pub medium: Medium,
} }
impl<'d, 'c, T> phy::Device for DriverAdapter<'d, 'c, T> impl<'d, 'c, T> phy::Device for DriverAdapter<'d, 'c, T>
@ -47,7 +46,19 @@ where
smolcaps.max_transmission_unit = caps.max_transmission_unit; smolcaps.max_transmission_unit = caps.max_transmission_unit;
smolcaps.max_burst_size = caps.max_burst_size; smolcaps.max_burst_size = caps.max_burst_size;
smolcaps.medium = self.medium; smolcaps.medium = match caps.medium {
#[cfg(feature = "medium-ethernet")]
Medium::Ethernet => phy::Medium::Ethernet,
#[cfg(feature = "medium-ip")]
Medium::Ip => phy::Medium::Ip,
#[cfg(feature = "medium-ieee802154")]
Medium::Ieee802154 => phy::Medium::Ieee802154,
#[allow(unreachable_patterns)]
_ => panic!(
"Unsupported medium {:?}. Make sure to enable it in embassy-net's Cargo features.",
caps.medium
),
};
smolcaps.checksum.ipv4 = convert(caps.checksum.ipv4); smolcaps.checksum.ipv4 = convert(caps.checksum.ipv4);
smolcaps.checksum.tcp = convert(caps.checksum.tcp); smolcaps.checksum.tcp = convert(caps.checksum.tcp);
smolcaps.checksum.udp = convert(caps.checksum.udp); smolcaps.checksum.udp = convert(caps.checksum.udp);

View File

@ -63,11 +63,7 @@ where
} }
/// Make a query for a given name and return the corresponding IP addresses. /// Make a query for a given name and return the corresponding IP addresses.
pub async fn query( pub async fn query(&self, name: &str, qtype: DnsQueryType) -> Result<Vec<IpAddress, 1>, Error> {
&self,
name: &str,
qtype: DnsQueryType,
) -> Result<Vec<IpAddress, { smoltcp::config::DNS_MAX_RESULT_COUNT }>, Error> {
self.stack.dns_query(name, qtype).await self.stack.dns_query(name, qtype).await
} }
} }
@ -105,8 +101,7 @@ where
async fn get_host_by_address( async fn get_host_by_address(
&self, &self,
_addr: embedded_nal_async::IpAddr, _addr: embedded_nal_async::IpAddr,
_result: &mut [u8], ) -> Result<heapless::String<256>, Self::Error> {
) -> Result<usize, Self::Error> {
todo!() todo!()
} }
} }

View File

@ -1,6 +1,5 @@
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait, impl_trait_projections))] #![cfg_attr(feature = "nightly", feature(async_fn_in_trait))]
#![cfg_attr(feature = "nightly", allow(stable_features, unknown_lints, async_fn_in_trait))]
#![warn(missing_docs)] #![warn(missing_docs)]
#![doc = include_str!("../README.md")] #![doc = include_str!("../README.md")]
@ -34,7 +33,6 @@ use heapless::Vec;
pub use smoltcp::iface::MulticastError; pub use smoltcp::iface::MulticastError;
#[allow(unused_imports)] #[allow(unused_imports)]
use smoltcp::iface::{Interface, SocketHandle, SocketSet, SocketStorage}; use smoltcp::iface::{Interface, SocketHandle, SocketSet, SocketStorage};
use smoltcp::phy::Medium;
#[cfg(feature = "dhcpv4")] #[cfg(feature = "dhcpv4")]
use smoltcp::socket::dhcpv4::{self, RetryConfig}; use smoltcp::socket::dhcpv4::{self, RetryConfig};
#[cfg(feature = "medium-ethernet")] #[cfg(feature = "medium-ethernet")]
@ -266,17 +264,14 @@ pub(crate) struct SocketStack {
next_local_port: u16, next_local_port: u16,
} }
fn to_smoltcp_hardware_address(addr: driver::HardwareAddress) -> (HardwareAddress, Medium) { fn to_smoltcp_hardware_address(addr: driver::HardwareAddress) -> HardwareAddress {
match addr { match addr {
#[cfg(feature = "medium-ethernet")] #[cfg(feature = "medium-ethernet")]
driver::HardwareAddress::Ethernet(eth) => (HardwareAddress::Ethernet(EthernetAddress(eth)), Medium::Ethernet), driver::HardwareAddress::Ethernet(eth) => HardwareAddress::Ethernet(EthernetAddress(eth)),
#[cfg(feature = "medium-ieee802154")] #[cfg(feature = "medium-ieee802154")]
driver::HardwareAddress::Ieee802154(ieee) => ( driver::HardwareAddress::Ieee802154(ieee) => HardwareAddress::Ieee802154(Ieee802154Address::Extended(ieee)),
HardwareAddress::Ieee802154(Ieee802154Address::Extended(ieee)),
Medium::Ieee802154,
),
#[cfg(feature = "medium-ip")] #[cfg(feature = "medium-ip")]
driver::HardwareAddress::Ip => (HardwareAddress::Ip, Medium::Ip), driver::HardwareAddress::Ip => HardwareAddress::Ip,
#[allow(unreachable_patterns)] #[allow(unreachable_patterns)]
_ => panic!( _ => panic!(
@ -294,8 +289,7 @@ impl<D: Driver> Stack<D> {
resources: &'static mut StackResources<SOCK>, resources: &'static mut StackResources<SOCK>,
random_seed: u64, random_seed: u64,
) -> Self { ) -> Self {
let (hardware_addr, medium) = to_smoltcp_hardware_address(device.hardware_address()); let mut iface_cfg = smoltcp::iface::Config::new(to_smoltcp_hardware_address(device.hardware_address()));
let mut iface_cfg = smoltcp::iface::Config::new(hardware_addr);
iface_cfg.random_seed = random_seed; iface_cfg.random_seed = random_seed;
let iface = Interface::new( let iface = Interface::new(
@ -303,7 +297,6 @@ impl<D: Driver> Stack<D> {
&mut DriverAdapter { &mut DriverAdapter {
inner: &mut device, inner: &mut device,
cx: None, cx: None,
medium,
}, },
instant_to_smoltcp(Instant::now()), instant_to_smoltcp(Instant::now()),
); );
@ -363,7 +356,7 @@ impl<D: Driver> Stack<D> {
/// Get the hardware address of the network interface. /// Get the hardware address of the network interface.
pub fn hardware_address(&self) -> HardwareAddress { pub fn hardware_address(&self) -> HardwareAddress {
self.with(|_s, i| to_smoltcp_hardware_address(i.device.hardware_address()).0) self.with(|_s, i| to_smoltcp_hardware_address(i.device.hardware_address()))
} }
/// Get whether the link is up. /// Get whether the link is up.
@ -494,11 +487,7 @@ impl<D: Driver> Stack<D> {
/// Make a query for a given name and return the corresponding IP addresses. /// Make a query for a given name and return the corresponding IP addresses.
#[cfg(feature = "dns")] #[cfg(feature = "dns")]
pub async fn dns_query( pub async fn dns_query(&self, name: &str, qtype: dns::DnsQueryType) -> Result<Vec<IpAddress, 1>, dns::Error> {
&self,
name: &str,
qtype: dns::DnsQueryType,
) -> Result<Vec<IpAddress, { smoltcp::config::DNS_MAX_RESULT_COUNT }>, dns::Error> {
// For A and AAAA queries we try detect whether `name` is just an IP address // For A and AAAA queries we try detect whether `name` is just an IP address
match qtype { match qtype {
#[cfg(feature = "proto-ipv4")] #[cfg(feature = "proto-ipv4")]
@ -520,10 +509,7 @@ impl<D: Driver> Stack<D> {
self.with_mut(|s, i| { self.with_mut(|s, i| {
let socket = s.sockets.get_mut::<dns::Socket>(i.dns_socket); let socket = s.sockets.get_mut::<dns::Socket>(i.dns_socket);
match socket.start_query(s.iface.context(), name, qtype) { match socket.start_query(s.iface.context(), name, qtype) {
Ok(handle) => { Ok(handle) => Poll::Ready(Ok(handle)),
s.waker.wake();
Poll::Ready(Ok(handle))
}
Err(dns::StartQueryError::NoFreeSlot) => { Err(dns::StartQueryError::NoFreeSlot) => {
i.dns_waker.register(cx.waker()); i.dns_waker.register(cx.waker());
Poll::Pending Poll::Pending
@ -823,28 +809,18 @@ impl<D: Driver> Inner<D> {
fn poll(&mut self, cx: &mut Context<'_>, s: &mut SocketStack) { fn poll(&mut self, cx: &mut Context<'_>, s: &mut SocketStack) {
s.waker.register(cx.waker()); s.waker.register(cx.waker());
let (_hardware_addr, medium) = to_smoltcp_hardware_address(self.device.hardware_address());
#[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))] #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))]
if self.device.capabilities().medium == embassy_net_driver::Medium::Ethernet
|| self.device.capabilities().medium == embassy_net_driver::Medium::Ieee802154
{ {
let do_set = match medium { s.iface
#[cfg(feature = "medium-ethernet")] .set_hardware_addr(to_smoltcp_hardware_address(self.device.hardware_address()));
Medium::Ethernet => true,
#[cfg(feature = "medium-ieee802154")]
Medium::Ieee802154 => true,
#[allow(unreachable_patterns)]
_ => false,
};
if do_set {
s.iface.set_hardware_addr(_hardware_addr);
}
} }
let timestamp = instant_to_smoltcp(Instant::now()); let timestamp = instant_to_smoltcp(Instant::now());
let mut smoldev = DriverAdapter { let mut smoldev = DriverAdapter {
cx: Some(cx), cx: Some(cx),
inner: &mut self.device, inner: &mut self.device,
medium,
}; };
s.iface.poll(timestamp, &mut smoldev, &mut s.sockets); s.iface.poll(timestamp, &mut smoldev, &mut s.sockets);
@ -865,9 +841,6 @@ impl<D: Driver> Inner<D> {
let socket = s.sockets.get_mut::<dhcpv4::Socket>(dhcp_handle); let socket = s.sockets.get_mut::<dhcpv4::Socket>(dhcp_handle);
if self.link_up { if self.link_up {
if old_link_up != self.link_up {
socket.reset();
}
match socket.poll() { match socket.poll() {
None => {} None => {}
Some(dhcpv4::Event::Deconfigured) => { Some(dhcpv4::Event::Deconfigured) => {

View File

@ -390,13 +390,6 @@ impl<'d> TcpIo<'d> {
// CAUTION: smoltcp semantics around EOF are different to what you'd expect // CAUTION: smoltcp semantics around EOF are different to what you'd expect
// from posix-like IO, so we have to tweak things here. // from posix-like IO, so we have to tweak things here.
self.with_mut(|s, _| match s.recv_slice(buf) { self.with_mut(|s, _| match s.recv_slice(buf) {
// Reading into empty buffer
Ok(0) if buf.is_empty() => {
// embedded_io_async::Read's contract is to not block if buf is empty. While
// this function is not a direct implementor of the trait method, we still don't
// want our future to never resolve.
Poll::Ready(Ok(0))
}
// No data ready // No data ready
Ok(0) => { Ok(0) => {
s.register_recv_waker(cx.waker()); s.register_recv_waker(cx.waker());
@ -586,10 +579,11 @@ mod embedded_io_impls {
/// TCP client compatible with `embedded-nal-async` traits. /// TCP client compatible with `embedded-nal-async` traits.
#[cfg(feature = "nightly")] #[cfg(feature = "nightly")]
pub mod client { pub mod client {
use core::cell::{Cell, UnsafeCell}; use core::cell::UnsafeCell;
use core::mem::MaybeUninit; use core::mem::MaybeUninit;
use core::ptr::NonNull; use core::ptr::NonNull;
use atomic_polyfill::{AtomicBool, Ordering};
use embedded_nal_async::IpAddr; use embedded_nal_async::IpAddr;
use super::*; use super::*;
@ -618,7 +612,10 @@ pub mod client {
async fn connect<'a>( async fn connect<'a>(
&'a self, &'a self,
remote: embedded_nal_async::SocketAddr, remote: embedded_nal_async::SocketAddr,
) -> Result<Self::Connection<'a>, Self::Error> { ) -> Result<Self::Connection<'a>, Self::Error>
where
Self: 'a,
{
let addr: crate::IpAddress = match remote.ip() { let addr: crate::IpAddress = match remote.ip() {
#[cfg(feature = "proto-ipv4")] #[cfg(feature = "proto-ipv4")]
IpAddr::V4(addr) => crate::IpAddress::Ipv4(crate::Ipv4Address::from_bytes(&addr.octets())), IpAddr::V4(addr) => crate::IpAddress::Ipv4(crate::Ipv4Address::from_bytes(&addr.octets())),
@ -705,13 +702,15 @@ pub mod client {
} }
} }
unsafe impl<const N: usize, const TX_SZ: usize, const RX_SZ: usize> Sync for TcpClientState<N, TX_SZ, RX_SZ> {}
struct Pool<T, const N: usize> { struct Pool<T, const N: usize> {
used: [Cell<bool>; N], used: [AtomicBool; N],
data: [UnsafeCell<MaybeUninit<T>>; N], data: [UnsafeCell<MaybeUninit<T>>; N],
} }
impl<T, const N: usize> Pool<T, N> { impl<T, const N: usize> Pool<T, N> {
const VALUE: Cell<bool> = Cell::new(false); const VALUE: AtomicBool = AtomicBool::new(false);
const UNINIT: UnsafeCell<MaybeUninit<T>> = UnsafeCell::new(MaybeUninit::uninit()); const UNINIT: UnsafeCell<MaybeUninit<T>> = UnsafeCell::new(MaybeUninit::uninit());
const fn new() -> Self { const fn new() -> Self {
@ -725,9 +724,7 @@ pub mod client {
impl<T, const N: usize> Pool<T, N> { impl<T, const N: usize> Pool<T, N> {
fn alloc(&self) -> Option<NonNull<T>> { fn alloc(&self) -> Option<NonNull<T>> {
for n in 0..N { for n in 0..N {
// this can't race because Pool is not Sync. if self.used[n].swap(true, Ordering::SeqCst) == false {
if !self.used[n].get() {
self.used[n].set(true);
let p = self.data[n].get() as *mut T; let p = self.data[n].get() as *mut T;
return Some(unsafe { NonNull::new_unchecked(p) }); return Some(unsafe { NonNull::new_unchecked(p) });
} }
@ -741,7 +738,7 @@ pub mod client {
let n = p.as_ptr().offset_from(origin); let n = p.as_ptr().offset_from(origin);
assert!(n >= 0); assert!(n >= 0);
assert!((n as usize) < N); assert!((n as usize) < N);
self.used[n as usize].set(false); self.used[n as usize].store(false, Ordering::SeqCst);
} }
} }
} }

View File

@ -94,8 +94,8 @@ _gpio-p1 = []
_nrf52832_anomaly_109 = [] _nrf52832_anomaly_109 = []
[dependencies] [dependencies]
embassy-time = { version = "0.1.5", path = "../embassy-time", optional = true } embassy-time = { version = "0.1.3", path = "../embassy-time", optional = true }
embassy-sync = { version = "0.4.0", path = "../embassy-sync" } embassy-sync = { version = "0.3.0", path = "../embassy-sync" }
embassy-hal-internal = {version = "0.1.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-3"] } embassy-hal-internal = {version = "0.1.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-3"] }
embassy-embedded-hal = {version = "0.1.0", path = "../embassy-embedded-hal" } embassy-embedded-hal = {version = "0.1.0", path = "../embassy-embedded-hal" }
embassy-usb-driver = {version = "0.1.0", path = "../embassy-usb-driver", optional=true } embassy-usb-driver = {version = "0.1.0", path = "../embassy-usb-driver", optional=true }
@ -110,6 +110,7 @@ defmt = { version = "0.3", optional = true }
log = { version = "0.4.14", optional = true } log = { version = "0.4.14", optional = true }
cortex-m-rt = ">=0.6.15,<0.8" cortex-m-rt = ">=0.6.15,<0.8"
cortex-m = "0.7.6" cortex-m = "0.7.6"
futures = { version = "0.3.17", default-features = false }
critical-section = "1.1" critical-section = "1.1"
rand_core = "0.6.3" rand_core = "0.6.3"
fixed = "1.10.0" fixed = "1.10.0"

View File

@ -12,7 +12,7 @@ use core::cmp::min;
use core::future::poll_fn; use core::future::poll_fn;
use core::marker::PhantomData; use core::marker::PhantomData;
use core::slice; use core::slice;
use core::sync::atomic::{compiler_fence, AtomicBool, AtomicU8, AtomicUsize, Ordering}; use core::sync::atomic::{compiler_fence, AtomicU8, AtomicUsize, Ordering};
use core::task::Poll; use core::task::Poll;
use embassy_hal_internal::atomic_ring_buffer::RingBuffer; use embassy_hal_internal::atomic_ring_buffer::RingBuffer;
@ -41,9 +41,7 @@ mod sealed {
pub rx_waker: AtomicWaker, pub rx_waker: AtomicWaker,
pub rx_buf: RingBuffer, pub rx_buf: RingBuffer,
pub rx_started: AtomicBool, pub rx_bufs: AtomicU8,
pub rx_started_count: AtomicU8,
pub rx_ended_count: AtomicU8,
pub rx_ppi_ch: AtomicU8, pub rx_ppi_ch: AtomicU8,
} }
} }
@ -67,9 +65,7 @@ impl State {
rx_waker: AtomicWaker::new(), rx_waker: AtomicWaker::new(),
rx_buf: RingBuffer::new(), rx_buf: RingBuffer::new(),
rx_started: AtomicBool::new(false), rx_bufs: AtomicU8::new(0),
rx_started_count: AtomicU8::new(0),
rx_ended_count: AtomicU8::new(0),
rx_ppi_ch: AtomicU8::new(0), rx_ppi_ch: AtomicU8::new(0),
} }
} }
@ -108,20 +104,28 @@ impl<U: UarteInstance> interrupt::typelevel::Handler<U::Interrupt> for Interrupt
s.rx_waker.wake(); s.rx_waker.wake();
} }
if r.events_endrx.read().bits() != 0 { // If not RXing, start.
//trace!(" irq_rx: endrx"); if s.rx_bufs.load(Ordering::Relaxed) == 0 {
r.events_endrx.reset(); let (ptr, len) = rx.push_buf();
if len >= half_len {
//trace!(" irq_rx: starting {:?}", half_len);
s.rx_bufs.store(1, Ordering::Relaxed);
let val = s.rx_ended_count.load(Ordering::Relaxed); // Set up the DMA read
s.rx_ended_count.store(val.wrapping_add(1), Ordering::Relaxed); r.rxd.ptr.write(|w| unsafe { w.ptr().bits(ptr as u32) });
r.rxd.maxcnt.write(|w| unsafe { w.maxcnt().bits(half_len as _) });
// Start UARTE Receive transaction
r.tasks_startrx.write(|w| unsafe { w.bits(1) });
rx.push_done(half_len);
r.intenset.write(|w| w.rxstarted().set());
}
} }
if r.events_rxstarted.read().bits() != 0 || !s.rx_started.load(Ordering::Relaxed) { if r.events_rxstarted.read().bits() != 0 {
//trace!(" irq_rx: rxstarted"); //trace!(" irq_rx: rxstarted");
let (ptr, len) = rx.push_buf(); let (ptr, len) = rx.push_buf();
if len >= half_len { if len >= half_len {
r.events_rxstarted.reset();
//trace!(" irq_rx: starting second {:?}", half_len); //trace!(" irq_rx: starting second {:?}", half_len);
// Set up the DMA read // Set up the DMA read
@ -130,50 +134,11 @@ impl<U: UarteInstance> interrupt::typelevel::Handler<U::Interrupt> for Interrupt
let chn = s.rx_ppi_ch.load(Ordering::Relaxed); let chn = s.rx_ppi_ch.load(Ordering::Relaxed);
// Enable endrx -> startrx PPI channel.
// From this point on, if endrx happens, startrx is automatically fired.
ppi::regs().chenset.write(|w| unsafe { w.bits(1 << chn) }); ppi::regs().chenset.write(|w| unsafe { w.bits(1 << chn) });
// It is possible that endrx happened BEFORE enabling the PPI. In this case
// the PPI channel doesn't trigger, and we'd hang. We have to detect this
// and manually start.
// check again in case endrx has happened between the last check and now.
if r.events_endrx.read().bits() != 0 {
//trace!(" irq_rx: endrx");
r.events_endrx.reset();
let val = s.rx_ended_count.load(Ordering::Relaxed);
s.rx_ended_count.store(val.wrapping_add(1), Ordering::Relaxed);
}
let rx_ended = s.rx_ended_count.load(Ordering::Relaxed);
let rx_started = s.rx_started_count.load(Ordering::Relaxed);
// If we started the same amount of transfers as ended, the last rxend has
// already occured.
let rxend_happened = rx_started == rx_ended;
// Check if the PPI channel is still enabled. The PPI channel disables itself
// when it fires, so if it's still enabled it hasn't fired.
let ppi_ch_enabled = ppi::regs().chen.read().bits() & (1 << chn) != 0;
// if rxend happened, and the ppi channel hasn't fired yet, the rxend got missed.
// this condition also naturally matches if `!started`, needed to kickstart the DMA.
if rxend_happened && ppi_ch_enabled {
//trace!("manually starting.");
// disable the ppi ch, it's of no use anymore.
ppi::regs().chenclr.write(|w| unsafe { w.bits(1 << chn) });
// manually start
r.tasks_startrx.write(|w| unsafe { w.bits(1) });
}
rx.push_done(half_len); rx.push_done(half_len);
s.rx_started_count.store(rx_started.wrapping_add(1), Ordering::Relaxed); r.events_rxstarted.reset();
s.rx_started.store(true, Ordering::Relaxed);
} else { } else {
//trace!(" irq_rx: rxstarted no buf"); //trace!(" irq_rx: rxstarted no buf");
r.intenclr.write(|w| w.rxstarted().clear()); r.intenclr.write(|w| w.rxstarted().clear());
@ -317,8 +282,6 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> {
let r = U::regs(); let r = U::regs();
let hwfc = cts.is_some();
rxd.conf().write(|w| w.input().connect().drive().h0h1()); rxd.conf().write(|w| w.input().connect().drive().h0h1());
r.psel.rxd.write(|w| unsafe { w.bits(rxd.psel_bits()) }); r.psel.rxd.write(|w| unsafe { w.bits(rxd.psel_bits()) });
@ -340,8 +303,7 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> {
// Initialize state // Initialize state
let s = U::buffered_state(); let s = U::buffered_state();
s.tx_count.store(0, Ordering::Relaxed); s.tx_count.store(0, Ordering::Relaxed);
s.rx_started_count.store(0, Ordering::Relaxed); s.rx_bufs.store(0, Ordering::Relaxed);
s.rx_ended_count.store(0, Ordering::Relaxed);
let len = tx_buffer.len(); let len = tx_buffer.len();
unsafe { s.tx_buf.init(tx_buffer.as_mut_ptr(), len) }; unsafe { s.tx_buf.init(tx_buffer.as_mut_ptr(), len) };
let len = rx_buffer.len(); let len = rx_buffer.len();
@ -349,7 +311,7 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> {
// Configure // Configure
r.config.write(|w| { r.config.write(|w| {
w.hwfc().bit(hwfc); w.hwfc().bit(false);
w.parity().variant(config.parity); w.parity().variant(config.parity);
w w
}); });
@ -371,7 +333,6 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> {
w.endtx().set(); w.endtx().set();
w.rxstarted().set(); w.rxstarted().set();
w.error().set(); w.error().set();
w.endrx().set();
w w
}); });

View File

@ -6,13 +6,10 @@ pub mod pac {
// To avoid cfg spam, we remove _ns or _s suffixes here. // To avoid cfg spam, we remove _ns or _s suffixes here.
pub use nrf5340_app_pac::NVIC_PRIO_BITS; pub use nrf5340_app_pac::NVIC_PRIO_BITS;
#[cfg(feature="rt")]
#[doc(no_inline)]
pub use nrf5340_app_pac::interrupt;
#[doc(no_inline)] #[doc(no_inline)]
pub use nrf5340_app_pac::{ pub use nrf5340_app_pac::{
interrupt,
Interrupt, Interrupt,
Peripherals, Peripherals,
@ -63,167 +60,156 @@ pub mod pac {
wdt0_ns as wdt0, wdt0_ns as wdt0,
}; };
/// Non-Secure mode (NS) peripherals #[cfg(feature = "nrf5340-app-ns")]
pub mod ns { #[doc(no_inline)]
#[cfg(feature = "nrf5340-app-ns")] pub use nrf5340_app_pac::{
#[doc(no_inline)] CLOCK_NS as CLOCK,
pub use nrf5340_app_pac::{ COMP_NS as COMP,
CLOCK_NS as CLOCK, CTRLAP_NS as CTRLAP,
COMP_NS as COMP, DCNF_NS as DCNF,
CTRLAP_NS as CTRLAP, DPPIC_NS as DPPIC,
DCNF_NS as DCNF, EGU0_NS as EGU0,
DPPIC_NS as DPPIC, EGU1_NS as EGU1,
EGU0_NS as EGU0, EGU2_NS as EGU2,
EGU1_NS as EGU1, EGU3_NS as EGU3,
EGU2_NS as EGU2, EGU4_NS as EGU4,
EGU3_NS as EGU3, EGU5_NS as EGU5,
EGU4_NS as EGU4, FPU_NS as FPU,
EGU5_NS as EGU5, GPIOTE1_NS as GPIOTE1,
FPU_NS as FPU, I2S0_NS as I2S0,
GPIOTE1_NS as GPIOTE1, IPC_NS as IPC,
I2S0_NS as I2S0, KMU_NS as KMU,
IPC_NS as IPC, LPCOMP_NS as LPCOMP,
KMU_NS as KMU, MUTEX_NS as MUTEX,
LPCOMP_NS as LPCOMP, NFCT_NS as NFCT,
MUTEX_NS as MUTEX, NVMC_NS as NVMC,
NFCT_NS as NFCT, OSCILLATORS_NS as OSCILLATORS,
NVMC_NS as NVMC, P0_NS as P0,
OSCILLATORS_NS as OSCILLATORS, P1_NS as P1,
P0_NS as P0, PDM0_NS as PDM0,
P1_NS as P1, POWER_NS as POWER,
PDM0_NS as PDM0, PWM0_NS as PWM0,
POWER_NS as POWER, PWM1_NS as PWM1,
PWM0_NS as PWM0, PWM2_NS as PWM2,
PWM1_NS as PWM1, PWM3_NS as PWM3,
PWM2_NS as PWM2, QDEC0_NS as QDEC0,
PWM3_NS as PWM3, QDEC1_NS as QDEC1,
QDEC0_NS as QDEC0, QSPI_NS as QSPI,
QDEC1_NS as QDEC1, REGULATORS_NS as REGULATORS,
QSPI_NS as QSPI, RESET_NS as RESET,
REGULATORS_NS as REGULATORS, RTC0_NS as RTC0,
RESET_NS as RESET, RTC1_NS as RTC1,
RTC0_NS as RTC0, SAADC_NS as SAADC,
RTC1_NS as RTC1, SPIM0_NS as SPIM0,
SAADC_NS as SAADC, SPIM1_NS as SPIM1,
SPIM0_NS as SPIM0, SPIM2_NS as SPIM2,
SPIM1_NS as SPIM1, SPIM3_NS as SPIM3,
SPIM2_NS as SPIM2, SPIM4_NS as SPIM4,
SPIM3_NS as SPIM3, SPIS0_NS as SPIS0,
SPIM4_NS as SPIM4, SPIS1_NS as SPIS1,
SPIS0_NS as SPIS0, SPIS2_NS as SPIS2,
SPIS1_NS as SPIS1, SPIS3_NS as SPIS3,
SPIS2_NS as SPIS2, TIMER0_NS as TIMER0,
SPIS3_NS as SPIS3, TIMER1_NS as TIMER1,
TIMER0_NS as TIMER0, TIMER2_NS as TIMER2,
TIMER1_NS as TIMER1, TWIM0_NS as TWIM0,
TIMER2_NS as TIMER2, TWIM1_NS as TWIM1,
TWIM0_NS as TWIM0, TWIM2_NS as TWIM2,
TWIM1_NS as TWIM1, TWIM3_NS as TWIM3,
TWIM2_NS as TWIM2, TWIS0_NS as TWIS0,
TWIM3_NS as TWIM3, TWIS1_NS as TWIS1,
TWIS0_NS as TWIS0, TWIS2_NS as TWIS2,
TWIS1_NS as TWIS1, TWIS3_NS as TWIS3,
TWIS2_NS as TWIS2, UARTE0_NS as UARTE0,
TWIS3_NS as TWIS3, UARTE1_NS as UARTE1,
UARTE0_NS as UARTE0, UARTE2_NS as UARTE2,
UARTE1_NS as UARTE1, UARTE3_NS as UARTE3,
UARTE2_NS as UARTE2, USBD_NS as USBD,
UARTE3_NS as UARTE3, USBREGULATOR_NS as USBREGULATOR,
USBD_NS as USBD, VMC_NS as VMC,
USBREGULATOR_NS as USBREGULATOR, WDT0_NS as WDT0,
VMC_NS as VMC, WDT1_NS as WDT1,
WDT0_NS as WDT0, };
WDT1_NS as WDT1,
};
}
/// Secure mode (S) peripherals #[cfg(feature = "nrf5340-app-s")]
pub mod s { #[doc(no_inline)]
#[cfg(feature = "nrf5340-app-s")] pub use nrf5340_app_pac::{
#[doc(no_inline)] CACHEDATA_S as CACHEDATA,
pub use nrf5340_app_pac::{ CACHEINFO_S as CACHEINFO,
CACHEDATA_S as CACHEDATA, CACHE_S as CACHE,
CACHEINFO_S as CACHEINFO, CLOCK_S as CLOCK,
CACHE_S as CACHE, COMP_S as COMP,
CLOCK_S as CLOCK, CRYPTOCELL_S as CRYPTOCELL,
COMP_S as COMP, CTI_S as CTI,
CRYPTOCELL_S as CRYPTOCELL, CTRLAP_S as CTRLAP,
CTI_S as CTI, DCNF_S as DCNF,
CTRLAP_S as CTRLAP, DPPIC_S as DPPIC,
DCNF_S as DCNF, EGU0_S as EGU0,
DPPIC_S as DPPIC, EGU1_S as EGU1,
EGU0_S as EGU0, EGU2_S as EGU2,
EGU1_S as EGU1, EGU3_S as EGU3,
EGU2_S as EGU2, EGU4_S as EGU4,
EGU3_S as EGU3, EGU5_S as EGU5,
EGU4_S as EGU4, FICR_S as FICR,
EGU5_S as EGU5, FPU_S as FPU,
FICR_S as FICR, GPIOTE0_S as GPIOTE0,
FPU_S as FPU, I2S0_S as I2S0,
GPIOTE0_S as GPIOTE0, IPC_S as IPC,
I2S0_S as I2S0, KMU_S as KMU,
IPC_S as IPC, LPCOMP_S as LPCOMP,
KMU_S as KMU, MUTEX_S as MUTEX,
LPCOMP_S as LPCOMP, NFCT_S as NFCT,
MUTEX_S as MUTEX, NVMC_S as NVMC,
NFCT_S as NFCT, OSCILLATORS_S as OSCILLATORS,
NVMC_S as NVMC, P0_S as P0,
OSCILLATORS_S as OSCILLATORS, P1_S as P1,
P0_S as P0, PDM0_S as PDM0,
P1_S as P1, POWER_S as POWER,
PDM0_S as PDM0, PWM0_S as PWM0,
POWER_S as POWER, PWM1_S as PWM1,
PWM0_S as PWM0, PWM2_S as PWM2,
PWM1_S as PWM1, PWM3_S as PWM3,
PWM2_S as PWM2, QDEC0_S as QDEC0,
PWM3_S as PWM3, QDEC1_S as QDEC1,
QDEC0_S as QDEC0, QSPI_S as QSPI,
QDEC1_S as QDEC1, REGULATORS_S as REGULATORS,
QSPI_S as QSPI, RESET_S as RESET,
REGULATORS_S as REGULATORS, RTC0_S as RTC0,
RESET_S as RESET, RTC1_S as RTC1,
RTC0_S as RTC0, SAADC_S as SAADC,
RTC1_S as RTC1, SPIM0_S as SPIM0,
SAADC_S as SAADC, SPIM1_S as SPIM1,
SPIM0_S as SPIM0, SPIM2_S as SPIM2,
SPIM1_S as SPIM1, SPIM3_S as SPIM3,
SPIM2_S as SPIM2, SPIM4_S as SPIM4,
SPIM3_S as SPIM3, SPIS0_S as SPIS0,
SPIM4_S as SPIM4, SPIS1_S as SPIS1,
SPIS0_S as SPIS0, SPIS2_S as SPIS2,
SPIS1_S as SPIS1, SPIS3_S as SPIS3,
SPIS2_S as SPIS2, SPU_S as SPU,
SPIS3_S as SPIS3, TAD_S as TAD,
SPU_S as SPU, TIMER0_S as TIMER0,
TAD_S as TAD, TIMER1_S as TIMER1,
TIMER0_S as TIMER0, TIMER2_S as TIMER2,
TIMER1_S as TIMER1, TWIM0_S as TWIM0,
TIMER2_S as TIMER2, TWIM1_S as TWIM1,
TWIM0_S as TWIM0, TWIM2_S as TWIM2,
TWIM1_S as TWIM1, TWIM3_S as TWIM3,
TWIM2_S as TWIM2, TWIS0_S as TWIS0,
TWIM3_S as TWIM3, TWIS1_S as TWIS1,
TWIS0_S as TWIS0, TWIS2_S as TWIS2,
TWIS1_S as TWIS1, TWIS3_S as TWIS3,
TWIS2_S as TWIS2, UARTE0_S as UARTE0,
TWIS3_S as TWIS3, UARTE1_S as UARTE1,
UARTE0_S as UARTE0, UARTE2_S as UARTE2,
UARTE1_S as UARTE1, UARTE3_S as UARTE3,
UARTE2_S as UARTE2, UICR_S as UICR,
UARTE3_S as UARTE3, USBD_S as USBD,
UICR_S as UICR, USBREGULATOR_S as USBREGULATOR,
USBD_S as USBD, VMC_S as VMC,
USBREGULATOR_S as USBREGULATOR, WDT0_S as WDT0,
VMC_S as VMC, WDT1_S as WDT1,
WDT0_S as WDT0, };
WDT1_S as WDT1,
};
}
#[cfg(feature = "_ns")]
pub use ns::*;
#[cfg(feature = "_s")]
pub use s::*;
} }
/// The maximum buffer size that the EasyDMA can send/recv in one operation. /// The maximum buffer size that the EasyDMA can send/recv in one operation.

View File

@ -7,12 +7,9 @@ pub mod pac {
pub use nrf5340_net_pac::NVIC_PRIO_BITS; pub use nrf5340_net_pac::NVIC_PRIO_BITS;
#[cfg(feature="rt")]
#[doc(no_inline)]
pub use nrf5340_net_pac::interrupt;
#[doc(no_inline)] #[doc(no_inline)]
pub use nrf5340_net_pac::{ pub use nrf5340_net_pac::{
interrupt,
Interrupt, Interrupt,
Peripherals, Peripherals,

View File

@ -7,12 +7,9 @@ pub mod pac {
pub use nrf9160_pac::NVIC_PRIO_BITS; pub use nrf9160_pac::NVIC_PRIO_BITS;
#[cfg(feature="rt")]
#[doc(no_inline)]
pub use nrf9160_pac::interrupt;
#[doc(no_inline)] #[doc(no_inline)]
pub use nrf9160_pac::{ pub use nrf9160_pac::{
interrupt,
Interrupt, Interrupt,
cc_host_rgf_s as cc_host_rgf, cc_host_rgf_s as cc_host_rgf,
@ -48,131 +45,122 @@ pub mod pac {
wdt_ns as wdt, wdt_ns as wdt,
}; };
/// Non-Secure mode (NS) peripherals #[cfg(feature = "nrf9160-ns")]
pub mod ns { #[doc(no_inline)]
#[doc(no_inline)] pub use nrf9160_pac::{
pub use nrf9160_pac::{ CLOCK_NS as CLOCK,
CLOCK_NS as CLOCK, DPPIC_NS as DPPIC,
DPPIC_NS as DPPIC, EGU0_NS as EGU0,
EGU0_NS as EGU0, EGU1_NS as EGU1,
EGU1_NS as EGU1, EGU2_NS as EGU2,
EGU2_NS as EGU2, EGU3_NS as EGU3,
EGU3_NS as EGU3, EGU4_NS as EGU4,
EGU4_NS as EGU4, EGU5_NS as EGU5,
EGU5_NS as EGU5, FPU_NS as FPU,
FPU_NS as FPU, GPIOTE1_NS as GPIOTE1,
GPIOTE1_NS as GPIOTE1, I2S_NS as I2S,
I2S_NS as I2S, IPC_NS as IPC,
IPC_NS as IPC, KMU_NS as KMU,
KMU_NS as KMU, NVMC_NS as NVMC,
NVMC_NS as NVMC, P0_NS as P0,
P0_NS as P0, PDM_NS as PDM,
PDM_NS as PDM, POWER_NS as POWER,
POWER_NS as POWER, PWM0_NS as PWM0,
PWM0_NS as PWM0, PWM1_NS as PWM1,
PWM1_NS as PWM1, PWM2_NS as PWM2,
PWM2_NS as PWM2, PWM3_NS as PWM3,
PWM3_NS as PWM3, REGULATORS_NS as REGULATORS,
REGULATORS_NS as REGULATORS, RTC0_NS as RTC0,
RTC0_NS as RTC0, RTC1_NS as RTC1,
RTC1_NS as RTC1, SAADC_NS as SAADC,
SAADC_NS as SAADC, SPIM0_NS as SPIM0,
SPIM0_NS as SPIM0, SPIM1_NS as SPIM1,
SPIM1_NS as SPIM1, SPIM2_NS as SPIM2,
SPIM2_NS as SPIM2, SPIM3_NS as SPIM3,
SPIM3_NS as SPIM3, SPIS0_NS as SPIS0,
SPIS0_NS as SPIS0, SPIS1_NS as SPIS1,
SPIS1_NS as SPIS1, SPIS2_NS as SPIS2,
SPIS2_NS as SPIS2, SPIS3_NS as SPIS3,
SPIS3_NS as SPIS3, TIMER0_NS as TIMER0,
TIMER0_NS as TIMER0, TIMER1_NS as TIMER1,
TIMER1_NS as TIMER1, TIMER2_NS as TIMER2,
TIMER2_NS as TIMER2, TWIM0_NS as TWIM0,
TWIM0_NS as TWIM0, TWIM1_NS as TWIM1,
TWIM1_NS as TWIM1, TWIM2_NS as TWIM2,
TWIM2_NS as TWIM2, TWIM3_NS as TWIM3,
TWIM3_NS as TWIM3, TWIS0_NS as TWIS0,
TWIS0_NS as TWIS0, TWIS1_NS as TWIS1,
TWIS1_NS as TWIS1, TWIS2_NS as TWIS2,
TWIS2_NS as TWIS2, TWIS3_NS as TWIS3,
TWIS3_NS as TWIS3, UARTE0_NS as UARTE0,
UARTE0_NS as UARTE0, UARTE1_NS as UARTE1,
UARTE1_NS as UARTE1, UARTE2_NS as UARTE2,
UARTE2_NS as UARTE2, UARTE3_NS as UARTE3,
UARTE3_NS as UARTE3, VMC_NS as VMC,
VMC_NS as VMC, WDT_NS as WDT,
WDT_NS as WDT, };
};
}
/// Secure mode (S) peripherals #[cfg(feature = "nrf9160-s")]
pub mod s { #[doc(no_inline)]
#[doc(no_inline)] pub use nrf9160_pac::{
pub use nrf9160_pac::{ CC_HOST_RGF_S as CC_HOST_RGF,
CC_HOST_RGF_S as CC_HOST_RGF, CLOCK_S as CLOCK,
CLOCK_S as CLOCK, CRYPTOCELL_S as CRYPTOCELL,
CRYPTOCELL_S as CRYPTOCELL, CTRL_AP_PERI_S as CTRL_AP_PERI,
CTRL_AP_PERI_S as CTRL_AP_PERI, DPPIC_S as DPPIC,
DPPIC_S as DPPIC, EGU0_S as EGU0,
EGU0_S as EGU0, EGU1_S as EGU1,
EGU1_S as EGU1, EGU2_S as EGU2,
EGU2_S as EGU2, EGU3_S as EGU3,
EGU3_S as EGU3, EGU4_S as EGU4,
EGU4_S as EGU4, EGU5_S as EGU5,
EGU5_S as EGU5, FICR_S as FICR,
FICR_S as FICR, FPU_S as FPU,
FPU_S as FPU, GPIOTE0_S as GPIOTE0,
GPIOTE0_S as GPIOTE0, I2S_S as I2S,
I2S_S as I2S, IPC_S as IPC,
IPC_S as IPC, KMU_S as KMU,
KMU_S as KMU, NVMC_S as NVMC,
NVMC_S as NVMC, P0_S as P0,
P0_S as P0, PDM_S as PDM,
PDM_S as PDM, POWER_S as POWER,
POWER_S as POWER, PWM0_S as PWM0,
PWM0_S as PWM0, PWM1_S as PWM1,
PWM1_S as PWM1, PWM2_S as PWM2,
PWM2_S as PWM2, PWM3_S as PWM3,
PWM3_S as PWM3, REGULATORS_S as REGULATORS,
REGULATORS_S as REGULATORS, RTC0_S as RTC0,
RTC0_S as RTC0, RTC1_S as RTC1,
RTC1_S as RTC1, SAADC_S as SAADC,
SAADC_S as SAADC, SPIM0_S as SPIM0,
SPIM0_S as SPIM0, SPIM1_S as SPIM1,
SPIM1_S as SPIM1, SPIM2_S as SPIM2,
SPIM2_S as SPIM2, SPIM3_S as SPIM3,
SPIM3_S as SPIM3, SPIS0_S as SPIS0,
SPIS0_S as SPIS0, SPIS1_S as SPIS1,
SPIS1_S as SPIS1, SPIS2_S as SPIS2,
SPIS2_S as SPIS2, SPIS3_S as SPIS3,
SPIS3_S as SPIS3, SPU_S as SPU,
SPU_S as SPU, TAD_S as TAD,
TAD_S as TAD, TIMER0_S as TIMER0,
TIMER0_S as TIMER0, TIMER1_S as TIMER1,
TIMER1_S as TIMER1, TIMER2_S as TIMER2,
TIMER2_S as TIMER2, TWIM0_S as TWIM0,
TWIM0_S as TWIM0, TWIM1_S as TWIM1,
TWIM1_S as TWIM1, TWIM2_S as TWIM2,
TWIM2_S as TWIM2, TWIM3_S as TWIM3,
TWIM3_S as TWIM3, TWIS0_S as TWIS0,
TWIS0_S as TWIS0, TWIS1_S as TWIS1,
TWIS1_S as TWIS1, TWIS2_S as TWIS2,
TWIS2_S as TWIS2, TWIS3_S as TWIS3,
TWIS3_S as TWIS3, UARTE0_S as UARTE0,
UARTE0_S as UARTE0, UARTE1_S as UARTE1,
UARTE1_S as UARTE1, UARTE2_S as UARTE2,
UARTE2_S as UARTE2, UARTE3_S as UARTE3,
UARTE3_S as UARTE3, UICR_S as UICR,
UICR_S as UICR, VMC_S as VMC,
VMC_S as VMC, WDT_S as WDT,
WDT_S as WDT, };
};
}
#[cfg(feature = "_ns")]
pub use ns::*;
#[cfg(feature = "_s")]
pub use s::*;
} }
/// The maximum buffer size that the EasyDMA can send/recv in one operation. /// The maximum buffer size that the EasyDMA can send/recv in one operation.

View File

@ -1,6 +1,5 @@
#![no_std] #![no_std]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait, impl_trait_projections))] #![cfg_attr(feature = "nightly", feature(async_fn_in_trait))]
#![cfg_attr(feature = "nightly", allow(stable_features, unknown_lints, async_fn_in_trait))]
#![doc = include_str!("../README.md")] #![doc = include_str!("../README.md")]
#![warn(missing_docs)] #![warn(missing_docs)]

View File

@ -2,7 +2,6 @@
#![macro_use] #![macro_use]
use core::future::poll_fn;
use core::marker::PhantomData; use core::marker::PhantomData;
use core::sync::atomic::{compiler_fence, Ordering}; use core::sync::atomic::{compiler_fence, Ordering};
use core::task::Poll; use core::task::Poll;
@ -10,6 +9,7 @@ use core::task::Poll;
use embassy_hal_internal::drop::OnDrop; use embassy_hal_internal::drop::OnDrop;
use embassy_hal_internal::{into_ref, PeripheralRef}; use embassy_hal_internal::{into_ref, PeripheralRef};
use fixed::types::I7F1; use fixed::types::I7F1;
use futures::future::poll_fn;
use crate::chip::EASY_DMA_SIZE; use crate::chip::EASY_DMA_SIZE;
use crate::gpio::sealed::Pin; use crate::gpio::sealed::Pin;

View File

@ -59,8 +59,8 @@ nightly = ["embedded-hal-1", "embedded-hal-async", "embedded-storage-async", "em
unstable-traits = ["embedded-hal-1", "embedded-hal-nb"] unstable-traits = ["embedded-hal-1", "embedded-hal-nb"]
[dependencies] [dependencies]
embassy-sync = { version = "0.4.0", path = "../embassy-sync" } embassy-sync = { version = "0.3.0", path = "../embassy-sync" }
embassy-time = { version = "0.1.5", path = "../embassy-time", features = [ "tick-hz-1_000_000" ] } embassy-time = { version = "0.1.3", path = "../embassy-time", features = [ "tick-hz-1_000_000" ] }
embassy-futures = { version = "0.1.0", path = "../embassy-futures" } embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
embassy-hal-internal = {version = "0.1.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-2"] } embassy-hal-internal = {version = "0.1.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-2"] }
embassy-embedded-hal = {version = "0.1.0", path = "../embassy-embedded-hal" } embassy-embedded-hal = {version = "0.1.0", path = "../embassy-embedded-hal" }
@ -94,5 +94,5 @@ pio = {version= "0.2.1" }
rp2040-boot2 = "0.3" rp2040-boot2 = "0.3"
[dev-dependencies] [dev-dependencies]
embassy-executor = { version = "0.3.3", path = "../embassy-executor", features = ["nightly", "arch-std", "executor-thread"] } embassy-executor = { version = "0.3.0", path = "../embassy-executor", features = ["nightly", "arch-std", "executor-thread"] }
static_cell = { version = "2" } static_cell = "1.1"

View File

@ -213,7 +213,6 @@ impl<'d> Adc<'d, Async> {
ch: &mut Channel<'_>, ch: &mut Channel<'_>,
buf: &mut [W], buf: &mut [W],
fcs_err: bool, fcs_err: bool,
div: u16,
dma: impl Peripheral<P = impl dma::Channel>, dma: impl Peripheral<P = impl dma::Channel>,
) -> Result<(), Error> { ) -> Result<(), Error> {
let r = Self::regs(); let r = Self::regs();
@ -259,7 +258,6 @@ impl<'d> Adc<'d, Async> {
// start conversions and wait for dma to finish. we can't report errors early // start conversions and wait for dma to finish. we can't report errors early
// because there's no interrupt to signal them, and inspecting every element // because there's no interrupt to signal them, and inspecting every element
// of the fifo is too costly to do here. // of the fifo is too costly to do here.
r.div().write_set(|w| w.set_int(div));
r.cs().write_set(|w| w.set_start_many(true)); r.cs().write_set(|w| w.set_start_many(true));
dma.await; dma.await;
mem::drop(auto_reset); mem::drop(auto_reset);
@ -277,10 +275,9 @@ impl<'d> Adc<'d, Async> {
&mut self, &mut self,
ch: &mut Channel<'_>, ch: &mut Channel<'_>,
buf: &mut [S], buf: &mut [S],
div: u16,
dma: impl Peripheral<P = impl dma::Channel>, dma: impl Peripheral<P = impl dma::Channel>,
) -> Result<(), Error> { ) -> Result<(), Error> {
self.read_many_inner(ch, buf, false, div, dma).await self.read_many_inner(ch, buf, false, dma).await
} }
#[inline] #[inline]
@ -288,12 +285,11 @@ impl<'d> Adc<'d, Async> {
&mut self, &mut self,
ch: &mut Channel<'_>, ch: &mut Channel<'_>,
buf: &mut [Sample], buf: &mut [Sample],
div: u16,
dma: impl Peripheral<P = impl dma::Channel>, dma: impl Peripheral<P = impl dma::Channel>,
) { ) {
// errors are reported in individual samples // errors are reported in individual samples
let _ = self let _ = self
.read_many_inner(ch, unsafe { mem::transmute::<_, &mut [u16]>(buf) }, true, div, dma) .read_many_inner(ch, unsafe { mem::transmute::<_, &mut [u16]>(buf) }, true, dma)
.await; .await;
} }
} }

View File

@ -1,6 +1,5 @@
#![no_std] #![no_std]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait, impl_trait_projections))] #![cfg_attr(feature = "nightly", feature(async_fn_in_trait))]
#![cfg_attr(feature = "nightly", allow(stable_features, unknown_lints, async_fn_in_trait))]
// This mod MUST go first, so that the others see its macros. // This mod MUST go first, so that the others see its macros.
pub(crate) mod fmt; pub(crate) mod fmt;

View File

@ -10,39 +10,16 @@ use crate::gpio::sealed::Pin as _;
use crate::gpio::{AnyPin, Pin as GpioPin}; use crate::gpio::{AnyPin, Pin as GpioPin};
use crate::{pac, peripherals, RegExt}; use crate::{pac, peripherals, RegExt};
/// The configuration of a PWM slice.
/// Note the period in clock cycles of a slice can be computed as:
/// `(top + 1) * (phase_correct ? 1 : 2) * divider`
#[non_exhaustive] #[non_exhaustive]
#[derive(Clone)] #[derive(Clone)]
pub struct Config { pub struct Config {
/// Inverts the PWM output signal on channel A.
pub invert_a: bool, pub invert_a: bool,
/// Inverts the PWM output signal on channel B.
pub invert_b: bool, pub invert_b: bool,
/// Enables phase-correct mode for PWM operation.
/// In phase-correct mode, the PWM signal is generated in such a way that
/// the pulse is always centered regardless of the duty cycle.
/// The output frequency is halved when phase-correct mode is enabled.
pub phase_correct: bool, pub phase_correct: bool,
/// Enables the PWM slice, allowing it to generate an output.
pub enable: bool, pub enable: bool,
/// A fractional clock divider, represented as a fixed-point number with
/// 8 integer bits and 4 fractional bits. It allows precise control over
/// the PWM output frequency by gating the PWM counter increment.
/// A higher value will result in a slower output frequency.
pub divider: fixed::FixedU16<fixed::types::extra::U4>, pub divider: fixed::FixedU16<fixed::types::extra::U4>,
/// The output on channel A goes high when `compare_a` is higher than the
/// counter. A compare of 0 will produce an always low output, while a
/// compare of `top + 1` will produce an always high output.
pub compare_a: u16, pub compare_a: u16,
/// The output on channel B goes high when `compare_b` is higher than the
/// counter. A compare of 0 will produce an always low output, while a
/// compare of `top + 1` will produce an always high output.
pub compare_b: u16, pub compare_b: u16,
/// The point at which the counter wraps, representing the maximum possible
/// period. The counter will either wrap to 0 or reverse depending on the
/// setting of `phase_correct`.
pub top: u16, pub top: u16,
} }
@ -196,9 +173,6 @@ impl<'d, T: Channel> Pwm<'d, T> {
}); });
} }
/// Advances a slices output phase by one count while it is running
/// by inserting a pulse into the clock enable. The counter
/// will not count faster than once per cycle.
#[inline] #[inline]
pub fn phase_advance(&mut self) { pub fn phase_advance(&mut self) {
let p = self.inner.regs(); let p = self.inner.regs();
@ -206,9 +180,6 @@ impl<'d, T: Channel> Pwm<'d, T> {
while p.csr().read().ph_adv() {} while p.csr().read().ph_adv() {}
} }
/// Retards a slices output phase by one count while it is running
/// by deleting a pulse from the clock enable. The counter will not
/// count backward when clock enable is permenantly low.
#[inline] #[inline]
pub fn phase_retard(&mut self) { pub fn phase_retard(&mut self) {
let p = self.inner.regs(); let p = self.inner.regs();

View File

@ -5,7 +5,7 @@ use core::task::Poll;
use atomic_polyfill::{AtomicU8, Ordering}; use atomic_polyfill::{AtomicU8, Ordering};
use embassy_hal_internal::atomic_ring_buffer::RingBuffer; use embassy_hal_internal::atomic_ring_buffer::RingBuffer;
use embassy_sync::waitqueue::AtomicWaker; use embassy_sync::waitqueue::AtomicWaker;
use embassy_time::Timer; use embassy_time::{Duration, Timer};
use super::*; use super::*;
use crate::clocks::clk_peri_freq; use crate::clocks::clk_peri_freq;
@ -435,7 +435,7 @@ impl<'d, T: Instance> BufferedUartTx<'d, T> {
Self::flush().await.unwrap(); Self::flush().await.unwrap();
while self.busy() {} while self.busy() {}
regs.uartlcr_h().write_set(|w| w.set_brk(true)); regs.uartlcr_h().write_set(|w| w.set_brk(true));
Timer::after_micros(wait_usecs).await; Timer::after(Duration::from_micros(wait_usecs)).await;
regs.uartlcr_h().write_clear(|w| w.set_brk(true)); regs.uartlcr_h().write_clear(|w| w.set_brk(true));
} }
} }

View File

@ -6,7 +6,7 @@ use atomic_polyfill::{AtomicU16, Ordering};
use embassy_futures::select::{select, Either}; use embassy_futures::select::{select, Either};
use embassy_hal_internal::{into_ref, PeripheralRef}; use embassy_hal_internal::{into_ref, PeripheralRef};
use embassy_sync::waitqueue::AtomicWaker; use embassy_sync::waitqueue::AtomicWaker;
use embassy_time::Timer; use embassy_time::{Duration, Timer};
use pac::uart::regs::Uartris; use pac::uart::regs::Uartris;
use crate::clocks::clk_peri_freq; use crate::clocks::clk_peri_freq;
@ -187,7 +187,7 @@ impl<'d, T: Instance, M: Mode> UartTx<'d, T, M> {
self.blocking_flush().unwrap(); self.blocking_flush().unwrap();
while self.busy() {} while self.busy() {}
regs.uartlcr_h().write_set(|w| w.set_brk(true)); regs.uartlcr_h().write_set(|w| w.set_brk(true));
Timer::after_micros(wait_usecs).await; Timer::after(Duration::from_micros(wait_usecs)).await;
regs.uartlcr_h().write_clear(|w| w.set_brk(true)); regs.uartlcr_h().write_clear(|w| w.set_brk(true));
} }
} }

View File

@ -12,16 +12,16 @@ features = ["stm32wb55rg"]
[dependencies] [dependencies]
embassy-stm32 = { version = "0.1.0", path = "../embassy-stm32" } embassy-stm32 = { version = "0.1.0", path = "../embassy-stm32" }
embassy-sync = { version = "0.4.0", path = "../embassy-sync" } embassy-sync = { version = "0.3.0", path = "../embassy-sync" }
embassy-time = { version = "0.1.5", path = "../embassy-time", optional = true } embassy-time = { version = "0.1.3", path = "../embassy-time", optional = true }
embassy-futures = { version = "0.1.0", path = "../embassy-futures" } embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
embassy-hal-internal = { version = "0.1.0", path = "../embassy-hal-internal" } embassy-hal-internal = { version = "0.1.0", path = "../embassy-hal-internal" }
embassy-embedded-hal = { version = "0.1.0", path = "../embassy-embedded-hal" } embassy-embedded-hal = { version = "0.1.0", path = "../embassy-embedded-hal" }
embassy-net-driver = { version = "0.2.0", path = "../embassy-net-driver", optional=true } embassy-net-driver = { version = "0.1.0", path = "../embassy-net-driver", optional=true }
defmt = { version = "0.3", optional = true } defmt = { version = "0.3", optional = true }
cortex-m = "0.7.6" cortex-m = "0.7.6"
heapless = "0.8" heapless = "0.7.16"
aligned = "0.4.1" aligned = "0.4.1"
bit_field = "0.10.2" bit_field = "0.10.2"

View File

@ -1,9 +1,5 @@
#![no_std] #![no_std]
#![cfg_attr(any(feature = "ble", feature = "mac"), feature(async_fn_in_trait))] #![cfg_attr(any(feature = "ble", feature = "mac"), feature(async_fn_in_trait))]
#![cfg_attr(
any(feature = "ble", feature = "mac"),
allow(stable_features, unknown_lints, async_fn_in_trait)
)]
#![cfg_attr(feature = "mac", feature(type_alias_impl_trait, concat_bytes))] #![cfg_attr(feature = "mac", feature(type_alias_impl_trait, concat_bytes))]
// This must go FIRST so that all the other modules see its macros. // This must go FIRST so that all the other modules see its macros.

View File

@ -1,8 +1,9 @@
#![allow(incomplete_features)]
#![deny(unused_must_use)] #![deny(unused_must_use)]
use core::task::Context; use core::task::Context;
use embassy_net_driver::{Capabilities, HardwareAddress, LinkState}; use embassy_net_driver::{Capabilities, HardwareAddress, LinkState, Medium};
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::channel::Channel; use embassy_sync::channel::Channel;
@ -59,15 +60,24 @@ impl<'d> embassy_net_driver::Driver for Driver<'d> {
let mut caps = Capabilities::default(); let mut caps = Capabilities::default();
caps.max_transmission_unit = MTU; caps.max_transmission_unit = MTU;
// caps.max_burst_size = Some(self.tx.len()); // caps.max_burst_size = Some(self.tx.len());
caps.medium = Medium::Ieee802154;
caps caps
} }
fn link_state(&mut self, _cx: &mut Context) -> LinkState { fn link_state(&mut self, _cx: &mut Context) -> LinkState {
// if self.phy.poll_link(&mut self.station_management, cx) {
// LinkState::Up
// } else {
// LinkState::Down
// }
LinkState::Down LinkState::Down
} }
fn hardware_address(&self) -> HardwareAddress { fn hardware_address(&self) -> HardwareAddress {
// self.mac_addr // self.mac_addr
HardwareAddress::Ieee802154([0; 8]) HardwareAddress::Ieee802154([0; 8])
} }
} }

View File

@ -18,7 +18,7 @@ flavors = [
{ regex_feature = "stm32f7.*", target = "thumbv7em-none-eabi" }, { regex_feature = "stm32f7.*", target = "thumbv7em-none-eabi" },
{ regex_feature = "stm32c0.*", target = "thumbv6m-none-eabi" }, { regex_feature = "stm32c0.*", target = "thumbv6m-none-eabi" },
{ regex_feature = "stm32g0.*", target = "thumbv6m-none-eabi" }, { regex_feature = "stm32g0.*", target = "thumbv6m-none-eabi" },
{ regex_feature = "stm32g4.*", target = "thumbv7em-none-eabi", features = ["low-power"] }, { regex_feature = "stm32g4.*", target = "thumbv7em-none-eabi" },
{ regex_feature = "stm32h5.*", target = "thumbv8m.main-none-eabihf" }, { regex_feature = "stm32h5.*", target = "thumbv8m.main-none-eabihf" },
{ regex_feature = "stm32h7.*", target = "thumbv7em-none-eabi" }, { regex_feature = "stm32h7.*", target = "thumbv7em-none-eabi" },
{ regex_feature = "stm32l0.*", target = "thumbv6m-none-eabi", features = ["low-power"] }, { regex_feature = "stm32l0.*", target = "thumbv6m-none-eabi", features = ["low-power"] },
@ -32,14 +32,14 @@ flavors = [
] ]
[dependencies] [dependencies]
embassy-sync = { version = "0.4.0", path = "../embassy-sync" } embassy-sync = { version = "0.3.0", path = "../embassy-sync" }
embassy-time = { version = "0.1.5", path = "../embassy-time", optional = true } embassy-time = { version = "0.1.3", path = "../embassy-time", optional = true }
embassy-futures = { version = "0.1.0", path = "../embassy-futures" } embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
embassy-hal-internal = {version = "0.1.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-4"] } embassy-hal-internal = {version = "0.1.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-4"] }
embassy-embedded-hal = {version = "0.1.0", path = "../embassy-embedded-hal" } embassy-embedded-hal = {version = "0.1.0", path = "../embassy-embedded-hal" }
embassy-net-driver = { version = "0.2.0", path = "../embassy-net-driver" } embassy-net-driver = { version = "0.1.0", path = "../embassy-net-driver" }
embassy-usb-driver = {version = "0.1.0", path = "../embassy-usb-driver", optional = true } embassy-usb-driver = {version = "0.1.0", path = "../embassy-usb-driver", optional = true }
embassy-executor = { version = "0.3.3", path = "../embassy-executor", optional = true } embassy-executor = { version = "0.3.0", path = "../embassy-executor", optional = true }
embedded-hal-02 = { package = "embedded-hal", version = "0.2.6", features = ["unproven"] } embedded-hal-02 = { package = "embedded-hal", version = "0.2.6", features = ["unproven"] }
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.1", optional = true} embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.1", optional = true}
@ -58,7 +58,8 @@ rand_core = "0.6.3"
sdio-host = "0.5.0" sdio-host = "0.5.0"
embedded-sdmmc = { git = "https://github.com/embassy-rs/embedded-sdmmc-rs", rev = "a4f293d3a6f72158385f79c98634cb8a14d0d2fc", optional = true } embedded-sdmmc = { git = "https://github.com/embassy-rs/embedded-sdmmc-rs", rev = "a4f293d3a6f72158385f79c98634cb8a14d0d2fc", optional = true }
critical-section = "1.1" critical-section = "1.1"
stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-fbb8f77326dd066aa6c0d66b3b46e76a569dda8b" } atomic-polyfill = "1.0.1"
stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-6bfa5a0dcec6a9bd42cea94ba11eeae1a17a7f2c" }
vcell = "0.1.3" vcell = "0.1.3"
bxcan = "0.7.0" bxcan = "0.7.0"
nb = "1.0.0" nb = "1.0.0"
@ -76,7 +77,7 @@ critical-section = { version = "1.1", features = ["std"] }
[build-dependencies] [build-dependencies]
proc-macro2 = "1.0.36" proc-macro2 = "1.0.36"
quote = "1.0.15" quote = "1.0.15"
stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-fbb8f77326dd066aa6c0d66b3b46e76a569dda8b", default-features = false, features = ["metadata"]} stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-6bfa5a0dcec6a9bd42cea94ba11eeae1a17a7f2c", default-features = false, features = ["metadata"]}
[features] [features]
@ -90,7 +91,6 @@ defmt = ["dep:defmt", "bxcan/unstable-defmt", "embassy-sync/defmt", "embassy-emb
exti = [] exti = []
low-power = [ "dep:embassy-executor", "embassy-executor/arch-cortex-m" ] low-power = [ "dep:embassy-executor", "embassy-executor/arch-cortex-m" ]
low-power-debug-with-sleep = []
embassy-executor = [] embassy-executor = []
## Automatically generate `memory.x` file using [`stm32-metapac`](https://docs.rs/stm32-metapac/) ## Automatically generate `memory.x` file using [`stm32-metapac`](https://docs.rs/stm32-metapac/)

View File

@ -1,40 +1,13 @@
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::fmt::Write as _; use std::fmt::Write as _;
use std::path::PathBuf; use std::path::PathBuf;
use std::{env, fs}; use std::{env, fs};
use proc_macro2::{Ident, TokenStream}; use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote}; use quote::{format_ident, quote};
use stm32_metapac::metadata::ir::{BlockItemInner, Enum, FieldSet}; use stm32_metapac::metadata::{MemoryRegionKind, METADATA};
use stm32_metapac::metadata::{MemoryRegionKind, PeripheralRccRegister, StopMode, METADATA};
fn main() { fn main() {
let target = env::var("TARGET").unwrap();
if target.starts_with("thumbv6m-") {
println!("cargo:rustc-cfg=cortex_m");
println!("cargo:rustc-cfg=armv6m");
} else if target.starts_with("thumbv7m-") {
println!("cargo:rustc-cfg=cortex_m");
println!("cargo:rustc-cfg=armv7m");
} else if target.starts_with("thumbv7em-") {
println!("cargo:rustc-cfg=cortex_m");
println!("cargo:rustc-cfg=armv7m");
println!("cargo:rustc-cfg=armv7em"); // (not currently used)
} else if target.starts_with("thumbv8m.base") {
println!("cargo:rustc-cfg=cortex_m");
println!("cargo:rustc-cfg=armv8m");
println!("cargo:rustc-cfg=armv8m_base");
} else if target.starts_with("thumbv8m.main") {
println!("cargo:rustc-cfg=cortex_m");
println!("cargo:rustc-cfg=armv8m");
println!("cargo:rustc-cfg=armv8m_main");
}
if target.ends_with("-eabihf") {
println!("cargo:rustc-cfg=has_fpu");
}
let chip_name = match env::vars() let chip_name = match env::vars()
.map(|(a, _)| a) .map(|(a, _)| a)
.filter(|x| x.starts_with("CARGO_FEATURE_STM32")) .filter(|x| x.starts_with("CARGO_FEATURE_STM32"))
@ -61,7 +34,6 @@ fn main() {
let mut singletons: Vec<String> = Vec::new(); let mut singletons: Vec<String> = Vec::new();
for p in METADATA.peripherals { for p in METADATA.peripherals {
if let Some(r) = &p.registers { if let Some(r) = &p.registers {
println!("cargo:rustc-cfg=peri_{}", p.name.to_ascii_lowercase());
match r.kind { match r.kind {
// Generate singletons per pin, not per port // Generate singletons per pin, not per port
"gpio" => { "gpio" => {
@ -353,7 +325,7 @@ fn main() {
// ======== // ========
// Generate DMA IRQs. // Generate DMA IRQs.
let mut dma_irqs: BTreeMap<&str, Vec<(&str, &str, &str)>> = BTreeMap::new(); let mut dma_irqs: HashMap<&str, Vec<(&str, &str, &str)>> = HashMap::new();
for p in METADATA.peripherals { for p in METADATA.peripherals {
if let Some(r) = &p.registers { if let Some(r) = &p.registers {
@ -372,74 +344,28 @@ fn main() {
} }
} }
let dma_irqs: TokenStream = dma_irqs for (irq, channels) in dma_irqs {
.iter() let irq = format_ident!("{}", irq);
.map(|(irq, channels)| {
let irq = format_ident!("{}", irq);
let xdma = format_ident!("{}", channels[0].0); let xdma = format_ident!("{}", channels[0].0);
let channels = channels.iter().map(|(_, dma, ch)| format_ident!("{}_{}", dma, ch)); let channels = channels.iter().map(|(_, dma, ch)| format_ident!("{}_{}", dma, ch));
quote! { g.extend(quote! {
#[cfg(feature = "rt")] #[cfg(feature = "rt")]
#[crate::interrupt] #[crate::interrupt]
unsafe fn #irq () { unsafe fn #irq () {
#( #(
<crate::peripherals::#channels as crate::dma::#xdma::sealed::Channel>::on_irq(); <crate::peripherals::#channels as crate::dma::#xdma::sealed::Channel>::on_irq();
)* )*
}
} }
}) });
.collect(); }
g.extend(dma_irqs);
// ========
// Extract the rcc registers
let rcc_registers = METADATA
.peripherals
.iter()
.filter_map(|p| p.registers.as_ref())
.find(|r| r.kind == "rcc")
.unwrap();
// ========
// Generate rcc fieldset and enum maps
let rcc_enum_map: HashMap<&str, HashMap<&str, &Enum>> = {
let rcc_blocks = rcc_registers.ir.blocks.iter().find(|b| b.name == "Rcc").unwrap().items;
let rcc_fieldsets: HashMap<&str, &FieldSet> = rcc_registers.ir.fieldsets.iter().map(|f| (f.name, f)).collect();
let rcc_enums: HashMap<&str, &Enum> = rcc_registers.ir.enums.iter().map(|e| (e.name, e)).collect();
rcc_blocks
.iter()
.filter_map(|b| match &b.inner {
BlockItemInner::Register(register) => register.fieldset.map(|f| (b.name, f)),
_ => None,
})
.filter_map(|(b, f)| {
rcc_fieldsets.get(f).map(|f| {
(
b,
f.fields
.iter()
.filter_map(|f| {
let enumm = f.enumm?;
let enumm = rcc_enums.get(enumm)?;
Some((f.name, *enumm))
})
.collect(),
)
})
})
.collect()
};
// ======== // ========
// Generate RccPeripheral impls // Generate RccPeripheral impls
let refcounted_peripherals = HashSet::from(["usart", "adc"]); let refcounted_peripherals = HashSet::from(["usart", "adc"]);
let mut refcount_statics = BTreeSet::new(); let mut refcount_statics = HashSet::new();
for p in METADATA.peripherals { for p in METADATA.peripherals {
if !singletons.contains(&p.name.to_string()) { if !singletons.contains(&p.name.to_string()) {
@ -454,8 +380,10 @@ fn main() {
let rst_reg = format_ident!("{}", rst.register.to_ascii_lowercase()); let rst_reg = format_ident!("{}", rst.register.to_ascii_lowercase());
let set_rst_field = format_ident!("set_{}", rst.field.to_ascii_lowercase()); let set_rst_field = format_ident!("set_{}", rst.field.to_ascii_lowercase());
quote! { quote! {
crate::pac::RCC.#rst_reg().modify(|w| w.#set_rst_field(true)); critical_section::with(|_| {
crate::pac::RCC.#rst_reg().modify(|w| w.#set_rst_field(false)); crate::pac::RCC.#rst_reg().modify(|w| w.#set_rst_field(true));
crate::pac::RCC.#rst_reg().modify(|w| w.#set_rst_field(false));
});
} }
} }
None => TokenStream::new(), None => TokenStream::new(),
@ -472,9 +400,9 @@ fn main() {
let ptype = if let Some(reg) = &p.registers { reg.kind } else { "" }; let ptype = if let Some(reg) = &p.registers { reg.kind } else { "" };
let pname = format_ident!("{}", p.name); let pname = format_ident!("{}", p.name);
let clk = format_ident!("{}", rcc.clock); let clk = format_ident!("{}", rcc.clock.to_ascii_lowercase());
let en_reg = format_ident!("{}", en.register); let en_reg = format_ident!("{}", en.register.to_ascii_lowercase());
let set_en_field = format_ident!("set_{}", en.field); let set_en_field = format_ident!("set_{}", en.field.to_ascii_lowercase());
let (before_enable, before_disable) = if refcounted_peripherals.contains(ptype) { let (before_enable, before_disable) = if refcounted_peripherals.contains(ptype) {
let refcount_static = let refcount_static =
@ -500,105 +428,31 @@ fn main() {
(TokenStream::new(), TokenStream::new()) (TokenStream::new(), TokenStream::new())
}; };
let mux_supported = HashSet::from(["c0", "h5", "h50", "h7", "h7ab", "h7rm0433", "g4", "l4"])
.contains(rcc_registers.version);
let mux_for = |mux: Option<&'static PeripheralRccRegister>| {
// restrict mux implementation to supported versions
if !mux_supported {
return None;
}
let mux = mux?;
let fieldset = rcc_enum_map.get(mux.register)?;
let enumm = fieldset.get(mux.field)?;
Some((mux, *enumm))
};
let clock_frequency = match mux_for(rcc.mux.as_ref()) {
Some((mux, rcc_enumm)) => {
let fieldset_name = format_ident!("{}", mux.register);
let field_name = format_ident!("{}", mux.field);
let enum_name = format_ident!("{}", rcc_enumm.name);
let match_arms: TokenStream = rcc_enumm
.variants
.iter()
.filter(|v| v.name != "DISABLE")
.map(|v| {
let variant_name = format_ident!("{}", v.name);
let clock_name = format_ident!("{}", v.name.to_ascii_lowercase());
if v.name.starts_with("HCLK") || v.name.starts_with("PCLK") || v.name == "SYS" {
quote! {
#enum_name::#variant_name => unsafe { crate::rcc::get_freqs().#clock_name },
}
} else {
quote! {
#enum_name::#variant_name => unsafe { crate::rcc::get_freqs().#clock_name.unwrap() },
}
}
})
.collect();
quote! {
use crate::pac::rcc::vals::#enum_name;
#[allow(unreachable_patterns)]
match crate::pac::RCC.#fieldset_name().read().#field_name() {
#match_arms
_ => unreachable!(),
}
}
}
None => quote! {
unsafe { crate::rcc::get_freqs().#clk }
},
};
/*
A refcount leak can result if the same field is shared by peripherals with different stop modes
This condition should be checked in stm32-data
*/
let stop_refcount = match rcc.stop_mode {
StopMode::Standby => None,
StopMode::Stop2 => Some(quote! { REFCOUNT_STOP2 }),
StopMode::Stop1 => Some(quote! { REFCOUNT_STOP1 }),
};
let (incr_stop_refcount, decr_stop_refcount) = match stop_refcount {
Some(stop_refcount) => (
quote! {
#[cfg(feature = "low-power")]
unsafe { crate::rcc::#stop_refcount += 1 };
},
quote! {
#[cfg(feature = "low-power")]
unsafe { crate::rcc::#stop_refcount -= 1 };
},
),
None => (TokenStream::new(), TokenStream::new()),
};
g.extend(quote! { g.extend(quote! {
impl crate::rcc::sealed::RccPeripheral for peripherals::#pname { impl crate::rcc::sealed::RccPeripheral for peripherals::#pname {
fn frequency() -> crate::time::Hertz { fn frequency() -> crate::time::Hertz {
#clock_frequency unsafe { crate::rcc::get_freqs().#clk }
} }
fn enable_and_reset_with_cs(_cs: critical_section::CriticalSection) { fn enable() {
#before_enable critical_section::with(|_| {
#incr_stop_refcount #before_enable
crate::pac::RCC.#en_reg().modify(|w| w.#set_en_field(true)); #[cfg(feature = "low-power")]
#after_enable crate::rcc::clock_refcount_add();
crate::pac::RCC.#en_reg().modify(|w| w.#set_en_field(true));
#after_enable
})
}
fn disable() {
critical_section::with(|_| {
#before_disable
crate::pac::RCC.#en_reg().modify(|w| w.#set_en_field(false));
#[cfg(feature = "low-power")]
crate::rcc::clock_refcount_sub();
})
}
fn reset() {
#rst #rst
} }
fn disable_with_cs(_cs: critical_section::CriticalSection) {
#before_disable
crate::pac::RCC.#en_reg().modify(|w| w.#set_en_field(false));
#decr_stop_refcount
}
} }
impl crate::rcc::RccPeripheral for peripherals::#pname {} impl crate::rcc::RccPeripheral for peripherals::#pname {}
@ -606,14 +460,12 @@ fn main() {
} }
} }
let refcount_mod: TokenStream = refcount_statics let mut refcount_mod = TokenStream::new();
.iter() for refcount_static in refcount_statics {
.map(|refcount_static| { refcount_mod.extend(quote! {
quote! { pub(crate) static mut #refcount_static: u8 = 0;
pub(crate) static mut #refcount_static: u8 = 0; });
} }
})
.collect();
g.extend(quote! { g.extend(quote! {
mod refcount_statics { mod refcount_statics {
@ -828,7 +680,7 @@ fn main() {
(("fmc", "NCE"), quote!(crate::fmc::NCEPin)), (("fmc", "NCE"), quote!(crate::fmc::NCEPin)),
(("fmc", "NOE"), quote!(crate::fmc::NOEPin)), (("fmc", "NOE"), quote!(crate::fmc::NOEPin)),
(("fmc", "NWE"), quote!(crate::fmc::NWEPin)), (("fmc", "NWE"), quote!(crate::fmc::NWEPin)),
(("fmc", "CLK"), quote!(crate::fmc::ClkPin)), (("fmc", "Clk"), quote!(crate::fmc::ClkPin)),
(("fmc", "BA0"), quote!(crate::fmc::BA0Pin)), (("fmc", "BA0"), quote!(crate::fmc::BA0Pin)),
(("fmc", "BA1"), quote!(crate::fmc::BA1Pin)), (("fmc", "BA1"), quote!(crate::fmc::BA1Pin)),
(("timer", "CH1"), quote!(crate::timer::Channel1Pin)), (("timer", "CH1"), quote!(crate::timer::Channel1Pin)),
@ -944,23 +796,17 @@ fn main() {
} }
if regs.kind == "opamp" { if regs.kind == "opamp" {
if pin.signal.starts_with("VP") { if !pin.signal.starts_with("VP") {
// Impl NonInvertingPin for the VP* signals (VP0, VP1, VP2, etc) continue;
let peri = format_ident!("{}", p.name);
let pin_name = format_ident!("{}", pin.pin);
let ch: u8 = pin.signal.strip_prefix("VP").unwrap().parse().unwrap();
g.extend(quote! {
impl_opamp_vp_pin!( #peri, #pin_name, #ch);
})
} else if pin.signal == "VOUT" {
// Impl OutputPin for the VOUT pin
let peri = format_ident!("{}", p.name);
let pin_name = format_ident!("{}", pin.pin);
g.extend(quote! {
impl_opamp_vout_pin!( #peri, #pin_name );
})
} }
let peri = format_ident!("{}", p.name);
let pin_name = format_ident!("{}", pin.pin);
let ch: u8 = pin.signal.strip_prefix("VP").unwrap().parse().unwrap();
g.extend(quote! {
impl_opamp_pin!( #peri, #pin_name, #ch);
})
} }
// DAC is special // DAC is special
@ -1049,7 +895,15 @@ fn main() {
// ======== // ========
// Generate Div/Mul impls for RCC prescalers/dividers/multipliers. // Generate Div/Mul impls for RCC prescalers/dividers/multipliers.
for e in rcc_registers.ir.enums { let rcc_registers = METADATA
.peripherals
.iter()
.filter_map(|p| p.registers.as_ref())
.find(|r| r.kind == "rcc")
.unwrap()
.ir;
for e in rcc_registers.enums {
fn is_rcc_name(e: &str) -> bool { fn is_rcc_name(e: &str) -> bool {
match e { match e {
"Pllp" | "Pllq" | "Pllr" | "Pllm" | "Plln" => true, "Pllp" | "Pllq" | "Pllr" | "Pllm" | "Plln" => true,

View File

@ -51,7 +51,8 @@ impl<T: Instance> super::sealed::AdcPin<T> for Temperature {
impl<'d, T: Instance> Adc<'d, T> { impl<'d, T: Instance> Adc<'d, T> {
pub fn new(adc: impl Peripheral<P = T> + 'd, delay: &mut impl DelayUs<u32>) -> Self { pub fn new(adc: impl Peripheral<P = T> + 'd, delay: &mut impl DelayUs<u32>) -> Self {
into_ref!(adc); into_ref!(adc);
T::enable_and_reset(); T::enable();
T::reset();
T::regs().cr2().modify(|reg| reg.set_adon(true)); T::regs().cr2().modify(|reg| reg.set_adon(true));
// 11.4: Before starting a calibration, the ADC must have been in power-on state (ADON bit = 1) // 11.4: Before starting a calibration, the ADC must have been in power-on state (ADON bit = 1)

View File

@ -64,7 +64,8 @@ impl<'d, T: Instance> Adc<'d, T> {
into_ref!(adc); into_ref!(adc);
T::enable_and_reset(); T::enable();
T::reset();
// Enable the adc regulator // Enable the adc regulator
T::regs().cr().modify(|w| w.set_advregen(vals::Advregen::INTERMEDIATE)); T::regs().cr().modify(|w| w.set_advregen(vals::Advregen::INTERMEDIATE));

View File

@ -74,9 +74,9 @@ pub(crate) mod sealed {
} }
} }
#[cfg(not(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_g0)))] #[cfg(not(any(adc_f1, adc_v1, adc_v2, adc_v4, adc_f3)))]
pub trait Instance: sealed::Instance + crate::Peripheral<P = Self> {} pub trait Instance: sealed::Instance + crate::Peripheral<P = Self> {}
#[cfg(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_g0))] #[cfg(any(adc_f1, adc_v1, adc_v2, adc_v4, adc_f3))]
pub trait Instance: sealed::Instance + crate::Peripheral<P = Self> + crate::rcc::RccPeripheral {} pub trait Instance: sealed::Instance + crate::Peripheral<P = Self> + crate::rcc::RccPeripheral {}
pub trait AdcPin<T: Instance>: sealed::AdcPin<T> {} pub trait AdcPin<T: Instance>: sealed::AdcPin<T> {}

View File

@ -61,7 +61,8 @@ impl<'d, T: Instance> Adc<'d, T> {
delay: &mut impl DelayUs<u32>, delay: &mut impl DelayUs<u32>,
) -> Self { ) -> Self {
into_ref!(adc); into_ref!(adc);
T::enable_and_reset(); T::enable();
T::reset();
// Delay 1μs when using HSI14 as the ADC clock. // Delay 1μs when using HSI14 as the ADC clock.
// //

View File

@ -95,7 +95,8 @@ where
{ {
pub fn new(adc: impl Peripheral<P = T> + 'd, delay: &mut impl DelayUs<u32>) -> Self { pub fn new(adc: impl Peripheral<P = T> + 'd, delay: &mut impl DelayUs<u32>) -> Self {
into_ref!(adc); into_ref!(adc);
T::enable_and_reset(); T::enable();
T::reset();
let presc = Prescaler::from_pclk2(T::frequency()); let presc = Prescaler::from_pclk2(T::frequency());
T::common_regs().ccr().modify(|w| w.set_adcpre(presc.adcpre())); T::common_regs().ccr().modify(|w| w.set_adcpre(presc.adcpre()));

View File

@ -9,6 +9,19 @@ pub const VREF_DEFAULT_MV: u32 = 3300;
/// VREF voltage used for factory calibration of VREFINTCAL register. /// VREF voltage used for factory calibration of VREFINTCAL register.
pub const VREF_CALIB_MV: u32 = 3000; pub const VREF_CALIB_MV: u32 = 3000;
/// Sadly we cannot use `RccPeripheral::enable` since devices are quite inconsistent ADC clock
/// configuration.
fn enable() {
critical_section::with(|_| {
#[cfg(any(stm32h7, stm32wl))]
crate::pac::RCC.apb2enr().modify(|w| w.set_adcen(true));
#[cfg(stm32g0)]
crate::pac::RCC.apbenr2().modify(|w| w.set_adcen(true));
#[cfg(any(stm32l4, stm32l5, stm32wb))]
crate::pac::RCC.ahb2enr().modify(|w| w.set_adcen(true));
});
}
pub struct VrefInt; pub struct VrefInt;
impl<T: Instance> AdcPin<T> for VrefInt {} impl<T: Instance> AdcPin<T> for VrefInt {}
impl<T: Instance> super::sealed::AdcPin<T> for VrefInt { impl<T: Instance> super::sealed::AdcPin<T> for VrefInt {
@ -48,7 +61,7 @@ impl<T: Instance> super::sealed::AdcPin<T> for Vbat {
impl<'d, T: Instance> Adc<'d, T> { impl<'d, T: Instance> Adc<'d, T> {
pub fn new(adc: impl Peripheral<P = T> + 'd, delay: &mut impl DelayUs<u32>) -> Self { pub fn new(adc: impl Peripheral<P = T> + 'd, delay: &mut impl DelayUs<u32>) -> Self {
into_ref!(adc); into_ref!(adc);
T::enable_and_reset(); enable();
T::regs().cr().modify(|reg| { T::regs().cr().modify(|reg| {
#[cfg(not(adc_g0))] #[cfg(not(adc_g0))]
reg.set_deeppwd(false); reg.set_deeppwd(false);

View File

@ -127,7 +127,8 @@ impl Prescaler {
impl<'d, T: Instance> Adc<'d, T> { impl<'d, T: Instance> Adc<'d, T> {
pub fn new(adc: impl Peripheral<P = T> + 'd, delay: &mut impl DelayUs<u16>) -> Self { pub fn new(adc: impl Peripheral<P = T> + 'd, delay: &mut impl DelayUs<u16>) -> Self {
embassy_hal_internal::into_ref!(adc); embassy_hal_internal::into_ref!(adc);
T::enable_and_reset(); T::enable();
T::reset();
let prescaler = Prescaler::from_ker_ck(T::frequency()); let prescaler = Prescaler::from_ker_ck(T::frequency());

View File

@ -136,7 +136,8 @@ impl<'d, T: Instance> Can<'d, T> {
rx.set_as_af(rx.af_num(), AFType::Input); rx.set_as_af(rx.af_num(), AFType::Input);
tx.set_as_af(tx.af_num(), AFType::OutputPushPull); tx.set_as_af(tx.af_num(), AFType::OutputPushPull);
T::enable_and_reset(); T::enable();
T::reset();
{ {
use crate::pac::can::vals::{Errie, Fmpie, Tmeie}; use crate::pac::can::vals::{Errie, Fmpie, Tmeie};

View File

@ -16,7 +16,9 @@ impl<'d> Crc<'d> {
// Note: enable and reset come from RccPeripheral. // Note: enable and reset come from RccPeripheral.
// enable CRC clock in RCC. // enable CRC clock in RCC.
CRC::enable_and_reset(); CRC::enable();
// Reset CRC to default values.
CRC::reset();
// Peripheral the peripheral // Peripheral the peripheral
let mut instance = Self { _peri: peripheral }; let mut instance = Self { _peri: peripheral };
instance.reset(); instance.reset();

View File

@ -69,13 +69,16 @@ impl<'d> Crc<'d> {
/// Instantiates the CRC32 peripheral and initializes it to default values. /// Instantiates the CRC32 peripheral and initializes it to default values.
pub fn new(peripheral: impl Peripheral<P = CRC> + 'd, config: Config) -> Self { pub fn new(peripheral: impl Peripheral<P = CRC> + 'd, config: Config) -> Self {
// Note: enable and reset come from RccPeripheral. // Note: enable and reset come from RccPeripheral.
// reset to default values and enable CRC clock in RCC. // enable CRC clock in RCC.
CRC::enable_and_reset(); CRC::enable();
// Reset CRC to default values.
CRC::reset();
into_ref!(peripheral); into_ref!(peripheral);
let mut instance = Self { let mut instance = Self {
_peripheral: peripheral, _peripheral: peripheral,
_config: config, _config: config,
}; };
CRC::reset();
instance.reconfigure(); instance.reconfigure();
instance.reset(); instance.reset();
instance instance

View File

@ -255,7 +255,8 @@ impl<'d, T: Instance, Tx> DacCh1<'d, T, Tx> {
) -> Self { ) -> Self {
pin.set_as_analog(); pin.set_as_analog();
into_ref!(peri, dma); into_ref!(peri, dma);
T::enable_and_reset(); T::enable();
T::reset();
let mut dac = Self { _peri: peri, dma }; let mut dac = Self { _peri: peri, dma };
@ -365,7 +366,8 @@ impl<'d, T: Instance, Tx> DacCh2<'d, T, Tx> {
) -> Self { ) -> Self {
pin.set_as_analog(); pin.set_as_analog();
into_ref!(_peri, dma); into_ref!(_peri, dma);
T::enable_and_reset(); T::enable();
T::reset();
let mut dac = Self { let mut dac = Self {
phantom: PhantomData, phantom: PhantomData,
@ -481,7 +483,8 @@ impl<'d, T: Instance, TxCh1, TxCh2> Dac<'d, T, TxCh1, TxCh2> {
pin_ch1.set_as_analog(); pin_ch1.set_as_analog();
pin_ch2.set_as_analog(); pin_ch2.set_as_analog();
into_ref!(peri, dma_ch1, dma_ch2); into_ref!(peri, dma_ch1, dma_ch2);
T::enable_and_reset(); T::enable();
T::reset();
let mut dac_ch1 = DacCh1 { let mut dac_ch1 = DacCh1 {
_peri: peri, _peri: peri,
@ -560,26 +563,35 @@ pub trait DacPin<T: Instance, const C: u8>: crate::gpio::Pin + 'static {}
foreach_peripheral!( foreach_peripheral!(
(dac, $inst:ident) => { (dac, $inst:ident) => {
// H7 uses single bit for both DAC1 and DAC2, this is a hack until a proper fix is implemented // H7 uses single bit for both DAC1 and DAC2, this is a hack until a proper fix is implemented
#[cfg(any(rcc_h7, rcc_h7rm0433))] #[cfg(any(rcc_h7, rcc_h7rm0433))]
impl crate::rcc::sealed::RccPeripheral for peripherals::$inst { impl crate::rcc::sealed::RccPeripheral for peripherals::$inst {
fn frequency() -> crate::time::Hertz { fn frequency() -> crate::time::Hertz {
critical_section::with(|_| unsafe { crate::rcc::get_freqs().pclk1 }) critical_section::with(|_| unsafe { crate::rcc::get_freqs().apb1 })
} }
fn enable_and_reset_with_cs(_cs: critical_section::CriticalSection) { fn reset() {
crate::pac::RCC.apb1lrstr().modify(|w| w.set_dac12rst(true)); critical_section::with(|_| {
crate::pac::RCC.apb1lrstr().modify(|w| w.set_dac12rst(false)); crate::pac::RCC.apb1lrstr().modify(|w| w.set_dac12rst(true));
crate::pac::RCC.apb1lenr().modify(|w| w.set_dac12en(true)); crate::pac::RCC.apb1lrstr().modify(|w| w.set_dac12rst(false));
} })
}
fn disable_with_cs(_cs: critical_section::CriticalSection) { fn enable() {
crate::pac::RCC.apb1lenr().modify(|w| w.set_dac12en(false)) critical_section::with(|_| {
} crate::pac::RCC.apb1lenr().modify(|w| w.set_dac12en(true));
} })
}
#[cfg(any(rcc_h7, rcc_h7rm0433))] fn disable() {
impl crate::rcc::RccPeripheral for peripherals::$inst {} critical_section::with(|_| {
crate::pac::RCC.apb1lenr().modify(|w| w.set_dac12en(false))
})
}
}
#[cfg(any(rcc_h7, rcc_h7rm0433))]
impl crate::rcc::RccPeripheral for peripherals::$inst {}
impl crate::dac::sealed::Instance for peripherals::$inst { impl crate::dac::sealed::Instance for peripherals::$inst {
fn regs() -> &'static crate::pac::dac::Dac { fn regs() -> &'static crate::pac::dac::Dac {

View File

@ -330,7 +330,8 @@ where
use_embedded_synchronization: bool, use_embedded_synchronization: bool,
edm: u8, edm: u8,
) -> Self { ) -> Self {
T::enable_and_reset(); T::reset();
T::enable();
peri.regs().cr().modify(|r| { peri.regs().cr().modify(|r| {
r.set_cm(true); // disable continuous mode (snapshot mode) r.set_cm(true); // disable continuous mode (snapshot mode)

View File

@ -2,9 +2,10 @@
use core::future::Future; use core::future::Future;
use core::pin::Pin; use core::pin::Pin;
use core::sync::atomic::{fence, AtomicUsize, Ordering}; use core::sync::atomic::{fence, Ordering};
use core::task::{Context, Poll, Waker}; use core::task::{Context, Poll, Waker};
use atomic_polyfill::AtomicUsize;
use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef}; use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef};
use embassy_sync::waitqueue::AtomicWaker; use embassy_sync::waitqueue::AtomicWaker;
@ -77,10 +78,10 @@ impl State {
static STATE: State = State::new(); static STATE: State = State::new();
/// safety: must be called only once /// safety: must be called only once
pub(crate) unsafe fn init(cs: critical_section::CriticalSection, irq_priority: Priority) { pub(crate) unsafe fn init(irq_priority: Priority) {
foreach_interrupt! { foreach_interrupt! {
($peri:ident, bdma, $block:ident, $signal_name:ident, $irq:ident) => { ($peri:ident, bdma, $block:ident, $signal_name:ident, $irq:ident) => {
crate::interrupt::typelevel::$irq::set_priority_with_cs(cs, irq_priority); crate::interrupt::typelevel::$irq::set_priority(irq_priority);
crate::interrupt::typelevel::$irq::enable(); crate::interrupt::typelevel::$irq::enable();
}; };
} }
@ -126,13 +127,7 @@ pub(crate) unsafe fn on_irq_inner(dma: pac::bdma::Dma, channel_num: usize, index
} else if isr.tcif(channel_num) && cr.read().tcie() { } else if isr.tcif(channel_num) && cr.read().tcie() {
// Acknowledge transfer complete interrupt // Acknowledge transfer complete interrupt
dma.ifcr().write(|w| w.set_tcif(channel_num, true)); dma.ifcr().write(|w| w.set_tcif(channel_num, true));
#[cfg(not(armv6m))]
STATE.complete_count[index].fetch_add(1, Ordering::Release); STATE.complete_count[index].fetch_add(1, Ordering::Release);
#[cfg(armv6m)]
critical_section::with(|_| {
let x = STATE.complete_count[index].load(Ordering::Relaxed);
STATE.complete_count[index].store(x + 1, Ordering::Release);
})
} else { } else {
return; return;
} }
@ -396,14 +391,7 @@ impl<'a, C: Channel> DmaCtrl for DmaCtrlImpl<'a, C> {
} }
fn reset_complete_count(&mut self) -> usize { fn reset_complete_count(&mut self) -> usize {
#[cfg(not(armv6m))] STATE.complete_count[self.0.index()].swap(0, Ordering::AcqRel)
return STATE.complete_count[self.0.index()].swap(0, Ordering::AcqRel);
#[cfg(armv6m)]
return critical_section::with(|_| {
let x = STATE.complete_count[self.0.index()].load(Ordering::Acquire);
STATE.complete_count[self.0.index()].store(0, Ordering::Release);
x
});
} }
fn set_waker(&mut self, waker: &Waker) { fn set_waker(&mut self, waker: &Waker) {

Some files were not shown because too many files have changed in this diff Show More