aboutsummaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorGerzain Mata <[email protected]>2025-07-29 01:19:22 -0700
committerGerzain Mata <[email protected]>2025-07-29 08:11:49 -0700
commit1b4ea556c0e99622a18c48126cfc6899ffa102b1 (patch)
tree158edb71711a270b00e634bbab55194cf35c4935 /examples
parent7cf7f8b0ef344cdbef76703d4d700fbfddda23c9 (diff)
STM32WBA usb-dfu example
- Added sample application - Added sample bootloader Removed trace import
Diffstat (limited to 'examples')
-rw-r--r--examples/boot/application/stm32wba-dfu/.cargo/config.toml9
-rw-r--r--examples/boot/application/stm32wba-dfu/Cargo.toml32
-rw-r--r--examples/boot/application/stm32wba-dfu/README.md9
-rw-r--r--examples/boot/application/stm32wba-dfu/build.rs37
-rw-r--r--examples/boot/application/stm32wba-dfu/memory.x15
-rw-r--r--examples/boot/application/stm32wba-dfu/secrets/key.sec2
-rw-r--r--examples/boot/application/stm32wba-dfu/src/main.rs114
-rw-r--r--examples/boot/bootloader/stm32wba-dfu/.cargo/config.toml8
-rw-r--r--examples/boot/bootloader/stm32wba-dfu/Cargo.toml64
-rw-r--r--examples/boot/bootloader/stm32wba-dfu/README.md63
-rw-r--r--examples/boot/bootloader/stm32wba-dfu/build.rs27
-rw-r--r--examples/boot/bootloader/stm32wba-dfu/memory.x18
-rw-r--r--examples/boot/bootloader/stm32wba-dfu/secrets/key.pub.short1
-rw-r--r--examples/boot/bootloader/stm32wba-dfu/src/main.rs158
14 files changed, 557 insertions, 0 deletions
diff --git a/examples/boot/application/stm32wba-dfu/.cargo/config.toml b/examples/boot/application/stm32wba-dfu/.cargo/config.toml
new file mode 100644
index 000000000..a18ec3944
--- /dev/null
+++ b/examples/boot/application/stm32wba-dfu/.cargo/config.toml
@@ -0,0 +1,9 @@
1[target.'cfg(all(target_arch = "arm", target_os = "none"))']
2# replace your chip as listed in `probe-rs chip list`
3runner = "probe-rs run --chip STM32WBA65RI"
4
5[build]
6target = "thumbv8m.main-none-eabihf"
7
8[env]
9DEFMT_LOG = "trace"
diff --git a/examples/boot/application/stm32wba-dfu/Cargo.toml b/examples/boot/application/stm32wba-dfu/Cargo.toml
new file mode 100644
index 000000000..30dc51274
--- /dev/null
+++ b/examples/boot/application/stm32wba-dfu/Cargo.toml
@@ -0,0 +1,32 @@
1[package]
2edition = "2021"
3name = "embassy-boot-stm32wba-dfu-examples"
4version = "0.1.0"
5license = "MIT OR Apache-2.0"
6
7[dependencies]
8embassy-sync = { version = "0.7.0", path = "../../../../embassy-sync" }
9embassy-executor = { version = "0.7.0", path = "../../../../embassy-executor", features = ["arch-cortex-m", "executor-thread"] }
10embassy-time = { version = "0.4.0", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] }
11embassy-stm32 = { version = "0.2.0", path = "../../../../embassy-stm32", features = ["stm32wba65ri", "time-driver-any", "exti"] }
12embassy-boot-stm32 = { version = "0.4.0", path = "../../../../embassy-boot-stm32", features = [] }
13embassy-embedded-hal = { version = "0.3.1", path = "../../../../embassy-embedded-hal" }
14embassy-usb = { version = "0.5.0", path = "../../../../embassy-usb" }
15embassy-usb-dfu = { version = "0.1.0", path = "../../../../embassy-usb-dfu", features = ["application", "cortex-m"] }
16
17defmt = { version = "1.0.1", optional = true }
18defmt-rtt = { version = "1.0.0", optional = true }
19panic-reset = { version = "0.1.1" }
20embedded-hal = { version = "0.2.6" }
21
22cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] }
23cortex-m-rt = "0.7.0"
24
25[features]
26defmt = [
27 "dep:defmt",
28 "dep:defmt-rtt",
29 "embassy-stm32/defmt",
30 "embassy-boot-stm32/defmt",
31 "embassy-sync/defmt",
32]
diff --git a/examples/boot/application/stm32wba-dfu/README.md b/examples/boot/application/stm32wba-dfu/README.md
new file mode 100644
index 000000000..30692034c
--- /dev/null
+++ b/examples/boot/application/stm32wba-dfu/README.md
@@ -0,0 +1,9 @@
1# Examples using bootloader
2
3Example for STM32WBA demonstrating the USB DFU application.
4
5## Usage
6
7```
8cargo flash --release --chip STM32WBA65RI
9```
diff --git a/examples/boot/application/stm32wba-dfu/build.rs b/examples/boot/application/stm32wba-dfu/build.rs
new file mode 100644
index 000000000..e1da69328
--- /dev/null
+++ b/examples/boot/application/stm32wba-dfu/build.rs
@@ -0,0 +1,37 @@
1//! This build script copies the `memory.x` file from the crate root into
2//! a directory where the linker can always find it at build time.
3//! For many projects this is optional, as the linker always searches the
4//! project root directory -- wherever `Cargo.toml` is. However, if you
5//! are using a workspace or have a more complicated build setup, this
6//! build script becomes required. Additionally, by requesting that
7//! Cargo re-run the build script whenever `memory.x` is changed,
8//! updating `memory.x` ensures a rebuild of the application with the
9//! new memory settings.
10
11use std::env;
12use std::fs::File;
13use std::io::Write;
14use std::path::PathBuf;
15
16fn main() {
17 // Put `memory.x` in our output directory and ensure it's
18 // on the linker search path.
19 let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
20 File::create(out.join("memory.x"))
21 .unwrap()
22 .write_all(include_bytes!("memory.x"))
23 .unwrap();
24 println!("cargo:rustc-link-search={}", out.display());
25
26 // By default, Cargo will re-run a build script whenever
27 // any file in the project changes. By specifying `memory.x`
28 // here, we ensure the build script is only re-run when
29 // `memory.x` is changed.
30 println!("cargo:rerun-if-changed=memory.x");
31
32 println!("cargo:rustc-link-arg-bins=--nmagic");
33 println!("cargo:rustc-link-arg-bins=-Tlink.x");
34 if env::var("CARGO_FEATURE_DEFMT").is_ok() {
35 println!("cargo:rustc-link-arg-bins=-Tdefmt.x");
36 }
37}
diff --git a/examples/boot/application/stm32wba-dfu/memory.x b/examples/boot/application/stm32wba-dfu/memory.x
new file mode 100644
index 000000000..fcdb6b6d2
--- /dev/null
+++ b/examples/boot/application/stm32wba-dfu/memory.x
@@ -0,0 +1,15 @@
1MEMORY
2{
3 /* NOTE 1 K = 1 KiBi = 1024 bytes */
4 BOOTLOADER : ORIGIN = 0x08000000, LENGTH = 80K
5 BOOTLOADER_STATE : ORIGIN = 0x08014000, LENGTH = 8K
6 FLASH : ORIGIN = 0x08016000, LENGTH = 120K
7 DFU : ORIGIN = 0x0803C000, LENGTH = 160K
8 RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 400K
9}
10
11__bootloader_state_start = ORIGIN(BOOTLOADER_STATE) - ORIGIN(BOOTLOADER);
12__bootloader_state_end = ORIGIN(BOOTLOADER_STATE) + LENGTH(BOOTLOADER_STATE) - ORIGIN(BOOTLOADER);
13
14__bootloader_dfu_start = ORIGIN(DFU) - ORIGIN(BOOTLOADER);
15__bootloader_dfu_end = ORIGIN(DFU) + LENGTH(DFU) - ORIGIN(BOOTLOADER);
diff --git a/examples/boot/application/stm32wba-dfu/secrets/key.sec b/examples/boot/application/stm32wba-dfu/secrets/key.sec
new file mode 100644
index 000000000..52e7f125b
--- /dev/null
+++ b/examples/boot/application/stm32wba-dfu/secrets/key.sec
@@ -0,0 +1,2 @@
1untrusted comment: signify secret key
2RWRCSwAAAAATdHQF3B4jEIoNZrjADRp2LbjJjNdNNzKwTCe4IB6mDNq96pe53nbNxwbdCc/T4hrz7W+Kx1MwrZ0Yz5xebSK5Z0Kh/3Cdf039U5f+eoTDS2fIGbohyUbrtwKzjyE0qXI=
diff --git a/examples/boot/application/stm32wba-dfu/src/main.rs b/examples/boot/application/stm32wba-dfu/src/main.rs
new file mode 100644
index 000000000..bf17a7150
--- /dev/null
+++ b/examples/boot/application/stm32wba-dfu/src/main.rs
@@ -0,0 +1,114 @@
1#![no_std]
2#![no_main]
3
4use core::cell::RefCell;
5
6#[cfg(feature = "defmt")]
7use defmt_rtt as _;
8use embassy_boot_stm32::{AlignedBuffer, BlockingFirmwareState, FirmwareUpdaterConfig};
9use embassy_executor::Spawner;
10use embassy_stm32::flash::{Flash, WRITE_SIZE};
11use embassy_stm32::usb::{self, Driver};
12use embassy_stm32::{bind_interrupts, peripherals};
13use embassy_sync::blocking_mutex::Mutex;
14use embassy_time::Duration;
15use embassy_usb::{msos, Builder};
16use embassy_usb_dfu::consts::DfuAttributes;
17use embassy_usb_dfu::{usb_dfu, Control, ResetImmediate};
18use panic_reset as _;
19
20bind_interrupts!(struct Irqs {
21 USB_OTG_HS => usb::InterruptHandler<peripherals::USB_OTG_HS>;
22});
23
24// This is a randomly generated GUID to allow clients on Windows to find your device.
25//
26// N.B. update to a custom GUID for your own device!
27const DEVICE_INTERFACE_GUIDS: &[&str] = &["{EAA9A5DC-30BA-44BC-9232-606CDC875321}"];
28
29#[embassy_executor::main]
30async fn main(_spawner: Spawner) {
31 let mut config = embassy_stm32::Config::default();
32
33 {
34 use embassy_stm32::rcc::*;
35 config.rcc.pll1 = Some(Pll {
36 source: PllSource::HSI,
37 prediv: PllPreDiv::DIV1, // PLLM = 1 → HSI / 1 = 16 MHz
38 mul: PllMul::MUL30, // PLLN = 30 → 16 MHz * 30 = 480 MHz VCO
39 divr: Some(PllDiv::DIV5), // PLLR = 5 → 96 MHz (Sysclk)
40 divq: Some(PllDiv::DIV10), // PLLQ = 10 → 48 MHz
41 divp: Some(PllDiv::DIV30), // PLLP = 30 → 16 MHz (USB_OTG_HS)
42 frac: Some(0), // Fractional part (disabled)
43 });
44
45 config.rcc.ahb_pre = AHBPrescaler::DIV1;
46 config.rcc.apb1_pre = APBPrescaler::DIV1;
47 config.rcc.apb2_pre = APBPrescaler::DIV1;
48 config.rcc.apb7_pre = APBPrescaler::DIV1;
49 config.rcc.ahb5_pre = AHB5Prescaler::DIV4;
50
51 config.rcc.voltage_scale = VoltageScale::RANGE1;
52 config.rcc.mux.otghssel = mux::Otghssel::PLL1_P;
53 config.rcc.sys = Sysclk::PLL1_R;
54 }
55
56 let p = embassy_stm32::init(config);
57 let flash = Flash::new_blocking(p.FLASH);
58 let flash = Mutex::new(RefCell::new(flash));
59
60 let config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash, &flash);
61 let mut magic = AlignedBuffer([0; WRITE_SIZE]);
62 let mut firmware_state = BlockingFirmwareState::from_config(config, &mut magic.0);
63 firmware_state.mark_booted().expect("Failed to mark booted");
64
65 // Create the driver, from the HAL.
66 let mut ep_out_buffer = [0u8; 256];
67 let mut config = embassy_stm32::usb::Config::default();
68 config.vbus_detection = false;
69
70 let driver = Driver::new_hs(p.USB_OTG_HS, Irqs, p.PD6, p.PD7, &mut ep_out_buffer, config);
71 let mut config = embassy_usb::Config::new(0xc0de, 0xcafe);
72 config.manufacturer = Some("Embassy");
73 config.product = Some("USB-DFU Runtime example");
74 config.serial_number = Some("1235678");
75
76 let mut config_descriptor = [0; 256];
77 let mut bos_descriptor = [0; 256];
78 let mut control_buf = [0; 64];
79 let mut state = Control::new(firmware_state, DfuAttributes::CAN_DOWNLOAD, ResetImmediate);
80 let mut builder = Builder::new(
81 driver,
82 config,
83 &mut config_descriptor,
84 &mut bos_descriptor,
85 &mut [],
86 &mut control_buf,
87 );
88
89 // We add MSOS headers so that the device automatically gets assigned the WinUSB driver on Windows.
90 // Otherwise users need to do this manually using a tool like Zadig.
91 //
92 // It seems these always need to be at added at the device level for this to work and for
93 // composite devices they also need to be added on the function level (as shown later).
94
95 builder.msos_descriptor(msos::windows_version::WIN8_1, 2);
96 builder.msos_feature(msos::CompatibleIdFeatureDescriptor::new("WINUSB", ""));
97 builder.msos_feature(msos::RegistryPropertyFeatureDescriptor::new(
98 "DeviceInterfaceGUIDs",
99 msos::PropertyData::RegMultiSz(DEVICE_INTERFACE_GUIDS),
100 ));
101
102 usb_dfu(&mut builder, &mut state, Duration::from_millis(1000), |func| {
103 // You likely don't have to add these function level headers if your USB device is not composite
104 // (i.e. if your device does not expose another interface in addition to DFU)
105 func.msos_feature(msos::CompatibleIdFeatureDescriptor::new("WINUSB", ""));
106 func.msos_feature(msos::RegistryPropertyFeatureDescriptor::new(
107 "DeviceInterfaceGUIDs",
108 msos::PropertyData::RegMultiSz(DEVICE_INTERFACE_GUIDS),
109 ));
110 });
111
112 let mut dev = builder.build();
113 dev.run().await
114}
diff --git a/examples/boot/bootloader/stm32wba-dfu/.cargo/config.toml b/examples/boot/bootloader/stm32wba-dfu/.cargo/config.toml
new file mode 100644
index 000000000..1896068d8
--- /dev/null
+++ b/examples/boot/bootloader/stm32wba-dfu/.cargo/config.toml
@@ -0,0 +1,8 @@
1[target.'cfg(all(target_arch = "arm", target_os = "none"))']
2runner = "probe-rs run --chip STM32WBA65RI"
3
4[build]
5target = "thumbv8m.main-none-eabihf"
6
7[env]
8DEFMT_LOG = "trace"
diff --git a/examples/boot/bootloader/stm32wba-dfu/Cargo.toml b/examples/boot/bootloader/stm32wba-dfu/Cargo.toml
new file mode 100644
index 000000000..9240d1808
--- /dev/null
+++ b/examples/boot/bootloader/stm32wba-dfu/Cargo.toml
@@ -0,0 +1,64 @@
1[package]
2edition = "2021"
3name = "stm32wba6-dfu-bootloader-example"
4version = "0.1.0"
5description = "Example USB DFUbootloader for the STM32WBA series of chips"
6license = "MIT OR Apache-2.0"
7
8[dependencies]
9defmt = { version = "1.0.1", optional = true }
10defmt-rtt = { version = "1.0.0", optional = true }
11
12embassy-stm32 = { path = "../../../../embassy-stm32", features = [] }
13embassy-boot-stm32 = { path = "../../../../embassy-boot-stm32" }
14cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] }
15embassy-sync = { version = "0.7.0", path = "../../../../embassy-sync" }
16cortex-m-rt = { version = "0.7" }
17embedded-storage = "0.3.1"
18embedded-storage-async = "0.4.0"
19cfg-if = "1.0.0"
20embassy-usb-dfu = { version = "0.1.0", path = "../../../../embassy-usb-dfu", features = ["dfu", "cortex-m"] }
21embassy-usb = { version = "0.5.0", path = "../../../../embassy-usb", default-features = false }
22embassy-futures = { version = "0.1.1", path = "../../../../embassy-futures" }
23
24[features]
25defmt = [
26 "dep:defmt",
27 "dep:defmt-rtt",
28 "embassy-boot-stm32/defmt",
29 "embassy-stm32/defmt",
30 "embassy-usb/defmt",
31 "embassy-usb-dfu/defmt"
32]
33verify = ["embassy-usb-dfu/ed25519-salty"]
34
35[profile.dev]
36debug = 2
37debug-assertions = true
38incremental = false
39opt-level = 'z'
40overflow-checks = true
41
42[profile.release]
43codegen-units = 1
44debug = 2
45debug-assertions = false
46incremental = false
47lto = 'fat'
48opt-level = 'z'
49overflow-checks = false
50
51# do not optimize proc-macro crates = faster builds from scratch
52[profile.dev.build-override]
53codegen-units = 8
54debug = false
55debug-assertions = false
56opt-level = 0
57overflow-checks = false
58
59[profile.release.build-override]
60codegen-units = 8
61debug = false
62debug-assertions = false
63opt-level = 0
64overflow-checks = false
diff --git a/examples/boot/bootloader/stm32wba-dfu/README.md b/examples/boot/bootloader/stm32wba-dfu/README.md
new file mode 100644
index 000000000..d50164255
--- /dev/null
+++ b/examples/boot/bootloader/stm32wba-dfu/README.md
@@ -0,0 +1,63 @@
1# Bootloader for STM32
2
3This bootloader implementation uses `embassy-boot` and `embassy-usb-dfu` to manage firmware updates and interact with the flash memory on STM32WB55 devices.
4
5## Prerequisites
6
7- Rust toolchain with `cargo` installed
8- `cargo-flash` for flashing the bootloader
9- `dfu-util` for firmware updates
10- `cargo-binutils` for binary generation
11
12## Usage
13
14### 1. Flash the Bootloader
15
16First, flash the bootloader to your device:
17
18```
19cargo flash --features embassy-stm32/stm32wba65ri --release --chip STM32WBA65RI
20```
21
22### 2. Build and Flash Application
23
24Generate your application binary and flash it using DFU:
25
26```
27cargo objcopy --release -- -O binary fw.bin
28dfu-util -d c0de:cafe -w -D fw.bin
29```
30
31### 3. Sign Updates Before Flashing (Optional)
32
33Currently, embassy-usb-dfu only supports a limited implementation of the generic support for ed25519-based update verfication in embassy-boot. This implementation assumes that a signature is simply concatenated to the end of an update binary. For more details, please see https://embassy.dev/book/#_verification and/or refer to the documentation for embassy-boot-dfu.
34
35To sign (and then verify) application updates, you will first need to generate a key pair:
36
37```
38signify-openbsd -G -n -p secrets/key.pub -s secrets/key.sec
39tail -n1 secrets/key.pub | base64 -d -i - | dd ibs=10 skip=1 > secrets/key.pub.short
40```
41
42Then you will need to sign all you binaries with the private key:
43
44```
45cargo objcopy --release -- -O binary fw.bin
46shasum -a 512 -b fw.bin | head -c128 | xxd -p -r > target/fw-hash.txt
47signify-openbsd -S -s secrets/key.sec -m target/fw-hash.txt -x target/fw-hash.sig
48cp fw.bin fw-signed.bin
49tail -n1 target/fw-hash.sig | base64 -d -i - | dd ibs=10 skip=1 >> fw-signed.bin
50dfu-util -d c0de:cafe -w -D fw-signed.bin
51```
52
53Finally, as shown in this example with the `verify` feature flag enabled, you then need to embed the public key into your bootloader so that it can verify update signatures.
54
55N.B. Please note that the exact steps above are NOT a good example of how to manage your keys securely. In a production environment, you should take great care to ensure that (at least the private key) is protected and not leaked into your version control system.
56
57## Troubleshooting
58
59- Make sure your device is in DFU mode before flashing
60- Verify the USB VID:PID matches your device (c0de:cafe)
61- Check USB connections if the device is not detected
62- Make sure the transfer size option of `dfu-util` matches the bootloader configuration. By default, `dfu-util` will use the transfer size reported by the device, but you can override it with the `-t` option if needed.
63- Make sure `control_buf` size is larger than or equal to the `usb_dfu` `BLOCK_SIZE` parameter (in this example, both are set to 4096 bytes).
diff --git a/examples/boot/bootloader/stm32wba-dfu/build.rs b/examples/boot/bootloader/stm32wba-dfu/build.rs
new file mode 100644
index 000000000..fd605991f
--- /dev/null
+++ b/examples/boot/bootloader/stm32wba-dfu/build.rs
@@ -0,0 +1,27 @@
1use std::env;
2use std::fs::File;
3use std::io::Write;
4use std::path::PathBuf;
5
6fn main() {
7 // Put `memory.x` in our output directory and ensure it's
8 // on the linker search path.
9 let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
10 File::create(out.join("memory.x"))
11 .unwrap()
12 .write_all(include_bytes!("memory.x"))
13 .unwrap();
14 println!("cargo:rustc-link-search={}", out.display());
15
16 // By default, Cargo will re-run a build script whenever
17 // any file in the project changes. By specifying `memory.x`
18 // here, we ensure the build script is only re-run when
19 // `memory.x` is changed.
20 println!("cargo:rerun-if-changed=memory.x");
21
22 println!("cargo:rustc-link-arg-bins=--nmagic");
23 println!("cargo:rustc-link-arg-bins=-Tlink.x");
24 if env::var("CARGO_FEATURE_DEFMT").is_ok() {
25 println!("cargo:rustc-link-arg-bins=-Tdefmt.x");
26 }
27}
diff --git a/examples/boot/bootloader/stm32wba-dfu/memory.x b/examples/boot/bootloader/stm32wba-dfu/memory.x
new file mode 100644
index 000000000..105c9e960
--- /dev/null
+++ b/examples/boot/bootloader/stm32wba-dfu/memory.x
@@ -0,0 +1,18 @@
1MEMORY
2{
3 /* NOTE 1 K = 1 KiBi = 1024 bytes */
4 FLASH : ORIGIN = 0x08000000, LENGTH = 80K
5 BOOTLOADER_STATE : ORIGIN = 0x08014000, LENGTH = 8K
6 ACTIVE : ORIGIN = 0x08016000, LENGTH = 120K
7 DFU : ORIGIN = 0x0803C000, LENGTH = 160K
8 RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 400K
9}
10
11__bootloader_state_start = ORIGIN(BOOTLOADER_STATE) - ORIGIN(FLASH);
12__bootloader_state_end = ORIGIN(BOOTLOADER_STATE) + LENGTH(BOOTLOADER_STATE) - ORIGIN(FLASH);
13
14__bootloader_active_start = ORIGIN(ACTIVE) - ORIGIN(FLASH);
15__bootloader_active_end = ORIGIN(ACTIVE) + LENGTH(ACTIVE) - ORIGIN(FLASH);
16
17__bootloader_dfu_start = ORIGIN(DFU) - ORIGIN(FLASH);
18__bootloader_dfu_end = ORIGIN(DFU) + LENGTH(DFU) - ORIGIN(FLASH); \ No newline at end of file
diff --git a/examples/boot/bootloader/stm32wba-dfu/secrets/key.pub.short b/examples/boot/bootloader/stm32wba-dfu/secrets/key.pub.short
new file mode 100644
index 000000000..7a4de8585
--- /dev/null
+++ b/examples/boot/bootloader/stm32wba-dfu/secrets/key.pub.short
@@ -0,0 +1 @@
gB��p�M�S��z��Kg��!�F���!4�r \ No newline at end of file
diff --git a/examples/boot/bootloader/stm32wba-dfu/src/main.rs b/examples/boot/bootloader/stm32wba-dfu/src/main.rs
new file mode 100644
index 000000000..75d8d4199
--- /dev/null
+++ b/examples/boot/bootloader/stm32wba-dfu/src/main.rs
@@ -0,0 +1,158 @@
1#![no_std]
2#![no_main]
3
4use core::cell::RefCell;
5
6use cortex_m_rt::{entry, exception};
7#[cfg(feature = "defmt")]
8use defmt_rtt as _;
9use embassy_boot_stm32::*;
10use embassy_stm32::flash::{Flash, BANK1_REGION, WRITE_SIZE};
11use embassy_stm32::usb::Driver;
12use embassy_stm32::{bind_interrupts, peripherals, usb, Config};
13use embassy_sync::blocking_mutex::Mutex;
14use embassy_usb::{msos, Builder};
15use embassy_usb_dfu::consts::DfuAttributes;
16use embassy_usb_dfu::{usb_dfu, Control, ResetImmediate};
17
18bind_interrupts!(struct Irqs {
19 USB_OTG_HS => usb::InterruptHandler<peripherals::USB_OTG_HS>;
20});
21
22// This is a randomly generated GUID to allow clients on Windows to find your device.
23//
24// N.B. update to a custom GUID for your own device!
25const DEVICE_INTERFACE_GUIDS: &[&str] = &["{EAA9A5DC-30BA-44BC-9232-606CDC875321}"];
26
27// This is a randomly generated example key.
28//
29// N.B. Please replace with your own!
30#[cfg(feature = "verify")]
31static PUBLIC_SIGNING_KEY: &[u8; 32] = include_bytes!("../secrets/key.pub.short");
32
33#[entry]
34fn main() -> ! {
35 let mut config = Config::default();
36
37 {
38 use embassy_stm32::rcc::*;
39 config.rcc.pll1 = Some(Pll {
40 source: PllSource::HSI,
41 prediv: PllPreDiv::DIV1, // PLLM = 1 → HSI / 1 = 16 MHz
42 mul: PllMul::MUL30, // PLLN = 30 → 16 MHz * 30 = 480 MHz VCO
43 divr: Some(PllDiv::DIV5), // PLLR = 5 → 96 MHz (Sysclk)
44 divq: Some(PllDiv::DIV10), // PLLQ = 10 → 48 MHz
45 divp: Some(PllDiv::DIV30), // PLLP = 30 → 16 MHz (USB_OTG_HS)
46 frac: Some(0), // Fractional part (disabled)
47 });
48
49 config.rcc.ahb_pre = AHBPrescaler::DIV1;
50 config.rcc.apb1_pre = APBPrescaler::DIV1;
51 config.rcc.apb2_pre = APBPrescaler::DIV1;
52 config.rcc.apb7_pre = APBPrescaler::DIV1;
53 config.rcc.ahb5_pre = AHB5Prescaler::DIV4;
54
55 config.rcc.voltage_scale = VoltageScale::RANGE1;
56 config.rcc.mux.otghssel = mux::Otghssel::PLL1_P;
57 config.rcc.sys = Sysclk::PLL1_R;
58 }
59
60 let p = embassy_stm32::init(config);
61
62 // Prevent a hard fault when accessing flash 'too early' after boot.
63 #[cfg(feature = "defmt")]
64 for _ in 0..10000000 {
65 cortex_m::asm::nop();
66 }
67
68 let layout = Flash::new_blocking(p.FLASH).into_blocking_regions();
69 let flash = Mutex::new(RefCell::new(layout.bank1_region));
70
71 let config = BootLoaderConfig::from_linkerfile_blocking(&flash, &flash, &flash);
72 let active_offset = config.active.offset();
73 let bl = BootLoader::prepare::<_, _, _, 2048>(config);
74
75 // Create the driver, from the HAL.
76 let mut ep_out_buffer = [0u8; 256];
77 let mut config = embassy_stm32::usb::Config::default();
78
79 config.vbus_detection = false;
80
81 if bl.state == State::DfuDetach {
82 let driver = Driver::new_hs(p.USB_OTG_HS, Irqs, p.PD6, p.PD7, &mut ep_out_buffer, config);
83 let mut config = embassy_usb::Config::new(0xc0de, 0xcafe);
84 config.manufacturer = Some("Embassy");
85 config.product = Some("USB-DFU Bootloader example");
86 config.serial_number = Some("1235678");
87
88 let fw_config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash, &flash);
89 let mut buffer = AlignedBuffer([0; WRITE_SIZE]);
90 let updater = BlockingFirmwareUpdater::new(fw_config, &mut buffer.0[..]);
91
92 let mut config_descriptor = [0; 256];
93 let mut bos_descriptor = [0; 256];
94 let mut control_buf = [0; 4096];
95
96 #[cfg(not(feature = "verify"))]
97 let mut state = Control::new(updater, DfuAttributes::CAN_DOWNLOAD, ResetImmediate);
98
99 #[cfg(feature = "verify")]
100 let mut state = Control::new(updater, DfuAttributes::CAN_DOWNLOAD, ResetImmediate, PUBLIC_SIGNING_KEY);
101
102 let mut builder = Builder::new(
103 driver,
104 config,
105 &mut config_descriptor,
106 &mut bos_descriptor,
107 &mut [],
108 &mut control_buf,
109 );
110
111 // We add MSOS headers so that the device automatically gets assigned the WinUSB driver on Windows.
112 // Otherwise users need to do this manually using a tool like Zadig.
113 //
114 // It seems these always need to be at added at the device level for this to work and for
115 // composite devices they also need to be added on the function level (as shown later).
116
117 builder.msos_descriptor(msos::windows_version::WIN8_1, 2);
118 builder.msos_feature(msos::CompatibleIdFeatureDescriptor::new("WINUSB", ""));
119 builder.msos_feature(msos::RegistryPropertyFeatureDescriptor::new(
120 "DeviceInterfaceGUIDs",
121 msos::PropertyData::RegMultiSz(DEVICE_INTERFACE_GUIDS),
122 ));
123
124 usb_dfu::<_, _, _, _, 4096>(&mut builder, &mut state, |func| {
125 // You likely don't have to add these function level headers if your USB device is not composite
126 // (i.e. if your device does not expose another interface in addition to DFU)
127 func.msos_feature(msos::CompatibleIdFeatureDescriptor::new("WINUSB", ""));
128 func.msos_feature(msos::RegistryPropertyFeatureDescriptor::new(
129 "DeviceInterfaceGUIDs",
130 msos::PropertyData::RegMultiSz(DEVICE_INTERFACE_GUIDS),
131 ));
132 });
133
134 let mut dev = builder.build();
135 embassy_futures::block_on(dev.run());
136 }
137
138 unsafe { bl.load(BANK1_REGION.base + active_offset) }
139}
140
141#[no_mangle]
142#[cfg_attr(target_os = "none", link_section = ".HardFault.user")]
143unsafe extern "C" fn HardFault() {
144 cortex_m::peripheral::SCB::sys_reset();
145}
146
147#[exception]
148unsafe fn DefaultHandler(_: i16) -> ! {
149 const SCB_ICSR: *const u32 = 0xE000_ED04 as *const u32;
150 let irqn = core::ptr::read_volatile(SCB_ICSR) as u8 as i16 - 16;
151
152 panic!("DefaultHandler #{:?}", irqn);
153}
154
155#[panic_handler]
156fn panic(_info: &core::panic::PanicInfo) -> ! {
157 cortex_m::asm::udf();
158}