Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(otgfs): Implement OTG_FS USB Driver #51

Merged
merged 7 commits into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 2 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,10 @@ license = "MIT OR Apache-2.0"
ch32-metapac = { features = [
"memory-x",
"rt",
], git = "https://github.com/ch32-rs/ch32-metapac.git", tag = "ch32-data-0f143d8ce505711e4667002b42b8a34eb9c1d039" }
# ch32-metapac = { features = ["memory-x","rt"], path = "../ch32-data/build/ch32-metapac" }
], git = "https://github.com/ch32-rs/ch32-metapac", rev = "43066e18cf51106dff448f679dfff368a41431d7" }

qingke = { version = "0.4.0", features = ["critical-section-impl"] }
qingke-rt = { version = "0.4.0", optional = true }
# qingke-rt = { version = "0.4.0", path = "../qingke/qingke-rt", optional = true }
# qingke = { version = "0.4.0", path = "../qingke", features = [
# "critical-section-impl",
# ] }

# TODO: remove this
embedded-hal-02 = { package = "embedded-hal", version = "0.2.6", features = [
Expand Down Expand Up @@ -54,8 +49,7 @@ embassy-hal-internal = "0.2.0"
[build-dependencies]
ch32-metapac = { features = [
"metadata",
], git = "https://github.com/ch32-rs/ch32-metapac.git", tag = "ch32-data-0f143d8ce505711e4667002b42b8a34eb9c1d039" }
# ch32-metapac = { default-features = false, features = ["metadata"], path = "../ch32-data/build/ch32-metapac" }
], git = "https://github.com/ch32-rs/ch32-metapac", rev = "43066e18cf51106dff448f679dfff368a41431d7" }

proc-macro2 = "1.0"
quote = "1.0"
Expand Down
23 changes: 14 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,22 @@ others should work if you are careful as most peripherals are similar enough.

For a full list of chip capabilities and peripherals, check the [ch32-data](https://github.com/ch32-rs/ch32-data) repository.

| Family | Status | Embassy | RCC | GPIO | UART*| SPI*| I2C | ADC | Timer(PWM) | EXTI*| RTC | DMA*| Delay | Others |
|--------|--------|---------|-----|------|------|-----|-----|-----|------------|------|-----|-----|-------| ------ |
| V2/V3 | | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | ✅ | | RNG, SDIO |
| V1 | | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❓ | | ❓ | ✅ | |
| V0 | | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❓ | | ❓ | ✅ | |
| X0 | | ✅ | ✅ | ✅ | ✅ | ✅ | ❓ | ✅ | ✅ | ✅ | | ✅ | | |
| L1 | | ✅ | ✅ | ✅ | ✅ | ✅ | ❓ | ✅ | ✅ | ❓ | | ❓ | | |
| CH641 | | ✅ | ✅ | ✅ | ❓ | N/A | ❓ | ✅ | ✅ | ❓ | | ❓ | ✅ | ISP |
| CH643 | TODO | | | | | | | | | | | | | |
| Family | V2/V3 | V1 | V0 | X0 | L1 | CH641 | CH643 |
|-------------|--------|-----|-----|-----|-----|--------|--------|
| Embassy | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | |
| RCC | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | |
| GPIO | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | |
| UART* | ✅ | ✅ | ✅ | ✅ | ✅ | ❓ | |
| SPI* | ✅ | ✅ | ✅ | ✅ | ✅ | N/A | |
| I2C | ✅ | ✅ | ✅ | ❓ | ❓ | ❓ | |
| ADC | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | |
| Timer(PWM) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | |
| USB/OTG FS | ✅ | N/A | N/A | N/A | N/A | N/A | |
| USB/OTG HS | ❌ | N/A | N/A | N/A | N/A | N/A | |


- ✅ : Expected to work
- ❌ : Not implemented
- ❓ : Not tested
- `*` marks the async driver
- TODO: I haven't got a dev board yet, help-wanted
Expand Down
3 changes: 3 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,9 @@ fn main() {
(("sdio", "D6"), quote!(crate::sdio::D6Pin)),
(("sdio", "D6"), quote!(crate::sdio::D7Pin)),
(("sdio", "D8"), quote!(crate::sdio::D8Pin)),
// otg_fs
(("otg", "DP"), quote!(crate::otg_fs::DpPin)),
(("otg", "DM"), quote!(crate::otg_fs::DmPin)),
// USB is splitted into multiple impls
(("usbd", "DP"), quote!(crate::usbd::DpPin)),
(("usbd", "DM"), quote!(crate::usbd::DmPin)),
Expand Down
1 change: 0 additions & 1 deletion examples/ch32v208/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ edition = "2021"
[dependencies]
ch32-hal = { path = "../../", features = [
"ch32v208wbu6",
"defmt",
"embassy",
"rt",
], default-features = false }
Expand Down
12 changes: 9 additions & 3 deletions examples/ch32v307/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,18 @@ ch32-hal = { path = "../../", features = [
] }
embassy-executor = { version = "0.6.0", features = [
"integrated-timers",
"arch-riscv32",
"arch-spin",
"executor-thread",
] }

critical-section = "1.2.0"

embassy-time = "0.3.2"
embassy-usb = "0.3.0"
nb = "1.1.0"

qingke = "0.4.0"
# qingke-rt = { version = "0.4.0", path = "../../../qingke/qingke-rt" }
# qingke = { version = "0.4.0", path = "../../../qingke" }
qingke-rt = "0.4.0"

# Not working for now
# defmt = "0.3"
Expand All @@ -39,6 +42,9 @@ ssd1306 = "0.9"
edrv-bmp180 = "0.0.1"
embedded-hal = "1.0.0"

# for usbfs_dfu
usb-dfu-target = "0.1.0"

[profile.release]
strip = false # symbols are not flashed to the microcontroller, so don't strip them.
lto = true
Expand Down
162 changes: 162 additions & 0 deletions examples/ch32v307/src/bin/usbfs_dfu.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
#![no_std]
#![no_main]

use panic_halt as _;
use ch32_hal::otg_fs::endpoint::EndpointDataBuffer;
use ch32_hal::otg_fs::{self, Driver};
use ch32_hal::{self as hal, bind_interrupts, peripherals, Config};
use embassy_executor::Spawner;
use embassy_usb::control::{InResponse, OutResponse, Recipient, RequestType};
use embassy_usb::{Builder, Handler};
use usb_dfu_target::consts::{DfuAttributes, DfuRequest};
use usb_dfu_target::{DfuHandler, UsbDfuDevice};

bind_interrupts!(struct Irq {
OTG_FS => otg_fs::InterruptHandler<peripherals::OTG_FS>;
});

const BLOCK_SIZE: usize = 64;

struct DfuDemoDevice;

impl DfuHandler for DfuDemoDevice {
fn write_data(&mut self, offset: usize, data: &[u8]) {
// Nothing
}

fn complete_download(&mut self) {
// TODO: nothing
}

fn upload(&self, buffer: &mut [u8], offset: usize) -> usize {
todo!()
}

fn is_write_complete(&self) -> bool {
true
}
}

#[embassy_executor::main(entry = "qingke_rt::entry")]
async fn main(spawner: Spawner) -> ! {
// setup clocks
let cfg = Config {
rcc: ch32_hal::rcc::Config::SYSCLK_FREQ_144MHZ_HSI,
..Default::default()
};
let p = hal::init(cfg);
hal::embassy::init();

/* USB DRIVER SECION */
let mut buffer: [EndpointDataBuffer; 1] = core::array::from_fn(|_| EndpointDataBuffer::default());
let driver = Driver::new(p.OTG_FS, p.PA12, p.PA11, &mut buffer);

// Create embassy-usb Config
let mut config = embassy_usb::Config::new(0x6666, 0xcafe);
config.manufacturer = Some("Embassy");
config.product = Some("USB DFU Demo");
config.serial_number = Some("12345678");
config.max_power = 100;
config.max_packet_size_0 = 64;

// Required for windows compatibility.
// https://developer.nordicsemi.com/nRF_Connect_SDK/doc/1.9.1/kconfig/CONFIG_CDC_ACM_IAD.html#help
config.device_class = 0x00;
config.device_sub_class = 0x00;
config.device_protocol = 0x00;
config.composite_with_iads = false;

// Create embassy-usb DeviceBuilder using the driver and config.
// It needs some buffers for building the descriptors.
let mut config_descriptor = [0; 256];
let mut bos_descriptor = [0; 256];
// You can also add a Microsoft OS descriptor.
let mut msos_descriptor = [0; 256];
let mut control_buf = [0; 64];

let mut dfu_device_handler = DfuDemoDevice;
let mut request_handler = DfuRequestHandler {
inner: UsbDfuDevice::new(&mut dfu_device_handler),
};

let mut builder = Builder::new(
driver,
config,
&mut config_descriptor,
&mut bos_descriptor,
&mut msos_descriptor,
&mut control_buf,
);

let mut func = builder.function(0x00, 0x00, 0x00);
let mut iface = func.interface();
let mut alt = {
use usb_dfu_target::consts::*;
iface.alt_setting(USB_CLASS_APPN_SPEC, APPN_SPEC_SUBCLASS_DFU, DFU_PROTOCOL_DFU, None)
};
let mut attr = DfuAttributes::empty();
attr.set(DfuAttributes::CAN_DOWNLOAD, true);
alt.descriptor(
usb_dfu_target::consts::DESC_DFU_FUNCTIONAL,
&[
attr.bits(),
0xc4,
0x09, // 2500ms timeout, doesn't affect operation as DETACH not necessary in bootloader code
(BLOCK_SIZE & 0xff) as u8,
((BLOCK_SIZE & 0xff00) >> 8) as u8,
0x10,
0x01, // DFU 1.1
],
);

drop(func);
builder.handler(&mut request_handler);

// Build the builder.
let mut usb = builder.build();

// Run the USB device.
let usb_fut = usb.run();

// Run everything concurrently.
// If we had made everything `'static` above instead, we could do this using separate tasks instead.
usb_fut.await;
/* END USB DRIVER */
}

struct DfuRequestHandler<'h> {
inner: UsbDfuDevice<'h>,
}

impl<'h> Handler for DfuRequestHandler<'h> {
fn control_out(&mut self, req: embassy_usb::control::Request, buf: &[u8]) -> Option<OutResponse> {
if (req.request_type, req.recipient) != (RequestType::Class, Recipient::Interface) {
return None;
}

match DfuRequest::try_from(req.request) {
Ok(req) => match self.inner.handle_control_out(req, buf) {
Ok(_) => Some(OutResponse::Accepted),
Err(_) => Some(OutResponse::Rejected),
},
Err(_) => Some(OutResponse::Rejected),
}
}

fn control_in<'a>(
&'a mut self,
req: embassy_usb::control::Request,
buf: &'a mut [u8],
) -> Option<embassy_usb::control::InResponse<'a>> {
if (req.request_type, req.recipient) != (RequestType::Class, Recipient::Interface) {
return None;
}
match DfuRequest::try_from(req.request) {
Ok(req) => match self.inner.handle_control_in(req, buf) {
Ok(buf) => Some(InResponse::Accepted(buf)),
Err(_) => Some(InResponse::Rejected),
},
Err(_) => Some(InResponse::Rejected),
}
}
}
5 changes: 3 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,9 @@ pub mod spi;
pub mod timer;
pub mod usart;

#[cfg(usb)]
pub mod usb;

#[cfg(otg)]
pub mod otg_fs;
#[cfg(usbd)]
pub mod usbd;

Expand Down
73 changes: 73 additions & 0 deletions src/macros.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#![macro_use]
#![allow(unused_macros)]

macro_rules! dma_trait {
($signal:ident, $instance:path$(, $mode:path)?) => {
Expand Down Expand Up @@ -45,3 +46,75 @@ macro_rules! new_dma {
})
}};
}

#[collapse_debuginfo(yes)]
macro_rules! panic {
($($x:tt)*) => {
{
#[cfg(not(feature = "defmt"))]
::core::panic!($($x)*);
#[cfg(feature = "defmt")]
::defmt::panic!($($x)*);
}
};
}

#[collapse_debuginfo(yes)]
macro_rules! trace {
($s:literal $(, $x:expr)* $(,)?) => {
{
#[cfg(feature = "defmt")]
::defmt::trace!($s $(, $x)*);
#[cfg(not(feature = "defmt"))]
let _ = ($( & $x ),*);
}
};
}

#[collapse_debuginfo(yes)]
macro_rules! debug {
($s:literal $(, $x:expr)* $(,)?) => {
{
#[cfg(feature = "defmt")]
::defmt::debug!($s $(, $x)*);
#[cfg(not(feature = "defmt"))]
let _ = ($( & $x ),*);
}
};
}

#[collapse_debuginfo(yes)]
macro_rules! info {
($s:literal $(, $x:expr)* $(,)?) => {
{
#[cfg(feature = "defmt")]
::defmt::info!($s $(, $x)*);
#[cfg(not(feature = "defmt"))]
let _ = ($( & $x ),*);
}
};
}

#[collapse_debuginfo(yes)]
macro_rules! warn {
($s:literal $(, $x:expr)* $(,)?) => {
{
#[cfg(feature = "defmt")]
::defmt::warn!($s $(, $x)*);
#[cfg(not(feature = "defmt"))]
let _ = ($( & $x ),*);
}
};
}

#[collapse_debuginfo(yes)]
macro_rules! error {
($s:literal $(, $x:expr)* $(,)?) => {
{
#[cfg(feature = "defmt")]
::defmt::error!($s $(, $x)*);
#[cfg(not(feature = "defmt"))]
let _ = ($( & $x ),*);
}
};
}
Loading
Loading