From 22ec789651055fab780658797b603353a4600c04 Mon Sep 17 00:00:00 2001 From: Scott Mabin Date: Thu, 19 Oct 2023 15:36:38 +0200 Subject: [PATCH] Unify examples This PR merges the chip specific examples into one folder, inside the esp-wifi project. To simplify building, alias' have been added to `esp-wifi/.cargo/config.toml` per chip to automatically select the right target and enable the chip feature. Add build script detection for invalid features Fix CI, use build instead of check to detect linker errors enable async feature of hal, this breaks because of interrupt definition for systimer upgrade hal rev upgrade hal rev c6 undo binding modifications fix esp now fix esp coex use released hals, update async examples sync example names sync example names Update examples.md Document alias update build alias --- .github/workflows/ci.yml | 123 +++------- Cargo.toml | 25 +- esp-wifi/.cargo/config.toml | 60 +++-- esp-wifi/Cargo.toml | 36 ++- esp-wifi/build.rs | 25 ++ .../examples/access_point.rs | 10 +- {examples-esp32 => esp-wifi}/examples/ble.rs | 17 +- .../examples/coex.rs | 10 +- .../examples/dhcp.rs | 10 +- .../examples/embassy_access_point.rs | 114 ++++----- .../examples/embassy_ble.rs | 107 ++++----- .../examples/embassy_dhcp.rs | 134 +++++------ .../examples/embassy_esp_now.rs | 78 +++---- .../examples/embassy_esp_now_duplex.rs | 120 ++++------ .../examples/esp_now.rs | 10 +- .../examples/static_ip.rs | 10 +- esp-wifi/src/ble/controller/mod.rs | 13 +- esp-wifi/src/esp_now/mod.rs | 16 +- esp-wifi/src/timer/riscv.rs | 6 +- esp-wifi/src/wifi/mod.rs | 12 +- esp-wifi/src/wifi/utils.rs | 2 +- examples-esp32/.cargo/config.toml | 13 -- examples-esp32/Cargo.toml | 49 ---- examples-esp32/examples/access_point.rs | 165 ------------- examples-esp32/examples/async_ble.rs | 174 -------------- examples-esp32/examples/coex.rs | 183 --------------- examples-esp32/examples/dhcp.rs | 153 ------------ .../examples/embassy_access_point.rs | 218 ----------------- examples-esp32/examples/embassy_dhcp.rs | 195 ---------------- examples-esp32/examples/embassy_esp_now.rs | 97 -------- .../examples/embassy_esp_now_duplex.rs | 133 ----------- examples-esp32/examples/esp_now.rs | 80 ------- examples-esp32/examples/static_ip.rs | 199 ---------------- examples-esp32/src/lib.rs | 3 - examples-esp32c2/.cargo/config.toml | 30 --- examples-esp32c2/Cargo.toml | 50 ---- examples-esp32c2/examples/access_point.rs | 160 ------------- examples-esp32c2/examples/async_ble.rs | 169 -------------- examples-esp32c2/examples/ble.rs | 151 ------------ examples-esp32c2/examples/dhcp.rs | 149 ------------ .../examples/embassy_access_point.rs | 214 ----------------- examples-esp32c2/examples/embassy_dhcp.rs | 191 --------------- examples-esp32c2/examples/embassy_esp_now.rs | 93 -------- .../examples/embassy_esp_now_duplex.rs | 130 ----------- examples-esp32c2/examples/esp_now.rs | 76 ------ examples-esp32c2/examples/static_ip.rs | 195 ---------------- examples-esp32c2/rust-toolchain.toml | 2 - examples-esp32c2/src/lib.rs | 3 - examples-esp32c3/.cargo/config.toml | 30 --- examples-esp32c3/Cargo.toml | 50 ---- examples-esp32c3/examples/async_ble.rs | 169 -------------- examples-esp32c3/examples/ble.rs | 151 ------------ .../examples/embassy_access_point.rs | 214 ----------------- examples-esp32c3/examples/embassy_dhcp.rs | 191 --------------- examples-esp32c3/examples/embassy_esp_now.rs | 93 -------- .../examples/embassy_esp_now_duplex.rs | 130 ----------- examples-esp32c3/rust-toolchain.toml | 2 - examples-esp32c3/src/lib.rs | 3 - examples-esp32c6/.cargo/config.toml | 15 -- examples-esp32c6/Cargo.toml | 50 ---- examples-esp32c6/examples/access_point.rs | 161 ------------- examples-esp32c6/examples/ble.rs | 151 ------------ examples-esp32c6/examples/dhcp.rs | 149 ------------ .../examples/embassy_esp_now_duplex.rs | 130 ----------- examples-esp32c6/examples/esp_now.rs | 76 ------ examples-esp32c6/examples/static_ip.rs | 195 ---------------- examples-esp32c6/rust-toolchain.toml | 2 - examples-esp32c6/src/lib.rs | 3 - examples-esp32s2/.cargo/config.toml | 29 --- examples-esp32s2/Cargo.toml | 47 ---- examples-esp32s2/examples/access_point.rs | 166 ------------- examples-esp32s2/examples/dhcp.rs | 154 ------------ .../examples/embassy_access_point.rs | 219 ------------------ examples-esp32s2/examples/embassy_dhcp.rs | 196 ---------------- examples-esp32s2/examples/embassy_esp_now.rs | 98 -------- examples-esp32s2/examples/esp_now.rs | 81 ------- examples-esp32s2/examples/static_ip.rs | 200 ---------------- examples-esp32s2/rust-toolchain.toml | 2 - examples-esp32s2/src/lib.rs | 3 - examples-esp32s3/.cargo/config.toml | 15 -- examples-esp32s3/Cargo.toml | 50 ---- examples-esp32s3/examples/access_point.rs | 166 ------------- examples-esp32s3/examples/async_ble.rs | 174 -------------- examples-esp32s3/examples/ble.rs | 156 ------------- examples-esp32s3/examples/coex.rs | 183 --------------- examples-esp32s3/examples/dhcp.rs | 154 ------------ .../examples/embassy_access_point.rs | 219 ------------------ examples-esp32s3/examples/embassy_dhcp.rs | 196 ---------------- examples-esp32s3/examples/embassy_esp_now.rs | 98 -------- .../examples/embassy_esp_now_duplex.rs | 133 ----------- examples-esp32s3/examples/esp_now.rs | 81 ------- examples-esp32s3/examples/static_ip.rs | 200 ---------------- examples-esp32s3/rust-toolchain.toml | 2 - examples-esp32s3/src/lib.rs | 3 - examples.md | 30 +-- ...rust-toolchain.toml => rust-toolchain.toml | 0 96 files changed, 449 insertions(+), 8784 deletions(-) rename {examples-esp32c3 => esp-wifi}/examples/access_point.rs (94%) rename {examples-esp32 => esp-wifi}/examples/ble.rs (89%) rename {examples-esp32c3 => esp-wifi}/examples/coex.rs (93%) rename {examples-esp32c3 => esp-wifi}/examples/dhcp.rs (93%) rename {examples-esp32c6 => esp-wifi}/examples/embassy_access_point.rs (82%) rename examples-esp32c6/examples/async_ble.rs => esp-wifi/examples/embassy_ble.rs (81%) rename {examples-esp32c6 => esp-wifi}/examples/embassy_dhcp.rs (80%) rename {examples-esp32c6 => esp-wifi}/examples/embassy_esp_now.rs (71%) rename {examples-esp32s2 => esp-wifi}/examples/embassy_esp_now_duplex.rs (70%) rename {examples-esp32c3 => esp-wifi}/examples/esp_now.rs (88%) rename {examples-esp32c3 => esp-wifi}/examples/static_ip.rs (95%) delete mode 100644 examples-esp32/.cargo/config.toml delete mode 100644 examples-esp32/Cargo.toml delete mode 100644 examples-esp32/examples/access_point.rs delete mode 100644 examples-esp32/examples/async_ble.rs delete mode 100644 examples-esp32/examples/coex.rs delete mode 100644 examples-esp32/examples/dhcp.rs delete mode 100644 examples-esp32/examples/embassy_access_point.rs delete mode 100644 examples-esp32/examples/embassy_dhcp.rs delete mode 100644 examples-esp32/examples/embassy_esp_now.rs delete mode 100644 examples-esp32/examples/embassy_esp_now_duplex.rs delete mode 100644 examples-esp32/examples/esp_now.rs delete mode 100644 examples-esp32/examples/static_ip.rs delete mode 100644 examples-esp32/src/lib.rs delete mode 100644 examples-esp32c2/.cargo/config.toml delete mode 100644 examples-esp32c2/Cargo.toml delete mode 100644 examples-esp32c2/examples/access_point.rs delete mode 100644 examples-esp32c2/examples/async_ble.rs delete mode 100644 examples-esp32c2/examples/ble.rs delete mode 100644 examples-esp32c2/examples/dhcp.rs delete mode 100644 examples-esp32c2/examples/embassy_access_point.rs delete mode 100644 examples-esp32c2/examples/embassy_dhcp.rs delete mode 100644 examples-esp32c2/examples/embassy_esp_now.rs delete mode 100644 examples-esp32c2/examples/embassy_esp_now_duplex.rs delete mode 100644 examples-esp32c2/examples/esp_now.rs delete mode 100644 examples-esp32c2/examples/static_ip.rs delete mode 100644 examples-esp32c2/rust-toolchain.toml delete mode 100644 examples-esp32c2/src/lib.rs delete mode 100644 examples-esp32c3/.cargo/config.toml delete mode 100644 examples-esp32c3/Cargo.toml delete mode 100644 examples-esp32c3/examples/async_ble.rs delete mode 100644 examples-esp32c3/examples/ble.rs delete mode 100644 examples-esp32c3/examples/embassy_access_point.rs delete mode 100644 examples-esp32c3/examples/embassy_dhcp.rs delete mode 100644 examples-esp32c3/examples/embassy_esp_now.rs delete mode 100644 examples-esp32c3/examples/embassy_esp_now_duplex.rs delete mode 100644 examples-esp32c3/rust-toolchain.toml delete mode 100644 examples-esp32c3/src/lib.rs delete mode 100644 examples-esp32c6/.cargo/config.toml delete mode 100644 examples-esp32c6/Cargo.toml delete mode 100644 examples-esp32c6/examples/access_point.rs delete mode 100644 examples-esp32c6/examples/ble.rs delete mode 100644 examples-esp32c6/examples/dhcp.rs delete mode 100644 examples-esp32c6/examples/embassy_esp_now_duplex.rs delete mode 100644 examples-esp32c6/examples/esp_now.rs delete mode 100644 examples-esp32c6/examples/static_ip.rs delete mode 100644 examples-esp32c6/rust-toolchain.toml delete mode 100644 examples-esp32c6/src/lib.rs delete mode 100644 examples-esp32s2/.cargo/config.toml delete mode 100644 examples-esp32s2/Cargo.toml delete mode 100644 examples-esp32s2/examples/access_point.rs delete mode 100644 examples-esp32s2/examples/dhcp.rs delete mode 100644 examples-esp32s2/examples/embassy_access_point.rs delete mode 100644 examples-esp32s2/examples/embassy_dhcp.rs delete mode 100644 examples-esp32s2/examples/embassy_esp_now.rs delete mode 100644 examples-esp32s2/examples/esp_now.rs delete mode 100644 examples-esp32s2/examples/static_ip.rs delete mode 100644 examples-esp32s2/rust-toolchain.toml delete mode 100644 examples-esp32s2/src/lib.rs delete mode 100644 examples-esp32s3/.cargo/config.toml delete mode 100644 examples-esp32s3/Cargo.toml delete mode 100644 examples-esp32s3/examples/access_point.rs delete mode 100644 examples-esp32s3/examples/async_ble.rs delete mode 100644 examples-esp32s3/examples/ble.rs delete mode 100644 examples-esp32s3/examples/coex.rs delete mode 100644 examples-esp32s3/examples/dhcp.rs delete mode 100644 examples-esp32s3/examples/embassy_access_point.rs delete mode 100644 examples-esp32s3/examples/embassy_dhcp.rs delete mode 100644 examples-esp32s3/examples/embassy_esp_now.rs delete mode 100644 examples-esp32s3/examples/embassy_esp_now_duplex.rs delete mode 100644 examples-esp32s3/examples/esp_now.rs delete mode 100644 examples-esp32s3/examples/static_ip.rs delete mode 100644 examples-esp32s3/rust-toolchain.toml delete mode 100644 examples-esp32s3/src/lib.rs rename examples-esp32/rust-toolchain.toml => rust-toolchain.toml (100%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 248df124..82415ae3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,10 +40,10 @@ jobs: - name: check-fmt run: cargo fmt --check - checks-xtensa: + builds: strategy: matrix: - chip: ["esp32", "esp32s2", "esp32s3"] + chip: ["esp32", "esp32s2", "esp32s3", "esp32c2", "esp32c3", "esp32c6"] runs-on: ubuntu-latest steps: @@ -51,91 +51,42 @@ jobs: - uses: esp-rs/xtensa-toolchain@v1.5 with: default: true - buildtargets: ${{ matrix.chip }} ldproxy: false - uses: Swatinem/rust-cache@v1 - - name: check - run: cd examples-${{ matrix.chip }} && cargo check - - name: check (common features) - run: cd examples-${{ matrix.chip }} && cargo check --features=async,wifi,esp-now,embassy-net,log - - name: check (common features + defmt) - run: cd examples-${{ matrix.chip }} && cargo check --no-default-features --features=${{ matrix.chip }},async,wifi,esp-now,embassy-net,defmt - - name: check (dhcp) - run: cd examples-${{ matrix.chip }} && cargo build --release --example=dhcp --features=wifi - - name: check (static_ip) - run: cd examples-${{ matrix.chip }} && cargo build --release --example=static_ip --features=wifi - - name: check (esp_now) - run: cd examples-${{ matrix.chip }} && cargo build --release --example=esp_now --features=esp-now - - name: check (embassy_esp_now) - run: cd examples-${{ matrix.chip }} && cargo build --release --example=embassy_esp_now --features=async,esp-now - - name: check (embassy_esp_now_duplex) - run: cd examples-${{ matrix.chip }} && cargo build --release --example=embassy_esp_now_duplex --features=async,esp-now - - name: check (embassy_dhcp) - run: cd examples-${{ matrix.chip }} && cargo build --release --example=embassy_dhcp --features=async,wifi,embassy-net - - name: check (embassy_access_point) - run: cd examples-${{ matrix.chip }} && cargo build --release --example=embassy_access_point --features=async,wifi,embassy-net + - name: build + run: cd esp-wifi && cargo b${{ matrix.chip }} + - name: build (common features) + run: cd esp-wifi && cargo b${{ matrix.chip }} --features=async,wifi,esp-now,embassy-net,log,${{ matrix.chip }}-hal/embassy-time-timg0 + - name: build (common features + defmt) + run: cd esp-wifi && cargo b${{ matrix.chip }} --no-default-features --features=async,wifi,esp-now,embassy-net,defmt,${{ matrix.chip }}-hal/embassy-time-timg0 + - name: build (dhcp) + run: cd esp-wifi && cargo b${{ matrix.chip }} --release --example=dhcp --features=wifi + - name: build (static_ip) + run: cd esp-wifi && cargo b${{ matrix.chip }} --release --example=static_ip --features=wifi + - name: build (esp_now) + run: cd esp-wifi && cargo b${{ matrix.chip }} --release --example=esp_now --features=esp-now + - name: build (embassy_esp_now) + run: cd esp-wifi && cargo b${{ matrix.chip }} --release --example=embassy_esp_now --features=async,esp-now,${{ matrix.chip }}-hal/embassy-time-timg0 + - name: build (embassy_esp_now_duplex) + run: cd esp-wifi && cargo b${{ matrix.chip }} --release --example=embassy_esp_now_duplex --features=async,esp-now,${{ matrix.chip }}-hal/embassy-time-timg0 + - name: build (embassy_dhcp) + run: cd esp-wifi && cargo b${{ matrix.chip }} --release --example=embassy_dhcp --features=async,wifi,embassy-net,${{ matrix.chip }}-hal/embassy-time-timg0 + - name: build (embassy_access_point) + run: cd esp-wifi && cargo b${{ matrix.chip }} --release --example=embassy_access_point --features=async,wifi,embassy-net,${{ matrix.chip }}-hal/embassy-time-timg0 - - name: check (common features + ble) - if: ${{ matrix.chip == 'esp32' || matrix.chip == 'esp32s3' }} - run: cd examples-${{ matrix.chip }} && cargo check --features=async,wifi,ble,esp-now,embassy-net,log - - name: check (common features + ble + defmt) - if: ${{ matrix.chip == 'esp32' || matrix.chip == 'esp32s3' }} - run: cd examples-${{ matrix.chip }} && cargo check --no-default-features --features=${{ matrix.chip }},async,wifi,ble,esp-now,embassy-net,defmt - - name: check (ble) - if: ${{ matrix.chip == 'esp32' || matrix.chip == 'esp32s3' }} - run: cd examples-${{ matrix.chip }} && cargo build --release --example=ble --features=ble - - name: check (async_ble) - if: ${{ matrix.chip == 'esp32' || matrix.chip == 'esp32s3' }} - run: cd examples-${{ matrix.chip }} && cargo build --release --example=async_ble --features=async,ble - - name: check (coex) - if: ${{ matrix.chip == 'esp32' || matrix.chip == 'esp32s3' }} - run: cd examples-${{ matrix.chip }} && cargo build --release --example=coex --features=wifi,ble,coex - - checks-riscv: - strategy: - matrix: - chip: ["esp32c2", "esp32c3", "esp32c6"] - - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: dtolnay/rust-toolchain@v1 - with: - target: riscv32imc-unknown-none-elf - toolchain: nightly-2023-05-16 - components: rust-src,rustfmt - - uses: Swatinem/rust-cache@v1 - - - name: check - run: cd examples-${{ matrix.chip }} && cargo +nightly-2023-05-16 check - - name: check (common features) - run: cd examples-${{ matrix.chip }} && cargo +nightly-2023-05-16 check --features=async,wifi,esp-now,embassy-net,log - - name: check (common features + defmt) - run: cd examples-${{ matrix.chip }} && cargo +nightly-2023-05-16 check --no-default-features --features=${{ matrix.chip }},async,wifi,esp-now,embassy-net,defmt - - name: check (dhcp) - run: cd examples-${{ matrix.chip }} && cargo +nightly-2023-05-16 build --release --example=dhcp --features=wifi - - name: check (static_ip) - run: cd examples-${{ matrix.chip }} && cargo +nightly-2023-05-16 build --release --example=static_ip --features=wifi - - name: check (esp_now) - run: cd examples-${{ matrix.chip }} && cargo +nightly-2023-05-16 build --release --example=esp_now --features=esp-now - - name: check (embassy_esp_now) - run: cd examples-${{ matrix.chip }} && cargo +nightly-2023-05-16 build --release --example=embassy_esp_now --features=async,esp-now - - name: check (embassy_esp_now_duplex) - run: cd examples-${{ matrix.chip }} && cargo +nightly-2023-05-16 build --release --example=embassy_esp_now_duplex --features=async,esp-now - - name: check (embassy_dhcp) - run: cd examples-${{ matrix.chip }} && cargo +nightly-2023-05-16 build --release --example=embassy_dhcp --features=async,wifi,embassy-net - - name: check (embassy_access_point) - run: cd examples-${{ matrix.chip }} && cargo +nightly-2023-05-16 build --release --example=embassy_access_point --features=async,wifi,embassy-net - - - name: check (common features + ble) - run: cd examples-${{ matrix.chip }} && cargo +nightly-2023-05-16 check --features=async,wifi,ble,esp-now,embassy-net,log - - name: check (common features + ble + defmt) - run: cd examples-${{ matrix.chip }} && cargo +nightly-2023-05-16 check --no-default-features --features=${{ matrix.chip }},async,wifi,ble,esp-now,embassy-net,defmt - - name: check (ble) - run: cd examples-${{ matrix.chip }} && cargo +nightly-2023-05-16 build --release --example=ble --features=ble - - name: check (async_ble) - run: cd examples-${{ matrix.chip }} && cargo +nightly-2023-05-16 build --release --example=async_ble --features=async,ble - - name: check (coex) - if: ${{ matrix.chip == 'esp32c3' }} - run: cd examples-${{ matrix.chip }} && cargo +nightly-2023-05-16 build --release --example=coex --features=wifi,ble,coex + - name: build (common features + ble) + if: ${{ matrix.chip != 'esp32s2' }} + run: cd esp-wifi && cargo b${{ matrix.chip }} --features=async,wifi,ble,esp-now,embassy-net,log,${{ matrix.chip }}-hal/embassy-time-timg0 + - name: build (common features + ble + defmt) + if: ${{ matrix.chip != 'esp32s2' }} + run: cd esp-wifi && cargo b${{ matrix.chip }} --no-default-features --features=async,wifi,ble,esp-now,embassy-net,defmt,${{ matrix.chip }}-hal/embassy-time-timg0 + - name: build (ble) + if: ${{ matrix.chip != 'esp32s2' }} + run: cd esp-wifi && cargo b${{ matrix.chip }} --release --example=ble --features=ble + - name: build (embassy_ble) + if: ${{ matrix.chip != 'esp32s2' }} + run: cd esp-wifi && cargo b${{ matrix.chip }} --release --example=embassy_ble --features=async,ble,${{ matrix.chip }}-hal/embassy-time-timg0 + - name: build (coex) + if: ${{ matrix.chip == 'esp32' || matrix.chip == 'esp32s3' || matrix.chip == 'esp32c3' }} + run: cd esp-wifi && cargo b${{ matrix.chip }} --release --example=coex --features=wifi,ble,coex diff --git a/Cargo.toml b/Cargo.toml index 77d3fe42..6da9972a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,12 +3,6 @@ members = [ "esp-wifi", "esp-wifi-sys", "xtask", - "examples-esp32c2", - "examples-esp32c3", - "examples-esp32c6", - "examples-esp32", - "examples-esp32s2", - "examples-esp32s3", ] exclude = [ "extras/esp-wifishark", @@ -27,12 +21,12 @@ lto = "off" [workspace.dependencies] defmt = "=0.3.5" -esp32c3-hal = { version = "0.12.0" } -esp32c2-hal = { version = "0.10.0" } -esp32c6-hal = { version = "0.5.0" } -esp32-hal = { version = "0.15.0" } -esp32s3-hal = { version = "0.12.0" } -esp32s2-hal = { version = "0.12.0" } +esp32c3-hal = { version = "0.13.0" } +esp32c2-hal = { version = "0.11.0" } +esp32c6-hal = { version = "0.6.0" } +esp32-hal = { version = "0.16.0" } +esp32s3-hal = { version = "0.13.0" } +esp32s2-hal = { version = "0.13.0" } smoltcp = { version = "0.10.0", default-features=false, features = ["proto-igmp", "proto-ipv4", "proto-dns", "socket-tcp", "socket-icmp", "socket-udp", "socket-dns", "medium-ethernet", "proto-dhcpv4", "socket-raw", "socket-dhcpv4"] } critical-section = "1.1.1" atomic-polyfill = "1.0.2" @@ -53,6 +47,7 @@ embassy-net-driver = { version = "0.1.0" } toml-cfg = "0.1.3" libm = "0.2.7" cfg-if = "1.0.0" +static_cell = { version = "1", features = ["nightly"] } embassy-net = { version = "0.1.0", features = ["nightly", "tcp", "udp", "dhcpv4", "medium-ethernet"] } bleps = { git = "https://github.com/bjoernQ/bleps", package = "bleps", rev = "b82f1e7009bef7e32f0918be5b186188aa5e7109", features = ["macros"] } @@ -63,7 +58,7 @@ esp-println = { version = "0.6.0" } esp-backtrace = { version = "0.8.0", features = ["panic-handler", "exception-handler", "print-uart"] } embedded-hal-async = { version = "1.0.0-rc.1" } -# patching esp32c6-hal for BLE - it would compile with 0.5.0 but not work +# required until https://github.com/esp-rs/esp-hal/pull/891 is released [patch.crates-io] -esp32c6-hal = { git = "https://github.com/esp-rs/esp-hal.git", rev = "4c34ebe9e264fcc31fabba862274adae8daa680a" } -esp-hal-common = { git = "https://github.com/esp-rs/esp-hal.git", rev = "4c34ebe9e264fcc31fabba862274adae8daa680a" } +esp32c3-hal = { git = "https://github.com/esp-rs/esp-hal.git", rev = "8eddb9e737a1bfe0a36f90f54103e9167114813a" } +esp-hal-common = { git = "https://github.com/esp-rs/esp-hal.git", rev = "8eddb9e737a1bfe0a36f90f54103e9167114813a" } \ No newline at end of file diff --git a/esp-wifi/.cargo/config.toml b/esp-wifi/.cargo/config.toml index 6d918fa4..6e6e2c19 100644 --- a/esp-wifi/.cargo/config.toml +++ b/esp-wifi/.cargo/config.toml @@ -1,12 +1,33 @@ +# Alias' for quickly building for different chips or running examples +# By default we enable +# - `embassy-time-timg0` as the examples assume we are using this time driver +# - `embassy-executor-thread` on Xtensa chips to take advantage of the Xtensa specific executor we have in esp-hal +[alias] +esp32 = "run --features esp32 --target xtensa-esp32-none-elf --features esp32-hal/embassy-time-timg0,esp32-hal/embassy-executor-thread" +esp32s2 = "run --features esp32s2 --target xtensa-esp32s2-none-elf --features esp32s2-hal/embassy-time-timg0,esp32s2-hal/embassy-executor-thread" +esp32s3 = "run --features esp32s3 --target xtensa-esp32s3-none-elf --features esp32s3-hal/embassy-time-timg0,esp32s3-hal/embassy-executor-thread" +esp32c2 = "run --features esp32c2 --target riscv32imc-unknown-none-elf --features esp32c2-hal/embassy-time-timg0" +esp32c3 = "run --features esp32c3 --target riscv32imc-unknown-none-elf --features esp32c3-hal/embassy-time-timg0" +esp32c6 = "run --features esp32c6 --target riscv32imac-unknown-none-elf --features esp32c6-hal/embassy-time-timg0" + +besp32 = "build --features esp32 --target xtensa-esp32-none-elf --features esp32-hal/embassy-time-timg0,esp32-hal/embassy-executor-thread" +besp32s2 = "build --features esp32s2 --target xtensa-esp32s2-none-elf --features esp32s2-hal/embassy-time-timg0,esp32s2-hal/embassy-executor-thread" +besp32s3 = "build --features esp32s3 --target xtensa-esp32s3-none-elf --features esp32s3-hal/embassy-time-timg0,esp32s3-hal/embassy-executor-thread" +besp32c2 = "build --features esp32c2 --target riscv32imc-unknown-none-elf --features esp32c2-hal/embassy-time-timg0" +besp32c3 = "build --features esp32c3 --target riscv32imc-unknown-none-elf --features esp32c3-hal/embassy-time-timg0" +besp32c6 = "build --features esp32c6 --target riscv32imac-unknown-none-elf --features esp32c6-hal/embassy-time-timg0" + [target.riscv32imc-unknown-none-elf] runner = "espflash flash --monitor" - rustflags = [ "-C", "link-arg=-Tlinkall.x", "-C", "link-arg=-Trom_functions.x", "-C", "force-frame-pointers", + # Enable the atomic codegen option for RISCV + "-C", "target-feature=+a", + # tell the core library have atomics even though it's not specified in the target definition "--cfg", "target_has_atomic_load_store", "--cfg", 'target_has_atomic_load_store="8"', @@ -23,72 +44,49 @@ rustflags = [ [target.riscv32imac-unknown-none-elf] runner = "espflash flash --monitor" - rustflags = [ "-C", "link-arg=-Tlinkall.x", "-C", "link-arg=-Trom_functions.x", - "-C", "force-frame-pointers", - - # tell the core library have atomics even though it's not specified in the target definition - "--cfg", "target_has_atomic_load_store", - "--cfg", 'target_has_atomic_load_store="8"', - "--cfg", 'target_has_atomic_load_store="16"', - "--cfg", 'target_has_atomic_load_store="32"', - "--cfg", 'target_has_atomic_load_store="ptr"', - # enable cas - "--cfg", "target_has_atomic", - "--cfg", 'target_has_atomic="8"', - "--cfg", 'target_has_atomic="16"', - "--cfg", 'target_has_atomic="32"', - "--cfg", 'target_has_atomic="ptr"', ] [target.xtensa-esp32-none-elf] runner = "espflash flash --monitor" - rustflags = [ - #"-C", "linker=rust-lld", - "-C", "link-arg=-Tlinkall.x", "-C", "link-arg=-Trom_functions.x", ] [target.xtensa-esp32s3-none-elf] runner = "espflash flash --monitor" - rustflags = [ - #"-C", "linker=rust-lld", - "-C", "link-arg=-Tlinkall.x", "-C", "link-arg=-Trom_functions.x", - - # for now disable loop optimization - "-C", "target-feature=-loop", ] [target.xtensa-esp32s2-none-elf] runner = "espflash flash --monitor" - rustflags = [ - #"-C", "linker=rust-lld", - "-C", "link-arg=-Tlinkall.x", "-C", "link-arg=-Trom_functions.x", # Enable the atomic codegen option for Xtensa "-C", "target-feature=+s32c1i", + # tell the core library have atomics even though it's not specified in the target definition + "--cfg", "target_has_atomic_load_store", + "--cfg", 'target_has_atomic_load_store="8"', + "--cfg", 'target_has_atomic_load_store="16"', + "--cfg", 'target_has_atomic_load_store="32"', + "--cfg", 'target_has_atomic_load_store="ptr"', # Tell the `core` library that we have atomics, even though it's not # specified in the target definition + "--cfg", 'target_has_atomic', "--cfg", 'target_has_atomic="8"', "--cfg", 'target_has_atomic="16"', "--cfg", 'target_has_atomic="32"', "--cfg", 'target_has_atomic="ptr"', ] -[build] -target = "riscv32imc-unknown-none-elf" - [unstable] build-std = [ "core" ] diff --git a/esp-wifi/Cargo.toml b/esp-wifi/Cargo.toml index fff04c17..8b7c3343 100644 --- a/esp-wifi/Cargo.toml +++ b/esp-wifi/Cargo.toml @@ -36,16 +36,33 @@ atomic_enum = { workspace = true } [build-dependencies] toml-cfg.workspace = true +[dev-dependencies] +esp-println = { workspace = true, features = ["log"] } +esp-backtrace = { workspace = true } +embedded-svc.workspace = true +embassy-executor = { workspace = true } +embassy-time.workspace = true +embassy-futures.workspace = true +futures-util.workspace = true +embassy-net = { workspace = true } +embassy-sync.workspace = true +bleps.workspace = true +embedded-io.workspace = true +embedded-hal-async = { workspace = true } +log = { workspace = true } +smoltcp.workspace = true +static_cell = { workspace = true } + [features] default = [ "utils", "log" ] # chip features -esp32c2 = [ "esp32c2-hal", "esp-wifi-sys/esp32c2" ] -esp32c3 = [ "esp32c3-hal", "esp-wifi-sys/esp32c3" ] -esp32c6 = [ "esp32c6-hal", "esp-wifi-sys/esp32c6" ] -esp32 = [ "esp32-hal", "esp-wifi-sys/esp32" ] -esp32s2 = [ "esp32s2-hal", "esp-wifi-sys/esp32s2" ] -esp32s3 = [ "esp32s3-hal", "esp-wifi-sys/esp32s3" ] +esp32c2 = [ "esp32c2-hal", "esp-wifi-sys/esp32c2", "esp-println/esp32c2", "esp-backtrace/esp32c2", "embassy-executor/arch-riscv32" ] +esp32c3 = [ "esp32c3-hal", "esp-wifi-sys/esp32c3", "esp-println/esp32c3", "esp-backtrace/esp32c3", "embassy-executor/arch-riscv32" ] +esp32c6 = [ "esp32c6-hal", "esp-wifi-sys/esp32c6", "esp-println/esp32c6", "esp-backtrace/esp32c6", "embassy-executor/arch-riscv32" ] +esp32 = [ "esp32-hal", "esp-wifi-sys/esp32", "esp-println/esp32", "esp-backtrace/esp32" ] +esp32s2 = [ "esp32s2-hal", "esp-wifi-sys/esp32s2", "esp-println/esp32s2", "esp-backtrace/esp32s2" ] +esp32s3 = [ "esp32s3-hal", "esp-wifi-sys/esp32s3", "esp-println/esp32s3", "esp-backtrace/esp32s3" ] # async features async = [ @@ -58,6 +75,13 @@ async = [ "esp32-hal?/embassy", "esp32s2-hal?/embassy", "esp32s3-hal?/embassy", + "esp32c3-hal?/async", + "esp32c2-hal?/async", + "esp32c6-hal?/async", + "esp32-hal?/async", + "esp32s2-hal?/async", + "esp32s3-hal?/async", + "bleps/async" ] embassy-net = ["dep:embassy-net-driver", "async"] diff --git a/esp-wifi/build.rs b/esp-wifi/build.rs index b3c8e9bb..e3f043ee 100644 --- a/esp-wifi/build.rs +++ b/esp-wifi/build.rs @@ -7,6 +7,31 @@ feature = "esp32s3", ))] fn main() -> Result<(), String> { + #[cfg(all(feature = "ble", feature = "esp32s2"))] + { + panic!( + r#" + + BLE is not supported on this target. + + "# + ); + } + #[cfg(all( + feature = "coex", + any(feature = "esp32s2", feature = "esp32c2", feature = "esp32c6") + ))] + { + panic!( + r#" + + COEX is not yet supported on this target. + + See https://github.com/esp-rs/esp-wifi/issues/92. + + "# + ); + } match std::env::var("OPT_LEVEL") { Ok(level) => { if level != "2" && level != "3" { diff --git a/examples-esp32c3/examples/access_point.rs b/esp-wifi/examples/access_point.rs similarity index 94% rename from examples-esp32c3/examples/access_point.rs rename to esp-wifi/examples/access_point.rs index dd45e723..36e88a11 100644 --- a/examples-esp32c3/examples/access_point.rs +++ b/esp-wifi/examples/access_point.rs @@ -12,7 +12,6 @@ use embedded_svc::ipv4::Interface; use embedded_svc::wifi::{AccessPointConfiguration, Configuration, Wifi}; use esp_backtrace as _; - use esp_println::{print, println}; use esp_wifi::initialize; use esp_wifi::wifi::utils::create_network_interface; @@ -20,8 +19,8 @@ use esp_wifi::wifi::WifiMode; use esp_wifi::wifi_interface::WifiStack; use esp_wifi::{current_millis, EspWifiInitFor}; use hal::clock::ClockControl; +use hal::Rng; use hal::{peripherals::Peripherals, prelude::*}; -use hal::{systimer::SystemTimer, Rng}; use smoltcp::iface::SocketStorage; @@ -35,7 +34,10 @@ fn main() -> ! { let system = peripherals.SYSTEM.split(); let clocks = ClockControl::max(system.clock_control).freeze(); - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; + #[cfg(target_arch = "xtensa")] + let timer = hal::timer::TimerGroup::new(peripherals.TIMG1, &clocks).timer0; + #[cfg(target_arch = "riscv32")] + let timer = hal::systimer::SystemTimer::new(peripherals.SYSTIMER).alarm0; let init = initialize( EspWifiInitFor::Wifi, timer, @@ -45,7 +47,7 @@ fn main() -> ! { ) .unwrap(); - let (wifi, ..) = peripherals.RADIO.split(); + let wifi = peripherals.WIFI; let mut socket_set_entries: [SocketStorage; 3] = Default::default(); let (iface, device, mut controller, sockets) = create_network_interface(&init, wifi, WifiMode::Ap, &mut socket_set_entries).unwrap(); diff --git a/examples-esp32/examples/ble.rs b/esp-wifi/examples/ble.rs similarity index 89% rename from examples-esp32/examples/ble.rs rename to esp-wifi/examples/ble.rs index 2f0a6b19..98be8d44 100644 --- a/examples-esp32/examples/ble.rs +++ b/esp-wifi/examples/ble.rs @@ -23,15 +23,13 @@ fn main() -> ! { let peripherals = Peripherals::take(); - let mut system = peripherals.DPORT.split(); + let system = peripherals.SYSTEM.split(); let clocks = ClockControl::max(system.clock_control).freeze(); - let timer = esp32_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; + #[cfg(target_arch = "xtensa")] + let timer = hal::timer::TimerGroup::new(peripherals.TIMG1, &clocks).timer0; + #[cfg(target_arch = "riscv32")] + let timer = hal::systimer::SystemTimer::new(peripherals.SYSTIMER).alarm0; let init = initialize( EspWifiInitFor::Ble, timer, @@ -42,11 +40,14 @@ fn main() -> ! { .unwrap(); let io = IO::new(peripherals.GPIO, peripherals.IO_MUX); + #[cfg(any(feature = "esp32", feature = "esp32s2", feature = "esp32s3"))] let button = io.pins.gpio0.into_pull_down_input(); + #[cfg(any(feature = "esp32c2", feature = "esp32c3", feature = "esp32c6"))] + let button = io.pins.gpio9.into_pull_down_input(); let mut debounce_cnt = 500; - let (_, mut bluetooth, ..) = peripherals.RADIO.split(); + let mut bluetooth = peripherals.BT; loop { let connector = BleConnector::new(&init, &mut bluetooth); diff --git a/examples-esp32c3/examples/coex.rs b/esp-wifi/examples/coex.rs similarity index 93% rename from examples-esp32c3/examples/coex.rs rename to esp-wifi/examples/coex.rs index 7ca64423..baa4fd87 100644 --- a/examples-esp32c3/examples/coex.rs +++ b/esp-wifi/examples/coex.rs @@ -26,7 +26,7 @@ use esp_backtrace as _; use esp_println::{print, println}; use esp_wifi::initialize; use esp_wifi::wifi::{utils::create_network_interface, WifiError}; -use hal::{clock::ClockControl, systimer::SystemTimer, Rng}; +use hal::{clock::ClockControl, Rng}; use hal::{peripherals::Peripherals, prelude::*}; use smoltcp::{iface::SocketStorage, wire::IpAddress, wire::Ipv4Address}; @@ -43,7 +43,10 @@ fn main() -> ! { let system = peripherals.SYSTEM.split(); let clocks = ClockControl::max(system.clock_control).freeze(); - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; + #[cfg(target_arch = "xtensa")] + let timer = hal::timer::TimerGroup::new(peripherals.TIMG1, &clocks).timer0; + #[cfg(target_arch = "riscv32")] + let timer = hal::systimer::SystemTimer::new(peripherals.SYSTIMER).alarm0; let init = initialize( EspWifiInitFor::WifiBle, timer, @@ -53,7 +56,8 @@ fn main() -> ! { ) .unwrap(); - let (wifi, bluetooth, ..) = peripherals.RADIO.split(); + let wifi = peripherals.WIFI; + let bluetooth = peripherals.BT; let mut socket_set_entries: [SocketStorage; 3] = Default::default(); let (iface, device, mut controller, sockets) = diff --git a/examples-esp32c3/examples/dhcp.rs b/esp-wifi/examples/dhcp.rs similarity index 93% rename from examples-esp32c3/examples/dhcp.rs rename to esp-wifi/examples/dhcp.rs index 9b516bc3..5f39eb14 100644 --- a/examples-esp32c3/examples/dhcp.rs +++ b/esp-wifi/examples/dhcp.rs @@ -10,15 +10,14 @@ use embedded_svc::ipv4::Interface; use embedded_svc::wifi::{AccessPointInfo, ClientConfiguration, Configuration, Wifi}; use esp_backtrace as _; - use esp_println::{print, println}; use esp_wifi::wifi::utils::create_network_interface; use esp_wifi::wifi::{WifiError, WifiMode}; use esp_wifi::wifi_interface::WifiStack; use esp_wifi::{current_millis, initialize, EspWifiInitFor}; use hal::clock::ClockControl; +use hal::Rng; use hal::{peripherals::Peripherals, prelude::*}; -use hal::{systimer::SystemTimer, Rng}; use smoltcp::iface::SocketStorage; use smoltcp::wire::IpAddress; use smoltcp::wire::Ipv4Address; @@ -36,7 +35,10 @@ fn main() -> ! { let system = peripherals.SYSTEM.split(); let clocks = ClockControl::max(system.clock_control).freeze(); - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; + #[cfg(target_arch = "xtensa")] + let timer = hal::timer::TimerGroup::new(peripherals.TIMG1, &clocks).timer0; + #[cfg(target_arch = "riscv32")] + let timer = hal::systimer::SystemTimer::new(peripherals.SYSTIMER).alarm0; let init = initialize( EspWifiInitFor::Wifi, timer, @@ -46,7 +48,7 @@ fn main() -> ! { ) .unwrap(); - let (wifi, ..) = peripherals.RADIO.split(); + let wifi = peripherals.WIFI; let mut socket_set_entries: [SocketStorage; 3] = Default::default(); let (iface, device, mut controller, sockets) = create_network_interface(&init, wifi, WifiMode::Sta, &mut socket_set_entries).unwrap(); diff --git a/examples-esp32c6/examples/embassy_access_point.rs b/esp-wifi/examples/embassy_access_point.rs similarity index 82% rename from examples-esp32c6/examples/embassy_access_point.rs rename to esp-wifi/examples/embassy_access_point.rs index 8c4fb9d6..6e51005d 100644 --- a/examples-esp32c6/examples/embassy_access_point.rs +++ b/esp-wifi/examples/embassy_access_point.rs @@ -4,7 +4,6 @@ #![feature(const_mut_refs)] #![feature(type_alias_impl_trait)] -use embassy_executor::_export::StaticCell; use embassy_net::tcp::TcpSocket; use embassy_net::ConfigV4; use embassy_net::{ @@ -14,40 +13,32 @@ use embassy_net::{ mod examples_util; use examples_util::hal; -use embassy_executor::Executor; +use embassy_executor::Spawner; use embassy_time::{Duration, Timer}; use embedded_svc::wifi::{AccessPointConfiguration, Configuration, Wifi}; use esp_backtrace as _; - use esp_println::{print, println}; use esp_wifi::wifi::{WifiController, WifiDevice, WifiEvent, WifiMode, WifiState}; use esp_wifi::{initialize, EspWifiInitFor}; use hal::clock::ClockControl; +use hal::Rng; use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; -use hal::{systimer::SystemTimer, Rng}; - -macro_rules! singleton { - ($val:expr) => {{ - type T = impl Sized; - static STATIC_CELL: StaticCell = StaticCell::new(); - let (x,) = STATIC_CELL.init(($val,)); - x - }}; -} - -static EXECUTOR: StaticCell = StaticCell::new(); +use static_cell::make_static; -#[entry] -fn main() -> ! { +#[main] +async fn main(spawner: Spawner) -> ! { #[cfg(feature = "log")] esp_println::logger::init_logger(log::LevelFilter::Info); let peripherals = Peripherals::take(); - let mut system = peripherals.PCR.split(); + let system = peripherals.SYSTEM.split(); let clocks = ClockControl::max(system.clock_control).freeze(); - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; + #[cfg(target_arch = "xtensa")] + let timer = hal::timer::TimerGroup::new(peripherals.TIMG1, &clocks).timer0; + #[cfg(target_arch = "riscv32")] + let timer = hal::systimer::SystemTimer::new(peripherals.SYSTIMER).alarm0; let init = initialize( EspWifiInitFor::Wifi, timer, @@ -57,15 +48,11 @@ fn main() -> ! { ) .unwrap(); - let (wifi, ..) = peripherals.RADIO.split(); + let wifi = peripherals.WIFI; let (wifi_interface, controller) = esp_wifi::wifi::new_with_mode(&init, wifi, WifiMode::Ap).unwrap(); - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); + let timer_group0 = TimerGroup::new(peripherals.TIMG0, &clocks); embassy::init(&clocks, timer_group0.timer0); let config = Config { @@ -79,54 +66,16 @@ fn main() -> ! { let seed = 1234; // very random, very secure seed // Init network stack - let stack = &*singleton!(Stack::new( + let stack = &*make_static!(Stack::new( wifi_interface, config, - singleton!(StackResources::<3>::new()), + make_static!(StackResources::<3>::new()), seed )); - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); - spawner.spawn(task(&stack)).ok(); - }) -} - -#[embassy_executor::task] -async fn connection(mut controller: WifiController<'static>) { - println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); - loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::ApStarted => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::ApStop).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} - } - if !matches!(controller.is_started(), Ok(true)) { - let client_config = Configuration::AccessPoint(AccessPointConfiguration { - ssid: "esp-wifi".into(), - ..Default::default() - }); - controller.set_configuration(&client_config).unwrap(); - println!("Starting wifi"); - controller.start().await.unwrap(); - println!("Wifi started!"); - } - } -} - -#[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await -} + spawner.spawn(connection(controller)).ok(); + spawner.spawn(net_task(&stack)).ok(); -#[embassy_executor::task] -async fn task(stack: &'static Stack>) { let mut rx_buffer = [0; 4096]; let mut tx_buffer = [0; 4096]; @@ -212,3 +161,34 @@ async fn task(stack: &'static Stack>) { socket.abort(); } } + +#[embassy_executor::task] +async fn connection(mut controller: WifiController<'static>) { + println!("start connection task"); + println!("Device capabilities: {:?}", controller.get_capabilities()); + loop { + match esp_wifi::wifi::get_wifi_state() { + WifiState::ApStarted => { + // wait until we're no longer connected + controller.wait_for_event(WifiEvent::ApStop).await; + Timer::after(Duration::from_millis(5000)).await + } + _ => {} + } + if !matches!(controller.is_started(), Ok(true)) { + let client_config = Configuration::AccessPoint(AccessPointConfiguration { + ssid: "esp-wifi".into(), + ..Default::default() + }); + controller.set_configuration(&client_config).unwrap(); + println!("Starting wifi"); + controller.start().await.unwrap(); + println!("Wifi started!"); + } + } +} + +#[embassy_executor::task] +async fn net_task(stack: &'static Stack>) { + stack.run().await +} diff --git a/examples-esp32c6/examples/async_ble.rs b/esp-wifi/examples/embassy_ble.rs similarity index 81% rename from examples-esp32c6/examples/async_ble.rs rename to esp-wifi/examples/embassy_ble.rs index 9d124306..0e568cb1 100644 --- a/examples-esp32c6/examples/async_ble.rs +++ b/esp-wifi/examples/embassy_ble.rs @@ -14,30 +14,69 @@ use bleps::{ attribute_server::NotificationData, gatt, }; -use embassy_executor::Executor; -use embassy_executor::_export::StaticCell; +use embassy_executor::Spawner; use embedded_hal_async::digital::Wait; use esp_backtrace as _; use esp_println::println; -use esp_wifi::{ - ble::controller::asynch::BleConnector, initialize, EspWifiInitFor, EspWifiInitialization, -}; +use esp_wifi::{ble::controller::asynch::BleConnector, initialize, EspWifiInitFor}; #[path = "../../examples-util/util.rs"] mod examples_util; use examples_util::hal; -use examples_util::BootButton; use hal::{ - clock::ClockControl, embassy, peripherals::*, prelude::*, radio::Bluetooth, - systimer::SystemTimer, timer::TimerGroup, Rng, IO, + clock::ClockControl, + embassy::{self}, + peripherals::*, + prelude::*, + timer::TimerGroup, + Rng, IO, }; -#[embassy_executor::task] -async fn run(init: EspWifiInitialization, mut bluetooth: Bluetooth, pin: BootButton) { +#[main] +async fn main(_spawner: Spawner) -> ! { + #[cfg(feature = "log")] + esp_println::logger::init_logger(log::LevelFilter::Info); + + let peripherals = Peripherals::take(); + + let system = peripherals.SYSTEM.split(); + let clocks = ClockControl::max(system.clock_control).freeze(); + + #[cfg(target_arch = "xtensa")] + let timer = hal::timer::TimerGroup::new(peripherals.TIMG1, &clocks).timer0; + #[cfg(target_arch = "riscv32")] + let timer = hal::systimer::SystemTimer::new(peripherals.SYSTIMER).alarm0; + let init = initialize( + EspWifiInitFor::Ble, + timer, + Rng::new(peripherals.RNG), + system.radio_clock_control, + &clocks, + ) + .unwrap(); + + let io = IO::new(peripherals.GPIO, peripherals.IO_MUX); + #[cfg(any(feature = "esp32", feature = "esp32s2", feature = "esp32s3"))] + let button = io.pins.gpio0.into_pull_down_input(); + #[cfg(any(feature = "esp32c2", feature = "esp32c3", feature = "esp32c6"))] + let button = io.pins.gpio9.into_pull_down_input(); + + // Async requires the GPIO interrupt to wake futures + hal::interrupt::enable( + hal::peripherals::Interrupt::GPIO, + hal::interrupt::Priority::Priority1, + ) + .unwrap(); + + let timer_group0 = TimerGroup::new(peripherals.TIMG0, &clocks); + embassy::init(&clocks, timer_group0.timer0); + + let mut bluetooth = peripherals.BT; + let connector = BleConnector::new(&init, &mut bluetooth); let mut ble = Ble::new(connector, esp_wifi::current_millis); println!("Connector created"); - let pin_ref = RefCell::new(pin); + let pin_ref = RefCell::new(button); loop { println!("{:?}", ble.init().await); @@ -121,49 +160,3 @@ async fn run(init: EspWifiInitialization, mut bluetooth: Bluetooth, pin: BootBut srv.run(&mut notifier).await.unwrap(); } } - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.PCR.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Ble, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let io = IO::new(peripherals.GPIO, peripherals.IO_MUX); - let button = io.pins.gpio9.into_pull_down_input(); - - // Async requires the GPIO interrupt to wake futures - hal::interrupt::enable( - hal::peripherals::Interrupt::GPIO, - hal::interrupt::Priority::Priority1, - ) - .unwrap(); - - let (_, bluetooth, ..) = peripherals.RADIO.split(); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(run(init, bluetooth, button)).ok(); - }); -} diff --git a/examples-esp32c6/examples/embassy_dhcp.rs b/esp-wifi/examples/embassy_dhcp.rs similarity index 80% rename from examples-esp32c6/examples/embassy_dhcp.rs rename to esp-wifi/examples/embassy_dhcp.rs index f323bbc9..89571c2c 100644 --- a/examples-esp32c6/examples/embassy_dhcp.rs +++ b/esp-wifi/examples/embassy_dhcp.rs @@ -2,50 +2,41 @@ #![no_main] #![feature(type_alias_impl_trait)] -use embassy_executor::_export::StaticCell; +use embassy_executor::Spawner; use embassy_net::tcp::TcpSocket; use embassy_net::{Config, Ipv4Address, Stack, StackResources}; #[path = "../../examples-util/util.rs"] mod examples_util; use examples_util::hal; -use embassy_executor::Executor; use embassy_time::{Duration, Timer}; use embedded_svc::wifi::{ClientConfiguration, Configuration, Wifi}; use esp_backtrace as _; - use esp_println::println; use esp_wifi::wifi::{WifiController, WifiDevice, WifiEvent, WifiMode, WifiState}; use esp_wifi::{initialize, EspWifiInitFor}; use hal::clock::ClockControl; +use hal::Rng; use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; -use hal::{systimer::SystemTimer, Rng}; +use static_cell::make_static; const SSID: &str = env!("SSID"); const PASSWORD: &str = env!("PASSWORD"); -macro_rules! singleton { - ($val:expr) => {{ - type T = impl Sized; - static STATIC_CELL: StaticCell = StaticCell::new(); - let (x,) = STATIC_CELL.init(($val,)); - x - }}; -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { +#[main] +async fn main(spawner: Spawner) -> ! { #[cfg(feature = "log")] esp_println::logger::init_logger(log::LevelFilter::Info); let peripherals = Peripherals::take(); - let mut system = peripherals.PCR.split(); + let system = peripherals.SYSTEM.split(); let clocks = ClockControl::max(system.clock_control).freeze(); - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; + #[cfg(target_arch = "xtensa")] + let timer = hal::timer::TimerGroup::new(peripherals.TIMG1, &clocks).timer0; + #[cfg(target_arch = "riscv32")] + let timer = hal::systimer::SystemTimer::new(peripherals.SYSTIMER).alarm0; let init = initialize( EspWifiInitFor::Wifi, timer, @@ -55,15 +46,11 @@ fn main() -> ! { ) .unwrap(); - let (wifi, ..) = peripherals.RADIO.split(); + let wifi = peripherals.WIFI; let (wifi_interface, controller) = esp_wifi::wifi::new_with_mode(&init, wifi, WifiMode::Sta).unwrap(); - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); + let timer_group0 = TimerGroup::new(peripherals.TIMG0, &clocks); embassy::init(&clocks, timer_group0.timer0); let config = Config::dhcpv4(Default::default()); @@ -71,64 +58,16 @@ fn main() -> ! { let seed = 1234; // very random, very secure seed // Init network stack - let stack = &*singleton!(Stack::new( + let stack = &*make_static!(Stack::new( wifi_interface, config, - singleton!(StackResources::<3>::new()), + make_static!(StackResources::<3>::new()), seed )); - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); - spawner.spawn(task(&stack)).ok(); - }) -} + spawner.spawn(connection(controller)).ok(); + spawner.spawn(net_task(&stack)).ok(); -#[embassy_executor::task] -async fn connection(mut controller: WifiController<'static>) { - println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); - loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::StaConnected => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::StaDisconnected).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} - } - if !matches!(controller.is_started(), Ok(true)) { - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - controller.set_configuration(&client_config).unwrap(); - println!("Starting wifi"); - controller.start().await.unwrap(); - println!("Wifi started!"); - } - println!("About to connect..."); - - match controller.connect().await { - Ok(_) => println!("Wifi connected!"), - Err(e) => { - println!("Failed to connect to wifi: {e:?}"); - Timer::after(Duration::from_millis(5000)).await - } - } - } -} - -#[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await -} - -#[embassy_executor::task] -async fn task(stack: &'static Stack>) { let mut rx_buffer = [0; 4096]; let mut tx_buffer = [0; 4096]; @@ -189,3 +128,44 @@ async fn task(stack: &'static Stack>) { Timer::after(Duration::from_millis(3000)).await; } } + +#[embassy_executor::task] +async fn connection(mut controller: WifiController<'static>) { + println!("start connection task"); + println!("Device capabilities: {:?}", controller.get_capabilities()); + loop { + match esp_wifi::wifi::get_wifi_state() { + WifiState::StaConnected => { + // wait until we're no longer connected + controller.wait_for_event(WifiEvent::StaDisconnected).await; + Timer::after(Duration::from_millis(5000)).await + } + _ => {} + } + if !matches!(controller.is_started(), Ok(true)) { + let client_config = Configuration::Client(ClientConfiguration { + ssid: SSID.into(), + password: PASSWORD.into(), + ..Default::default() + }); + controller.set_configuration(&client_config).unwrap(); + println!("Starting wifi"); + controller.start().await.unwrap(); + println!("Wifi started!"); + } + println!("About to connect..."); + + match controller.connect().await { + Ok(_) => println!("Wifi connected!"), + Err(e) => { + println!("Failed to connect to wifi: {e:?}"); + Timer::after(Duration::from_millis(5000)).await + } + } + } +} + +#[embassy_executor::task] +async fn net_task(stack: &'static Stack>) { + stack.run().await +} diff --git a/examples-esp32c6/examples/embassy_esp_now.rs b/esp-wifi/examples/embassy_esp_now.rs similarity index 71% rename from examples-esp32c6/examples/embassy_esp_now.rs rename to esp-wifi/examples/embassy_esp_now.rs index fae89b14..f3e47087 100644 --- a/examples-esp32c6/examples/embassy_esp_now.rs +++ b/esp-wifi/examples/embassy_esp_now.rs @@ -2,25 +2,51 @@ #![no_main] #![feature(type_alias_impl_trait)] -use embassy_executor::_export::StaticCell; use embassy_futures::select::{select, Either}; #[path = "../../examples-util/util.rs"] mod examples_util; use examples_util::hal; -use embassy_executor::Executor; +use embassy_executor::Spawner; use embassy_time::{Duration, Ticker}; use esp_backtrace as _; - use esp_println::println; -use esp_wifi::esp_now::{EspNow, PeerInfo, BROADCAST_ADDRESS}; +use esp_wifi::esp_now::{PeerInfo, BROADCAST_ADDRESS}; use esp_wifi::{initialize, EspWifiInitFor}; use hal::clock::ClockControl; +use hal::Rng; use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; -use hal::{systimer::SystemTimer, Rng}; -#[embassy_executor::task] -async fn run(mut esp_now: EspNow<'static>) { +#[main] +async fn main(_spawner: Spawner) -> ! { + #[cfg(feature = "log")] + esp_println::logger::init_logger(log::LevelFilter::Info); + + let peripherals = Peripherals::take(); + + let system = peripherals.SYSTEM.split(); + let clocks = ClockControl::max(system.clock_control).freeze(); + + #[cfg(target_arch = "xtensa")] + let timer = hal::timer::TimerGroup::new(peripherals.TIMG1, &clocks).timer0; + #[cfg(target_arch = "riscv32")] + let timer = hal::systimer::SystemTimer::new(peripherals.SYSTIMER).alarm0; + let init = initialize( + EspWifiInitFor::Wifi, + timer, + Rng::new(peripherals.RNG), + system.radio_clock_control, + &clocks, + ) + .unwrap(); + + let wifi = peripherals.WIFI; + let mut esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); + println!("esp-now version {}", esp_now.get_version().unwrap()); + + let timer_group0 = TimerGroup::new(peripherals.TIMG0, &clocks); + embassy::init(&clocks, timer_group0.timer0); + let mut ticker = Ticker::every(Duration::from_secs(5)); loop { let res = select(ticker.next(), async { @@ -53,41 +79,3 @@ async fn run(mut esp_now: EspNow<'static>) { } } } - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.PCR.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(run(esp_now)).ok(); - }) -} diff --git a/examples-esp32s2/examples/embassy_esp_now_duplex.rs b/esp-wifi/examples/embassy_esp_now_duplex.rs similarity index 70% rename from examples-esp32s2/examples/embassy_esp_now_duplex.rs rename to esp-wifi/examples/embassy_esp_now_duplex.rs index 9572c57c..f2e7c5d2 100644 --- a/examples-esp32s2/examples/embassy_esp_now_duplex.rs +++ b/esp-wifi/examples/embassy_esp_now_duplex.rs @@ -2,14 +2,13 @@ #![no_main] #![feature(type_alias_impl_trait)] -use embassy_executor::_export::StaticCell; use embassy_sync::blocking_mutex::raw::NoopRawMutex; use embassy_sync::mutex::Mutex; #[path = "../../examples-util/util.rs"] mod examples_util; use examples_util::hal; -use embassy_executor::Executor; +use embassy_executor::Spawner; use embassy_time::{Duration, Ticker}; use esp_backtrace as _; @@ -19,25 +18,45 @@ use esp_wifi::{initialize, EspWifiInitFor}; use hal::clock::ClockControl; use hal::Rng; use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; +use static_cell::make_static; -#[embassy_executor::task] -async fn broadcaster(sender: &'static Mutex>) { - let mut ticker = Ticker::every(Duration::from_secs(1)); - loop { - ticker.next().await; +#[main] +async fn main(spawner: Spawner) -> ! { + #[cfg(feature = "log")] + esp_println::logger::init_logger(log::LevelFilter::Info); - println!("Send Broadcast..."); - let mut sender = sender.lock().await; - let status = sender.send_async(&BROADCAST_ADDRESS, b"Hello.").await; - println!("Send broadcast status: {:?}", status); - } -} + let peripherals = Peripherals::take(); + + let system = peripherals.SYSTEM.split(); + let clocks = ClockControl::max(system.clock_control).freeze(); + + #[cfg(target_arch = "xtensa")] + let timer = hal::timer::TimerGroup::new(peripherals.TIMG1, &clocks).timer0; + #[cfg(target_arch = "riscv32")] + let timer = hal::systimer::SystemTimer::new(peripherals.SYSTIMER).alarm0; + let init = initialize( + EspWifiInitFor::Wifi, + timer, + Rng::new(peripherals.RNG), + system.radio_clock_control, + &clocks, + ) + .unwrap(); + + let wifi = peripherals.WIFI; + let esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); + println!("esp-now version {}", esp_now.get_version().unwrap()); + + let timer_group0 = TimerGroup::new(peripherals.TIMG0, &clocks); + embassy::init(&clocks, timer_group0.timer0); + + let (manager, sender, receiver) = esp_now.split(); + let manager = make_static!(manager); + let sender = make_static!(Mutex::::new(sender)); + + spawner.spawn(listener(manager, receiver)).ok(); + spawner.spawn(broadcaster(sender)).ok(); -#[embassy_executor::task] -async fn sayhello( - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, -) { let mut ticker = Ticker::every(Duration::from_millis(500)); loop { ticker.next().await; @@ -59,6 +78,19 @@ async fn sayhello( } } +#[embassy_executor::task] +async fn broadcaster(sender: &'static Mutex>) { + let mut ticker = Ticker::every(Duration::from_secs(1)); + loop { + ticker.next().await; + + println!("Send Broadcast..."); + let mut sender = sender.lock().await; + let status = sender.send_async(&BROADCAST_ADDRESS, b"Hello.").await; + println!("Send broadcast status: {:?}", status); + } +} + #[embassy_executor::task] async fn listener(manager: &'static EspNowManager<'static>, mut receiver: EspNowReceiver<'static>) { loop { @@ -79,55 +111,3 @@ async fn listener(manager: &'static EspNowManager<'static>, mut receiver: EspNow } } } - -static EXECUTOR: StaticCell = StaticCell::new(); -static ESP_NOW_MANAGER: StaticCell> = StaticCell::new(); -static ESP_NOW_SENDER: StaticCell>> = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let wifi = peripherals.RADIO.split(); - let esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - - let (manager, sender, receiver) = esp_now.split(); - let manager = ESP_NOW_MANAGER.init(manager); - let sender: &'static _ = ESP_NOW_SENDER.init(Mutex::new(sender)); - - executor.run(|spawner| { - spawner.spawn(listener(manager, receiver)).ok(); - spawner.spawn(broadcaster(sender)).ok(); - spawner.spawn(sayhello(manager, sender)).ok(); - }) -} diff --git a/examples-esp32c3/examples/esp_now.rs b/esp-wifi/examples/esp_now.rs similarity index 88% rename from examples-esp32c3/examples/esp_now.rs rename to esp-wifi/examples/esp_now.rs index 42be53f3..c106d7e1 100644 --- a/examples-esp32c3/examples/esp_now.rs +++ b/esp-wifi/examples/esp_now.rs @@ -2,7 +2,6 @@ #![no_main] use esp_backtrace as _; - use esp_println::println; use esp_wifi::esp_now::{PeerInfo, BROADCAST_ADDRESS}; use esp_wifi::{current_millis, initialize, EspWifiInitFor}; @@ -10,8 +9,8 @@ use esp_wifi::{current_millis, initialize, EspWifiInitFor}; mod examples_util; use examples_util::hal; use hal::clock::ClockControl; +use hal::Rng; use hal::{peripherals::Peripherals, prelude::*}; -use hal::{systimer::SystemTimer, Rng}; #[entry] fn main() -> ! { @@ -23,7 +22,10 @@ fn main() -> ! { let system = peripherals.SYSTEM.split(); let clocks = ClockControl::max(system.clock_control).freeze(); - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; + #[cfg(target_arch = "xtensa")] + let timer = hal::timer::TimerGroup::new(peripherals.TIMG1, &clocks).timer0; + #[cfg(target_arch = "riscv32")] + let timer = hal::systimer::SystemTimer::new(peripherals.SYSTIMER).alarm0; let init = initialize( EspWifiInitFor::Wifi, timer, @@ -33,7 +35,7 @@ fn main() -> ! { ) .unwrap(); - let (wifi, ..) = peripherals.RADIO.split(); + let wifi = peripherals.WIFI; let mut esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); println!("esp-now version {}", esp_now.get_version().unwrap()); diff --git a/examples-esp32c3/examples/static_ip.rs b/esp-wifi/examples/static_ip.rs similarity index 95% rename from examples-esp32c3/examples/static_ip.rs rename to esp-wifi/examples/static_ip.rs index c79ee8c6..2f606ea9 100644 --- a/examples-esp32c3/examples/static_ip.rs +++ b/esp-wifi/examples/static_ip.rs @@ -10,7 +10,6 @@ use embedded_svc::ipv4::Interface; use embedded_svc::wifi::{AccessPointInfo, ClientConfiguration, Configuration, Wifi}; use esp_backtrace as _; - use esp_println::{print, println}; use esp_wifi::initialize; use esp_wifi::wifi::WifiMode; @@ -18,8 +17,8 @@ use esp_wifi::wifi::{utils::create_network_interface, WifiError}; use esp_wifi::wifi_interface::WifiStack; use esp_wifi::{current_millis, EspWifiInitFor}; use hal::clock::ClockControl; +use hal::Rng; use hal::{peripherals::Peripherals, prelude::*}; -use hal::{systimer::SystemTimer, Rng}; use smoltcp::iface::SocketStorage; @@ -38,7 +37,10 @@ fn main() -> ! { let system = peripherals.SYSTEM.split(); let clocks = ClockControl::max(system.clock_control).freeze(); - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; + #[cfg(target_arch = "xtensa")] + let timer = hal::timer::TimerGroup::new(peripherals.TIMG1, &clocks).timer0; + #[cfg(target_arch = "riscv32")] + let timer = hal::systimer::SystemTimer::new(peripherals.SYSTIMER).alarm0; let init = initialize( EspWifiInitFor::Wifi, timer, @@ -48,7 +50,7 @@ fn main() -> ! { ) .unwrap(); - let (wifi, ..) = peripherals.RADIO.split(); + let wifi = peripherals.WIFI; let mut socket_set_entries: [SocketStorage; 3] = Default::default(); let (iface, device, mut controller, sockets) = create_network_interface(&init, wifi, WifiMode::Sta, &mut socket_set_entries).unwrap(); diff --git a/esp-wifi/src/ble/controller/mod.rs b/esp-wifi/src/ble/controller/mod.rs index 16648073..f544ba65 100644 --- a/esp-wifi/src/ble/controller/mod.rs +++ b/esp-wifi/src/ble/controller/mod.rs @@ -3,22 +3,19 @@ use embedded_io::{ Error, Io, }; -use crate::hal::{ - peripheral::{Peripheral, PeripheralRef}, - radio, -}; +use crate::hal::peripheral::{Peripheral, PeripheralRef}; use crate::EspWifiInitialization; use super::{read_hci, read_next, send_hci}; pub struct BleConnector<'d> { - _device: PeripheralRef<'d, radio::Bluetooth>, + _device: PeripheralRef<'d, crate::hal::peripherals::BT>, } impl<'d> BleConnector<'d> { pub fn new( init: &EspWifiInitialization, - device: impl Peripheral

+ 'd, + device: impl Peripheral

+ 'd, ) -> BleConnector<'d> { if !init.is_ble() { panic!("Not initialized for BLE use"); @@ -103,13 +100,13 @@ pub mod asynch { } pub struct BleConnector<'d> { - _device: PeripheralRef<'d, crate::hal::radio::Bluetooth>, + _device: PeripheralRef<'d, crate::hal::peripherals::BT>, } impl<'d> BleConnector<'d> { pub fn new( init: &EspWifiInitialization, - device: impl Peripheral

+ 'd, + device: impl Peripheral

+ 'd, ) -> BleConnector<'d> { if !init.is_ble() { panic!("Not initialized for BLE use"); diff --git a/esp-wifi/src/esp_now/mod.rs b/esp-wifi/src/esp_now/mod.rs index 2a6b45f2..75609681 100644 --- a/esp-wifi/src/esp_now/mod.rs +++ b/esp-wifi/src/esp_now/mod.rs @@ -16,7 +16,6 @@ use critical_section::Mutex; use crate::compat::queue::SimpleQueue; use crate::hal::peripheral::{Peripheral, PeripheralRef}; -use crate::hal::radio; use crate::EspWifiInitialization; use crate::binary::include::*; @@ -263,8 +262,8 @@ pub struct EspNowWithWifiCreateToken { } pub fn enable_esp_now_with_wifi( - device: crate::hal::radio::Wifi, -) -> (crate::hal::radio::Wifi, EspNowWithWifiCreateToken) { + device: crate::hal::peripherals::WIFI, +) -> (crate::hal::peripherals::WIFI, EspNowWithWifiCreateToken) { (device, EspNowWithWifiCreateToken { _private: () }) } @@ -535,7 +534,7 @@ impl<'d> Drop for EspNowRc<'d> { /// Currently this implementation (when used together with traditional Wi-Fi) ONLY support STA mode. /// pub struct EspNow<'d> { - _device: Option>, + _device: Option>, manager: EspNowManager<'d>, sender: EspNowSender<'d>, receiver: EspNowReceiver<'d>, @@ -544,7 +543,7 @@ pub struct EspNow<'d> { impl<'d> EspNow<'d> { pub fn new( inited: &EspWifiInitialization, - device: impl Peripheral

+ 'd, + device: impl Peripheral

+ 'd, ) -> Result, EspNowError> { EspNow::new_internal(inited, Some(device.into_ref())) } @@ -553,12 +552,15 @@ impl<'d> EspNow<'d> { inited: &EspWifiInitialization, _token: EspNowWithWifiCreateToken, ) -> Result, EspNowError> { - EspNow::new_internal(inited, None::>) + EspNow::new_internal( + inited, + None::>, + ) } fn new_internal( inited: &EspWifiInitialization, - device: Option>, + device: Option>, ) -> Result, EspNowError> { if !inited.is_wifi() { return Err(EspNowError::Error(Error::NotInitialized)); diff --git a/esp-wifi/src/timer/riscv.rs b/esp-wifi/src/timer/riscv.rs index 1edad73d..aea23e7d 100644 --- a/esp-wifi/src/timer/riscv.rs +++ b/esp-wifi/src/timer/riscv.rs @@ -35,9 +35,9 @@ pub fn setup_timer(systimer: TimeBase) { } let alarm0 = systimer.into_periodic(); - alarm0.set_period(TIMESLICE_FREQUENCY.into()); + alarm0.set_period(TIMESLICE_FREQUENCY.into_duration()); alarm0.clear_interrupt(); - alarm0.interrupt_enable(true); + alarm0.enable_interrupt(true); critical_section::with(|cs| ALARM0.borrow_ref_mut(cs).replace(alarm0)); @@ -83,7 +83,7 @@ fn FROM_CPU_INTR3(trap_frame: &mut TrapFrame) { let mut alarm0 = ALARM0.borrow_ref_mut(cs); let alarm0 = unwrap!(alarm0.as_mut()); - alarm0.set_period(TIMESLICE_FREQUENCY.into()); + alarm0.set_period(TIMESLICE_FREQUENCY.into_duration()); alarm0.clear_interrupt(); }); diff --git a/esp-wifi/src/wifi/mod.rs b/esp-wifi/src/wifi/mod.rs index 4ecc8cc7..a3a1fedf 100644 --- a/esp-wifi/src/wifi/mod.rs +++ b/esp-wifi/src/wifi/mod.rs @@ -893,7 +893,7 @@ pub fn wifi_start_scan( pub fn new_with_config<'d>( inited: &EspWifiInitialization, - device: impl Peripheral

+ 'd, + device: impl Peripheral

+ 'd, config: embedded_svc::wifi::Configuration, ) -> Result<(WifiDevice<'d>, WifiController<'d>), WifiError> { if !inited.is_wifi() { @@ -910,7 +910,7 @@ pub fn new_with_config<'d>( pub fn new_with_mode<'d>( inited: &EspWifiInitialization, - device: impl Peripheral

+ 'd, + device: impl Peripheral

+ 'd, mode: WifiMode, ) -> Result<(WifiDevice<'d>, WifiController<'d>), WifiError> { new_with_config( @@ -925,11 +925,11 @@ pub fn new_with_mode<'d>( /// A wifi device implementing smoltcp's Device trait. pub struct WifiDevice<'d> { - _device: PeripheralRef<'d, crate::hal::radio::Wifi>, + _device: PeripheralRef<'d, crate::hal::peripherals::WIFI>, } impl<'d> WifiDevice<'d> { - pub(crate) fn new(_device: PeripheralRef<'d, crate::hal::radio::Wifi>) -> WifiDevice { + pub(crate) fn new(_device: PeripheralRef<'d, crate::hal::peripherals::WIFI>) -> WifiDevice { Self { _device } } @@ -967,13 +967,13 @@ fn convert_ap_info(record: &include::wifi_ap_record_t) -> AccessPointInfo { /// A wifi controller implementing embedded_svc::Wifi traits pub struct WifiController<'d> { - _device: PeripheralRef<'d, crate::hal::radio::Wifi>, + _device: PeripheralRef<'d, crate::hal::peripherals::WIFI>, config: embedded_svc::wifi::Configuration, } impl<'d> WifiController<'d> { pub(crate) fn new_with_config( - _device: PeripheralRef<'d, crate::hal::radio::Wifi>, + _device: PeripheralRef<'d, crate::hal::peripherals::WIFI>, config: embedded_svc::wifi::Configuration, ) -> Result { // We set up the controller with the default config because we need to call diff --git a/esp-wifi/src/wifi/utils.rs b/esp-wifi/src/wifi/utils.rs index c5cb3f6a..9fde25bf 100644 --- a/esp-wifi/src/wifi/utils.rs +++ b/esp-wifi/src/wifi/utils.rs @@ -14,7 +14,7 @@ use super::{WifiController, WifiDevice, WifiError, WifiMode}; /// You can use the provided macros to create and pass a suitable backing storage. pub fn create_network_interface<'a, 'd>( inited: &EspWifiInitialization, - device: impl crate::hal::peripheral::Peripheral

+ 'd, + device: impl crate::hal::peripheral::Peripheral

+ 'd, mode: WifiMode, storage: &'a mut [SocketStorage<'a>], ) -> Result<(Interface, WifiDevice<'d>, WifiController<'d>, SocketSet<'a>), WifiError> { diff --git a/examples-esp32/.cargo/config.toml b/examples-esp32/.cargo/config.toml deleted file mode 100644 index fa914cec..00000000 --- a/examples-esp32/.cargo/config.toml +++ /dev/null @@ -1,13 +0,0 @@ -[target.xtensa-esp32-none-elf] -runner = "espflash flash --monitor" - -rustflags = [ - "-C", "link-arg=-Tlinkall.x", - "-C", "link-arg=-Trom_functions.x", -] - -[build] -target = "xtensa-esp32-none-elf" - -[unstable] -build-std = [ "core" ] diff --git a/examples-esp32/Cargo.toml b/examples-esp32/Cargo.toml deleted file mode 100644 index cd881734..00000000 --- a/examples-esp32/Cargo.toml +++ /dev/null @@ -1,49 +0,0 @@ -[package] -name = "examples-esp32" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -embedded-svc.workspace = true -bleps.workspace = true -embassy-executor = { workspace = true, optional = true } -embassy-time.workspace = true -embassy-futures.workspace = true -futures-util.workspace = true -embedded-io.workspace = true -smoltcp.workspace = true -log = { workspace = true, optional = true } -heapless.workspace = true -embassy-net = { workspace = true, optional = true } -embassy-sync.workspace = true - -esp32-hal.workspace = true -esp-backtrace = { workspace = true, features = ["esp32"] } -esp-wifi = { path = "../esp-wifi", default-features = false, features = ["esp32", "utils"] } -embedded-hal-async = { workspace = true, optional = true } - -[dev-dependencies] -esp-println = { workspace = true, features = ["esp32", "log"] } - -[features] -default = ["esp32", "log"] -esp32 = [] -async = ["esp-wifi/async", "bleps/async", "dep:embedded-hal-async", "esp32-hal/async", "esp32-hal/embassy-time-timg0", "dep:embassy-executor", "embassy-executor?/arch-xtensa"] -embassy-net = ["esp-wifi/embassy-net","dep:embassy-net"] -wifi-logs = ["esp-wifi/wifi-logs"] -dump-packets = ["esp-wifi/dump-packets"] -utils = ["esp-wifi/utils"] -enumset = ["esp-wifi/enumset"] -embedded-svc = [ "esp-wifi/embedded-svc" ] -wifi = ["esp-wifi/wifi"] -ble = ["esp-wifi/ble"] -phy-enable-usb = ["esp-wifi/phy-enable-usb"] -ps-min-modem = ["esp-wifi/ps-min-modem"] -ps-max-modem = ["esp-wifi/ps-max-modem"] -esp-now = ["esp-wifi/esp-now"] -ipv6 = ["esp-wifi/ipv6"] -coex = ["esp-wifi/coex"] -log = ["esp-wifi/log", "dep:log", "esp-println/log"] -defmt = ["esp-wifi/defmt", "esp-println/defmt"] diff --git a/examples-esp32/examples/access_point.rs b/examples-esp32/examples/access_point.rs deleted file mode 100644 index ddf87805..00000000 --- a/examples-esp32/examples/access_point.rs +++ /dev/null @@ -1,165 +0,0 @@ -#![no_std] -#![no_main] -#![feature(c_variadic)] -#![feature(const_mut_refs)] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; -use esp_println::{print, println}; -use esp_wifi::initialize; -use esp_wifi::wifi::utils::create_network_interface; -use esp_wifi::wifi::WifiMode; -use esp_wifi::wifi_interface::WifiStack; -use esp_wifi::{current_millis, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{peripherals::Peripherals, prelude::*}; - -use smoltcp::iface::SocketStorage; - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.DPORT.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Ap, &mut socket_set_entries).unwrap(); - let mut wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::AccessPoint(AccessPointConfiguration { - ssid: "esp-wifi".into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("{:?}", controller.get_capabilities()); - - wifi_stack - .set_iface_configuration(&embedded_svc::ipv4::Configuration::Client( - embedded_svc::ipv4::ClientConfiguration::Fixed(embedded_svc::ipv4::ClientSettings { - ip: embedded_svc::ipv4::Ipv4Addr::from(parse_ip("192.168.2.1")), - subnet: embedded_svc::ipv4::Subnet { - gateway: embedded_svc::ipv4::Ipv4Addr::from(parse_ip("192.168.2.1")), - mask: embedded_svc::ipv4::Mask(24), - }, - dns: None, - secondary_dns: None, - }), - )) - .unwrap(); - - println!("Start busy loop on main. Connect to the AP `esp-wifi` and point your browser to http://192.168.2.1:8080/"); - println!("Use a static IP in the range 192.168.2.2 .. 192.168.2.255, use gateway 192.168.2.1"); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - socket.listen(8080).unwrap(); - - loop { - socket.work(); - - if !socket.is_open() { - socket.listen(8080).unwrap(); - } - - if socket.is_connected() { - println!("Connected"); - - let mut time_out = false; - let wait_end = current_millis() + 20 * 1000; - let mut buffer = [0u8; 1024]; - let mut pos = 0; - loop { - if let Ok(len) = socket.read(&mut buffer[pos..]) { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - time_out = true; - break; - } - } - - if !time_out { - socket - .write_all( - b"HTTP/1.0 200 OK\r\n\r\n\ - \ - \ -

Hello Rust! Hello esp-wifi!

\ - \ - \r\n\ - ", - ) - .unwrap(); - - socket.flush().unwrap(); - } - - socket.close(); - - println!("Done\n"); - println!(); - } - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} - -fn parse_ip(ip: &str) -> [u8; 4] { - let mut result = [0u8; 4]; - for (idx, octet) in ip.split(".").into_iter().enumerate() { - result[idx] = u8::from_str_radix(octet, 10).unwrap(); - } - result -} diff --git a/examples-esp32/examples/async_ble.rs b/examples-esp32/examples/async_ble.rs deleted file mode 100644 index e55b6dac..00000000 --- a/examples-esp32/examples/async_ble.rs +++ /dev/null @@ -1,174 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] -#![feature(async_closure)] - -use core::cell::RefCell; - -use bleps::{ - ad_structure::{ - create_advertising_data, AdStructure, BR_EDR_NOT_SUPPORTED, LE_GENERAL_DISCOVERABLE, - }, - async_attribute_server::AttributeServer, - asynch::Ble, - attribute_server::NotificationData, - gatt, -}; -use embassy_executor::Executor; -use embassy_executor::_export::StaticCell; -use embedded_hal_async::digital::Wait; -use esp_backtrace as _; -use esp_println::println; -use esp_wifi::{ - ble::controller::asynch::BleConnector, initialize, EspWifiInitFor, EspWifiInitialization, -}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; -use examples_util::BootButton; -use hal::{ - clock::ClockControl, embassy, peripherals::*, prelude::*, radio::Bluetooth, timer::TimerGroup, - Rng, IO, -}; - -#[embassy_executor::task] -async fn run(init: EspWifiInitialization, mut bluetooth: Bluetooth, pin: BootButton) { - let connector = BleConnector::new(&init, &mut bluetooth); - let mut ble = Ble::new(connector, esp_wifi::current_millis); - println!("Connector created"); - - let pin_ref = RefCell::new(pin); - - loop { - println!("{:?}", ble.init().await); - println!("{:?}", ble.cmd_set_le_advertising_parameters().await); - println!( - "{:?}", - ble.cmd_set_le_advertising_data( - create_advertising_data(&[ - AdStructure::Flags(LE_GENERAL_DISCOVERABLE | BR_EDR_NOT_SUPPORTED), - AdStructure::ServiceUuids16(&[Uuid::Uuid16(0x1809)]), - AdStructure::CompleteLocalName(examples_util::SOC_NAME), - ]) - .unwrap() - ) - .await - ); - println!("{:?}", ble.cmd_set_le_advertise_enable(true).await); - - println!("started advertising"); - - let mut rf = |_offset: usize, data: &mut [u8]| { - data[..20].copy_from_slice(&b"Hello Bare-Metal BLE"[..]); - 17 - }; - let mut wf = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut wf2 = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut rf3 = |_offset: usize, data: &mut [u8]| { - data[..5].copy_from_slice(&b"Hola!"[..]); - 5 - }; - let mut wf3 = |offset: usize, data: &[u8]| { - println!("RECEIVED: Offset {}, data {:?}", offset, data); - }; - - gatt!([service { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - characteristics: [ - characteristic { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - read: rf, - write: wf, - }, - characteristic { - uuid: "957312e0-2354-11eb-9f10-fbc30a62cf38", - write: wf2, - }, - characteristic { - name: "my_characteristic", - uuid: "987312e0-2354-11eb-9f10-fbc30a62cf38", - notify: true, - read: rf3, - write: wf3, - }, - ], - },]); - - let mut srv = AttributeServer::new(&mut ble, &mut gatt_attributes); - - let counter = RefCell::new(0u8); - let mut notifier = async || { - // TODO how to check if notifications are enabled for the characteristic? - // maybe pass something into the closure which just can query the characterisic value - // probably passing in the attribute server won't work? - pin_ref.borrow_mut().wait_for_rising_edge().await.unwrap(); - let mut data = [0u8; 13]; - data.copy_from_slice(b"Notification0"); - { - let mut counter = counter.borrow_mut(); - data[data.len() - 1] += *counter; - *counter = (*counter + 1) % 10; - } - NotificationData::new(my_characteristic_handle, &data) - }; - - srv.run(&mut notifier).await.unwrap(); - } -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.DPORT.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Ble, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let io = IO::new(peripherals.GPIO, peripherals.IO_MUX); - let button = io.pins.gpio0.into_pull_down_input(); - - // Async requires the GPIO interrupt to wake futures - hal::interrupt::enable( - hal::peripherals::Interrupt::GPIO, - hal::interrupt::Priority::Priority1, - ) - .unwrap(); - - let (_, bluetooth, ..) = peripherals.RADIO.split(); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(run(init, bluetooth, button)).ok(); - }); -} diff --git a/examples-esp32/examples/coex.rs b/examples-esp32/examples/coex.rs deleted file mode 100644 index 09f195a6..00000000 --- a/examples-esp32/examples/coex.rs +++ /dev/null @@ -1,183 +0,0 @@ -#![no_std] -#![no_main] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use bleps::{ - ad_structure::{ - create_advertising_data, AdStructure, BR_EDR_NOT_SUPPORTED, LE_GENERAL_DISCOVERABLE, - }, - att::Uuid, - Ble, HciConnector, -}; - -use esp_wifi::{ - ble::controller::BleConnector, current_millis, wifi::WifiMode, wifi_interface::WifiStack, - EspWifiInitFor, -}; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointInfo, ClientConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; -use esp_println::{print, println}; -use esp_wifi::initialize; -use esp_wifi::wifi::{utils::create_network_interface, WifiError}; -use hal::{clock::ClockControl, Rng}; -use hal::{peripherals::Peripherals, prelude::*}; -use smoltcp::{iface::SocketStorage, wire::IpAddress, wire::Ipv4Address}; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.DPORT.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::WifiBle, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, bluetooth, ..) = peripherals.RADIO.split(); - - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Sta, &mut socket_set_entries).unwrap(); - let wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("Start Wifi Scan"); - let res: Result<(heapless::Vec, usize), WifiError> = controller.scan_n(); - if let Ok((res, _count)) = res { - for ap in res { - println!("{:?}", ap); - } - } - - println!("{:?}", controller.get_capabilities()); - println!("wifi_connect {:?}", controller.connect()); - - // wait to get connected - println!("Wait to get connected"); - loop { - let res = controller.is_connected(); - match res { - Ok(connected) => { - if connected { - break; - } - } - Err(err) => { - println!("{:?}", err); - loop {} - } - } - } - println!("{:?}", controller.is_connected()); - - // wait for getting an ip address - println!("Wait to get an ip address"); - loop { - wifi_stack.work(); - - if wifi_stack.is_iface_up() { - println!("got ip {:?}", wifi_stack.get_ip_info()); - break; - } - } - - let connector = BleConnector::new(&init, bluetooth); - let hci = HciConnector::new(connector, esp_wifi::current_millis); - let mut ble = Ble::new(&hci); - - println!("{:?}", ble.init()); - println!("{:?}", ble.cmd_set_le_advertising_parameters()); - println!( - "{:?}", - ble.cmd_set_le_advertising_data( - create_advertising_data(&[ - AdStructure::Flags(LE_GENERAL_DISCOVERABLE | BR_EDR_NOT_SUPPORTED), - AdStructure::ServiceUuids16(&[Uuid::Uuid16(0x1809)]), - AdStructure::CompleteLocalName(examples_util::SOC_NAME), - ]) - .unwrap() - ) - ); - println!("{:?}", ble.cmd_set_le_advertise_enable(true)); - - println!("started advertising"); - - println!("Start busy loop on main"); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - loop { - println!("Making HTTP request"); - socket.work(); - - socket - .open(IpAddress::Ipv4(Ipv4Address::new(142, 250, 185, 115)), 80) - .unwrap(); - - socket - .write(b"GET / HTTP/1.0\r\nHost: www.mobile-j.de\r\n\r\n") - .unwrap(); - socket.flush().unwrap(); - - let wait_end = current_millis() + 20 * 1000; - loop { - let mut buffer = [0u8; 512]; - if let Ok(len) = socket.read(&mut buffer) { - let to_print = unsafe { core::str::from_utf8_unchecked(&buffer[..len]) }; - print!("{}", to_print); - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - break; - } - } - println!(); - - socket.disconnect(); - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} diff --git a/examples-esp32/examples/dhcp.rs b/examples-esp32/examples/dhcp.rs deleted file mode 100644 index 22cecfca..00000000 --- a/examples-esp32/examples/dhcp.rs +++ /dev/null @@ -1,153 +0,0 @@ -#![no_std] -#![no_main] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointInfo, ClientConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; -use esp_println::{print, println}; -use esp_wifi::wifi::utils::create_network_interface; -use esp_wifi::wifi::{WifiError, WifiMode}; -use esp_wifi::wifi_interface::WifiStack; -use esp_wifi::{current_millis, initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{peripherals::Peripherals, prelude::*}; -use smoltcp::iface::SocketStorage; -use smoltcp::wire::IpAddress; -use smoltcp::wire::Ipv4Address; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.DPORT.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Sta, &mut socket_set_entries).unwrap(); - let wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("Start Wifi Scan"); - let res: Result<(heapless::Vec, usize), WifiError> = controller.scan_n(); - if let Ok((res, _count)) = res { - for ap in res { - println!("{:?}", ap); - } - } - - println!("{:?}", controller.get_capabilities()); - println!("wifi_connect {:?}", controller.connect()); - - // wait to get connected - println!("Wait to get connected"); - loop { - let res = controller.is_connected(); - match res { - Ok(connected) => { - if connected { - break; - } - } - Err(err) => { - println!("{:?}", err); - loop {} - } - } - } - println!("{:?}", controller.is_connected()); - - // wait for getting an ip address - println!("Wait to get an ip address"); - loop { - wifi_stack.work(); - - if wifi_stack.is_iface_up() { - println!("got ip {:?}", wifi_stack.get_ip_info()); - break; - } - } - - println!("Start busy loop on main"); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - loop { - println!("Making HTTP request"); - socket.work(); - - socket - .open(IpAddress::Ipv4(Ipv4Address::new(142, 250, 185, 115)), 80) - .unwrap(); - - socket - .write(b"GET / HTTP/1.0\r\nHost: www.mobile-j.de\r\n\r\n") - .unwrap(); - socket.flush().unwrap(); - - let wait_end = current_millis() + 20 * 1000; - loop { - let mut buffer = [0u8; 512]; - if let Ok(len) = socket.read(&mut buffer) { - let to_print = unsafe { core::str::from_utf8_unchecked(&buffer[..len]) }; - print!("{}", to_print); - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - break; - } - } - println!(); - - socket.disconnect(); - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} diff --git a/examples-esp32/examples/embassy_access_point.rs b/examples-esp32/examples/embassy_access_point.rs deleted file mode 100644 index 4af20d81..00000000 --- a/examples-esp32/examples/embassy_access_point.rs +++ /dev/null @@ -1,218 +0,0 @@ -#![no_std] -#![no_main] -#![feature(c_variadic)] -#![feature(const_mut_refs)] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_net::tcp::TcpSocket; -use embassy_net::ConfigV4; -use embassy_net::{ - Config, IpListenEndpoint, Ipv4Address, Ipv4Cidr, Stack, StackResources, StaticConfigV4, -}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Timer}; -use embedded_svc::wifi::{AccessPointConfiguration, Configuration, Wifi}; -use esp_backtrace as _; -use esp_println::{print, println}; -use esp_wifi::wifi::{WifiController, WifiDevice, WifiEvent, WifiMode, WifiState}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; - -macro_rules! singleton { - ($val:expr) => {{ - type T = impl Sized; - static STATIC_CELL: StaticCell = StaticCell::new(); - let (x,) = STATIC_CELL.init(($val,)); - x - }}; -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.DPORT.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let (wifi_interface, controller) = - esp_wifi::wifi::new_with_mode(&init, wifi, WifiMode::Ap).unwrap(); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - - let config = Config { - ipv4: ConfigV4::Static(StaticConfigV4 { - address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 2, 1), 24), - gateway: Some(Ipv4Address::from_bytes(&[192, 168, 2, 1])), - dns_servers: Default::default(), - }), - }; - - let seed = 1234; // very random, very secure seed - - // Init network stack - let stack = &*singleton!(Stack::new( - wifi_interface, - config, - singleton!(StackResources::<3>::new()), - seed - )); - - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); - spawner.spawn(task(&stack)).ok(); - }) -} - -#[embassy_executor::task] -async fn connection(mut controller: WifiController<'static>) { - println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); - loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::ApStarted => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::ApStop).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} - } - if !matches!(controller.is_started(), Ok(true)) { - let client_config = Configuration::AccessPoint(AccessPointConfiguration { - ssid: "esp-wifi".into(), - ..Default::default() - }); - controller.set_configuration(&client_config).unwrap(); - println!("Starting wifi"); - controller.start().await.unwrap(); - println!("Wifi started!"); - } - } -} - -#[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await -} - -#[embassy_executor::task] -async fn task(stack: &'static Stack>) { - let mut rx_buffer = [0; 4096]; - let mut tx_buffer = [0; 4096]; - - loop { - if stack.is_link_up() { - break; - } - Timer::after(Duration::from_millis(500)).await; - } - println!("Connect to the AP `esp-wifi` and point your browser to http://192.168.2.1:8080/"); - println!("Use a static IP in the range 192.168.2.2 .. 192.168.2.255, use gateway 192.168.2.1"); - - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); - socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); - loop { - println!("Wait for connection..."); - let r = socket - .accept(IpListenEndpoint { - addr: None, - port: 8080, - }) - .await; - println!("Connected..."); - - if let Err(e) = r { - println!("connect error: {:?}", e); - continue; - } - - use embedded_io::asynch::Write; - - let mut buffer = [0u8; 1024]; - let mut pos = 0; - loop { - match socket.read(&mut buffer).await { - Ok(0) => { - println!("read EOF"); - break; - } - Ok(len) => { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } - Err(e) => { - println!("read error: {:?}", e); - break; - } - }; - } - - let r = socket - .write_all( - b"HTTP/1.0 200 OK\r\n\r\n\ - \ - \ -

Hello Rust! Hello esp-wifi!

\ - \ - \r\n\ - ", - ) - .await; - if let Err(e) = r { - println!("write error: {:?}", e); - } - - let r = socket.flush().await; - if let Err(e) = r { - println!("flush error: {:?}", e); - } - Timer::after(Duration::from_millis(1000)).await; - - socket.close(); - Timer::after(Duration::from_millis(1000)).await; - - socket.abort(); - } -} diff --git a/examples-esp32/examples/embassy_dhcp.rs b/examples-esp32/examples/embassy_dhcp.rs deleted file mode 100644 index 0411adf9..00000000 --- a/examples-esp32/examples/embassy_dhcp.rs +++ /dev/null @@ -1,195 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_net::tcp::TcpSocket; -use embassy_net::{Config, Ipv4Address, Stack, StackResources}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Timer}; -use embedded_svc::wifi::{ClientConfiguration, Configuration, Wifi}; -use esp_backtrace as _; -use esp_println::println; -use esp_wifi::wifi::{WifiController, WifiDevice, WifiEvent, WifiMode, WifiState}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); - -macro_rules! singleton { - ($val:expr) => {{ - type T = impl Sized; - static STATIC_CELL: StaticCell = StaticCell::new(); - let (x,) = STATIC_CELL.init(($val,)); - x - }}; -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.DPORT.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let (wifi_interface, controller) = - esp_wifi::wifi::new_with_mode(&init, wifi, WifiMode::Sta).unwrap(); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - - let config = Config::dhcpv4(Default::default()); - - let seed = 1234; // very random, very secure seed - - // Init network stack - let stack = &*singleton!(Stack::new( - wifi_interface, - config, - singleton!(StackResources::<3>::new()), - seed - )); - - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); - spawner.spawn(task(&stack)).ok(); - }) -} - -#[embassy_executor::task] -async fn connection(mut controller: WifiController<'static>) { - println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); - loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::StaConnected => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::StaDisconnected).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} - } - if !matches!(controller.is_started(), Ok(true)) { - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - controller.set_configuration(&client_config).unwrap(); - println!("Starting wifi"); - controller.start().await.unwrap(); - println!("Wifi started!"); - } - println!("About to connect..."); - - match controller.connect().await { - Ok(_) => println!("Wifi connected!"), - Err(e) => { - println!("Failed to connect to wifi: {e:?}"); - Timer::after(Duration::from_millis(5000)).await - } - } - } -} - -#[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await -} - -#[embassy_executor::task] -async fn task(stack: &'static Stack>) { - let mut rx_buffer = [0; 4096]; - let mut tx_buffer = [0; 4096]; - - loop { - if stack.is_link_up() { - break; - } - Timer::after(Duration::from_millis(500)).await; - } - - println!("Waiting to get IP address..."); - loop { - if let Some(config) = stack.config_v4() { - println!("Got IP: {}", config.address); - break; - } - Timer::after(Duration::from_millis(500)).await; - } - - loop { - Timer::after(Duration::from_millis(1_000)).await; - - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); - - socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); - - let remote_endpoint = (Ipv4Address::new(142, 250, 185, 115), 80); - println!("connecting..."); - let r = socket.connect(remote_endpoint).await; - if let Err(e) = r { - println!("connect error: {:?}", e); - continue; - } - println!("connected!"); - let mut buf = [0; 1024]; - loop { - use embedded_io::asynch::Write; - let r = socket - .write_all(b"GET / HTTP/1.0\r\nHost: www.mobile-j.de\r\n\r\n") - .await; - if let Err(e) = r { - println!("write error: {:?}", e); - break; - } - let n = match socket.read(&mut buf).await { - Ok(0) => { - println!("read EOF"); - break; - } - Ok(n) => n, - Err(e) => { - println!("read error: {:?}", e); - break; - } - }; - println!("{}", core::str::from_utf8(&buf[..n]).unwrap()); - } - Timer::after(Duration::from_millis(3000)).await; - } -} diff --git a/examples-esp32/examples/embassy_esp_now.rs b/examples-esp32/examples/embassy_esp_now.rs deleted file mode 100644 index 60e427df..00000000 --- a/examples-esp32/examples/embassy_esp_now.rs +++ /dev/null @@ -1,97 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_futures::select::{select, Either}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Ticker}; -use esp_backtrace as _; -use esp_println::println; -use esp_wifi::esp_now::{EspNow, PeerInfo, BROADCAST_ADDRESS}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; - -#[embassy_executor::task] -async fn run(mut esp_now: EspNow<'static>) { - let mut ticker = Ticker::every(Duration::from_secs(5)); - loop { - let res = select(ticker.next(), async { - let r = esp_now.receive_async().await; - println!("Received {:?}", r); - if r.info.dst_address == BROADCAST_ADDRESS { - if !esp_now.peer_exists(&r.info.src_address) { - esp_now - .add_peer(PeerInfo { - peer_address: r.info.src_address, - lmk: None, - channel: None, - encrypt: false, - }) - .unwrap(); - } - let status = esp_now.send_async(&r.info.src_address, b"Hello Peer").await; - println!("Send hello to peer status: {:?}", status); - } - }) - .await; - - match res { - Either::First(_) => { - println!("Send"); - let status = esp_now.send_async(&BROADCAST_ADDRESS, b"0123456789").await; - println!("Send broadcast status: {:?}", status) - } - Either::Second(_) => (), - } - } -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.DPORT.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(run(esp_now)).ok(); - }) -} diff --git a/examples-esp32/examples/embassy_esp_now_duplex.rs b/examples-esp32/examples/embassy_esp_now_duplex.rs deleted file mode 100644 index 618055b4..00000000 --- a/examples-esp32/examples/embassy_esp_now_duplex.rs +++ /dev/null @@ -1,133 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_sync::blocking_mutex::raw::NoopRawMutex; -use embassy_sync::mutex::Mutex; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Ticker}; -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::esp_now::{EspNowManager, EspNowReceiver, EspNowSender, PeerInfo, BROADCAST_ADDRESS}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; - -#[embassy_executor::task] -async fn broadcaster(sender: &'static Mutex>) { - let mut ticker = Ticker::every(Duration::from_secs(1)); - loop { - ticker.next().await; - - println!("Send Broadcast..."); - let mut sender = sender.lock().await; - let status = sender.send_async(&BROADCAST_ADDRESS, b"Hello.").await; - println!("Send broadcast status: {:?}", status); - } -} - -#[embassy_executor::task] -async fn sayhello( - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, -) { - let mut ticker = Ticker::every(Duration::from_millis(500)); - loop { - ticker.next().await; - let peer = match manager.fetch_peer(false) { - Ok(peer) => peer, - Err(_) => { - if let Ok(peer) = manager.fetch_peer(true) { - peer - } else { - continue; - } - } - }; - - println!("Send hello to peer {:?}", peer.peer_address); - let mut sender = sender.lock().await; - let status = sender.send_async(&peer.peer_address, b"Hello Peer.").await; - println!("Send hello status: {:?}", status); - } -} - -#[embassy_executor::task] -async fn listener(manager: &'static EspNowManager<'static>, mut receiver: EspNowReceiver<'static>) { - loop { - let r = receiver.receive_async().await; - println!("Received {:?}", r.get_data()); - if r.info.dst_address == BROADCAST_ADDRESS { - if !manager.peer_exists(&r.info.src_address) { - manager - .add_peer(PeerInfo { - peer_address: r.info.src_address, - lmk: None, - channel: None, - encrypt: false, - }) - .unwrap(); - println!("Added peer {:?}", r.info.src_address); - } - } - } -} - -static EXECUTOR: StaticCell = StaticCell::new(); -static ESP_NOW_MANAGER: StaticCell> = StaticCell::new(); -static ESP_NOW_SENDER: StaticCell>> = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.DPORT.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - - let (manager, sender, receiver) = esp_now.split(); - let manager = ESP_NOW_MANAGER.init(manager); - let sender: &'static _ = ESP_NOW_SENDER.init(Mutex::new(sender)); - - executor.run(|spawner| { - spawner.spawn(listener(manager, receiver)).ok(); - spawner.spawn(broadcaster(sender)).ok(); - spawner.spawn(sayhello(manager, sender)).ok(); - }) -} diff --git a/examples-esp32/examples/esp_now.rs b/examples-esp32/examples/esp_now.rs deleted file mode 100644 index 419e74ec..00000000 --- a/examples-esp32/examples/esp_now.rs +++ /dev/null @@ -1,80 +0,0 @@ -#![no_std] -#![no_main] - -use esp_backtrace as _; -use esp_println::println; -use esp_wifi::esp_now::{PeerInfo, BROADCAST_ADDRESS}; -use esp_wifi::{current_millis, initialize, EspWifiInitFor}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{peripherals::Peripherals, prelude::*}; - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.DPORT.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let mut next_send_time = current_millis() + 5 * 1000; - loop { - let r = esp_now.receive(); - if let Some(r) = r { - println!("Received {:?}", r); - - if r.info.dst_address == BROADCAST_ADDRESS { - if !esp_now.peer_exists(&r.info.src_address) { - esp_now - .add_peer(PeerInfo { - peer_address: r.info.src_address, - lmk: None, - channel: None, - encrypt: false, - }) - .unwrap(); - } - let status = esp_now - .send(&r.info.src_address, b"Hello Peer") - .unwrap() - .wait(); - println!("Send hello to peer status: {:?}", status); - } - } - - if current_millis() >= next_send_time { - next_send_time = current_millis() + 5 * 1000; - println!("Send"); - let status = esp_now - .send(&BROADCAST_ADDRESS, b"0123456789") - .unwrap() - .wait(); - println!("Send broadcast status: {:?}", status) - } - } -} diff --git a/examples-esp32/examples/static_ip.rs b/examples-esp32/examples/static_ip.rs deleted file mode 100644 index af4a7333..00000000 --- a/examples-esp32/examples/static_ip.rs +++ /dev/null @@ -1,199 +0,0 @@ -#![no_std] -#![no_main] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointInfo, ClientConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; -use esp_println::{print, println}; -use esp_wifi::initialize; -use esp_wifi::wifi::WifiMode; -use esp_wifi::wifi::{utils::create_network_interface, WifiError}; -use esp_wifi::wifi_interface::WifiStack; -use esp_wifi::{current_millis, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{peripherals::Peripherals, prelude::*}; - -use smoltcp::iface::SocketStorage; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); -const STATIC_IP: &str = env!("STATIC_IP"); -const GATEWAY_IP: &str = env!("GATEWAY_IP"); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.DPORT.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Sta, &mut socket_set_entries).unwrap(); - let mut wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("Start Wifi Scan"); - let res: Result<(heapless::Vec, usize), WifiError> = controller.scan_n(); - if let Ok((res, _count)) = res { - for ap in res { - println!("{:?}", ap); - } - } - - println!("{:?}", controller.get_capabilities()); - println!("wifi_connect {:?}", controller.connect()); - - // wait to get connected - println!("Wait to get connected"); - loop { - let res = controller.is_connected(); - match res { - Ok(connected) => { - if connected { - break; - } - } - Err(err) => { - println!("{:?}", err); - loop {} - } - } - } - println!("{:?}", controller.is_connected()); - - println!("Setting static IP {}", STATIC_IP); - - wifi_stack - .set_iface_configuration(&embedded_svc::ipv4::Configuration::Client( - embedded_svc::ipv4::ClientConfiguration::Fixed(embedded_svc::ipv4::ClientSettings { - ip: embedded_svc::ipv4::Ipv4Addr::from(parse_ip(STATIC_IP)), - subnet: embedded_svc::ipv4::Subnet { - gateway: embedded_svc::ipv4::Ipv4Addr::from(parse_ip(GATEWAY_IP)), - mask: embedded_svc::ipv4::Mask(24), - }, - dns: None, - secondary_dns: None, - }), - )) - .unwrap(); - - println!( - "Start busy loop on main. Point your browser to http://{}:8080/", - STATIC_IP - ); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - socket.listen(8080).unwrap(); - - loop { - socket.work(); - - if !socket.is_open() { - socket.listen(8080).unwrap(); - } - - if socket.is_connected() { - println!("Connected"); - - let mut time_out = false; - let wait_end = current_millis() + 20 * 1000; - let mut buffer = [0u8; 1024]; - let mut pos = 0; - loop { - if let Ok(len) = socket.read(&mut buffer[pos..]) { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - time_out = true; - break; - } - } - - if !time_out { - socket.write_all( - b"HTTP/1.0 200 OK\r\n\r\n\ - \ - \ -

Hello Rust! Hello esp-wifi!

\ - - \ - \r\n\ - " - ).unwrap(); - - socket.flush().unwrap(); - } - - socket.close(); - - println!("Done\n"); - println!(); - } - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} - -fn parse_ip(ip: &str) -> [u8; 4] { - let mut result = [0u8; 4]; - for (idx, octet) in ip.split(".").into_iter().enumerate() { - result[idx] = u8::from_str_radix(octet, 10).unwrap(); - } - result -} diff --git a/examples-esp32/src/lib.rs b/examples-esp32/src/lib.rs deleted file mode 100644 index 0c3fcbb6..00000000 --- a/examples-esp32/src/lib.rs +++ /dev/null @@ -1,3 +0,0 @@ -#![no_std] - -// no code here - see examples folder diff --git a/examples-esp32c2/.cargo/config.toml b/examples-esp32c2/.cargo/config.toml deleted file mode 100644 index dbc6dfe0..00000000 --- a/examples-esp32c2/.cargo/config.toml +++ /dev/null @@ -1,30 +0,0 @@ -[target.riscv32imc-unknown-none-elf] -runner = "espflash flash --monitor" - -rustflags = [ - "-C", "link-arg=-Tlinkall.x", - "-C", "link-arg=-Trom_functions.x", - - "-C", "force-frame-pointers", - - # enable the atomic codegen option for RISCV - "-C", "target-feature=+a", - # tell the core library have atomics even though it's not specified in the target definition - "--cfg", "target_has_atomic_load_store", - "--cfg", 'target_has_atomic_load_store="8"', - "--cfg", 'target_has_atomic_load_store="16"', - "--cfg", 'target_has_atomic_load_store="32"', - "--cfg", 'target_has_atomic_load_store="ptr"', - # enable cas - "--cfg", "target_has_atomic", - "--cfg", 'target_has_atomic="8"', - "--cfg", 'target_has_atomic="16"', - "--cfg", 'target_has_atomic="32"', - "--cfg", 'target_has_atomic="ptr"', -] - -[build] -target = "riscv32imc-unknown-none-elf" - -[unstable] -build-std = [ "core" ] diff --git a/examples-esp32c2/Cargo.toml b/examples-esp32c2/Cargo.toml deleted file mode 100644 index b9ddf9b8..00000000 --- a/examples-esp32c2/Cargo.toml +++ /dev/null @@ -1,50 +0,0 @@ -[package] -name = "examples-esp32c2" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -embedded-svc.workspace = true -bleps.workspace = true -embassy-executor = { workspace = true, optional = true } -embassy-time.workspace = true -embassy-futures.workspace = true -futures-util.workspace = true -embedded-io.workspace = true -smoltcp.workspace = true -log = { workspace = true, optional = true } -heapless.workspace = true -embassy-net = { workspace = true, optional = true } -embassy-sync.workspace = true - -esp32c2-hal.workspace = true -esp-backtrace = { workspace = true, features = ["esp32c2"] } -esp-wifi = { path = "../esp-wifi", default-features = false, features = ["esp32c2", "utils"] } -embedded-hal-async = { workspace = true, optional = true } - -[dev-dependencies] -esp-println = { workspace = true, features = [ "esp32c2", "log" ] } - -[features] -default = ["esp32c2", "log"] -esp32c2 = [] -async = ["esp-wifi/async", "bleps/async", "dep:embedded-hal-async", "esp32c2-hal/async", "esp32c2-hal/embassy-time-timg0", "dep:embassy-executor", "embassy-executor?/arch-riscv32"] -embassy-net = ["esp-wifi/embassy-net","dep:embassy-net"] -wifi-logs = ["esp-wifi/wifi-logs"] -dump-packets = ["esp-wifi/dump-packets"] -utils = ["esp-wifi/utils"] -enumset = ["esp-wifi/enumset"] -# required for wifi feature -embedded-svc = [ "esp-wifi/embedded-svc" ] -wifi = ["esp-wifi/wifi", "embedded-svc"] -ble = ["esp-wifi/ble"] -phy-enable-usb = ["esp-wifi/phy-enable-usb"] -ps-min-modem = ["esp-wifi/ps-min-modem"] -ps-max-modem = ["esp-wifi/ps-max-modem"] -esp-now = ["esp-wifi/esp-now"] -ipv6 = ["esp-wifi/ipv6"] -#coex = ["esp-wifi/coex"] -log = ["esp-wifi/log", "dep:log", "esp-println/log"] -defmt = ["esp-wifi/defmt", "esp-println/defmt"] diff --git a/examples-esp32c2/examples/access_point.rs b/examples-esp32c2/examples/access_point.rs deleted file mode 100644 index 413e3d35..00000000 --- a/examples-esp32c2/examples/access_point.rs +++ /dev/null @@ -1,160 +0,0 @@ -#![no_std] -#![no_main] -#![feature(c_variadic)] -#![feature(const_mut_refs)] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; -use esp_println::{print, println}; -use esp_wifi::initialize; -use esp_wifi::wifi::utils::create_network_interface; -use esp_wifi::wifi::WifiMode; -use esp_wifi::wifi_interface::WifiStack; -use esp_wifi::{current_millis, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::{peripherals::Peripherals, prelude::*}; -use hal::{systimer::SystemTimer, Rng}; - -use smoltcp::iface::SocketStorage; - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Ap, &mut socket_set_entries).unwrap(); - let mut wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::AccessPoint(AccessPointConfiguration { - ssid: "esp-wifi".into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("{:?}", controller.get_capabilities()); - - wifi_stack - .set_iface_configuration(&embedded_svc::ipv4::Configuration::Client( - embedded_svc::ipv4::ClientConfiguration::Fixed(embedded_svc::ipv4::ClientSettings { - ip: embedded_svc::ipv4::Ipv4Addr::from(parse_ip("192.168.2.1")), - subnet: embedded_svc::ipv4::Subnet { - gateway: embedded_svc::ipv4::Ipv4Addr::from(parse_ip("192.168.2.1")), - mask: embedded_svc::ipv4::Mask(24), - }, - dns: None, - secondary_dns: None, - }), - )) - .unwrap(); - - println!("Start busy loop on main. Connect to the AP `esp-wifi` and point your browser to http://192.168.2.1:8080/"); - println!("Use a static IP in the range 192.168.2.2 .. 192.168.2.255, use gateway 192.168.2.1"); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - socket.listen(8080).unwrap(); - - loop { - socket.work(); - - if !socket.is_open() { - socket.listen(8080).unwrap(); - } - - if socket.is_connected() { - println!("Connected"); - - let mut time_out = false; - let wait_end = current_millis() + 20 * 1000; - let mut buffer = [0u8; 1024]; - let mut pos = 0; - loop { - if let Ok(len) = socket.read(&mut buffer[pos..]) { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - time_out = true; - break; - } - } - - if !time_out { - socket - .write_all( - b"HTTP/1.0 200 OK\r\n\r\n\ - \ - \ -

Hello Rust! Hello esp-wifi!

\ - \ - \r\n\ - ", - ) - .unwrap(); - - socket.flush().unwrap(); - } - - socket.close(); - - println!("Done\n"); - println!(); - } - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} - -fn parse_ip(ip: &str) -> [u8; 4] { - let mut result = [0u8; 4]; - for (idx, octet) in ip.split(".").into_iter().enumerate() { - result[idx] = u8::from_str_radix(octet, 10).unwrap(); - } - result -} diff --git a/examples-esp32c2/examples/async_ble.rs b/examples-esp32c2/examples/async_ble.rs deleted file mode 100644 index 7174a2d1..00000000 --- a/examples-esp32c2/examples/async_ble.rs +++ /dev/null @@ -1,169 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] -#![feature(async_closure)] - -use core::cell::RefCell; - -use bleps::{ - ad_structure::{ - create_advertising_data, AdStructure, BR_EDR_NOT_SUPPORTED, LE_GENERAL_DISCOVERABLE, - }, - async_attribute_server::AttributeServer, - asynch::Ble, - attribute_server::NotificationData, - gatt, -}; -use embassy_executor::Executor; -use embassy_executor::_export::StaticCell; -use embedded_hal_async::digital::Wait; -use esp_backtrace as _; -use esp_println::println; -use esp_wifi::{ - ble::controller::asynch::BleConnector, initialize, EspWifiInitFor, EspWifiInitialization, -}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; -use examples_util::BootButton; -use hal::{ - clock::ClockControl, embassy, peripherals::*, prelude::*, radio::Bluetooth, - systimer::SystemTimer, timer::TimerGroup, Rng, IO, -}; - -#[embassy_executor::task] -async fn run(init: EspWifiInitialization, mut bluetooth: Bluetooth, pin: BootButton) { - let connector = BleConnector::new(&init, &mut bluetooth); - let mut ble = Ble::new(connector, esp_wifi::current_millis); - println!("Connector created"); - - let pin_ref = RefCell::new(pin); - - loop { - println!("{:?}", ble.init().await); - println!("{:?}", ble.cmd_set_le_advertising_parameters().await); - println!( - "{:?}", - ble.cmd_set_le_advertising_data( - create_advertising_data(&[ - AdStructure::Flags(LE_GENERAL_DISCOVERABLE | BR_EDR_NOT_SUPPORTED), - AdStructure::ServiceUuids16(&[Uuid::Uuid16(0x1809)]), - AdStructure::CompleteLocalName(examples_util::SOC_NAME), - ]) - .unwrap() - ) - .await - ); - println!("{:?}", ble.cmd_set_le_advertise_enable(true).await); - - println!("started advertising"); - - let mut rf = |_offset: usize, data: &mut [u8]| { - data[..20].copy_from_slice(&b"Hello Bare-Metal BLE"[..]); - 17 - }; - let mut wf = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut wf2 = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut rf3 = |_offset: usize, data: &mut [u8]| { - data[..5].copy_from_slice(&b"Hola!"[..]); - 5 - }; - let mut wf3 = |offset: usize, data: &[u8]| { - println!("RECEIVED: Offset {}, data {:?}", offset, data); - }; - - gatt!([service { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - characteristics: [ - characteristic { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - read: rf, - write: wf, - }, - characteristic { - uuid: "957312e0-2354-11eb-9f10-fbc30a62cf38", - write: wf2, - }, - characteristic { - name: "my_characteristic", - uuid: "987312e0-2354-11eb-9f10-fbc30a62cf38", - notify: true, - read: rf3, - write: wf3, - }, - ], - },]); - - let mut srv = AttributeServer::new(&mut ble, &mut gatt_attributes); - - let counter = RefCell::new(0u8); - let mut notifier = async || { - // TODO how to check if notifications are enabled for the characteristic? - // maybe pass something into the closure which just can query the characterisic value - // probably passing in the attribute server won't work? - pin_ref.borrow_mut().wait_for_rising_edge().await.unwrap(); - let mut data = [0u8; 13]; - data.copy_from_slice(b"Notification0"); - { - let mut counter = counter.borrow_mut(); - data[data.len() - 1] += *counter; - *counter = (*counter + 1) % 10; - } - NotificationData::new(my_characteristic_handle, &data) - }; - - srv.run(&mut notifier).await.unwrap(); - } -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Ble, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let io = IO::new(peripherals.GPIO, peripherals.IO_MUX); - let button = io.pins.gpio9.into_pull_down_input(); - - // Async requires the GPIO interrupt to wake futures - hal::interrupt::enable( - hal::peripherals::Interrupt::GPIO, - hal::interrupt::Priority::Priority1, - ) - .unwrap(); - - let (_, bluetooth, ..) = peripherals.RADIO.split(); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(run(init, bluetooth, button)).ok(); - }); -} diff --git a/examples-esp32c2/examples/ble.rs b/examples-esp32c2/examples/ble.rs deleted file mode 100644 index 4aff7c99..00000000 --- a/examples-esp32c2/examples/ble.rs +++ /dev/null @@ -1,151 +0,0 @@ -#![no_std] -#![no_main] - -use bleps::{ - ad_structure::{ - create_advertising_data, AdStructure, BR_EDR_NOT_SUPPORTED, LE_GENERAL_DISCOVERABLE, - }, - attribute_server::{AttributeServer, NotificationData, WorkResult}, - gatt, Ble, HciConnector, -}; -use esp_backtrace as _; -use esp_println::println; -use esp_wifi::{ble::controller::BleConnector, initialize, EspWifiInitFor}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; -use hal::{clock::ClockControl, peripherals::*, prelude::*, systimer::SystemTimer, Rng, IO}; - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Ble, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let io = IO::new(peripherals.GPIO, peripherals.IO_MUX); - let button = io.pins.gpio9.into_pull_down_input(); - - let mut debounce_cnt = 500; - - let (_, mut bluetooth, ..) = peripherals.RADIO.split(); - - loop { - let connector = BleConnector::new(&init, &mut bluetooth); - let hci = HciConnector::new(connector, esp_wifi::current_millis); - let mut ble = Ble::new(&hci); - - println!("{:?}", ble.init()); - println!("{:?}", ble.cmd_set_le_advertising_parameters()); - println!( - "{:?}", - ble.cmd_set_le_advertising_data( - create_advertising_data(&[ - AdStructure::Flags(LE_GENERAL_DISCOVERABLE | BR_EDR_NOT_SUPPORTED), - AdStructure::ServiceUuids16(&[Uuid::Uuid16(0x1809)]), - AdStructure::CompleteLocalName(examples_util::SOC_NAME), - ]) - .unwrap() - ) - ); - println!("{:?}", ble.cmd_set_le_advertise_enable(true)); - - println!("started advertising"); - - let mut rf = |_offset: usize, data: &mut [u8]| { - data[..20].copy_from_slice(&b"Hello Bare-Metal BLE"[..]); - 17 - }; - let mut wf = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut wf2 = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut rf3 = |_offset: usize, data: &mut [u8]| { - data[..5].copy_from_slice(&b"Hola!"[..]); - 5 - }; - let mut wf3 = |offset: usize, data: &[u8]| { - println!("RECEIVED: Offset {}, data {:?}", offset, data); - }; - - gatt!([service { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - characteristics: [ - characteristic { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - read: rf, - write: wf, - }, - characteristic { - uuid: "957312e0-2354-11eb-9f10-fbc30a62cf38", - write: wf2, - }, - characteristic { - name: "my_characteristic", - uuid: "987312e0-2354-11eb-9f10-fbc30a62cf38", - notify: true, - read: rf3, - write: wf3, - }, - ], - },]); - - let mut srv = AttributeServer::new(&mut ble, &mut gatt_attributes); - - loop { - let mut notification = None; - - if button.is_low().unwrap() && debounce_cnt > 0 { - debounce_cnt -= 1; - if debounce_cnt == 0 { - let mut cccd = [0u8; 1]; - if let Some(1) = srv.get_characteristic_value( - my_characteristic_notify_enable_handle, - 0, - &mut cccd, - ) { - // if notifications enabled - if cccd[0] == 1 { - notification = Some(NotificationData::new( - my_characteristic_handle, - &b"Notification"[..], - )); - } - } - } - }; - - if button.is_high().unwrap() { - debounce_cnt = 500; - } - - match srv.do_work_with_notification(notification) { - Ok(res) => { - if let WorkResult::GotDisconnected = res { - break; - } - } - Err(err) => { - println!("{:?}", err); - } - } - } - } -} diff --git a/examples-esp32c2/examples/dhcp.rs b/examples-esp32c2/examples/dhcp.rs deleted file mode 100644 index 9b516bc3..00000000 --- a/examples-esp32c2/examples/dhcp.rs +++ /dev/null @@ -1,149 +0,0 @@ -#![no_std] -#![no_main] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointInfo, ClientConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; - -use esp_println::{print, println}; -use esp_wifi::wifi::utils::create_network_interface; -use esp_wifi::wifi::{WifiError, WifiMode}; -use esp_wifi::wifi_interface::WifiStack; -use esp_wifi::{current_millis, initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::{peripherals::Peripherals, prelude::*}; -use hal::{systimer::SystemTimer, Rng}; -use smoltcp::iface::SocketStorage; -use smoltcp::wire::IpAddress; -use smoltcp::wire::Ipv4Address; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Sta, &mut socket_set_entries).unwrap(); - let wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("Start Wifi Scan"); - let res: Result<(heapless::Vec, usize), WifiError> = controller.scan_n(); - if let Ok((res, _count)) = res { - for ap in res { - println!("{:?}", ap); - } - } - - println!("{:?}", controller.get_capabilities()); - println!("wifi_connect {:?}", controller.connect()); - - // wait to get connected - println!("Wait to get connected"); - loop { - let res = controller.is_connected(); - match res { - Ok(connected) => { - if connected { - break; - } - } - Err(err) => { - println!("{:?}", err); - loop {} - } - } - } - println!("{:?}", controller.is_connected()); - - // wait for getting an ip address - println!("Wait to get an ip address"); - loop { - wifi_stack.work(); - - if wifi_stack.is_iface_up() { - println!("got ip {:?}", wifi_stack.get_ip_info()); - break; - } - } - - println!("Start busy loop on main"); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - loop { - println!("Making HTTP request"); - socket.work(); - - socket - .open(IpAddress::Ipv4(Ipv4Address::new(142, 250, 185, 115)), 80) - .unwrap(); - - socket - .write(b"GET / HTTP/1.0\r\nHost: www.mobile-j.de\r\n\r\n") - .unwrap(); - socket.flush().unwrap(); - - let wait_end = current_millis() + 20 * 1000; - loop { - let mut buffer = [0u8; 512]; - if let Ok(len) = socket.read(&mut buffer) { - let to_print = unsafe { core::str::from_utf8_unchecked(&buffer[..len]) }; - print!("{}", to_print); - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - break; - } - } - println!(); - - socket.disconnect(); - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} diff --git a/examples-esp32c2/examples/embassy_access_point.rs b/examples-esp32c2/examples/embassy_access_point.rs deleted file mode 100644 index 8c486466..00000000 --- a/examples-esp32c2/examples/embassy_access_point.rs +++ /dev/null @@ -1,214 +0,0 @@ -#![no_std] -#![no_main] -#![feature(c_variadic)] -#![feature(const_mut_refs)] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_net::tcp::TcpSocket; -use embassy_net::ConfigV4; -use embassy_net::{ - Config, IpListenEndpoint, Ipv4Address, Ipv4Cidr, Stack, StackResources, StaticConfigV4, -}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Timer}; -use embedded_svc::wifi::{AccessPointConfiguration, Configuration, Wifi}; -use esp_backtrace as _; - -use esp_println::{print, println}; -use esp_wifi::wifi::{WifiController, WifiDevice, WifiEvent, WifiMode, WifiState}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; -use hal::{systimer::SystemTimer, Rng}; - -macro_rules! singleton { - ($val:expr) => {{ - type T = impl Sized; - static STATIC_CELL: StaticCell = StaticCell::new(); - let (x,) = STATIC_CELL.init(($val,)); - x - }}; -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let (wifi_interface, controller) = - esp_wifi::wifi::new_with_mode(&init, wifi, WifiMode::Ap).unwrap(); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - - let config = Config { - ipv4: ConfigV4::Static(StaticConfigV4 { - address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 2, 1), 24), - gateway: Some(Ipv4Address::from_bytes(&[192, 168, 2, 1])), - dns_servers: Default::default(), - }), - }; - - let seed = 1234; // very random, very secure seed - - // Init network stack - let stack = &*singleton!(Stack::new( - wifi_interface, - config, - singleton!(StackResources::<3>::new()), - seed - )); - - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); - spawner.spawn(task(&stack)).ok(); - }) -} - -#[embassy_executor::task] -async fn connection(mut controller: WifiController<'static>) { - println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); - loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::ApStarted => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::ApStop).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} - } - if !matches!(controller.is_started(), Ok(true)) { - let client_config = Configuration::AccessPoint(AccessPointConfiguration { - ssid: "esp-wifi".into(), - ..Default::default() - }); - controller.set_configuration(&client_config).unwrap(); - println!("Starting wifi"); - controller.start().await.unwrap(); - println!("Wifi started!"); - } - } -} - -#[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await -} - -#[embassy_executor::task] -async fn task(stack: &'static Stack>) { - let mut rx_buffer = [0; 4096]; - let mut tx_buffer = [0; 4096]; - - loop { - if stack.is_link_up() { - break; - } - Timer::after(Duration::from_millis(500)).await; - } - println!("Connect to the AP `esp-wifi` and point your browser to http://192.168.2.1:8080/"); - println!("Use a static IP in the range 192.168.2.2 .. 192.168.2.255, use gateway 192.168.2.1"); - - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); - socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); - loop { - println!("Wait for connection..."); - let r = socket - .accept(IpListenEndpoint { - addr: None, - port: 8080, - }) - .await; - println!("Connected..."); - - if let Err(e) = r { - println!("connect error: {:?}", e); - continue; - } - - use embedded_io::asynch::Write; - - let mut buffer = [0u8; 1024]; - let mut pos = 0; - loop { - match socket.read(&mut buffer).await { - Ok(0) => { - println!("read EOF"); - break; - } - Ok(len) => { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } - Err(e) => { - println!("read error: {:?}", e); - break; - } - }; - } - - let r = socket - .write_all( - b"HTTP/1.0 200 OK\r\n\r\n\ - \ - \ -

Hello Rust! Hello esp-wifi!

\ - \ - \r\n\ - ", - ) - .await; - if let Err(e) = r { - println!("write error: {:?}", e); - } - - let r = socket.flush().await; - if let Err(e) = r { - println!("flush error: {:?}", e); - } - Timer::after(Duration::from_millis(1000)).await; - - socket.close(); - Timer::after(Duration::from_millis(1000)).await; - - socket.abort(); - } -} diff --git a/examples-esp32c2/examples/embassy_dhcp.rs b/examples-esp32c2/examples/embassy_dhcp.rs deleted file mode 100644 index 8ca6a23a..00000000 --- a/examples-esp32c2/examples/embassy_dhcp.rs +++ /dev/null @@ -1,191 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_net::tcp::TcpSocket; -use embassy_net::{Config, Ipv4Address, Stack, StackResources}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Timer}; -use embedded_svc::wifi::{ClientConfiguration, Configuration, Wifi}; -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::wifi::{WifiController, WifiDevice, WifiEvent, WifiMode, WifiState}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; -use hal::{systimer::SystemTimer, Rng}; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); - -macro_rules! singleton { - ($val:expr) => {{ - type T = impl Sized; - static STATIC_CELL: StaticCell = StaticCell::new(); - let (x,) = STATIC_CELL.init(($val,)); - x - }}; -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let (wifi_interface, controller) = - esp_wifi::wifi::new_with_mode(&init, wifi, WifiMode::Sta).unwrap(); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - - let config = Config::dhcpv4(Default::default()); - - let seed = 1234; // very random, very secure seed - - // Init network stack - let stack = &*singleton!(Stack::new( - wifi_interface, - config, - singleton!(StackResources::<3>::new()), - seed - )); - - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); - spawner.spawn(task(&stack)).ok(); - }) -} - -#[embassy_executor::task] -async fn connection(mut controller: WifiController<'static>) { - println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); - loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::StaConnected => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::StaDisconnected).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} - } - if !matches!(controller.is_started(), Ok(true)) { - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - controller.set_configuration(&client_config).unwrap(); - println!("Starting wifi"); - controller.start().await.unwrap(); - println!("Wifi started!"); - } - println!("About to connect..."); - - match controller.connect().await { - Ok(_) => println!("Wifi connected!"), - Err(e) => { - println!("Failed to connect to wifi: {e:?}"); - Timer::after(Duration::from_millis(5000)).await - } - } - } -} - -#[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await -} - -#[embassy_executor::task] -async fn task(stack: &'static Stack>) { - let mut rx_buffer = [0; 4096]; - let mut tx_buffer = [0; 4096]; - - loop { - if stack.is_link_up() { - break; - } - Timer::after(Duration::from_millis(500)).await; - } - - println!("Waiting to get IP address..."); - loop { - if let Some(config) = stack.config_v4() { - println!("Got IP: {}", config.address); - break; - } - Timer::after(Duration::from_millis(500)).await; - } - - loop { - Timer::after(Duration::from_millis(1_000)).await; - - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); - - socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); - - let remote_endpoint = (Ipv4Address::new(142, 250, 185, 115), 80); - println!("connecting..."); - let r = socket.connect(remote_endpoint).await; - if let Err(e) = r { - println!("connect error: {:?}", e); - continue; - } - println!("connected!"); - let mut buf = [0; 1024]; - loop { - use embedded_io::asynch::Write; - let r = socket - .write_all(b"GET / HTTP/1.0\r\nHost: www.mobile-j.de\r\n\r\n") - .await; - if let Err(e) = r { - println!("write error: {:?}", e); - break; - } - let n = match socket.read(&mut buf).await { - Ok(0) => { - println!("read EOF"); - break; - } - Ok(n) => n, - Err(e) => { - println!("read error: {:?}", e); - break; - } - }; - println!("{}", core::str::from_utf8(&buf[..n]).unwrap()); - } - Timer::after(Duration::from_millis(3000)).await; - } -} diff --git a/examples-esp32c2/examples/embassy_esp_now.rs b/examples-esp32c2/examples/embassy_esp_now.rs deleted file mode 100644 index e15d07b4..00000000 --- a/examples-esp32c2/examples/embassy_esp_now.rs +++ /dev/null @@ -1,93 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_futures::select::{select, Either}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Ticker}; -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::esp_now::{EspNow, PeerInfo, BROADCAST_ADDRESS}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; -use hal::{systimer::SystemTimer, Rng}; - -#[embassy_executor::task] -async fn run(mut esp_now: EspNow<'static>) { - let mut ticker = Ticker::every(Duration::from_secs(5)); - loop { - let res = select(ticker.next(), async { - let r = esp_now.receive_async().await; - println!("Received {:?}", r); - if r.info.dst_address == BROADCAST_ADDRESS { - if !esp_now.peer_exists(&r.info.src_address) { - esp_now - .add_peer(PeerInfo { - peer_address: r.info.src_address, - lmk: None, - channel: None, - encrypt: false, - }) - .unwrap(); - } - let status = esp_now.send_async(&r.info.src_address, b"Hello Peer").await; - println!("Send hello to peer status: {:?}", status); - } - }) - .await; - - match res { - Either::First(_) => { - println!("Send"); - let status = esp_now.send_async(&BROADCAST_ADDRESS, b"0123456789").await; - println!("Send broadcast status: {:?}", status) - } - Either::Second(_) => (), - } - } -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(run(esp_now)).ok(); - }) -} diff --git a/examples-esp32c2/examples/embassy_esp_now_duplex.rs b/examples-esp32c2/examples/embassy_esp_now_duplex.rs deleted file mode 100644 index 60d1a9d9..00000000 --- a/examples-esp32c2/examples/embassy_esp_now_duplex.rs +++ /dev/null @@ -1,130 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_sync::blocking_mutex::raw::NoopRawMutex; -use embassy_sync::mutex::Mutex; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Ticker}; -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::esp_now::{EspNowManager, EspNowReceiver, EspNowSender, PeerInfo, BROADCAST_ADDRESS}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{ - embassy, peripherals::Peripherals, prelude::*, systimer::SystemTimer, timer::TimerGroup, -}; - -#[embassy_executor::task] -async fn broadcaster(sender: &'static Mutex>) { - let mut ticker = Ticker::every(Duration::from_secs(1)); - loop { - ticker.next().await; - - println!("Send Broadcast..."); - let mut sender = sender.lock().await; - let status = sender.send_async(&BROADCAST_ADDRESS, b"Hello.").await; - println!("Send broadcast status: {:?}", status); - } -} - -#[embassy_executor::task] -async fn sayhello( - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, -) { - let mut ticker = Ticker::every(Duration::from_millis(500)); - loop { - ticker.next().await; - let peer = match manager.fetch_peer(false) { - Ok(peer) => peer, - Err(_) => { - if let Ok(peer) = manager.fetch_peer(true) { - peer - } else { - continue; - } - } - }; - - println!("Send hello to peer {:?}", peer.peer_address); - let mut sender = sender.lock().await; - let status = sender.send_async(&peer.peer_address, b"Hello Peer.").await; - println!("Send hello status: {:?}", status); - } -} - -#[embassy_executor::task] -async fn listener(manager: &'static EspNowManager<'static>, mut receiver: EspNowReceiver<'static>) { - loop { - let r = receiver.receive_async().await; - println!("Received {:?}", r.get_data()); - if r.info.dst_address == BROADCAST_ADDRESS { - if !manager.peer_exists(&r.info.src_address) { - manager - .add_peer(PeerInfo { - peer_address: r.info.src_address, - lmk: None, - channel: None, - encrypt: false, - }) - .unwrap(); - println!("Added peer {:?}", r.info.src_address); - } - } - } -} - -static EXECUTOR: StaticCell = StaticCell::new(); -static ESP_NOW_MANAGER: StaticCell> = StaticCell::new(); -static ESP_NOW_SENDER: StaticCell>> = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - - let (manager, sender, receiver) = esp_now.split(); - let manager = ESP_NOW_MANAGER.init(manager); - let sender: &'static _ = ESP_NOW_SENDER.init(Mutex::new(sender)); - - executor.run(|spawner| { - spawner.spawn(listener(manager, receiver)).ok(); - spawner.spawn(broadcaster(sender)).ok(); - spawner.spawn(sayhello(manager, sender)).ok(); - }) -} diff --git a/examples-esp32c2/examples/esp_now.rs b/examples-esp32c2/examples/esp_now.rs deleted file mode 100644 index 42be53f3..00000000 --- a/examples-esp32c2/examples/esp_now.rs +++ /dev/null @@ -1,76 +0,0 @@ -#![no_std] -#![no_main] - -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::esp_now::{PeerInfo, BROADCAST_ADDRESS}; -use esp_wifi::{current_millis, initialize, EspWifiInitFor}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; -use hal::clock::ClockControl; -use hal::{peripherals::Peripherals, prelude::*}; -use hal::{systimer::SystemTimer, Rng}; - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let mut next_send_time = current_millis() + 5 * 1000; - loop { - let r = esp_now.receive(); - if let Some(r) = r { - println!("Received {:?}", r); - - if r.info.dst_address == BROADCAST_ADDRESS { - if !esp_now.peer_exists(&r.info.src_address) { - esp_now - .add_peer(PeerInfo { - peer_address: r.info.src_address, - lmk: None, - channel: None, - encrypt: false, - }) - .unwrap(); - } - let status = esp_now - .send(&r.info.src_address, b"Hello Peer") - .unwrap() - .wait(); - println!("Send hello to peer status: {:?}", status); - } - } - - if current_millis() >= next_send_time { - next_send_time = current_millis() + 5 * 1000; - println!("Send"); - let status = esp_now - .send(&BROADCAST_ADDRESS, b"0123456789") - .unwrap() - .wait(); - println!("Send broadcast status: {:?}", status) - } - } -} diff --git a/examples-esp32c2/examples/static_ip.rs b/examples-esp32c2/examples/static_ip.rs deleted file mode 100644 index c79ee8c6..00000000 --- a/examples-esp32c2/examples/static_ip.rs +++ /dev/null @@ -1,195 +0,0 @@ -#![no_std] -#![no_main] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointInfo, ClientConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; - -use esp_println::{print, println}; -use esp_wifi::initialize; -use esp_wifi::wifi::WifiMode; -use esp_wifi::wifi::{utils::create_network_interface, WifiError}; -use esp_wifi::wifi_interface::WifiStack; -use esp_wifi::{current_millis, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::{peripherals::Peripherals, prelude::*}; -use hal::{systimer::SystemTimer, Rng}; - -use smoltcp::iface::SocketStorage; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); -const STATIC_IP: &str = env!("STATIC_IP"); -const GATEWAY_IP: &str = env!("GATEWAY_IP"); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Sta, &mut socket_set_entries).unwrap(); - let mut wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("Start Wifi Scan"); - let res: Result<(heapless::Vec, usize), WifiError> = controller.scan_n(); - if let Ok((res, _count)) = res { - for ap in res { - println!("{:?}", ap); - } - } - - println!("{:?}", controller.get_capabilities()); - println!("wifi_connect {:?}", controller.connect()); - - // wait to get connected - println!("Wait to get connected"); - loop { - let res = controller.is_connected(); - match res { - Ok(connected) => { - if connected { - break; - } - } - Err(err) => { - println!("{:?}", err); - loop {} - } - } - } - println!("{:?}", controller.is_connected()); - - println!("Setting static IP {}", STATIC_IP); - - wifi_stack - .set_iface_configuration(&embedded_svc::ipv4::Configuration::Client( - embedded_svc::ipv4::ClientConfiguration::Fixed(embedded_svc::ipv4::ClientSettings { - ip: embedded_svc::ipv4::Ipv4Addr::from(parse_ip(STATIC_IP)), - subnet: embedded_svc::ipv4::Subnet { - gateway: embedded_svc::ipv4::Ipv4Addr::from(parse_ip(GATEWAY_IP)), - mask: embedded_svc::ipv4::Mask(24), - }, - dns: None, - secondary_dns: None, - }), - )) - .unwrap(); - - println!( - "Start busy loop on main. Point your browser to http://{}:8080/", - STATIC_IP - ); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - socket.listen(8080).unwrap(); - - loop { - socket.work(); - - if !socket.is_open() { - socket.listen(8080).unwrap(); - } - - if socket.is_connected() { - println!("Connected"); - - let mut time_out = false; - let wait_end = current_millis() + 20 * 1000; - let mut buffer = [0u8; 1024]; - let mut pos = 0; - loop { - if let Ok(len) = socket.read(&mut buffer[pos..]) { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - time_out = true; - break; - } - } - - if !time_out { - socket.write_all( - b"HTTP/1.0 200 OK\r\n\r\n\ - \ - \ -

Hello Rust! Hello esp-wifi!

\ - - \ - \r\n\ - " - ).unwrap(); - - socket.flush().unwrap(); - } - - socket.close(); - - println!("Done\n"); - println!(); - } - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} - -fn parse_ip(ip: &str) -> [u8; 4] { - let mut result = [0u8; 4]; - for (idx, octet) in ip.split(".").into_iter().enumerate() { - result[idx] = u8::from_str_radix(octet, 10).unwrap(); - } - result -} diff --git a/examples-esp32c2/rust-toolchain.toml b/examples-esp32c2/rust-toolchain.toml deleted file mode 100644 index 5d56faf9..00000000 --- a/examples-esp32c2/rust-toolchain.toml +++ /dev/null @@ -1,2 +0,0 @@ -[toolchain] -channel = "nightly" diff --git a/examples-esp32c2/src/lib.rs b/examples-esp32c2/src/lib.rs deleted file mode 100644 index 0c3fcbb6..00000000 --- a/examples-esp32c2/src/lib.rs +++ /dev/null @@ -1,3 +0,0 @@ -#![no_std] - -// no code here - see examples folder diff --git a/examples-esp32c3/.cargo/config.toml b/examples-esp32c3/.cargo/config.toml deleted file mode 100644 index dbc6dfe0..00000000 --- a/examples-esp32c3/.cargo/config.toml +++ /dev/null @@ -1,30 +0,0 @@ -[target.riscv32imc-unknown-none-elf] -runner = "espflash flash --monitor" - -rustflags = [ - "-C", "link-arg=-Tlinkall.x", - "-C", "link-arg=-Trom_functions.x", - - "-C", "force-frame-pointers", - - # enable the atomic codegen option for RISCV - "-C", "target-feature=+a", - # tell the core library have atomics even though it's not specified in the target definition - "--cfg", "target_has_atomic_load_store", - "--cfg", 'target_has_atomic_load_store="8"', - "--cfg", 'target_has_atomic_load_store="16"', - "--cfg", 'target_has_atomic_load_store="32"', - "--cfg", 'target_has_atomic_load_store="ptr"', - # enable cas - "--cfg", "target_has_atomic", - "--cfg", 'target_has_atomic="8"', - "--cfg", 'target_has_atomic="16"', - "--cfg", 'target_has_atomic="32"', - "--cfg", 'target_has_atomic="ptr"', -] - -[build] -target = "riscv32imc-unknown-none-elf" - -[unstable] -build-std = [ "core" ] diff --git a/examples-esp32c3/Cargo.toml b/examples-esp32c3/Cargo.toml deleted file mode 100644 index ddac011c..00000000 --- a/examples-esp32c3/Cargo.toml +++ /dev/null @@ -1,50 +0,0 @@ -[package] -name = "examples-esp32c3" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -embedded-svc.workspace = true -bleps.workspace = true -embassy-executor = { workspace = true, optional = true } -embassy-time.workspace = true -embassy-futures.workspace = true -futures-util.workspace = true -embedded-io.workspace = true -smoltcp.workspace = true -log = { workspace = true, optional = true } -heapless.workspace = true -embassy-net = { workspace = true, optional = true } -embassy-sync.workspace = true - -esp32c3-hal.workspace = true -esp-backtrace = { workspace = true, features = ["esp32c3"] } -esp-wifi = { path = "../esp-wifi", default-features = false, features = ["esp32c3", "utils"] } -embedded-hal-async = { workspace = true, optional = true } - -[dev-dependencies] -esp-println = { workspace = true, features = [ "esp32c3", "log" ] } - -[features] -default = ["esp32c3", "log"] -esp32c3 = [] -async = ["esp-wifi/async", "bleps/async", "dep:embedded-hal-async", "esp32c3-hal/async", "esp32c3-hal/embassy-time-timg0", "dep:embassy-executor", "embassy-executor?/arch-riscv32"] -embassy-net = ["esp-wifi/embassy-net","dep:embassy-net"] -wifi-logs = ["esp-wifi/wifi-logs"] -dump-packets = ["esp-wifi/dump-packets"] -utils = ["esp-wifi/utils"] -enumset = ["esp-wifi/enumset"] -# required for wifi feature -embedded-svc = [ "esp-wifi/embedded-svc" ] -wifi = ["esp-wifi/wifi", "embedded-svc"] -ble = ["esp-wifi/ble"] -phy-enable-usb = ["esp-wifi/phy-enable-usb"] -ps-min-modem = ["esp-wifi/ps-min-modem"] -ps-max-modem = ["esp-wifi/ps-max-modem"] -esp-now = ["esp-wifi/esp-now"] -ipv6 = ["esp-wifi/ipv6"] -coex = ["esp-wifi/coex"] -log = ["esp-wifi/log", "dep:log", "esp-println/log"] -defmt = ["esp-wifi/defmt", "esp-println/defmt"] diff --git a/examples-esp32c3/examples/async_ble.rs b/examples-esp32c3/examples/async_ble.rs deleted file mode 100644 index 7174a2d1..00000000 --- a/examples-esp32c3/examples/async_ble.rs +++ /dev/null @@ -1,169 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] -#![feature(async_closure)] - -use core::cell::RefCell; - -use bleps::{ - ad_structure::{ - create_advertising_data, AdStructure, BR_EDR_NOT_SUPPORTED, LE_GENERAL_DISCOVERABLE, - }, - async_attribute_server::AttributeServer, - asynch::Ble, - attribute_server::NotificationData, - gatt, -}; -use embassy_executor::Executor; -use embassy_executor::_export::StaticCell; -use embedded_hal_async::digital::Wait; -use esp_backtrace as _; -use esp_println::println; -use esp_wifi::{ - ble::controller::asynch::BleConnector, initialize, EspWifiInitFor, EspWifiInitialization, -}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; -use examples_util::BootButton; -use hal::{ - clock::ClockControl, embassy, peripherals::*, prelude::*, radio::Bluetooth, - systimer::SystemTimer, timer::TimerGroup, Rng, IO, -}; - -#[embassy_executor::task] -async fn run(init: EspWifiInitialization, mut bluetooth: Bluetooth, pin: BootButton) { - let connector = BleConnector::new(&init, &mut bluetooth); - let mut ble = Ble::new(connector, esp_wifi::current_millis); - println!("Connector created"); - - let pin_ref = RefCell::new(pin); - - loop { - println!("{:?}", ble.init().await); - println!("{:?}", ble.cmd_set_le_advertising_parameters().await); - println!( - "{:?}", - ble.cmd_set_le_advertising_data( - create_advertising_data(&[ - AdStructure::Flags(LE_GENERAL_DISCOVERABLE | BR_EDR_NOT_SUPPORTED), - AdStructure::ServiceUuids16(&[Uuid::Uuid16(0x1809)]), - AdStructure::CompleteLocalName(examples_util::SOC_NAME), - ]) - .unwrap() - ) - .await - ); - println!("{:?}", ble.cmd_set_le_advertise_enable(true).await); - - println!("started advertising"); - - let mut rf = |_offset: usize, data: &mut [u8]| { - data[..20].copy_from_slice(&b"Hello Bare-Metal BLE"[..]); - 17 - }; - let mut wf = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut wf2 = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut rf3 = |_offset: usize, data: &mut [u8]| { - data[..5].copy_from_slice(&b"Hola!"[..]); - 5 - }; - let mut wf3 = |offset: usize, data: &[u8]| { - println!("RECEIVED: Offset {}, data {:?}", offset, data); - }; - - gatt!([service { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - characteristics: [ - characteristic { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - read: rf, - write: wf, - }, - characteristic { - uuid: "957312e0-2354-11eb-9f10-fbc30a62cf38", - write: wf2, - }, - characteristic { - name: "my_characteristic", - uuid: "987312e0-2354-11eb-9f10-fbc30a62cf38", - notify: true, - read: rf3, - write: wf3, - }, - ], - },]); - - let mut srv = AttributeServer::new(&mut ble, &mut gatt_attributes); - - let counter = RefCell::new(0u8); - let mut notifier = async || { - // TODO how to check if notifications are enabled for the characteristic? - // maybe pass something into the closure which just can query the characterisic value - // probably passing in the attribute server won't work? - pin_ref.borrow_mut().wait_for_rising_edge().await.unwrap(); - let mut data = [0u8; 13]; - data.copy_from_slice(b"Notification0"); - { - let mut counter = counter.borrow_mut(); - data[data.len() - 1] += *counter; - *counter = (*counter + 1) % 10; - } - NotificationData::new(my_characteristic_handle, &data) - }; - - srv.run(&mut notifier).await.unwrap(); - } -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Ble, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let io = IO::new(peripherals.GPIO, peripherals.IO_MUX); - let button = io.pins.gpio9.into_pull_down_input(); - - // Async requires the GPIO interrupt to wake futures - hal::interrupt::enable( - hal::peripherals::Interrupt::GPIO, - hal::interrupt::Priority::Priority1, - ) - .unwrap(); - - let (_, bluetooth, ..) = peripherals.RADIO.split(); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(run(init, bluetooth, button)).ok(); - }); -} diff --git a/examples-esp32c3/examples/ble.rs b/examples-esp32c3/examples/ble.rs deleted file mode 100644 index 4aff7c99..00000000 --- a/examples-esp32c3/examples/ble.rs +++ /dev/null @@ -1,151 +0,0 @@ -#![no_std] -#![no_main] - -use bleps::{ - ad_structure::{ - create_advertising_data, AdStructure, BR_EDR_NOT_SUPPORTED, LE_GENERAL_DISCOVERABLE, - }, - attribute_server::{AttributeServer, NotificationData, WorkResult}, - gatt, Ble, HciConnector, -}; -use esp_backtrace as _; -use esp_println::println; -use esp_wifi::{ble::controller::BleConnector, initialize, EspWifiInitFor}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; -use hal::{clock::ClockControl, peripherals::*, prelude::*, systimer::SystemTimer, Rng, IO}; - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Ble, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let io = IO::new(peripherals.GPIO, peripherals.IO_MUX); - let button = io.pins.gpio9.into_pull_down_input(); - - let mut debounce_cnt = 500; - - let (_, mut bluetooth, ..) = peripherals.RADIO.split(); - - loop { - let connector = BleConnector::new(&init, &mut bluetooth); - let hci = HciConnector::new(connector, esp_wifi::current_millis); - let mut ble = Ble::new(&hci); - - println!("{:?}", ble.init()); - println!("{:?}", ble.cmd_set_le_advertising_parameters()); - println!( - "{:?}", - ble.cmd_set_le_advertising_data( - create_advertising_data(&[ - AdStructure::Flags(LE_GENERAL_DISCOVERABLE | BR_EDR_NOT_SUPPORTED), - AdStructure::ServiceUuids16(&[Uuid::Uuid16(0x1809)]), - AdStructure::CompleteLocalName(examples_util::SOC_NAME), - ]) - .unwrap() - ) - ); - println!("{:?}", ble.cmd_set_le_advertise_enable(true)); - - println!("started advertising"); - - let mut rf = |_offset: usize, data: &mut [u8]| { - data[..20].copy_from_slice(&b"Hello Bare-Metal BLE"[..]); - 17 - }; - let mut wf = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut wf2 = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut rf3 = |_offset: usize, data: &mut [u8]| { - data[..5].copy_from_slice(&b"Hola!"[..]); - 5 - }; - let mut wf3 = |offset: usize, data: &[u8]| { - println!("RECEIVED: Offset {}, data {:?}", offset, data); - }; - - gatt!([service { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - characteristics: [ - characteristic { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - read: rf, - write: wf, - }, - characteristic { - uuid: "957312e0-2354-11eb-9f10-fbc30a62cf38", - write: wf2, - }, - characteristic { - name: "my_characteristic", - uuid: "987312e0-2354-11eb-9f10-fbc30a62cf38", - notify: true, - read: rf3, - write: wf3, - }, - ], - },]); - - let mut srv = AttributeServer::new(&mut ble, &mut gatt_attributes); - - loop { - let mut notification = None; - - if button.is_low().unwrap() && debounce_cnt > 0 { - debounce_cnt -= 1; - if debounce_cnt == 0 { - let mut cccd = [0u8; 1]; - if let Some(1) = srv.get_characteristic_value( - my_characteristic_notify_enable_handle, - 0, - &mut cccd, - ) { - // if notifications enabled - if cccd[0] == 1 { - notification = Some(NotificationData::new( - my_characteristic_handle, - &b"Notification"[..], - )); - } - } - } - }; - - if button.is_high().unwrap() { - debounce_cnt = 500; - } - - match srv.do_work_with_notification(notification) { - Ok(res) => { - if let WorkResult::GotDisconnected = res { - break; - } - } - Err(err) => { - println!("{:?}", err); - } - } - } - } -} diff --git a/examples-esp32c3/examples/embassy_access_point.rs b/examples-esp32c3/examples/embassy_access_point.rs deleted file mode 100644 index 8c486466..00000000 --- a/examples-esp32c3/examples/embassy_access_point.rs +++ /dev/null @@ -1,214 +0,0 @@ -#![no_std] -#![no_main] -#![feature(c_variadic)] -#![feature(const_mut_refs)] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_net::tcp::TcpSocket; -use embassy_net::ConfigV4; -use embassy_net::{ - Config, IpListenEndpoint, Ipv4Address, Ipv4Cidr, Stack, StackResources, StaticConfigV4, -}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Timer}; -use embedded_svc::wifi::{AccessPointConfiguration, Configuration, Wifi}; -use esp_backtrace as _; - -use esp_println::{print, println}; -use esp_wifi::wifi::{WifiController, WifiDevice, WifiEvent, WifiMode, WifiState}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; -use hal::{systimer::SystemTimer, Rng}; - -macro_rules! singleton { - ($val:expr) => {{ - type T = impl Sized; - static STATIC_CELL: StaticCell = StaticCell::new(); - let (x,) = STATIC_CELL.init(($val,)); - x - }}; -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let (wifi_interface, controller) = - esp_wifi::wifi::new_with_mode(&init, wifi, WifiMode::Ap).unwrap(); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - - let config = Config { - ipv4: ConfigV4::Static(StaticConfigV4 { - address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 2, 1), 24), - gateway: Some(Ipv4Address::from_bytes(&[192, 168, 2, 1])), - dns_servers: Default::default(), - }), - }; - - let seed = 1234; // very random, very secure seed - - // Init network stack - let stack = &*singleton!(Stack::new( - wifi_interface, - config, - singleton!(StackResources::<3>::new()), - seed - )); - - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); - spawner.spawn(task(&stack)).ok(); - }) -} - -#[embassy_executor::task] -async fn connection(mut controller: WifiController<'static>) { - println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); - loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::ApStarted => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::ApStop).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} - } - if !matches!(controller.is_started(), Ok(true)) { - let client_config = Configuration::AccessPoint(AccessPointConfiguration { - ssid: "esp-wifi".into(), - ..Default::default() - }); - controller.set_configuration(&client_config).unwrap(); - println!("Starting wifi"); - controller.start().await.unwrap(); - println!("Wifi started!"); - } - } -} - -#[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await -} - -#[embassy_executor::task] -async fn task(stack: &'static Stack>) { - let mut rx_buffer = [0; 4096]; - let mut tx_buffer = [0; 4096]; - - loop { - if stack.is_link_up() { - break; - } - Timer::after(Duration::from_millis(500)).await; - } - println!("Connect to the AP `esp-wifi` and point your browser to http://192.168.2.1:8080/"); - println!("Use a static IP in the range 192.168.2.2 .. 192.168.2.255, use gateway 192.168.2.1"); - - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); - socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); - loop { - println!("Wait for connection..."); - let r = socket - .accept(IpListenEndpoint { - addr: None, - port: 8080, - }) - .await; - println!("Connected..."); - - if let Err(e) = r { - println!("connect error: {:?}", e); - continue; - } - - use embedded_io::asynch::Write; - - let mut buffer = [0u8; 1024]; - let mut pos = 0; - loop { - match socket.read(&mut buffer).await { - Ok(0) => { - println!("read EOF"); - break; - } - Ok(len) => { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } - Err(e) => { - println!("read error: {:?}", e); - break; - } - }; - } - - let r = socket - .write_all( - b"HTTP/1.0 200 OK\r\n\r\n\ - \ - \ -

Hello Rust! Hello esp-wifi!

\ - \ - \r\n\ - ", - ) - .await; - if let Err(e) = r { - println!("write error: {:?}", e); - } - - let r = socket.flush().await; - if let Err(e) = r { - println!("flush error: {:?}", e); - } - Timer::after(Duration::from_millis(1000)).await; - - socket.close(); - Timer::after(Duration::from_millis(1000)).await; - - socket.abort(); - } -} diff --git a/examples-esp32c3/examples/embassy_dhcp.rs b/examples-esp32c3/examples/embassy_dhcp.rs deleted file mode 100644 index 8ca6a23a..00000000 --- a/examples-esp32c3/examples/embassy_dhcp.rs +++ /dev/null @@ -1,191 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_net::tcp::TcpSocket; -use embassy_net::{Config, Ipv4Address, Stack, StackResources}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Timer}; -use embedded_svc::wifi::{ClientConfiguration, Configuration, Wifi}; -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::wifi::{WifiController, WifiDevice, WifiEvent, WifiMode, WifiState}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; -use hal::{systimer::SystemTimer, Rng}; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); - -macro_rules! singleton { - ($val:expr) => {{ - type T = impl Sized; - static STATIC_CELL: StaticCell = StaticCell::new(); - let (x,) = STATIC_CELL.init(($val,)); - x - }}; -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let (wifi_interface, controller) = - esp_wifi::wifi::new_with_mode(&init, wifi, WifiMode::Sta).unwrap(); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - - let config = Config::dhcpv4(Default::default()); - - let seed = 1234; // very random, very secure seed - - // Init network stack - let stack = &*singleton!(Stack::new( - wifi_interface, - config, - singleton!(StackResources::<3>::new()), - seed - )); - - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); - spawner.spawn(task(&stack)).ok(); - }) -} - -#[embassy_executor::task] -async fn connection(mut controller: WifiController<'static>) { - println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); - loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::StaConnected => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::StaDisconnected).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} - } - if !matches!(controller.is_started(), Ok(true)) { - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - controller.set_configuration(&client_config).unwrap(); - println!("Starting wifi"); - controller.start().await.unwrap(); - println!("Wifi started!"); - } - println!("About to connect..."); - - match controller.connect().await { - Ok(_) => println!("Wifi connected!"), - Err(e) => { - println!("Failed to connect to wifi: {e:?}"); - Timer::after(Duration::from_millis(5000)).await - } - } - } -} - -#[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await -} - -#[embassy_executor::task] -async fn task(stack: &'static Stack>) { - let mut rx_buffer = [0; 4096]; - let mut tx_buffer = [0; 4096]; - - loop { - if stack.is_link_up() { - break; - } - Timer::after(Duration::from_millis(500)).await; - } - - println!("Waiting to get IP address..."); - loop { - if let Some(config) = stack.config_v4() { - println!("Got IP: {}", config.address); - break; - } - Timer::after(Duration::from_millis(500)).await; - } - - loop { - Timer::after(Duration::from_millis(1_000)).await; - - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); - - socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); - - let remote_endpoint = (Ipv4Address::new(142, 250, 185, 115), 80); - println!("connecting..."); - let r = socket.connect(remote_endpoint).await; - if let Err(e) = r { - println!("connect error: {:?}", e); - continue; - } - println!("connected!"); - let mut buf = [0; 1024]; - loop { - use embedded_io::asynch::Write; - let r = socket - .write_all(b"GET / HTTP/1.0\r\nHost: www.mobile-j.de\r\n\r\n") - .await; - if let Err(e) = r { - println!("write error: {:?}", e); - break; - } - let n = match socket.read(&mut buf).await { - Ok(0) => { - println!("read EOF"); - break; - } - Ok(n) => n, - Err(e) => { - println!("read error: {:?}", e); - break; - } - }; - println!("{}", core::str::from_utf8(&buf[..n]).unwrap()); - } - Timer::after(Duration::from_millis(3000)).await; - } -} diff --git a/examples-esp32c3/examples/embassy_esp_now.rs b/examples-esp32c3/examples/embassy_esp_now.rs deleted file mode 100644 index 74640f86..00000000 --- a/examples-esp32c3/examples/embassy_esp_now.rs +++ /dev/null @@ -1,93 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_futures::select::{select, Either}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Ticker}; -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::esp_now::{EspNow, PeerInfo, BROADCAST_ADDRESS}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; -use hal::{systimer::SystemTimer, Rng}; - -#[embassy_executor::task] -async fn run(mut esp_now: EspNow<'static>) { - let mut ticker = Ticker::every(Duration::from_secs(5)); - loop { - let res = select(ticker.next(), async { - let r = esp_now.receive_async().await; - println!("Received {:?}", r); - if r.info.dst_address == BROADCAST_ADDRESS { - if !esp_now.peer_exists(&r.info.src_address) { - esp_now - .add_peer(PeerInfo { - peer_address: r.info.src_address, - lmk: None, - channel: None, - encrypt: false, - }) - .unwrap(); - } - let status = esp_now.send_async(&r.info.src_address, b"Hello Peer").await; - println!("Send hello to peer status: {:?}", status); - } - }) - .await; - - match res { - Either::First(_) => { - println!("Send"); - let status = esp_now.send_async(&BROADCAST_ADDRESS, b"0123456789").await; - println!("Send broadcast status: {:?}", status); - } - Either::Second(_) => (), - } - } -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(run(esp_now)).ok(); - }) -} diff --git a/examples-esp32c3/examples/embassy_esp_now_duplex.rs b/examples-esp32c3/examples/embassy_esp_now_duplex.rs deleted file mode 100644 index 60d1a9d9..00000000 --- a/examples-esp32c3/examples/embassy_esp_now_duplex.rs +++ /dev/null @@ -1,130 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_sync::blocking_mutex::raw::NoopRawMutex; -use embassy_sync::mutex::Mutex; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Ticker}; -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::esp_now::{EspNowManager, EspNowReceiver, EspNowSender, PeerInfo, BROADCAST_ADDRESS}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{ - embassy, peripherals::Peripherals, prelude::*, systimer::SystemTimer, timer::TimerGroup, -}; - -#[embassy_executor::task] -async fn broadcaster(sender: &'static Mutex>) { - let mut ticker = Ticker::every(Duration::from_secs(1)); - loop { - ticker.next().await; - - println!("Send Broadcast..."); - let mut sender = sender.lock().await; - let status = sender.send_async(&BROADCAST_ADDRESS, b"Hello.").await; - println!("Send broadcast status: {:?}", status); - } -} - -#[embassy_executor::task] -async fn sayhello( - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, -) { - let mut ticker = Ticker::every(Duration::from_millis(500)); - loop { - ticker.next().await; - let peer = match manager.fetch_peer(false) { - Ok(peer) => peer, - Err(_) => { - if let Ok(peer) = manager.fetch_peer(true) { - peer - } else { - continue; - } - } - }; - - println!("Send hello to peer {:?}", peer.peer_address); - let mut sender = sender.lock().await; - let status = sender.send_async(&peer.peer_address, b"Hello Peer.").await; - println!("Send hello status: {:?}", status); - } -} - -#[embassy_executor::task] -async fn listener(manager: &'static EspNowManager<'static>, mut receiver: EspNowReceiver<'static>) { - loop { - let r = receiver.receive_async().await; - println!("Received {:?}", r.get_data()); - if r.info.dst_address == BROADCAST_ADDRESS { - if !manager.peer_exists(&r.info.src_address) { - manager - .add_peer(PeerInfo { - peer_address: r.info.src_address, - lmk: None, - channel: None, - encrypt: false, - }) - .unwrap(); - println!("Added peer {:?}", r.info.src_address); - } - } - } -} - -static EXECUTOR: StaticCell = StaticCell::new(); -static ESP_NOW_MANAGER: StaticCell> = StaticCell::new(); -static ESP_NOW_SENDER: StaticCell>> = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - - let (manager, sender, receiver) = esp_now.split(); - let manager = ESP_NOW_MANAGER.init(manager); - let sender: &'static _ = ESP_NOW_SENDER.init(Mutex::new(sender)); - - executor.run(|spawner| { - spawner.spawn(listener(manager, receiver)).ok(); - spawner.spawn(broadcaster(sender)).ok(); - spawner.spawn(sayhello(manager, sender)).ok(); - }) -} diff --git a/examples-esp32c3/rust-toolchain.toml b/examples-esp32c3/rust-toolchain.toml deleted file mode 100644 index 5d56faf9..00000000 --- a/examples-esp32c3/rust-toolchain.toml +++ /dev/null @@ -1,2 +0,0 @@ -[toolchain] -channel = "nightly" diff --git a/examples-esp32c3/src/lib.rs b/examples-esp32c3/src/lib.rs deleted file mode 100644 index 0c3fcbb6..00000000 --- a/examples-esp32c3/src/lib.rs +++ /dev/null @@ -1,3 +0,0 @@ -#![no_std] - -// no code here - see examples folder diff --git a/examples-esp32c6/.cargo/config.toml b/examples-esp32c6/.cargo/config.toml deleted file mode 100644 index 6e7478e9..00000000 --- a/examples-esp32c6/.cargo/config.toml +++ /dev/null @@ -1,15 +0,0 @@ -[target.riscv32imac-unknown-none-elf] -runner = "espflash flash --monitor" - -rustflags = [ - "-C", "link-arg=-Tlinkall.x", - "-C", "link-arg=-Trom_functions.x", - - "-C", "force-frame-pointers", -] - -[build] -target = "riscv32imac-unknown-none-elf" - -[unstable] -build-std = [ "core" ] diff --git a/examples-esp32c6/Cargo.toml b/examples-esp32c6/Cargo.toml deleted file mode 100644 index 53a01aed..00000000 --- a/examples-esp32c6/Cargo.toml +++ /dev/null @@ -1,50 +0,0 @@ -[package] -name = "examples-esp32c6" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -embedded-svc.workspace = true -bleps.workspace = true -embassy-executor = { workspace = true, optional = true } -embassy-time.workspace = true -embassy-futures.workspace = true -futures-util.workspace = true -embedded-io.workspace = true -smoltcp.workspace = true -log = { workspace = true, optional = true } -heapless.workspace = true -embassy-net = { workspace = true, optional = true } -embassy-sync.workspace = true - -esp32c6-hal.workspace = true -esp-backtrace = { workspace = true, features = ["esp32c6"] } -esp-wifi = { path = "../esp-wifi", default-features = false, features = ["esp32c6", "utils"] } -embedded-hal-async = { workspace = true, optional = true } - -[dev-dependencies] -esp-println = { workspace = true, features = [ "esp32c6", "log" ] } - -[features] -default = ["esp32c6", "log"] -esp32c6 = [] -async = ["esp-wifi/async", "bleps/async", "dep:embedded-hal-async", "esp32c6-hal/async", "esp32c6-hal/embassy-time-timg0", "dep:embassy-executor", "embassy-executor?/arch-riscv32"] -embassy-net = ["esp-wifi/embassy-net", "dep:embassy-net"] -wifi-logs = ["esp-wifi/wifi-logs"] -dump-packets = ["esp-wifi/dump-packets"] -utils = ["esp-wifi/utils"] -enumset = ["esp-wifi/enumset"] -# required for wifi feature -embedded-svc = [ "esp-wifi/embedded-svc" ] -wifi = ["esp-wifi/wifi", "embedded-svc"] -ble = ["esp-wifi/ble"] -phy-enable-usb = ["esp-wifi/phy-enable-usb"] -ps-min-modem = ["esp-wifi/ps-min-modem"] -ps-max-modem = ["esp-wifi/ps-max-modem"] -esp-now = ["esp-wifi/esp-now"] -ipv6 = ["esp-wifi/ipv6"] -#coex = ["esp-wifi/coex"] -log = ["esp-wifi/log", "dep:log", "esp-println/log"] -defmt = ["esp-wifi/defmt", "esp-println/defmt"] diff --git a/examples-esp32c6/examples/access_point.rs b/examples-esp32c6/examples/access_point.rs deleted file mode 100644 index 2d393402..00000000 --- a/examples-esp32c6/examples/access_point.rs +++ /dev/null @@ -1,161 +0,0 @@ -#![no_std] -#![no_main] -#![feature(c_variadic)] -#![feature(const_mut_refs)] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; - -use esp_println::{print, println}; -use esp_wifi::initialize; -use esp_wifi::wifi::utils::create_network_interface; -use esp_wifi::wifi::WifiMode; -use esp_wifi::wifi_interface::WifiStack; -use esp_wifi::{current_millis, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::{peripherals::Peripherals, prelude::*}; -use hal::{systimer::SystemTimer, Rng}; - -use smoltcp::iface::SocketStorage; - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let system = peripherals.PCR.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Ap, &mut socket_set_entries).unwrap(); - let mut wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::AccessPoint(AccessPointConfiguration { - ssid: "esp-wifi".into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("{:?}", controller.get_capabilities()); - - wifi_stack - .set_iface_configuration(&embedded_svc::ipv4::Configuration::Client( - embedded_svc::ipv4::ClientConfiguration::Fixed(embedded_svc::ipv4::ClientSettings { - ip: embedded_svc::ipv4::Ipv4Addr::from(parse_ip("192.168.2.1")), - subnet: embedded_svc::ipv4::Subnet { - gateway: embedded_svc::ipv4::Ipv4Addr::from(parse_ip("192.168.2.1")), - mask: embedded_svc::ipv4::Mask(24), - }, - dns: None, - secondary_dns: None, - }), - )) - .unwrap(); - - println!("Start busy loop on main. Connect to the AP `esp-wifi` and point your browser to http://192.168.2.1:8080/"); - println!("Use a static IP in the range 192.168.2.2 .. 192.168.2.255, use gateway 192.168.2.1"); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - socket.listen(8080).unwrap(); - - loop { - socket.work(); - - if !socket.is_open() { - socket.listen(8080).unwrap(); - } - - if socket.is_connected() { - println!("Connected"); - - let mut time_out = false; - let wait_end = current_millis() + 20 * 1000; - let mut buffer = [0u8; 1024]; - let mut pos = 0; - loop { - if let Ok(len) = socket.read(&mut buffer[pos..]) { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - time_out = true; - break; - } - } - - if !time_out { - socket - .write_all( - b"HTTP/1.0 200 OK\r\n\r\n\ - \ - \ -

Hello Rust! Hello esp-wifi!

\ - \ - \r\n\ - ", - ) - .unwrap(); - - socket.flush().unwrap(); - } - - socket.close(); - - println!("Done\n"); - println!(); - } - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} - -fn parse_ip(ip: &str) -> [u8; 4] { - let mut result = [0u8; 4]; - for (idx, octet) in ip.split(".").into_iter().enumerate() { - result[idx] = u8::from_str_radix(octet, 10).unwrap(); - } - result -} diff --git a/examples-esp32c6/examples/ble.rs b/examples-esp32c6/examples/ble.rs deleted file mode 100644 index 8de1f09f..00000000 --- a/examples-esp32c6/examples/ble.rs +++ /dev/null @@ -1,151 +0,0 @@ -#![no_std] -#![no_main] - -use bleps::{ - ad_structure::{ - create_advertising_data, AdStructure, BR_EDR_NOT_SUPPORTED, LE_GENERAL_DISCOVERABLE, - }, - attribute_server::{AttributeServer, NotificationData, WorkResult}, - gatt, Ble, HciConnector, -}; -use esp_backtrace as _; -use esp_println::println; -use esp_wifi::{ble::controller::BleConnector, initialize, EspWifiInitFor}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; -use hal::{clock::ClockControl, peripherals::*, prelude::*, systimer::SystemTimer, Rng, IO}; - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let system = peripherals.PCR.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Ble, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let io = IO::new(peripherals.GPIO, peripherals.IO_MUX); - let button = io.pins.gpio9.into_pull_down_input(); - - let mut debounce_cnt = 500; - - let (_, mut bluetooth, ..) = peripherals.RADIO.split(); - - loop { - let connector = BleConnector::new(&init, &mut bluetooth); - let hci = HciConnector::new(connector, esp_wifi::current_millis); - let mut ble = Ble::new(&hci); - - println!("{:?}", ble.init()); - println!("{:?}", ble.cmd_set_le_advertising_parameters()); - println!( - "{:?}", - ble.cmd_set_le_advertising_data( - create_advertising_data(&[ - AdStructure::Flags(LE_GENERAL_DISCOVERABLE | BR_EDR_NOT_SUPPORTED), - AdStructure::ServiceUuids16(&[Uuid::Uuid16(0x1809)]), - AdStructure::CompleteLocalName(examples_util::SOC_NAME), - ]) - .unwrap() - ) - ); - println!("{:?}", ble.cmd_set_le_advertise_enable(true)); - - println!("started advertising"); - - let mut rf = |_offset: usize, data: &mut [u8]| { - data[..20].copy_from_slice(&b"Hello Bare-Metal BLE"[..]); - 17 - }; - let mut wf = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut wf2 = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut rf3 = |_offset: usize, data: &mut [u8]| { - data[..5].copy_from_slice(&b"Hola!"[..]); - 5 - }; - let mut wf3 = |offset: usize, data: &[u8]| { - println!("RECEIVED: Offset {}, data {:?}", offset, data); - }; - - gatt!([service { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - characteristics: [ - characteristic { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - read: rf, - write: wf, - }, - characteristic { - uuid: "957312e0-2354-11eb-9f10-fbc30a62cf38", - write: wf2, - }, - characteristic { - name: "my_characteristic", - uuid: "987312e0-2354-11eb-9f10-fbc30a62cf38", - notify: true, - read: rf3, - write: wf3, - }, - ], - },]); - - let mut srv = AttributeServer::new(&mut ble, &mut gatt_attributes); - - loop { - let mut notification = None; - - if button.is_low().unwrap() && debounce_cnt > 0 { - debounce_cnt -= 1; - if debounce_cnt == 0 { - let mut cccd = [0u8; 1]; - if let Some(1) = srv.get_characteristic_value( - my_characteristic_notify_enable_handle, - 0, - &mut cccd, - ) { - // if notifications enabled - if cccd[0] == 1 { - notification = Some(NotificationData::new( - my_characteristic_handle, - &b"Notification"[..], - )); - } - } - } - }; - - if button.is_high().unwrap() { - debounce_cnt = 500; - } - - match srv.do_work_with_notification(notification) { - Ok(res) => { - if let WorkResult::GotDisconnected = res { - break; - } - } - Err(err) => { - println!("{:?}", err); - } - } - } - } -} diff --git a/examples-esp32c6/examples/dhcp.rs b/examples-esp32c6/examples/dhcp.rs deleted file mode 100644 index ccf3fc2b..00000000 --- a/examples-esp32c6/examples/dhcp.rs +++ /dev/null @@ -1,149 +0,0 @@ -#![no_std] -#![no_main] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointInfo, ClientConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; - -use esp_println::{print, println}; -use esp_wifi::wifi::utils::create_network_interface; -use esp_wifi::wifi::{WifiError, WifiMode}; -use esp_wifi::wifi_interface::WifiStack; -use esp_wifi::{current_millis, initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::{peripherals::Peripherals, prelude::*}; -use hal::{systimer::SystemTimer, Rng}; -use smoltcp::iface::SocketStorage; -use smoltcp::wire::IpAddress; -use smoltcp::wire::Ipv4Address; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let system = peripherals.PCR.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Sta, &mut socket_set_entries).unwrap(); - let wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("Start Wifi Scan"); - let res: Result<(heapless::Vec, usize), WifiError> = controller.scan_n(); - if let Ok((res, _count)) = res { - for ap in res { - println!("{:?}", ap); - } - } - - println!("{:?}", controller.get_capabilities()); - println!("wifi_connect {:?}", controller.connect()); - - // wait to get connected - println!("Wait to get connected"); - loop { - let res = controller.is_connected(); - match res { - Ok(connected) => { - if connected { - break; - } - } - Err(err) => { - println!("{:?}", err); - loop {} - } - } - } - println!("{:?}", controller.is_connected()); - - // wait for getting an ip address - println!("Wait to get an ip address"); - loop { - wifi_stack.work(); - - if wifi_stack.is_iface_up() { - println!("got ip {:?}", wifi_stack.get_ip_info()); - break; - } - } - - println!("Start busy loop on main"); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - loop { - println!("Making HTTP request"); - socket.work(); - - socket - .open(IpAddress::Ipv4(Ipv4Address::new(142, 250, 185, 115)), 80) - .unwrap(); - - socket - .write(b"GET / HTTP/1.0\r\nHost: www.mobile-j.de\r\n\r\n") - .unwrap(); - socket.flush().unwrap(); - - let wait_end = current_millis() + 20 * 1000; - loop { - let mut buffer = [0u8; 512]; - if let Ok(len) = socket.read(&mut buffer) { - let to_print = unsafe { core::str::from_utf8_unchecked(&buffer[..len]) }; - print!("{}", to_print); - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - break; - } - } - println!(); - - socket.disconnect(); - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} diff --git a/examples-esp32c6/examples/embassy_esp_now_duplex.rs b/examples-esp32c6/examples/embassy_esp_now_duplex.rs deleted file mode 100644 index 7592c216..00000000 --- a/examples-esp32c6/examples/embassy_esp_now_duplex.rs +++ /dev/null @@ -1,130 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_sync::blocking_mutex::raw::NoopRawMutex; -use embassy_sync::mutex::Mutex; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Ticker}; -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::esp_now::{EspNowManager, EspNowReceiver, EspNowSender, PeerInfo, BROADCAST_ADDRESS}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{ - embassy, peripherals::Peripherals, prelude::*, systimer::SystemTimer, timer::TimerGroup, -}; - -#[embassy_executor::task] -async fn broadcaster(sender: &'static Mutex>) { - let mut ticker = Ticker::every(Duration::from_secs(1)); - loop { - ticker.next().await; - - println!("Send Broadcast..."); - let mut sender = sender.lock().await; - let status = sender.send_async(&BROADCAST_ADDRESS, b"Hello.").await; - println!("Send broadcast status: {:?}", status); - } -} - -#[embassy_executor::task] -async fn sayhello( - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, -) { - let mut ticker = Ticker::every(Duration::from_millis(500)); - loop { - ticker.next().await; - let peer = match manager.fetch_peer(false) { - Ok(peer) => peer, - Err(_) => { - if let Ok(peer) = manager.fetch_peer(true) { - peer - } else { - continue; - } - } - }; - - println!("Send hello to peer {:?}", peer.peer_address); - let mut sender = sender.lock().await; - let status = sender.send_async(&peer.peer_address, b"Hello Peer.").await; - println!("Send hello status: {:?}", status); - } -} - -#[embassy_executor::task] -async fn listener(manager: &'static EspNowManager<'static>, mut receiver: EspNowReceiver<'static>) { - loop { - let r = receiver.receive_async().await; - println!("Received {:?}", r.get_data()); - if r.info.dst_address == BROADCAST_ADDRESS { - if !manager.peer_exists(&r.info.src_address) { - manager - .add_peer(PeerInfo { - peer_address: r.info.src_address, - lmk: None, - channel: None, - encrypt: false, - }) - .unwrap(); - println!("Added peer {:?}", r.info.src_address); - } - } - } -} - -static EXECUTOR: StaticCell = StaticCell::new(); -static ESP_NOW_MANAGER: StaticCell> = StaticCell::new(); -static ESP_NOW_SENDER: StaticCell>> = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.PCR.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - - let (manager, sender, receiver) = esp_now.split(); - let manager = ESP_NOW_MANAGER.init(manager); - let sender: &'static _ = ESP_NOW_SENDER.init(Mutex::new(sender)); - - executor.run(|spawner| { - spawner.spawn(listener(manager, receiver)).ok(); - spawner.spawn(broadcaster(sender)).ok(); - spawner.spawn(sayhello(manager, sender)).ok(); - }) -} diff --git a/examples-esp32c6/examples/esp_now.rs b/examples-esp32c6/examples/esp_now.rs deleted file mode 100644 index 7452a7b4..00000000 --- a/examples-esp32c6/examples/esp_now.rs +++ /dev/null @@ -1,76 +0,0 @@ -#![no_std] -#![no_main] - -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::esp_now::{PeerInfo, BROADCAST_ADDRESS}; -use esp_wifi::{current_millis, initialize, EspWifiInitFor}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; -use hal::clock::ClockControl; -use hal::{peripherals::Peripherals, prelude::*}; -use hal::{systimer::SystemTimer, Rng}; - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let system = peripherals.PCR.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let mut next_send_time = current_millis() + 5 * 1000; - loop { - let r = esp_now.receive(); - if let Some(r) = r { - println!("Received {:?}", r); - - if r.info.dst_address == BROADCAST_ADDRESS { - if !esp_now.peer_exists(&r.info.src_address) { - esp_now - .add_peer(PeerInfo { - peer_address: r.info.src_address, - lmk: None, - channel: None, - encrypt: false, - }) - .unwrap(); - } - let status = esp_now - .send(&r.info.src_address, b"Hello Peer") - .unwrap() - .wait(); - println!("Send hello to peer status: {:?}", status); - } - } - - if current_millis() >= next_send_time { - next_send_time = current_millis() + 5 * 1000; - println!("Send"); - let status = esp_now - .send(&BROADCAST_ADDRESS, b"0123456789") - .unwrap() - .wait(); - println!("Send broadcast status: {:?}", status) - } - } -} diff --git a/examples-esp32c6/examples/static_ip.rs b/examples-esp32c6/examples/static_ip.rs deleted file mode 100644 index 34f51d21..00000000 --- a/examples-esp32c6/examples/static_ip.rs +++ /dev/null @@ -1,195 +0,0 @@ -#![no_std] -#![no_main] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointInfo, ClientConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; - -use esp_println::{print, println}; -use esp_wifi::initialize; -use esp_wifi::wifi::WifiMode; -use esp_wifi::wifi::{utils::create_network_interface, WifiError}; -use esp_wifi::wifi_interface::WifiStack; -use esp_wifi::{current_millis, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::{peripherals::Peripherals, prelude::*}; -use hal::{systimer::SystemTimer, Rng}; - -use smoltcp::iface::SocketStorage; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); -const STATIC_IP: &str = env!("STATIC_IP"); -const GATEWAY_IP: &str = env!("GATEWAY_IP"); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let system = peripherals.PCR.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = SystemTimer::new(peripherals.SYSTIMER).alarm0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Sta, &mut socket_set_entries).unwrap(); - let mut wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("Start Wifi Scan"); - let res: Result<(heapless::Vec, usize), WifiError> = controller.scan_n(); - if let Ok((res, _count)) = res { - for ap in res { - println!("{:?}", ap); - } - } - - println!("{:?}", controller.get_capabilities()); - println!("wifi_connect {:?}", controller.connect()); - - // wait to get connected - println!("Wait to get connected"); - loop { - let res = controller.is_connected(); - match res { - Ok(connected) => { - if connected { - break; - } - } - Err(err) => { - println!("{:?}", err); - loop {} - } - } - } - println!("{:?}", controller.is_connected()); - - println!("Setting static IP {}", STATIC_IP); - - wifi_stack - .set_iface_configuration(&embedded_svc::ipv4::Configuration::Client( - embedded_svc::ipv4::ClientConfiguration::Fixed(embedded_svc::ipv4::ClientSettings { - ip: embedded_svc::ipv4::Ipv4Addr::from(parse_ip(STATIC_IP)), - subnet: embedded_svc::ipv4::Subnet { - gateway: embedded_svc::ipv4::Ipv4Addr::from(parse_ip(GATEWAY_IP)), - mask: embedded_svc::ipv4::Mask(24), - }, - dns: None, - secondary_dns: None, - }), - )) - .unwrap(); - - println!( - "Start busy loop on main. Point your browser to http://{}:8080/", - STATIC_IP - ); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - socket.listen(8080).unwrap(); - - loop { - socket.work(); - - if !socket.is_open() { - socket.listen(8080).unwrap(); - } - - if socket.is_connected() { - println!("Connected"); - - let mut time_out = false; - let wait_end = current_millis() + 20 * 1000; - let mut buffer = [0u8; 1024]; - let mut pos = 0; - loop { - if let Ok(len) = socket.read(&mut buffer[pos..]) { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - time_out = true; - break; - } - } - - if !time_out { - socket.write_all( - b"HTTP/1.0 200 OK\r\n\r\n\ - \ - \ -

Hello Rust! Hello esp-wifi!

\ - - \ - \r\n\ - " - ).unwrap(); - - socket.flush().unwrap(); - } - - socket.close(); - - println!("Done\n"); - println!(); - } - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} - -fn parse_ip(ip: &str) -> [u8; 4] { - let mut result = [0u8; 4]; - for (idx, octet) in ip.split(".").into_iter().enumerate() { - result[idx] = u8::from_str_radix(octet, 10).unwrap(); - } - result -} diff --git a/examples-esp32c6/rust-toolchain.toml b/examples-esp32c6/rust-toolchain.toml deleted file mode 100644 index 5d56faf9..00000000 --- a/examples-esp32c6/rust-toolchain.toml +++ /dev/null @@ -1,2 +0,0 @@ -[toolchain] -channel = "nightly" diff --git a/examples-esp32c6/src/lib.rs b/examples-esp32c6/src/lib.rs deleted file mode 100644 index 0c3fcbb6..00000000 --- a/examples-esp32c6/src/lib.rs +++ /dev/null @@ -1,3 +0,0 @@ -#![no_std] - -// no code here - see examples folder diff --git a/examples-esp32s2/.cargo/config.toml b/examples-esp32s2/.cargo/config.toml deleted file mode 100644 index 9fb1e242..00000000 --- a/examples-esp32s2/.cargo/config.toml +++ /dev/null @@ -1,29 +0,0 @@ -[target.xtensa-esp32s2-none-elf] -runner = "espflash flash --monitor" - -rustflags = [ - "-C", "link-arg=-Tlinkall.x", - "-C", "link-arg=-Trom_functions.x", - - # enable the atomic codegen option for Xtensa - "-C", "target-feature=+s32c1i", - - # tell the core library have atomics even though it's not specified in the target definition - "--cfg", "target_has_atomic_load_store", - "--cfg", 'target_has_atomic_load_store="8"', - "--cfg", 'target_has_atomic_load_store="16"', - "--cfg", 'target_has_atomic_load_store="32"', - "--cfg", 'target_has_atomic_load_store="ptr"', - # enable cas - "--cfg", "target_has_atomic", - "--cfg", 'target_has_atomic="8"', - "--cfg", 'target_has_atomic="16"', - "--cfg", 'target_has_atomic="32"', - "--cfg", 'target_has_atomic="ptr"', -] - -[build] -target = "xtensa-esp32s2-none-elf" - -[unstable] -build-std = [ "core" ] diff --git a/examples-esp32s2/Cargo.toml b/examples-esp32s2/Cargo.toml deleted file mode 100644 index a2705678..00000000 --- a/examples-esp32s2/Cargo.toml +++ /dev/null @@ -1,47 +0,0 @@ -[package] -name = "examples-esp32s2" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -embedded-svc.workspace = true -bleps.workspace = true -embassy-executor = { workspace = true, optional = true } -embassy-time.workspace = true -embassy-futures.workspace = true -futures-util.workspace = true -embedded-io.workspace = true -smoltcp.workspace = true -log = { workspace = true, optional = true } -heapless.workspace = true -embassy-net = { workspace = true, optional = true } -embassy-sync.workspace = true - -esp32s2-hal.workspace = true -esp-backtrace = { workspace = true, features = ["esp32s2"] } -esp-wifi = { path = "../esp-wifi", default-features = false, features = ["esp32s2", "utils"] } - -[dev-dependencies] -esp-println = { workspace = true, features = [ "esp32s2", "log" ] } - -[features] -default = ["esp32s2", "log"] -esp32s2 = [] -async = ["esp-wifi/async", "esp32s2-hal/embassy-time-timg0", "dep:embassy-executor", "embassy-executor?/arch-xtensa"] -embassy-net = ["esp-wifi/embassy-net","dep:embassy-net"] -wifi-logs = ["esp-wifi/wifi-logs"] -dump-packets = ["esp-wifi/dump-packets"] -utils = ["esp-wifi/utils"] -enumset = ["esp-wifi/enumset"] -# required for wifi feature -embedded-svc = [ "esp-wifi/embedded-svc" ] -wifi = ["esp-wifi/wifi", "embedded-svc"] -phy-enable-usb = ["esp-wifi/phy-enable-usb"] -ps-min-modem = ["esp-wifi/ps-min-modem"] -ps-max-modem = ["esp-wifi/ps-max-modem"] -esp-now = ["esp-wifi/esp-now"] -ipv6 = ["esp-wifi/ipv6"] -log = ["esp-wifi/log", "dep:log", "esp-println/log"] -defmt = ["esp-wifi/defmt", "esp-println/defmt"] diff --git a/examples-esp32s2/examples/access_point.rs b/examples-esp32s2/examples/access_point.rs deleted file mode 100644 index f4e32cf7..00000000 --- a/examples-esp32s2/examples/access_point.rs +++ /dev/null @@ -1,166 +0,0 @@ -#![no_std] -#![no_main] -#![feature(c_variadic)] -#![feature(const_mut_refs)] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; - -use esp_println::{print, println}; -use esp_wifi::initialize; -use esp_wifi::wifi::utils::create_network_interface; -use esp_wifi::wifi::WifiMode; -use esp_wifi::wifi_interface::WifiStack; -use esp_wifi::{current_millis, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{peripherals::Peripherals, prelude::*}; - -use smoltcp::iface::SocketStorage; - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s2_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let wifi = peripherals.RADIO.split(); - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Ap, &mut socket_set_entries).unwrap(); - let mut wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::AccessPoint(AccessPointConfiguration { - ssid: "esp-wifi".into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("{:?}", controller.get_capabilities()); - - wifi_stack - .set_iface_configuration(&embedded_svc::ipv4::Configuration::Client( - embedded_svc::ipv4::ClientConfiguration::Fixed(embedded_svc::ipv4::ClientSettings { - ip: embedded_svc::ipv4::Ipv4Addr::from(parse_ip("192.168.2.1")), - subnet: embedded_svc::ipv4::Subnet { - gateway: embedded_svc::ipv4::Ipv4Addr::from(parse_ip("192.168.2.1")), - mask: embedded_svc::ipv4::Mask(24), - }, - dns: None, - secondary_dns: None, - }), - )) - .unwrap(); - - println!("Start busy loop on main. Connect to the AP `esp-wifi` and point your browser to http://192.168.2.1:8080/"); - println!("Use a static IP in the range 192.168.2.2 .. 192.168.2.255, use gateway 192.168.2.1"); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - socket.listen(8080).unwrap(); - - loop { - socket.work(); - - if !socket.is_open() { - socket.listen(8080).unwrap(); - } - - if socket.is_connected() { - println!("Connected"); - - let mut time_out = false; - let wait_end = current_millis() + 20 * 1000; - let mut buffer = [0u8; 1024]; - let mut pos = 0; - loop { - if let Ok(len) = socket.read(&mut buffer[pos..]) { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - time_out = true; - break; - } - } - - if !time_out { - socket - .write_all( - b"HTTP/1.0 200 OK\r\n\r\n\ - \ - \ -

Hello Rust! Hello esp-wifi!

\ - \ - \r\n\ - ", - ) - .unwrap(); - - socket.flush().unwrap(); - } - - socket.close(); - - println!("Done\n"); - println!(); - } - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} - -fn parse_ip(ip: &str) -> [u8; 4] { - let mut result = [0u8; 4]; - for (idx, octet) in ip.split(".").into_iter().enumerate() { - result[idx] = u8::from_str_radix(octet, 10).unwrap(); - } - result -} diff --git a/examples-esp32s2/examples/dhcp.rs b/examples-esp32s2/examples/dhcp.rs deleted file mode 100644 index 3d57e307..00000000 --- a/examples-esp32s2/examples/dhcp.rs +++ /dev/null @@ -1,154 +0,0 @@ -#![no_std] -#![no_main] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointInfo, ClientConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; - -use esp_println::{print, println}; -use esp_wifi::wifi::utils::create_network_interface; -use esp_wifi::wifi::{WifiError, WifiMode}; -use esp_wifi::wifi_interface::WifiStack; -use esp_wifi::{current_millis, initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{peripherals::Peripherals, prelude::*}; -use smoltcp::iface::SocketStorage; -use smoltcp::wire::IpAddress; -use smoltcp::wire::Ipv4Address; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s2_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let wifi = peripherals.RADIO.split(); - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Sta, &mut socket_set_entries).unwrap(); - let wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("Start Wifi Scan"); - let res: Result<(heapless::Vec, usize), WifiError> = controller.scan_n(); - if let Ok((res, _count)) = res { - for ap in res { - println!("{:?}", ap); - } - } - - println!("{:?}", controller.get_capabilities()); - println!("wifi_connect {:?}", controller.connect()); - - // wait to get connected - println!("Wait to get connected"); - loop { - let res = controller.is_connected(); - match res { - Ok(connected) => { - if connected { - break; - } - } - Err(err) => { - println!("{:?}", err); - loop {} - } - } - } - println!("{:?}", controller.is_connected()); - - // wait for getting an ip address - println!("Wait to get an ip address"); - loop { - wifi_stack.work(); - - if wifi_stack.is_iface_up() { - println!("got ip {:?}", wifi_stack.get_ip_info()); - break; - } - } - - println!("Start busy loop on main"); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - loop { - println!("Making HTTP request"); - socket.work(); - - socket - .open(IpAddress::Ipv4(Ipv4Address::new(142, 250, 185, 115)), 80) - .unwrap(); - - socket - .write(b"GET / HTTP/1.0\r\nHost: www.mobile-j.de\r\n\r\n") - .unwrap(); - socket.flush().unwrap(); - - let wait_end = current_millis() + 20 * 1000; - loop { - let mut buffer = [0u8; 512]; - if let Ok(len) = socket.read(&mut buffer) { - let to_print = unsafe { core::str::from_utf8_unchecked(&buffer[..len]) }; - print!("{}", to_print); - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - break; - } - } - println!(); - - socket.disconnect(); - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} diff --git a/examples-esp32s2/examples/embassy_access_point.rs b/examples-esp32s2/examples/embassy_access_point.rs deleted file mode 100644 index 2799cb85..00000000 --- a/examples-esp32s2/examples/embassy_access_point.rs +++ /dev/null @@ -1,219 +0,0 @@ -#![no_std] -#![no_main] -#![feature(c_variadic)] -#![feature(const_mut_refs)] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_net::tcp::TcpSocket; -use embassy_net::ConfigV4; -use embassy_net::{ - Config, IpListenEndpoint, Ipv4Address, Ipv4Cidr, Stack, StackResources, StaticConfigV4, -}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Timer}; -use embedded_svc::wifi::{AccessPointConfiguration, Configuration, Wifi}; -use esp_backtrace as _; - -use esp_println::{print, println}; -use esp_wifi::wifi::{WifiController, WifiDevice, WifiEvent, WifiMode, WifiState}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; - -macro_rules! singleton { - ($val:expr) => {{ - type T = impl Sized; - static STATIC_CELL: StaticCell = StaticCell::new(); - let (x,) = STATIC_CELL.init(($val,)); - x - }}; -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s2_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let wifi = peripherals.RADIO.split(); - let (wifi_interface, controller) = - esp_wifi::wifi::new_with_mode(&init, wifi, WifiMode::Ap).unwrap(); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - - let config = Config { - ipv4: ConfigV4::Static(StaticConfigV4 { - address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 2, 1), 24), - gateway: Some(Ipv4Address::from_bytes(&[192, 168, 2, 1])), - dns_servers: Default::default(), - }), - }; - - let seed = 1234; // very random, very secure seed - - // Init network stack - let stack = &*singleton!(Stack::new( - wifi_interface, - config, - singleton!(StackResources::<3>::new()), - seed - )); - - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); - spawner.spawn(task(&stack)).ok(); - }) -} - -#[embassy_executor::task] -async fn connection(mut controller: WifiController<'static>) { - println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); - loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::ApStarted => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::ApStop).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} - } - if !matches!(controller.is_started(), Ok(true)) { - let client_config = Configuration::AccessPoint(AccessPointConfiguration { - ssid: "esp-wifi".into(), - ..Default::default() - }); - controller.set_configuration(&client_config).unwrap(); - println!("Starting wifi"); - controller.start().await.unwrap(); - println!("Wifi started!"); - } - } -} - -#[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await -} - -#[embassy_executor::task] -async fn task(stack: &'static Stack>) { - let mut rx_buffer = [0; 4096]; - let mut tx_buffer = [0; 4096]; - - loop { - if stack.is_link_up() { - break; - } - Timer::after(Duration::from_millis(500)).await; - } - println!("Connect to the AP `esp-wifi` and point your browser to http://192.168.2.1:8080/"); - println!("Use a static IP in the range 192.168.2.2 .. 192.168.2.255, use gateway 192.168.2.1"); - - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); - socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); - loop { - println!("Wait for connection..."); - let r = socket - .accept(IpListenEndpoint { - addr: None, - port: 8080, - }) - .await; - println!("Connected..."); - - if let Err(e) = r { - println!("connect error: {:?}", e); - continue; - } - - use embedded_io::asynch::Write; - - let mut buffer = [0u8; 1024]; - let mut pos = 0; - loop { - match socket.read(&mut buffer).await { - Ok(0) => { - println!("read EOF"); - break; - } - Ok(len) => { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } - Err(e) => { - println!("read error: {:?}", e); - break; - } - }; - } - - let r = socket - .write_all( - b"HTTP/1.0 200 OK\r\n\r\n\ - \ - \ -

Hello Rust! Hello esp-wifi!

\ - \ - \r\n\ - ", - ) - .await; - if let Err(e) = r { - println!("write error: {:?}", e); - } - - let r = socket.flush().await; - if let Err(e) = r { - println!("flush error: {:?}", e); - } - Timer::after(Duration::from_millis(1000)).await; - - socket.close(); - Timer::after(Duration::from_millis(1000)).await; - - socket.abort(); - } -} diff --git a/examples-esp32s2/examples/embassy_dhcp.rs b/examples-esp32s2/examples/embassy_dhcp.rs deleted file mode 100644 index 921cded2..00000000 --- a/examples-esp32s2/examples/embassy_dhcp.rs +++ /dev/null @@ -1,196 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_net::tcp::TcpSocket; -use embassy_net::{Config, Ipv4Address, Stack, StackResources}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Timer}; -use embedded_svc::wifi::{ClientConfiguration, Configuration, Wifi}; -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::wifi::{WifiController, WifiDevice, WifiEvent, WifiMode, WifiState}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); - -macro_rules! singleton { - ($val:expr) => {{ - type T = impl Sized; - static STATIC_CELL: StaticCell = StaticCell::new(); - let (x,) = STATIC_CELL.init(($val,)); - x - }}; -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s2_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let wifi = peripherals.RADIO.split(); - let (wifi_interface, controller) = - esp_wifi::wifi::new_with_mode(&init, wifi, WifiMode::Sta).unwrap(); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - - let config = Config::dhcpv4(Default::default()); - - let seed = 1234; // very random, very secure seed - - // Init network stack - let stack = &*singleton!(Stack::new( - wifi_interface, - config, - singleton!(StackResources::<3>::new()), - seed - )); - - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); - spawner.spawn(task(&stack)).ok(); - }) -} - -#[embassy_executor::task] -async fn connection(mut controller: WifiController<'static>) { - println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); - loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::StaConnected => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::StaDisconnected).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} - } - if !matches!(controller.is_started(), Ok(true)) { - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - controller.set_configuration(&client_config).unwrap(); - println!("Starting wifi"); - controller.start().await.unwrap(); - println!("Wifi started!"); - } - println!("About to connect..."); - - match controller.connect().await { - Ok(_) => println!("Wifi connected!"), - Err(e) => { - println!("Failed to connect to wifi: {e:?}"); - Timer::after(Duration::from_millis(5000)).await - } - } - } -} - -#[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await -} - -#[embassy_executor::task] -async fn task(stack: &'static Stack>) { - let mut rx_buffer = [0; 4096]; - let mut tx_buffer = [0; 4096]; - - loop { - if stack.is_link_up() { - break; - } - Timer::after(Duration::from_millis(500)).await; - } - - println!("Waiting to get IP address..."); - loop { - if let Some(config) = stack.config_v4() { - println!("Got IP: {}", config.address); - break; - } - Timer::after(Duration::from_millis(500)).await; - } - - loop { - Timer::after(Duration::from_millis(1_000)).await; - - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); - - socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); - - let remote_endpoint = (Ipv4Address::new(142, 250, 185, 115), 80); - println!("connecting..."); - let r = socket.connect(remote_endpoint).await; - if let Err(e) = r { - println!("connect error: {:?}", e); - continue; - } - println!("connected!"); - let mut buf = [0; 1024]; - loop { - use embedded_io::asynch::Write; - let r = socket - .write_all(b"GET / HTTP/1.0\r\nHost: www.mobile-j.de\r\n\r\n") - .await; - if let Err(e) = r { - println!("write error: {:?}", e); - break; - } - let n = match socket.read(&mut buf).await { - Ok(0) => { - println!("read EOF"); - break; - } - Ok(n) => n, - Err(e) => { - println!("read error: {:?}", e); - break; - } - }; - println!("{}", core::str::from_utf8(&buf[..n]).unwrap()); - } - Timer::after(Duration::from_millis(3000)).await; - } -} diff --git a/examples-esp32s2/examples/embassy_esp_now.rs b/examples-esp32s2/examples/embassy_esp_now.rs deleted file mode 100644 index d9109568..00000000 --- a/examples-esp32s2/examples/embassy_esp_now.rs +++ /dev/null @@ -1,98 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_futures::select::{select, Either}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Ticker}; -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::esp_now::{EspNow, PeerInfo, BROADCAST_ADDRESS}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; - -#[embassy_executor::task] -async fn run(mut esp_now: EspNow<'static>) { - let mut ticker = Ticker::every(Duration::from_secs(5)); - loop { - let res = select(ticker.next(), async { - let r = esp_now.receive_async().await; - println!("Received {:?}", r); - if r.info.dst_address == BROADCAST_ADDRESS { - if !esp_now.peer_exists(&r.info.src_address) { - esp_now - .add_peer(PeerInfo { - peer_address: r.info.src_address, - lmk: None, - channel: None, - encrypt: false, - }) - .unwrap(); - } - let status = esp_now.send_async(&r.info.src_address, b"Hello Peer").await; - println!("Send hello to peer status: {:?}", status); - } - }) - .await; - - match res { - Either::First(_) => { - println!("Send"); - let status = esp_now.send_async(&BROADCAST_ADDRESS, b"0123456789").await; - println!("Send broadcast status: {:?}", status) - } - Either::Second(_) => (), - } - } -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s2_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let wifi = peripherals.RADIO.split(); - let esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(run(esp_now)).ok(); - }) -} diff --git a/examples-esp32s2/examples/esp_now.rs b/examples-esp32s2/examples/esp_now.rs deleted file mode 100644 index a2181b79..00000000 --- a/examples-esp32s2/examples/esp_now.rs +++ /dev/null @@ -1,81 +0,0 @@ -#![no_std] -#![no_main] - -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::esp_now::{PeerInfo, BROADCAST_ADDRESS}; -use esp_wifi::{current_millis, initialize, EspWifiInitFor}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{peripherals::Peripherals, prelude::*}; - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s2_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let wifi = peripherals.RADIO.split(); - let mut esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let mut next_send_time = current_millis() + 5 * 1000; - loop { - let r = esp_now.receive(); - if let Some(r) = r { - println!("Received {:?}", r); - - if r.info.dst_address == BROADCAST_ADDRESS { - if !esp_now.peer_exists(&r.info.src_address) { - esp_now - .add_peer(PeerInfo { - peer_address: r.info.src_address, - lmk: None, - channel: None, - encrypt: false, - }) - .unwrap(); - } - let status = esp_now - .send(&r.info.src_address, b"Hello Peer") - .unwrap() - .wait(); - println!("Send hello to peer status: {:?}", status); - } - } - - if current_millis() >= next_send_time { - next_send_time = current_millis() + 5 * 1000; - println!("Send"); - let status = esp_now - .send(&BROADCAST_ADDRESS, b"0123456789") - .unwrap() - .wait(); - println!("Send broadcast status: {:?}", status) - } - } -} diff --git a/examples-esp32s2/examples/static_ip.rs b/examples-esp32s2/examples/static_ip.rs deleted file mode 100644 index 55a333ec..00000000 --- a/examples-esp32s2/examples/static_ip.rs +++ /dev/null @@ -1,200 +0,0 @@ -#![no_std] -#![no_main] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointInfo, ClientConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; - -use esp_println::{print, println}; -use esp_wifi::initialize; -use esp_wifi::wifi::WifiMode; -use esp_wifi::wifi::{utils::create_network_interface, WifiError}; -use esp_wifi::wifi_interface::WifiStack; -use esp_wifi::{current_millis, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{peripherals::Peripherals, prelude::*}; - -use smoltcp::iface::SocketStorage; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); -const STATIC_IP: &str = env!("STATIC_IP"); -const GATEWAY_IP: &str = env!("GATEWAY_IP"); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s2_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let wifi = peripherals.RADIO.split(); - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Sta, &mut socket_set_entries).unwrap(); - let mut wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("Start Wifi Scan"); - let res: Result<(heapless::Vec, usize), WifiError> = controller.scan_n(); - if let Ok((res, _count)) = res { - for ap in res { - println!("{:?}", ap); - } - } - - println!("{:?}", controller.get_capabilities()); - println!("wifi_connect {:?}", controller.connect()); - - // wait to get connected - println!("Wait to get connected"); - loop { - let res = controller.is_connected(); - match res { - Ok(connected) => { - if connected { - break; - } - } - Err(err) => { - println!("{:?}", err); - loop {} - } - } - } - println!("{:?}", controller.is_connected()); - - println!("Setting static IP {}", STATIC_IP); - - wifi_stack - .set_iface_configuration(&embedded_svc::ipv4::Configuration::Client( - embedded_svc::ipv4::ClientConfiguration::Fixed(embedded_svc::ipv4::ClientSettings { - ip: embedded_svc::ipv4::Ipv4Addr::from(parse_ip(STATIC_IP)), - subnet: embedded_svc::ipv4::Subnet { - gateway: embedded_svc::ipv4::Ipv4Addr::from(parse_ip(GATEWAY_IP)), - mask: embedded_svc::ipv4::Mask(24), - }, - dns: None, - secondary_dns: None, - }), - )) - .unwrap(); - - println!( - "Start busy loop on main. Point your browser to http://{}:8080/", - STATIC_IP - ); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - socket.listen(8080).unwrap(); - - loop { - socket.work(); - - if !socket.is_open() { - socket.listen(8080).unwrap(); - } - - if socket.is_connected() { - println!("Connected"); - - let mut time_out = false; - let wait_end = current_millis() + 20 * 1000; - let mut buffer = [0u8; 1024]; - let mut pos = 0; - loop { - if let Ok(len) = socket.read(&mut buffer[pos..]) { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - time_out = true; - break; - } - } - - if !time_out { - socket.write_all( - b"HTTP/1.0 200 OK\r\n\r\n\ - \ - \ -

Hello Rust! Hello esp-wifi!

\ - - \ - \r\n\ - " - ).unwrap(); - - socket.flush().unwrap(); - } - - socket.close(); - - println!("Done\n"); - println!(); - } - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} - -fn parse_ip(ip: &str) -> [u8; 4] { - let mut result = [0u8; 4]; - for (idx, octet) in ip.split(".").into_iter().enumerate() { - result[idx] = u8::from_str_radix(octet, 10).unwrap(); - } - result -} diff --git a/examples-esp32s2/rust-toolchain.toml b/examples-esp32s2/rust-toolchain.toml deleted file mode 100644 index a2f5ab50..00000000 --- a/examples-esp32s2/rust-toolchain.toml +++ /dev/null @@ -1,2 +0,0 @@ -[toolchain] -channel = "esp" diff --git a/examples-esp32s2/src/lib.rs b/examples-esp32s2/src/lib.rs deleted file mode 100644 index 0c3fcbb6..00000000 --- a/examples-esp32s2/src/lib.rs +++ /dev/null @@ -1,3 +0,0 @@ -#![no_std] - -// no code here - see examples folder diff --git a/examples-esp32s3/.cargo/config.toml b/examples-esp32s3/.cargo/config.toml deleted file mode 100644 index c1645c9a..00000000 --- a/examples-esp32s3/.cargo/config.toml +++ /dev/null @@ -1,15 +0,0 @@ -[target.xtensa-esp32s3-none-elf] -runner = "espflash flash --monitor" - -rustflags = [ - "-C", "link-arg=-Tlinkall.x", - "-C", "link-arg=-Trom_functions.x", - - "-C", "target-feature=-loop", -] - -[build] -target = "xtensa-esp32s3-none-elf" - -[unstable] -build-std = [ "core" ] diff --git a/examples-esp32s3/Cargo.toml b/examples-esp32s3/Cargo.toml deleted file mode 100644 index 7e122ff8..00000000 --- a/examples-esp32s3/Cargo.toml +++ /dev/null @@ -1,50 +0,0 @@ -[package] -name = "examples-esp32s3" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -embedded-svc.workspace = true -bleps.workspace = true -embassy-executor = { workspace = true, optional = true } -embassy-time.workspace = true -embassy-futures.workspace = true -futures-util.workspace = true -embedded-io.workspace = true -smoltcp.workspace = true -log = { workspace = true, optional = true } -heapless.workspace = true -embassy-net = { workspace = true, optional = true } -embassy-sync.workspace = true - -esp32s3-hal.workspace = true -esp-backtrace = { workspace = true, features = ["esp32s3"] } -esp-wifi = { path = "../esp-wifi", default-features = false, features = ["esp32s3", "utils"] } -embedded-hal-async = { workspace = true, optional = true } - -[dev-dependencies] -esp-println = { workspace = true, features = [ "esp32s3", "log" ] } - -[features] -default = ["esp32s3", "log"] -esp32s3 = [] -async = ["esp-wifi/async", "bleps/async", "dep:embedded-hal-async", "esp32s3-hal/async", "esp32s3-hal/embassy-time-timg0", "dep:embassy-executor", "embassy-executor?/arch-xtensa"] -embassy-net = ["esp-wifi/embassy-net","dep:embassy-net"] -wifi-logs = ["esp-wifi/wifi-logs"] -dump-packets = ["esp-wifi/dump-packets"] -utils = ["esp-wifi/utils"] -enumset = ["esp-wifi/enumset"] -# required for wifi feature -embedded-svc = [ "esp-wifi/embedded-svc" ] -wifi = ["esp-wifi/wifi", "embedded-svc"] -ble = ["esp-wifi/ble"] -phy-enable-usb = ["esp-wifi/phy-enable-usb"] -ps-min-modem = ["esp-wifi/ps-min-modem"] -ps-max-modem = ["esp-wifi/ps-max-modem"] -esp-now = ["esp-wifi/esp-now"] -ipv6 = ["esp-wifi/ipv6"] -coex = ["esp-wifi/coex"] -log = ["esp-wifi/log", "dep:log", "esp-println/log"] -defmt = ["esp-wifi/defmt", "esp-println/defmt"] diff --git a/examples-esp32s3/examples/access_point.rs b/examples-esp32s3/examples/access_point.rs deleted file mode 100644 index cdd8e67e..00000000 --- a/examples-esp32s3/examples/access_point.rs +++ /dev/null @@ -1,166 +0,0 @@ -#![no_std] -#![no_main] -#![feature(c_variadic)] -#![feature(const_mut_refs)] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; - -use esp_println::{print, println}; -use esp_wifi::initialize; -use esp_wifi::wifi::utils::create_network_interface; -use esp_wifi::wifi::WifiMode; -use esp_wifi::wifi_interface::WifiStack; -use esp_wifi::{current_millis, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{peripherals::Peripherals, prelude::*}; - -use smoltcp::iface::SocketStorage; - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s3_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Ap, &mut socket_set_entries).unwrap(); - let mut wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::AccessPoint(AccessPointConfiguration { - ssid: "esp-wifi".into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("{:?}", controller.get_capabilities()); - - wifi_stack - .set_iface_configuration(&embedded_svc::ipv4::Configuration::Client( - embedded_svc::ipv4::ClientConfiguration::Fixed(embedded_svc::ipv4::ClientSettings { - ip: embedded_svc::ipv4::Ipv4Addr::from(parse_ip("192.168.2.1")), - subnet: embedded_svc::ipv4::Subnet { - gateway: embedded_svc::ipv4::Ipv4Addr::from(parse_ip("192.168.2.1")), - mask: embedded_svc::ipv4::Mask(24), - }, - dns: None, - secondary_dns: None, - }), - )) - .unwrap(); - - println!("Start busy loop on main. Connect to the AP `esp-wifi` and point your browser to http://192.168.2.1:8080/"); - println!("Use a static IP in the range 192.168.2.2 .. 192.168.2.255, use gateway 192.168.2.1"); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - socket.listen(8080).unwrap(); - - loop { - socket.work(); - - if !socket.is_open() { - socket.listen(8080).unwrap(); - } - - if socket.is_connected() { - println!("Connected"); - - let mut time_out = false; - let wait_end = current_millis() + 20 * 1000; - let mut buffer = [0u8; 1024]; - let mut pos = 0; - loop { - if let Ok(len) = socket.read(&mut buffer[pos..]) { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - time_out = true; - break; - } - } - - if !time_out { - socket - .write_all( - b"HTTP/1.0 200 OK\r\n\r\n\ - \ - \ -

Hello Rust! Hello esp-wifi!

\ - \ - \r\n\ - ", - ) - .unwrap(); - - socket.flush().unwrap(); - } - - socket.close(); - - println!("Done\n"); - println!(); - } - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} - -fn parse_ip(ip: &str) -> [u8; 4] { - let mut result = [0u8; 4]; - for (idx, octet) in ip.split(".").into_iter().enumerate() { - result[idx] = u8::from_str_radix(octet, 10).unwrap(); - } - result -} diff --git a/examples-esp32s3/examples/async_ble.rs b/examples-esp32s3/examples/async_ble.rs deleted file mode 100644 index 807dba32..00000000 --- a/examples-esp32s3/examples/async_ble.rs +++ /dev/null @@ -1,174 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] -#![feature(async_closure)] - -use core::cell::RefCell; - -use bleps::{ - ad_structure::{ - create_advertising_data, AdStructure, BR_EDR_NOT_SUPPORTED, LE_GENERAL_DISCOVERABLE, - }, - async_attribute_server::AttributeServer, - asynch::Ble, - attribute_server::NotificationData, - gatt, -}; -use embassy_executor::Executor; -use embassy_executor::_export::StaticCell; -use embedded_hal_async::digital::Wait; -use esp_backtrace as _; -use esp_println::println; -use esp_wifi::{ - ble::controller::asynch::BleConnector, initialize, EspWifiInitFor, EspWifiInitialization, -}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; -use examples_util::BootButton; -use hal::{ - clock::ClockControl, embassy, peripherals::*, prelude::*, radio::Bluetooth, timer::TimerGroup, - Rng, IO, -}; - -#[embassy_executor::task] -async fn run(init: EspWifiInitialization, mut bluetooth: Bluetooth, pin: BootButton) { - let connector = BleConnector::new(&init, &mut bluetooth); - let mut ble = Ble::new(connector, esp_wifi::current_millis); - println!("Connector created"); - - let pin_ref = RefCell::new(pin); - - loop { - println!("{:?}", ble.init().await); - println!("{:?}", ble.cmd_set_le_advertising_parameters().await); - println!( - "{:?}", - ble.cmd_set_le_advertising_data( - create_advertising_data(&[ - AdStructure::Flags(LE_GENERAL_DISCOVERABLE | BR_EDR_NOT_SUPPORTED), - AdStructure::ServiceUuids16(&[Uuid::Uuid16(0x1809)]), - AdStructure::CompleteLocalName(examples_util::SOC_NAME), - ]) - .unwrap() - ) - .await - ); - println!("{:?}", ble.cmd_set_le_advertise_enable(true).await); - - println!("started advertising"); - - let mut rf = |_offset: usize, data: &mut [u8]| { - data[..20].copy_from_slice(&b"Hello Bare-Metal BLE"[..]); - 17 - }; - let mut wf = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut wf2 = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut rf3 = |_offset: usize, data: &mut [u8]| { - data[..5].copy_from_slice(&b"Hola!"[..]); - 5 - }; - let mut wf3 = |offset: usize, data: &[u8]| { - println!("RECEIVED: Offset {}, data {:?}", offset, data); - }; - - gatt!([service { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - characteristics: [ - characteristic { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - read: rf, - write: wf, - }, - characteristic { - uuid: "957312e0-2354-11eb-9f10-fbc30a62cf38", - write: wf2, - }, - characteristic { - name: "my_characteristic", - uuid: "987312e0-2354-11eb-9f10-fbc30a62cf38", - notify: true, - read: rf3, - write: wf3, - }, - ], - },]); - - let mut srv = AttributeServer::new(&mut ble, &mut gatt_attributes); - - let counter = RefCell::new(0u8); - let mut notifier = async || { - // TODO how to check if notifications are enabled for the characteristic? - // maybe pass something into the closure which just can query the characterisic value - // probably passing in the attribute server won't work? - pin_ref.borrow_mut().wait_for_rising_edge().await.unwrap(); - let mut data = [0u8; 13]; - data.copy_from_slice(b"Notification0"); - { - let mut counter = counter.borrow_mut(); - data[data.len() - 1] += *counter; - *counter = (*counter + 1) % 10; - } - NotificationData::new(my_characteristic_handle, &data) - }; - - srv.run(&mut notifier).await.unwrap(); - } -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s3_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Ble, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let io = IO::new(peripherals.GPIO, peripherals.IO_MUX); - let button = io.pins.gpio0.into_pull_down_input(); - - // Async requires the GPIO interrupt to wake futures - hal::interrupt::enable( - hal::peripherals::Interrupt::GPIO, - hal::interrupt::Priority::Priority1, - ) - .unwrap(); - - let (_, bluetooth, ..) = peripherals.RADIO.split(); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(run(init, bluetooth, button)).ok(); - }); -} diff --git a/examples-esp32s3/examples/ble.rs b/examples-esp32s3/examples/ble.rs deleted file mode 100644 index b5fa25ad..00000000 --- a/examples-esp32s3/examples/ble.rs +++ /dev/null @@ -1,156 +0,0 @@ -#![no_std] -#![no_main] - -use bleps::{ - ad_structure::{ - create_advertising_data, AdStructure, BR_EDR_NOT_SUPPORTED, LE_GENERAL_DISCOVERABLE, - }, - attribute_server::{AttributeServer, NotificationData, WorkResult}, - gatt, Ble, HciConnector, -}; -use esp_backtrace as _; -use esp_println::println; -use esp_wifi::{ble::controller::BleConnector, initialize, EspWifiInitFor}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; -use hal::{clock::ClockControl, peripherals::*, prelude::*, Rng, IO}; - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s3_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Ble, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let io = IO::new(peripherals.GPIO, peripherals.IO_MUX); - let button = io.pins.gpio0.into_pull_down_input(); - - let mut debounce_cnt = 500; - - let (_, mut bluetooth, ..) = peripherals.RADIO.split(); - - loop { - let connector = BleConnector::new(&init, &mut bluetooth); - let hci = HciConnector::new(connector, esp_wifi::current_millis); - let mut ble = Ble::new(&hci); - - println!("{:?}", ble.init()); - println!("{:?}", ble.cmd_set_le_advertising_parameters()); - println!( - "{:?}", - ble.cmd_set_le_advertising_data( - create_advertising_data(&[ - AdStructure::Flags(LE_GENERAL_DISCOVERABLE | BR_EDR_NOT_SUPPORTED), - AdStructure::ServiceUuids16(&[Uuid::Uuid16(0x1809)]), - AdStructure::CompleteLocalName(examples_util::SOC_NAME), - ]) - .unwrap() - ) - ); - println!("{:?}", ble.cmd_set_le_advertise_enable(true)); - - println!("started advertising"); - - let mut rf = |_offset: usize, data: &mut [u8]| { - data[..20].copy_from_slice(&b"Hello Bare-Metal BLE"[..]); - 17 - }; - let mut wf = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut wf2 = |offset: usize, data: &[u8]| { - println!("RECEIVED: {} {:?}", offset, data); - }; - - let mut rf3 = |_offset: usize, data: &mut [u8]| { - data[..5].copy_from_slice(&b"Hola!"[..]); - 5 - }; - let mut wf3 = |offset: usize, data: &[u8]| { - println!("RECEIVED: Offset {}, data {:?}", offset, data); - }; - - gatt!([service { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - characteristics: [ - characteristic { - uuid: "937312e0-2354-11eb-9f10-fbc30a62cf38", - read: rf, - write: wf, - }, - characteristic { - uuid: "957312e0-2354-11eb-9f10-fbc30a62cf38", - write: wf2, - }, - characteristic { - name: "my_characteristic", - uuid: "987312e0-2354-11eb-9f10-fbc30a62cf38", - notify: true, - read: rf3, - write: wf3, - }, - ], - },]); - - let mut srv = AttributeServer::new(&mut ble, &mut gatt_attributes); - - loop { - let mut notification = None; - - if button.is_low().unwrap() && debounce_cnt > 0 { - debounce_cnt -= 1; - if debounce_cnt == 0 { - let mut cccd = [0u8; 1]; - if let Some(1) = srv.get_characteristic_value( - my_characteristic_notify_enable_handle, - 0, - &mut cccd, - ) { - // if notifications enabled - if cccd[0] == 1 { - notification = Some(NotificationData::new( - my_characteristic_handle, - &b"Notification"[..], - )); - } - } - } - }; - - if button.is_high().unwrap() { - debounce_cnt = 500; - } - - match srv.do_work_with_notification(notification) { - Ok(res) => { - if let WorkResult::GotDisconnected = res { - break; - } - } - Err(err) => { - println!("{:?}", err); - } - } - } - } -} diff --git a/examples-esp32s3/examples/coex.rs b/examples-esp32s3/examples/coex.rs deleted file mode 100644 index 28d2901e..00000000 --- a/examples-esp32s3/examples/coex.rs +++ /dev/null @@ -1,183 +0,0 @@ -#![no_std] -#![no_main] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use bleps::{ - ad_structure::{ - create_advertising_data, AdStructure, BR_EDR_NOT_SUPPORTED, LE_GENERAL_DISCOVERABLE, - }, - att::Uuid, - Ble, HciConnector, -}; - -use esp_wifi::{ - ble::controller::BleConnector, current_millis, wifi::WifiMode, wifi_interface::WifiStack, - EspWifiInitFor, -}; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointInfo, ClientConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; -use esp_println::{print, println}; -use esp_wifi::initialize; -use esp_wifi::wifi::{utils::create_network_interface, WifiError}; -use hal::{clock::ClockControl, Rng}; -use hal::{peripherals::Peripherals, prelude::*}; -use smoltcp::{iface::SocketStorage, wire::IpAddress, wire::Ipv4Address}; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s3_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::WifiBle, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, bluetooth, ..) = peripherals.RADIO.split(); - - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Sta, &mut socket_set_entries).unwrap(); - let wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("Start Wifi Scan"); - let res: Result<(heapless::Vec, usize), WifiError> = controller.scan_n(); - if let Ok((res, _count)) = res { - for ap in res { - println!("{:?}", ap); - } - } - - println!("{:?}", controller.get_capabilities()); - println!("wifi_connect {:?}", controller.connect()); - - // wait to get connected - println!("Wait to get connected"); - loop { - let res = controller.is_connected(); - match res { - Ok(connected) => { - if connected { - break; - } - } - Err(err) => { - println!("{:?}", err); - loop {} - } - } - } - println!("{:?}", controller.is_connected()); - - // wait for getting an ip address - println!("Wait to get an ip address"); - loop { - wifi_stack.work(); - - if wifi_stack.is_iface_up() { - println!("got ip {:?}", wifi_stack.get_ip_info()); - break; - } - } - - let connector = BleConnector::new(&init, bluetooth); - let hci = HciConnector::new(connector, esp_wifi::current_millis); - let mut ble = Ble::new(&hci); - - println!("{:?}", ble.init()); - println!("{:?}", ble.cmd_set_le_advertising_parameters()); - println!( - "{:?}", - ble.cmd_set_le_advertising_data( - create_advertising_data(&[ - AdStructure::Flags(LE_GENERAL_DISCOVERABLE | BR_EDR_NOT_SUPPORTED), - AdStructure::ServiceUuids16(&[Uuid::Uuid16(0x1809)]), - AdStructure::CompleteLocalName(examples_util::SOC_NAME), - ]) - .unwrap() - ) - ); - println!("{:?}", ble.cmd_set_le_advertise_enable(true)); - - println!("started advertising"); - - println!("Start busy loop on main"); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - loop { - println!("Making HTTP request"); - socket.work(); - - socket - .open(IpAddress::Ipv4(Ipv4Address::new(142, 250, 185, 115)), 80) - .unwrap(); - - socket - .write(b"GET / HTTP/1.0\r\nHost: www.mobile-j.de\r\n\r\n") - .unwrap(); - socket.flush().unwrap(); - - let wait_end = current_millis() + 20 * 1000; - loop { - let mut buffer = [0u8; 512]; - if let Ok(len) = socket.read(&mut buffer) { - let to_print = unsafe { core::str::from_utf8_unchecked(&buffer[..len]) }; - print!("{}", to_print); - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - break; - } - } - println!(); - - socket.disconnect(); - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} diff --git a/examples-esp32s3/examples/dhcp.rs b/examples-esp32s3/examples/dhcp.rs deleted file mode 100644 index abace712..00000000 --- a/examples-esp32s3/examples/dhcp.rs +++ /dev/null @@ -1,154 +0,0 @@ -#![no_std] -#![no_main] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointInfo, ClientConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; - -use esp_println::{print, println}; -use esp_wifi::wifi::utils::create_network_interface; -use esp_wifi::wifi::{WifiError, WifiMode}; -use esp_wifi::wifi_interface::WifiStack; -use esp_wifi::{current_millis, initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{peripherals::Peripherals, prelude::*}; -use smoltcp::iface::SocketStorage; -use smoltcp::wire::IpAddress; -use smoltcp::wire::Ipv4Address; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s3_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Sta, &mut socket_set_entries).unwrap(); - let wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("Start Wifi Scan"); - let res: Result<(heapless::Vec, usize), WifiError> = controller.scan_n(); - if let Ok((res, _count)) = res { - for ap in res { - println!("{:?}", ap); - } - } - - println!("{:?}", controller.get_capabilities()); - println!("wifi_connect {:?}", controller.connect()); - - // wait to get connected - println!("Wait to get connected"); - loop { - let res = controller.is_connected(); - match res { - Ok(connected) => { - if connected { - break; - } - } - Err(err) => { - println!("{:?}", err); - loop {} - } - } - } - println!("{:?}", controller.is_connected()); - - // wait for getting an ip address - println!("Wait to get an ip address"); - loop { - wifi_stack.work(); - - if wifi_stack.is_iface_up() { - println!("got ip {:?}", wifi_stack.get_ip_info()); - break; - } - } - - println!("Start busy loop on main"); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - loop { - println!("Making HTTP request"); - socket.work(); - - socket - .open(IpAddress::Ipv4(Ipv4Address::new(142, 250, 185, 115)), 80) - .unwrap(); - - socket - .write(b"GET / HTTP/1.0\r\nHost: www.mobile-j.de\r\n\r\n") - .unwrap(); - socket.flush().unwrap(); - - let wait_end = current_millis() + 20 * 1000; - loop { - let mut buffer = [0u8; 512]; - if let Ok(len) = socket.read(&mut buffer) { - let to_print = unsafe { core::str::from_utf8_unchecked(&buffer[..len]) }; - print!("{}", to_print); - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - break; - } - } - println!(); - - socket.disconnect(); - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} diff --git a/examples-esp32s3/examples/embassy_access_point.rs b/examples-esp32s3/examples/embassy_access_point.rs deleted file mode 100644 index ebfa745d..00000000 --- a/examples-esp32s3/examples/embassy_access_point.rs +++ /dev/null @@ -1,219 +0,0 @@ -#![no_std] -#![no_main] -#![feature(c_variadic)] -#![feature(const_mut_refs)] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_net::tcp::TcpSocket; -use embassy_net::ConfigV4; -use embassy_net::{ - Config, IpListenEndpoint, Ipv4Address, Ipv4Cidr, Stack, StackResources, StaticConfigV4, -}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Timer}; -use embedded_svc::wifi::{AccessPointConfiguration, Configuration, Wifi}; -use esp_backtrace as _; - -use esp_println::{print, println}; -use esp_wifi::wifi::{WifiController, WifiDevice, WifiEvent, WifiMode, WifiState}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; - -macro_rules! singleton { - ($val:expr) => {{ - type T = impl Sized; - static STATIC_CELL: StaticCell = StaticCell::new(); - let (x,) = STATIC_CELL.init(($val,)); - x - }}; -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s3_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let (wifi_interface, controller) = - esp_wifi::wifi::new_with_mode(&init, wifi, WifiMode::Ap).unwrap(); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - - let config = Config { - ipv4: ConfigV4::Static(StaticConfigV4 { - address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 2, 1), 24), - gateway: Some(Ipv4Address::from_bytes(&[192, 168, 2, 1])), - dns_servers: Default::default(), - }), - }; - - let seed = 1234; // very random, very secure seed - - // Init network stack - let stack = &*singleton!(Stack::new( - wifi_interface, - config, - singleton!(StackResources::<3>::new()), - seed - )); - - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); - spawner.spawn(task(&stack)).ok(); - }) -} - -#[embassy_executor::task] -async fn connection(mut controller: WifiController<'static>) { - println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); - loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::ApStarted => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::ApStop).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} - } - if !matches!(controller.is_started(), Ok(true)) { - let client_config = Configuration::AccessPoint(AccessPointConfiguration { - ssid: "esp-wifi".into(), - ..Default::default() - }); - controller.set_configuration(&client_config).unwrap(); - println!("Starting wifi"); - controller.start().await.unwrap(); - println!("Wifi started!"); - } - } -} - -#[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await -} - -#[embassy_executor::task] -async fn task(stack: &'static Stack>) { - let mut rx_buffer = [0; 4096]; - let mut tx_buffer = [0; 4096]; - - loop { - if stack.is_link_up() { - break; - } - Timer::after(Duration::from_millis(500)).await; - } - println!("Connect to the AP `esp-wifi` and point your browser to http://192.168.2.1:8080/"); - println!("Use a static IP in the range 192.168.2.2 .. 192.168.2.255, use gateway 192.168.2.1"); - - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); - socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); - loop { - println!("Wait for connection..."); - let r = socket - .accept(IpListenEndpoint { - addr: None, - port: 8080, - }) - .await; - println!("Connected..."); - - if let Err(e) = r { - println!("connect error: {:?}", e); - continue; - } - - use embedded_io::asynch::Write; - - let mut buffer = [0u8; 1024]; - let mut pos = 0; - loop { - match socket.read(&mut buffer).await { - Ok(0) => { - println!("read EOF"); - break; - } - Ok(len) => { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } - Err(e) => { - println!("read error: {:?}", e); - break; - } - }; - } - - let r = socket - .write_all( - b"HTTP/1.0 200 OK\r\n\r\n\ - \ - \ -

Hello Rust! Hello esp-wifi!

\ - \ - \r\n\ - ", - ) - .await; - if let Err(e) = r { - println!("write error: {:?}", e); - } - - let r = socket.flush().await; - if let Err(e) = r { - println!("flush error: {:?}", e); - } - Timer::after(Duration::from_millis(1000)).await; - - socket.close(); - Timer::after(Duration::from_millis(1000)).await; - - socket.abort(); - } -} diff --git a/examples-esp32s3/examples/embassy_dhcp.rs b/examples-esp32s3/examples/embassy_dhcp.rs deleted file mode 100644 index 4b139e2e..00000000 --- a/examples-esp32s3/examples/embassy_dhcp.rs +++ /dev/null @@ -1,196 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_net::tcp::TcpSocket; -use embassy_net::{Config, Ipv4Address, Stack, StackResources}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Timer}; -use embedded_svc::wifi::{ClientConfiguration, Configuration, Wifi}; -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::wifi::{WifiController, WifiDevice, WifiEvent, WifiMode, WifiState}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); - -macro_rules! singleton { - ($val:expr) => {{ - type T = impl Sized; - static STATIC_CELL: StaticCell = StaticCell::new(); - let (x,) = STATIC_CELL.init(($val,)); - x - }}; -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s3_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let (wifi_interface, controller) = - esp_wifi::wifi::new_with_mode(&init, wifi, WifiMode::Sta).unwrap(); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - - let config = Config::dhcpv4(Default::default()); - - let seed = 1234; // very random, very secure seed - - // Init network stack - let stack = &*singleton!(Stack::new( - wifi_interface, - config, - singleton!(StackResources::<3>::new()), - seed - )); - - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); - spawner.spawn(task(&stack)).ok(); - }) -} - -#[embassy_executor::task] -async fn connection(mut controller: WifiController<'static>) { - println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); - loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::StaConnected => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::StaDisconnected).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} - } - if !matches!(controller.is_started(), Ok(true)) { - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - controller.set_configuration(&client_config).unwrap(); - println!("Starting wifi"); - controller.start().await.unwrap(); - println!("Wifi started!"); - } - println!("About to connect..."); - - match controller.connect().await { - Ok(_) => println!("Wifi connected!"), - Err(e) => { - println!("Failed to connect to wifi: {e:?}"); - Timer::after(Duration::from_millis(5000)).await - } - } - } -} - -#[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await -} - -#[embassy_executor::task] -async fn task(stack: &'static Stack>) { - let mut rx_buffer = [0; 4096]; - let mut tx_buffer = [0; 4096]; - - loop { - if stack.is_link_up() { - break; - } - Timer::after(Duration::from_millis(500)).await; - } - - println!("Waiting to get IP address..."); - loop { - if let Some(config) = stack.config_v4() { - println!("Got IP: {}", config.address); - break; - } - Timer::after(Duration::from_millis(500)).await; - } - - loop { - Timer::after(Duration::from_millis(1_000)).await; - - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); - - socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); - - let remote_endpoint = (Ipv4Address::new(142, 250, 185, 115), 80); - println!("connecting..."); - let r = socket.connect(remote_endpoint).await; - if let Err(e) = r { - println!("connect error: {:?}", e); - continue; - } - println!("connected!"); - let mut buf = [0; 1024]; - loop { - use embedded_io::asynch::Write; - let r = socket - .write_all(b"GET / HTTP/1.0\r\nHost: www.mobile-j.de\r\n\r\n") - .await; - if let Err(e) = r { - println!("write error: {:?}", e); - break; - } - let n = match socket.read(&mut buf).await { - Ok(0) => { - println!("read EOF"); - break; - } - Ok(n) => n, - Err(e) => { - println!("read error: {:?}", e); - break; - } - }; - println!("{}", core::str::from_utf8(&buf[..n]).unwrap()); - } - Timer::after(Duration::from_millis(3000)).await; - } -} diff --git a/examples-esp32s3/examples/embassy_esp_now.rs b/examples-esp32s3/examples/embassy_esp_now.rs deleted file mode 100644 index 9fb4dec9..00000000 --- a/examples-esp32s3/examples/embassy_esp_now.rs +++ /dev/null @@ -1,98 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_futures::select::{select, Either}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Ticker}; -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::esp_now::{EspNow, PeerInfo, BROADCAST_ADDRESS}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; - -#[embassy_executor::task] -async fn run(mut esp_now: EspNow<'static>) { - let mut ticker = Ticker::every(Duration::from_secs(5)); - loop { - let res = select(ticker.next(), async { - let r = esp_now.receive_async().await; - println!("Received {:?}", r); - if r.info.dst_address == BROADCAST_ADDRESS { - if !esp_now.peer_exists(&r.info.src_address) { - esp_now - .add_peer(PeerInfo { - peer_address: r.info.src_address, - lmk: None, - channel: None, - encrypt: false, - }) - .unwrap(); - } - let status = esp_now.send_async(&r.info.src_address, b"Hello Peer").await; - println!("Send hello to peer status: {:?}", status); - } - }) - .await; - - match res { - Either::First(_) => { - println!("Send"); - let status = esp_now.send_async(&BROADCAST_ADDRESS, b"0123456789").await; - println!("Send broadcast status: {:?}", status) - } - Either::Second(_) => (), - } - } -} - -static EXECUTOR: StaticCell = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s3_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(run(esp_now)).ok(); - }) -} diff --git a/examples-esp32s3/examples/embassy_esp_now_duplex.rs b/examples-esp32s3/examples/embassy_esp_now_duplex.rs deleted file mode 100644 index 014aac29..00000000 --- a/examples-esp32s3/examples/embassy_esp_now_duplex.rs +++ /dev/null @@ -1,133 +0,0 @@ -#![no_std] -#![no_main] -#![feature(type_alias_impl_trait)] - -use embassy_executor::_export::StaticCell; -use embassy_sync::blocking_mutex::raw::NoopRawMutex; -use embassy_sync::mutex::Mutex; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embassy_executor::Executor; -use embassy_time::{Duration, Ticker}; -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::esp_now::{EspNowManager, EspNowReceiver, EspNowSender, PeerInfo, BROADCAST_ADDRESS}; -use esp_wifi::{initialize, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup}; - -#[embassy_executor::task] -async fn broadcaster(sender: &'static Mutex>) { - let mut ticker = Ticker::every(Duration::from_secs(1)); - loop { - ticker.next().await; - - println!("Send Broadcast..."); - let mut sender = sender.lock().await; - let status = sender.send_async(&BROADCAST_ADDRESS, b"Hello.").await; - println!("Send broadcast status: {:?}", status); - } -} - -#[embassy_executor::task] -async fn sayhello( - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, -) { - let mut ticker = Ticker::every(Duration::from_millis(500)); - loop { - ticker.next().await; - let peer = match manager.fetch_peer(false) { - Ok(peer) => peer, - Err(_) => { - if let Ok(peer) = manager.fetch_peer(true) { - peer - } else { - continue; - } - } - }; - - println!("Send hello to peer {:?}", peer.peer_address); - let mut sender = sender.lock().await; - let status = sender.send_async(&peer.peer_address, b"Hello Peer.").await; - println!("Send hello status: {:?}", status); - } -} - -#[embassy_executor::task] -async fn listener(manager: &'static EspNowManager<'static>, mut receiver: EspNowReceiver<'static>) { - loop { - let r = receiver.receive_async().await; - println!("Received {:?}", r.get_data()); - if r.info.dst_address == BROADCAST_ADDRESS { - if !manager.peer_exists(&r.info.src_address) { - manager - .add_peer(PeerInfo { - peer_address: r.info.src_address, - lmk: None, - channel: None, - encrypt: false, - }) - .unwrap(); - println!("Added peer {:?}", r.info.src_address); - } - } - } -} - -static EXECUTOR: StaticCell = StaticCell::new(); -static ESP_NOW_MANAGER: StaticCell> = StaticCell::new(); -static ESP_NOW_SENDER: StaticCell>> = StaticCell::new(); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let timer_group0 = TimerGroup::new( - peripherals.TIMG0, - &clocks, - &mut system.peripheral_clock_control, - ); - embassy::init(&clocks, timer_group0.timer0); - let executor = EXECUTOR.init(Executor::new()); - - let (manager, sender, receiver) = esp_now.split(); - let manager = ESP_NOW_MANAGER.init(manager); - let sender: &'static _ = ESP_NOW_SENDER.init(Mutex::new(sender)); - - executor.run(|spawner| { - spawner.spawn(listener(manager, receiver)).ok(); - spawner.spawn(broadcaster(sender)).ok(); - spawner.spawn(sayhello(manager, sender)).ok(); - }) -} diff --git a/examples-esp32s3/examples/esp_now.rs b/examples-esp32s3/examples/esp_now.rs deleted file mode 100644 index f96a98f0..00000000 --- a/examples-esp32s3/examples/esp_now.rs +++ /dev/null @@ -1,81 +0,0 @@ -#![no_std] -#![no_main] - -use esp_backtrace as _; - -use esp_println::println; -use esp_wifi::esp_now::{PeerInfo, BROADCAST_ADDRESS}; -use esp_wifi::{current_millis, initialize, EspWifiInitFor}; -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{peripherals::Peripherals, prelude::*}; - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s3_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut esp_now = esp_wifi::esp_now::EspNow::new(&init, wifi).unwrap(); - - println!("esp-now version {}", esp_now.get_version().unwrap()); - - let mut next_send_time = current_millis() + 5 * 1000; - loop { - let r = esp_now.receive(); - if let Some(r) = r { - println!("Received {:?}", r); - - if r.info.dst_address == BROADCAST_ADDRESS { - if !esp_now.peer_exists(&r.info.src_address) { - esp_now - .add_peer(PeerInfo { - peer_address: r.info.src_address, - lmk: None, - channel: None, - encrypt: false, - }) - .unwrap(); - } - let status = esp_now - .send(&r.info.src_address, b"Hello Peer") - .unwrap() - .wait(); - println!("Send hello to peer status: {:?}", status); - } - } - - if current_millis() >= next_send_time { - next_send_time = current_millis() + 5 * 1000; - println!("Send"); - let status = esp_now - .send(&BROADCAST_ADDRESS, b"0123456789") - .unwrap() - .wait(); - println!("Send broadcast status: {:?}", status) - } - } -} diff --git a/examples-esp32s3/examples/static_ip.rs b/examples-esp32s3/examples/static_ip.rs deleted file mode 100644 index 500f75e3..00000000 --- a/examples-esp32s3/examples/static_ip.rs +++ /dev/null @@ -1,200 +0,0 @@ -#![no_std] -#![no_main] - -#[path = "../../examples-util/util.rs"] -mod examples_util; -use examples_util::hal; - -use embedded_io::blocking::*; -use embedded_svc::ipv4::Interface; -use embedded_svc::wifi::{AccessPointInfo, ClientConfiguration, Configuration, Wifi}; - -use esp_backtrace as _; - -use esp_println::{print, println}; -use esp_wifi::initialize; -use esp_wifi::wifi::WifiMode; -use esp_wifi::wifi::{utils::create_network_interface, WifiError}; -use esp_wifi::wifi_interface::WifiStack; -use esp_wifi::{current_millis, EspWifiInitFor}; -use hal::clock::ClockControl; -use hal::Rng; -use hal::{peripherals::Peripherals, prelude::*}; - -use smoltcp::iface::SocketStorage; - -const SSID: &str = env!("SSID"); -const PASSWORD: &str = env!("PASSWORD"); -const STATIC_IP: &str = env!("STATIC_IP"); -const GATEWAY_IP: &str = env!("GATEWAY_IP"); - -#[entry] -fn main() -> ! { - #[cfg(feature = "log")] - esp_println::logger::init_logger(log::LevelFilter::Info); - - let peripherals = Peripherals::take(); - - let mut system = peripherals.SYSTEM.split(); - let clocks = ClockControl::max(system.clock_control).freeze(); - - let timer = esp32s3_hal::timer::TimerGroup::new( - peripherals.TIMG1, - &clocks, - &mut system.peripheral_clock_control, - ) - .timer0; - let init = initialize( - EspWifiInitFor::Wifi, - timer, - Rng::new(peripherals.RNG), - system.radio_clock_control, - &clocks, - ) - .unwrap(); - - let (wifi, ..) = peripherals.RADIO.split(); - let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiMode::Sta, &mut socket_set_entries).unwrap(); - let mut wifi_stack = WifiStack::new(iface, device, sockets, current_millis); - - let client_config = Configuration::Client(ClientConfiguration { - ssid: SSID.into(), - password: PASSWORD.into(), - ..Default::default() - }); - let res = controller.set_configuration(&client_config); - println!("wifi_set_configuration returned {:?}", res); - - controller.start().unwrap(); - println!("is wifi started: {:?}", controller.is_started()); - - println!("Start Wifi Scan"); - let res: Result<(heapless::Vec, usize), WifiError> = controller.scan_n(); - if let Ok((res, _count)) = res { - for ap in res { - println!("{:?}", ap); - } - } - - println!("{:?}", controller.get_capabilities()); - println!("wifi_connect {:?}", controller.connect()); - - // wait to get connected - println!("Wait to get connected"); - loop { - let res = controller.is_connected(); - match res { - Ok(connected) => { - if connected { - break; - } - } - Err(err) => { - println!("{:?}", err); - loop {} - } - } - } - println!("{:?}", controller.is_connected()); - - println!("Setting static IP {}", STATIC_IP); - - wifi_stack - .set_iface_configuration(&embedded_svc::ipv4::Configuration::Client( - embedded_svc::ipv4::ClientConfiguration::Fixed(embedded_svc::ipv4::ClientSettings { - ip: embedded_svc::ipv4::Ipv4Addr::from(parse_ip(STATIC_IP)), - subnet: embedded_svc::ipv4::Subnet { - gateway: embedded_svc::ipv4::Ipv4Addr::from(parse_ip(GATEWAY_IP)), - mask: embedded_svc::ipv4::Mask(24), - }, - dns: None, - secondary_dns: None, - }), - )) - .unwrap(); - - println!( - "Start busy loop on main. Point your browser to http://{}:8080/", - STATIC_IP - ); - - let mut rx_buffer = [0u8; 1536]; - let mut tx_buffer = [0u8; 1536]; - let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); - - socket.listen(8080).unwrap(); - - loop { - socket.work(); - - if !socket.is_open() { - socket.listen(8080).unwrap(); - } - - if socket.is_connected() { - println!("Connected"); - - let mut time_out = false; - let wait_end = current_millis() + 20 * 1000; - let mut buffer = [0u8; 1024]; - let mut pos = 0; - loop { - if let Ok(len) = socket.read(&mut buffer[pos..]) { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } else { - break; - } - - if current_millis() > wait_end { - println!("Timeout"); - time_out = true; - break; - } - } - - if !time_out { - socket.write_all( - b"HTTP/1.0 200 OK\r\n\r\n\ - \ - \ -

Hello Rust! Hello esp-wifi!

\ - - \ - \r\n\ - " - ).unwrap(); - - socket.flush().unwrap(); - } - - socket.close(); - - println!("Done\n"); - println!(); - } - - let wait_end = current_millis() + 5 * 1000; - while current_millis() < wait_end { - socket.work(); - } - } -} - -fn parse_ip(ip: &str) -> [u8; 4] { - let mut result = [0u8; 4]; - for (idx, octet) in ip.split(".").into_iter().enumerate() { - result[idx] = u8::from_str_radix(octet, 10).unwrap(); - } - result -} diff --git a/examples-esp32s3/rust-toolchain.toml b/examples-esp32s3/rust-toolchain.toml deleted file mode 100644 index a2f5ab50..00000000 --- a/examples-esp32s3/rust-toolchain.toml +++ /dev/null @@ -1,2 +0,0 @@ -[toolchain] -channel = "esp" diff --git a/examples-esp32s3/src/lib.rs b/examples-esp32s3/src/lib.rs deleted file mode 100644 index 0c3fcbb6..00000000 --- a/examples-esp32s3/src/lib.rs +++ /dev/null @@ -1,3 +0,0 @@ -#![no_std] - -// no code here - see examples folder diff --git a/examples.md b/examples.md index 4c1f690c..cbaa4ff7 100644 --- a/examples.md +++ b/examples.md @@ -1,6 +1,10 @@ ## Examples -To build these ensure you are in the `examples-esp32XXX` directory matching your target as othewise the `config.toml` will not apply +To build these ensure you are in the `esp-wifi` and you are using the right chip name invocation. For example, to build for the `esp32c3`, please run + +``` +cargo esp32c3 --release ... +``` ### dhcp @@ -8,7 +12,7 @@ To build these ensure you are in the `examples-esp32XXX` directory matching your - gets an ip address via DHCP - performs an HTTP get request to some "random" server -`cargo run --example dhcp --release --features "embedded-svc,wifi"` +`cargo $CHIP --example dhcp --release --features "embedded-svc,wifi"` ### static_ip @@ -18,7 +22,7 @@ To build these ensure you are in the `examples-esp32XXX` directory matching your - uses the given static IP - responds with some HTML content when connecting to port 8080 -`cargo run --example static_ip --release --features "embedded-svc,wifi"` +`cargo $CHIP --example static_ip --release --features "embedded-svc,wifi"` ### ble @@ -27,15 +31,15 @@ To build these ensure you are in the `examples-esp32XXX` directory matching your - pressing the boot-button on a dev-board will send a notification if it is subscribed - this uses a toy level BLE stack - might not work with every BLE central device (tested with Android and Windows Bluetooth LE Explorer) -`cargo run --example ble --release --features "ble"` +`cargo $CHIP --example ble --release --features "ble"` **NOTE:** ESP32-S2 doesn't support bluetooth -### async_ble +### embassy_ble - same as `ble` but async -`cargo run --example async_ble --release --features "async,ble"` +`cargo $CHIP --example embassy_ble --release --features "async,ble"` **NOTE:** ESP32-S2 doesn't support bluetooth @@ -47,7 +51,7 @@ To build these ensure you are in the `examples-esp32XXX` directory matching your - does BLE advertising - coex support is still somewhat flaky -`cargo run --example coex --release --features "embedded-svc,wifi,ble"` +`cargo $CHIP --example coex --release --features "embedded-svc,wifi,ble"` **NOTE:** Not currently available for the ESP32, ESP32-C2, ESP32-C6 or ESP32-S2 @@ -55,25 +59,25 @@ To build these ensure you are in the `examples-esp32XXX` directory matching your - broadcasts, receives and sends messages via esp-now -`cargo run --example esp_now --release --features "esp-now"` +`cargo $CHIP --example esp_now --release --features "esp-now"` ### embassy_esp_now - broadcasts, receives and sends messages via esp-now in an async way -`cargo run --example embassy_esp_now --release --features "async,esp-now"` +`cargo $CHIP --example embassy_esp_now --release --features "async,esp-now"` ### embassy_esp_now_duplex - asynchronously broadcasts, receives and sends messages via esp-now in multiple embassy tasks -`cargo run --example embassy_esp_now_duplex --release --features "async,esp-now"` +`cargo $CHIP --example embassy_esp_now_duplex --release --features "async,esp-now"` ### embassy_dhcp - Read and Write to sockets over WiFi asyncronously using embassy-executor. -`cargo run --example embassy_dhcp --release --features "async,embedded-svc,wifi,embassy-net"` +`cargo $CHIP --example embassy_dhcp --release --features "async,embedded-svc,wifi,embassy-net"` ### access_point @@ -82,7 +86,7 @@ To build these ensure you are in the `examples-esp32XXX` directory matching your - open http://192.168.2.1:8080/ in your browser - on Android you might need to choose _Keep Accesspoint_ when it tells you the WiFi has no internet connection, Chrome might not want to load the URL - you can use a shell and try `curl` and `ping` -`cargo run --example access_point --release --features "embedded-svc,wifi"` +`cargo $CHIP --example access_point --release --features "embedded-svc,wifi"` ### embassy_access_point @@ -91,4 +95,4 @@ To build these ensure you are in the `examples-esp32XXX` directory matching your - open http://192.168.2.1:8080/ in your browser - on Android you might need to choose _Keep Accesspoint_ when it tells you the WiFi has no internet connection, Chrome might not want to load the URL - you can use a shell and try `curl` and `ping` -`cargo run --example embassy_access_point --release --features "async,embedded-svc,wifi,embassy-net"` \ No newline at end of file +`cargo $CHIP --example embassy_access_point --release --features "async,embedded-svc,wifi,embassy-net"` \ No newline at end of file diff --git a/examples-esp32/rust-toolchain.toml b/rust-toolchain.toml similarity index 100% rename from examples-esp32/rust-toolchain.toml rename to rust-toolchain.toml