diff options
| author | bors[bot] <26634292+bors[bot]@users.noreply.github.com> | 2022-04-24 20:47:37 +0000 |
|---|---|---|
| committer | GitHub <[email protected]> | 2022-04-24 20:47:37 +0000 |
| commit | a1746f4ddac734cd8912007b6155ca340df89f19 (patch) | |
| tree | eb92a11c250eee2797e14357a8baf5172d9d9dec | |
| parent | b578e060d731434e900b0e70adc5b560a2f595b4 (diff) | |
| parent | d409026b95c24c1582e17d3f40daea2b75cb9304 (diff) | |
Merge #717
717: WIP: USB CDC NCM (Ethernet over USB) r=Dirbaio a=Dirbaio
TODO:
- [x] Add support for string handling in `embassy-usb`, remove the MAC addr string hax
- [x] Harden parsing of incoming NTBs to avoid panics.
- [ ] Parse all datagrams in a NDP, not just the first. -- tricky, I've made it tell the host we support only one packet per NTB instead.
- [ ] Add support for all required control transfers. -- WONTFIX, seems no OS cares about those.
- [x] Works on Linux
- [x] Doesn't work on Android, make it work
- [x] Check if it works in Windows (Win10 has some sort of CDC NCM support afaict?) -- works on Win11, CDC-NCM not supported on Win10
- [x] Check if it works in MacOS (I don't know if it's supposed to) - WORKS
I won't add the `embassy-net` driver to `embassy-usb-ncm` for now because `embassy-net` buffer management will likely be refactored soon, so there's not much point to it.
Co-authored-by: Dario Nieuwenhuis <[email protected]>
| -rw-r--r-- | embassy-net/src/tcp_socket.rs | 6 | ||||
| -rw-r--r-- | embassy-usb-ncm/Cargo.toml | 19 | ||||
| -rw-r--r-- | embassy-usb-ncm/src/fmt.rs | 225 | ||||
| -rw-r--r-- | embassy-usb-ncm/src/lib.rs | 489 | ||||
| -rw-r--r-- | examples/nrf/Cargo.toml | 4 | ||||
| -rw-r--r-- | examples/nrf/src/bin/usb_ethernet.rs | 277 | ||||
| -rw-r--r-- | examples/nrf/src/bin/usb_hid_keyboard.rs | 4 | ||||
| -rw-r--r-- | examples/nrf/src/bin/usb_hid_mouse.rs | 5 | ||||
| -rw-r--r-- | examples/nrf/src/bin/usb_serial.rs | 7 | ||||
| -rw-r--r-- | examples/nrf/src/bin/usb_serial_multitask.rs | 7 |
10 files changed, 1032 insertions, 11 deletions
diff --git a/embassy-net/src/tcp_socket.rs b/embassy-net/src/tcp_socket.rs index 4836f8075..5637505d4 100644 --- a/embassy-net/src/tcp_socket.rs +++ b/embassy-net/src/tcp_socket.rs | |||
| @@ -58,7 +58,7 @@ impl<'a> TcpSocket<'a> { | |||
| 58 | .await | 58 | .await |
| 59 | } | 59 | } |
| 60 | 60 | ||
| 61 | pub async fn listen<T>(&mut self, local_endpoint: T) -> Result<()> | 61 | pub async fn accept<T>(&mut self, local_endpoint: T) -> Result<()> |
| 62 | where | 62 | where |
| 63 | T: Into<IpEndpoint>, | 63 | T: Into<IpEndpoint>, |
| 64 | { | 64 | { |
| @@ -66,9 +66,7 @@ impl<'a> TcpSocket<'a> { | |||
| 66 | 66 | ||
| 67 | futures::future::poll_fn(|cx| { | 67 | futures::future::poll_fn(|cx| { |
| 68 | self.with(|s, _| match s.state() { | 68 | self.with(|s, _| match s.state() { |
| 69 | TcpState::Closed | TcpState::TimeWait => Poll::Ready(Err(Error::Unaddressable)), | 69 | TcpState::Listen | TcpState::SynSent | TcpState::SynReceived => { |
| 70 | TcpState::Listen => Poll::Ready(Ok(())), | ||
| 71 | TcpState::SynSent | TcpState::SynReceived => { | ||
| 72 | s.register_send_waker(cx.waker()); | 70 | s.register_send_waker(cx.waker()); |
| 73 | Poll::Pending | 71 | Poll::Pending |
| 74 | } | 72 | } |
diff --git a/embassy-usb-ncm/Cargo.toml b/embassy-usb-ncm/Cargo.toml new file mode 100644 index 000000000..aaef01d6d --- /dev/null +++ b/embassy-usb-ncm/Cargo.toml | |||
| @@ -0,0 +1,19 @@ | |||
| 1 | [package] | ||
| 2 | name = "embassy-usb-ncm" | ||
| 3 | version = "0.1.0" | ||
| 4 | edition = "2021" | ||
| 5 | |||
| 6 | [package.metadata.embassy_docs] | ||
| 7 | src_base = "https://github.com/embassy-rs/embassy/blob/embassy-usb-ncm-v$VERSION/embassy-usb-ncm/src/" | ||
| 8 | src_base_git = "https://github.com/embassy-rs/embassy/blob/master/embassy-usb-ncm/src/" | ||
| 9 | features = ["defmt"] | ||
| 10 | flavors = [ | ||
| 11 | { name = "default", target = "thumbv7em-none-eabihf" }, | ||
| 12 | ] | ||
| 13 | |||
| 14 | [dependencies] | ||
| 15 | embassy = { version = "0.1.0", path = "../embassy" } | ||
| 16 | embassy-usb = { version = "0.1.0", path = "../embassy-usb" } | ||
| 17 | |||
| 18 | defmt = { version = "0.3", optional = true } | ||
| 19 | log = { version = "0.4.14", optional = true } | ||
diff --git a/embassy-usb-ncm/src/fmt.rs b/embassy-usb-ncm/src/fmt.rs new file mode 100644 index 000000000..066970813 --- /dev/null +++ b/embassy-usb-ncm/src/fmt.rs | |||
| @@ -0,0 +1,225 @@ | |||
| 1 | #![macro_use] | ||
| 2 | #![allow(unused_macros)] | ||
| 3 | |||
| 4 | #[cfg(all(feature = "defmt", feature = "log"))] | ||
| 5 | compile_error!("You may not enable both `defmt` and `log` features."); | ||
| 6 | |||
| 7 | macro_rules! assert { | ||
| 8 | ($($x:tt)*) => { | ||
| 9 | { | ||
| 10 | #[cfg(not(feature = "defmt"))] | ||
| 11 | ::core::assert!($($x)*); | ||
| 12 | #[cfg(feature = "defmt")] | ||
| 13 | ::defmt::assert!($($x)*); | ||
| 14 | } | ||
| 15 | }; | ||
| 16 | } | ||
| 17 | |||
| 18 | macro_rules! assert_eq { | ||
| 19 | ($($x:tt)*) => { | ||
| 20 | { | ||
| 21 | #[cfg(not(feature = "defmt"))] | ||
| 22 | ::core::assert_eq!($($x)*); | ||
| 23 | #[cfg(feature = "defmt")] | ||
| 24 | ::defmt::assert_eq!($($x)*); | ||
| 25 | } | ||
| 26 | }; | ||
| 27 | } | ||
| 28 | |||
| 29 | macro_rules! assert_ne { | ||
| 30 | ($($x:tt)*) => { | ||
| 31 | { | ||
| 32 | #[cfg(not(feature = "defmt"))] | ||
| 33 | ::core::assert_ne!($($x)*); | ||
| 34 | #[cfg(feature = "defmt")] | ||
| 35 | ::defmt::assert_ne!($($x)*); | ||
| 36 | } | ||
| 37 | }; | ||
| 38 | } | ||
| 39 | |||
| 40 | macro_rules! debug_assert { | ||
| 41 | ($($x:tt)*) => { | ||
| 42 | { | ||
| 43 | #[cfg(not(feature = "defmt"))] | ||
| 44 | ::core::debug_assert!($($x)*); | ||
| 45 | #[cfg(feature = "defmt")] | ||
| 46 | ::defmt::debug_assert!($($x)*); | ||
| 47 | } | ||
| 48 | }; | ||
| 49 | } | ||
| 50 | |||
| 51 | macro_rules! debug_assert_eq { | ||
| 52 | ($($x:tt)*) => { | ||
| 53 | { | ||
| 54 | #[cfg(not(feature = "defmt"))] | ||
| 55 | ::core::debug_assert_eq!($($x)*); | ||
| 56 | #[cfg(feature = "defmt")] | ||
| 57 | ::defmt::debug_assert_eq!($($x)*); | ||
| 58 | } | ||
| 59 | }; | ||
| 60 | } | ||
| 61 | |||
| 62 | macro_rules! debug_assert_ne { | ||
| 63 | ($($x:tt)*) => { | ||
| 64 | { | ||
| 65 | #[cfg(not(feature = "defmt"))] | ||
| 66 | ::core::debug_assert_ne!($($x)*); | ||
| 67 | #[cfg(feature = "defmt")] | ||
| 68 | ::defmt::debug_assert_ne!($($x)*); | ||
| 69 | } | ||
| 70 | }; | ||
| 71 | } | ||
| 72 | |||
| 73 | macro_rules! todo { | ||
| 74 | ($($x:tt)*) => { | ||
| 75 | { | ||
| 76 | #[cfg(not(feature = "defmt"))] | ||
| 77 | ::core::todo!($($x)*); | ||
| 78 | #[cfg(feature = "defmt")] | ||
| 79 | ::defmt::todo!($($x)*); | ||
| 80 | } | ||
| 81 | }; | ||
| 82 | } | ||
| 83 | |||
| 84 | macro_rules! unreachable { | ||
| 85 | ($($x:tt)*) => { | ||
| 86 | { | ||
| 87 | #[cfg(not(feature = "defmt"))] | ||
| 88 | ::core::unreachable!($($x)*); | ||
| 89 | #[cfg(feature = "defmt")] | ||
| 90 | ::defmt::unreachable!($($x)*); | ||
| 91 | } | ||
| 92 | }; | ||
| 93 | } | ||
| 94 | |||
| 95 | macro_rules! panic { | ||
| 96 | ($($x:tt)*) => { | ||
| 97 | { | ||
| 98 | #[cfg(not(feature = "defmt"))] | ||
| 99 | ::core::panic!($($x)*); | ||
| 100 | #[cfg(feature = "defmt")] | ||
| 101 | ::defmt::panic!($($x)*); | ||
| 102 | } | ||
| 103 | }; | ||
| 104 | } | ||
| 105 | |||
| 106 | macro_rules! trace { | ||
| 107 | ($s:literal $(, $x:expr)* $(,)?) => { | ||
| 108 | { | ||
| 109 | #[cfg(feature = "log")] | ||
| 110 | ::log::trace!($s $(, $x)*); | ||
| 111 | #[cfg(feature = "defmt")] | ||
| 112 | ::defmt::trace!($s $(, $x)*); | ||
| 113 | #[cfg(not(any(feature = "log", feature="defmt")))] | ||
| 114 | let _ = ($( & $x ),*); | ||
| 115 | } | ||
| 116 | }; | ||
| 117 | } | ||
| 118 | |||
| 119 | macro_rules! debug { | ||
| 120 | ($s:literal $(, $x:expr)* $(,)?) => { | ||
| 121 | { | ||
| 122 | #[cfg(feature = "log")] | ||
| 123 | ::log::debug!($s $(, $x)*); | ||
| 124 | #[cfg(feature = "defmt")] | ||
| 125 | ::defmt::debug!($s $(, $x)*); | ||
| 126 | #[cfg(not(any(feature = "log", feature="defmt")))] | ||
| 127 | let _ = ($( & $x ),*); | ||
| 128 | } | ||
| 129 | }; | ||
| 130 | } | ||
| 131 | |||
| 132 | macro_rules! info { | ||
| 133 | ($s:literal $(, $x:expr)* $(,)?) => { | ||
| 134 | { | ||
| 135 | #[cfg(feature = "log")] | ||
| 136 | ::log::info!($s $(, $x)*); | ||
| 137 | #[cfg(feature = "defmt")] | ||
| 138 | ::defmt::info!($s $(, $x)*); | ||
| 139 | #[cfg(not(any(feature = "log", feature="defmt")))] | ||
| 140 | let _ = ($( & $x ),*); | ||
| 141 | } | ||
| 142 | }; | ||
| 143 | } | ||
| 144 | |||
| 145 | macro_rules! warn { | ||
| 146 | ($s:literal $(, $x:expr)* $(,)?) => { | ||
| 147 | { | ||
| 148 | #[cfg(feature = "log")] | ||
| 149 | ::log::warn!($s $(, $x)*); | ||
| 150 | #[cfg(feature = "defmt")] | ||
| 151 | ::defmt::warn!($s $(, $x)*); | ||
| 152 | #[cfg(not(any(feature = "log", feature="defmt")))] | ||
| 153 | let _ = ($( & $x ),*); | ||
| 154 | } | ||
| 155 | }; | ||
| 156 | } | ||
| 157 | |||
| 158 | macro_rules! error { | ||
| 159 | ($s:literal $(, $x:expr)* $(,)?) => { | ||
| 160 | { | ||
| 161 | #[cfg(feature = "log")] | ||
| 162 | ::log::error!($s $(, $x)*); | ||
| 163 | #[cfg(feature = "defmt")] | ||
| 164 | ::defmt::error!($s $(, $x)*); | ||
| 165 | #[cfg(not(any(feature = "log", feature="defmt")))] | ||
| 166 | let _ = ($( & $x ),*); | ||
| 167 | } | ||
| 168 | }; | ||
| 169 | } | ||
| 170 | |||
| 171 | #[cfg(feature = "defmt")] | ||
| 172 | macro_rules! unwrap { | ||
| 173 | ($($x:tt)*) => { | ||
| 174 | ::defmt::unwrap!($($x)*) | ||
| 175 | }; | ||
| 176 | } | ||
| 177 | |||
| 178 | #[cfg(not(feature = "defmt"))] | ||
| 179 | macro_rules! unwrap { | ||
| 180 | ($arg:expr) => { | ||
| 181 | match $crate::fmt::Try::into_result($arg) { | ||
| 182 | ::core::result::Result::Ok(t) => t, | ||
| 183 | ::core::result::Result::Err(e) => { | ||
| 184 | ::core::panic!("unwrap of `{}` failed: {:?}", ::core::stringify!($arg), e); | ||
| 185 | } | ||
| 186 | } | ||
| 187 | }; | ||
| 188 | ($arg:expr, $($msg:expr),+ $(,)? ) => { | ||
| 189 | match $crate::fmt::Try::into_result($arg) { | ||
| 190 | ::core::result::Result::Ok(t) => t, | ||
| 191 | ::core::result::Result::Err(e) => { | ||
| 192 | ::core::panic!("unwrap of `{}` failed: {}: {:?}", ::core::stringify!($arg), ::core::format_args!($($msg,)*), e); | ||
| 193 | } | ||
| 194 | } | ||
| 195 | } | ||
| 196 | } | ||
| 197 | |||
| 198 | #[derive(Debug, Copy, Clone, Eq, PartialEq)] | ||
| 199 | pub struct NoneError; | ||
| 200 | |||
| 201 | pub trait Try { | ||
| 202 | type Ok; | ||
| 203 | type Error; | ||
| 204 | fn into_result(self) -> Result<Self::Ok, Self::Error>; | ||
| 205 | } | ||
| 206 | |||
| 207 | impl<T> Try for Option<T> { | ||
| 208 | type Ok = T; | ||
| 209 | type Error = NoneError; | ||
| 210 | |||
| 211 | #[inline] | ||
| 212 | fn into_result(self) -> Result<T, NoneError> { | ||
| 213 | self.ok_or(NoneError) | ||
| 214 | } | ||
| 215 | } | ||
| 216 | |||
| 217 | impl<T, E> Try for Result<T, E> { | ||
| 218 | type Ok = T; | ||
| 219 | type Error = E; | ||
| 220 | |||
| 221 | #[inline] | ||
| 222 | fn into_result(self) -> Self { | ||
| 223 | self | ||
| 224 | } | ||
| 225 | } | ||
diff --git a/embassy-usb-ncm/src/lib.rs b/embassy-usb-ncm/src/lib.rs new file mode 100644 index 000000000..3a5abee8d --- /dev/null +++ b/embassy-usb-ncm/src/lib.rs | |||
| @@ -0,0 +1,489 @@ | |||
| 1 | #![no_std] | ||
| 2 | |||
| 3 | // This mod MUST go first, so that the others see its macros. | ||
| 4 | pub(crate) mod fmt; | ||
| 5 | |||
| 6 | use core::cell::Cell; | ||
| 7 | use core::intrinsics::copy_nonoverlapping; | ||
| 8 | use core::mem::{size_of, MaybeUninit}; | ||
| 9 | use embassy_usb::control::{self, ControlHandler, InResponse, OutResponse, Request}; | ||
| 10 | use embassy_usb::driver::{Endpoint, EndpointError, EndpointIn, EndpointOut}; | ||
| 11 | use embassy_usb::{driver::Driver, types::*, Builder}; | ||
| 12 | |||
| 13 | /// This should be used as `device_class` when building the `UsbDevice`. | ||
| 14 | pub const USB_CLASS_CDC: u8 = 0x02; | ||
| 15 | |||
| 16 | const USB_CLASS_CDC_DATA: u8 = 0x0a; | ||
| 17 | const CDC_SUBCLASS_NCM: u8 = 0x0d; | ||
| 18 | |||
| 19 | const CDC_PROTOCOL_NONE: u8 = 0x00; | ||
| 20 | const CDC_PROTOCOL_NTB: u8 = 0x01; | ||
| 21 | |||
| 22 | const CS_INTERFACE: u8 = 0x24; | ||
| 23 | const CDC_TYPE_HEADER: u8 = 0x00; | ||
| 24 | const CDC_TYPE_UNION: u8 = 0x06; | ||
| 25 | const CDC_TYPE_ETHERNET: u8 = 0x0F; | ||
| 26 | const CDC_TYPE_NCM: u8 = 0x1A; | ||
| 27 | |||
| 28 | const REQ_SEND_ENCAPSULATED_COMMAND: u8 = 0x00; | ||
| 29 | //const REQ_GET_ENCAPSULATED_COMMAND: u8 = 0x01; | ||
| 30 | //const REQ_SET_ETHERNET_MULTICAST_FILTERS: u8 = 0x40; | ||
| 31 | //const REQ_SET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER: u8 = 0x41; | ||
| 32 | //const REQ_GET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER: u8 = 0x42; | ||
| 33 | //const REQ_SET_ETHERNET_PACKET_FILTER: u8 = 0x43; | ||
| 34 | //const REQ_GET_ETHERNET_STATISTIC: u8 = 0x44; | ||
| 35 | const REQ_GET_NTB_PARAMETERS: u8 = 0x80; | ||
| 36 | //const REQ_GET_NET_ADDRESS: u8 = 0x81; | ||
| 37 | //const REQ_SET_NET_ADDRESS: u8 = 0x82; | ||
| 38 | //const REQ_GET_NTB_FORMAT: u8 = 0x83; | ||
| 39 | //const REQ_SET_NTB_FORMAT: u8 = 0x84; | ||
| 40 | //const REQ_GET_NTB_INPUT_SIZE: u8 = 0x85; | ||
| 41 | const REQ_SET_NTB_INPUT_SIZE: u8 = 0x86; | ||
| 42 | //const REQ_GET_MAX_DATAGRAM_SIZE: u8 = 0x87; | ||
| 43 | //const REQ_SET_MAX_DATAGRAM_SIZE: u8 = 0x88; | ||
| 44 | //const REQ_GET_CRC_MODE: u8 = 0x89; | ||
| 45 | //const REQ_SET_CRC_MODE: u8 = 0x8A; | ||
| 46 | |||
| 47 | //const NOTIF_MAX_PACKET_SIZE: u16 = 8; | ||
| 48 | //const NOTIF_POLL_INTERVAL: u8 = 20; | ||
| 49 | |||
| 50 | const NTB_MAX_SIZE: usize = 2048; | ||
| 51 | const SIG_NTH: u32 = 0x484d434e; | ||
| 52 | const SIG_NDP_NO_FCS: u32 = 0x304d434e; | ||
| 53 | const SIG_NDP_WITH_FCS: u32 = 0x314d434e; | ||
| 54 | |||
| 55 | const ALTERNATE_SETTING_DISABLED: u8 = 0x00; | ||
| 56 | const ALTERNATE_SETTING_ENABLED: u8 = 0x01; | ||
| 57 | |||
| 58 | /// Simple NTB header (NTH+NDP all in one) for sending packets | ||
| 59 | #[repr(packed)] | ||
| 60 | #[allow(unused)] | ||
| 61 | struct NtbOutHeader { | ||
| 62 | // NTH | ||
| 63 | nth_sig: u32, | ||
| 64 | nth_len: u16, | ||
| 65 | nth_seq: u16, | ||
| 66 | nth_total_len: u16, | ||
| 67 | nth_first_index: u16, | ||
| 68 | |||
| 69 | // NDP | ||
| 70 | ndp_sig: u32, | ||
| 71 | ndp_len: u16, | ||
| 72 | ndp_next_index: u16, | ||
| 73 | ndp_datagram_index: u16, | ||
| 74 | ndp_datagram_len: u16, | ||
| 75 | ndp_term1: u16, | ||
| 76 | ndp_term2: u16, | ||
| 77 | } | ||
| 78 | |||
| 79 | #[repr(packed)] | ||
| 80 | #[allow(unused)] | ||
| 81 | struct NtbParameters { | ||
| 82 | length: u16, | ||
| 83 | formats_supported: u16, | ||
| 84 | in_params: NtbParametersDir, | ||
| 85 | out_params: NtbParametersDir, | ||
| 86 | } | ||
| 87 | |||
| 88 | #[repr(packed)] | ||
| 89 | #[allow(unused)] | ||
| 90 | struct NtbParametersDir { | ||
| 91 | max_size: u32, | ||
| 92 | divisor: u16, | ||
| 93 | payload_remainder: u16, | ||
| 94 | out_alignment: u16, | ||
| 95 | max_datagram_count: u16, | ||
| 96 | } | ||
| 97 | |||
| 98 | fn byteify<T>(buf: &mut [u8], data: T) -> &[u8] { | ||
| 99 | let len = size_of::<T>(); | ||
| 100 | unsafe { copy_nonoverlapping(&data as *const _ as *const u8, buf.as_mut_ptr(), len) } | ||
| 101 | &buf[..len] | ||
| 102 | } | ||
| 103 | |||
| 104 | pub struct State<'a> { | ||
| 105 | comm_control: MaybeUninit<CommControl<'a>>, | ||
| 106 | data_control: MaybeUninit<DataControl>, | ||
| 107 | shared: ControlShared, | ||
| 108 | } | ||
| 109 | |||
| 110 | impl<'a> State<'a> { | ||
| 111 | pub fn new() -> Self { | ||
| 112 | Self { | ||
| 113 | comm_control: MaybeUninit::uninit(), | ||
| 114 | data_control: MaybeUninit::uninit(), | ||
| 115 | shared: Default::default(), | ||
| 116 | } | ||
| 117 | } | ||
| 118 | } | ||
| 119 | |||
| 120 | /// Shared data between Control and CdcAcmClass | ||
| 121 | struct ControlShared { | ||
| 122 | mac_addr: Cell<[u8; 6]>, | ||
| 123 | } | ||
| 124 | |||
| 125 | impl Default for ControlShared { | ||
| 126 | fn default() -> Self { | ||
| 127 | ControlShared { | ||
| 128 | mac_addr: Cell::new([0; 6]), | ||
| 129 | } | ||
| 130 | } | ||
| 131 | } | ||
| 132 | |||
| 133 | struct CommControl<'a> { | ||
| 134 | mac_addr_string: StringIndex, | ||
| 135 | shared: &'a ControlShared, | ||
| 136 | } | ||
| 137 | |||
| 138 | impl<'d> ControlHandler for CommControl<'d> { | ||
| 139 | fn control_out(&mut self, req: control::Request, _data: &[u8]) -> OutResponse { | ||
| 140 | match req.request { | ||
| 141 | REQ_SEND_ENCAPSULATED_COMMAND => { | ||
| 142 | // We don't actually support encapsulated commands but pretend we do for standards | ||
| 143 | // compatibility. | ||
| 144 | OutResponse::Accepted | ||
| 145 | } | ||
| 146 | REQ_SET_NTB_INPUT_SIZE => { | ||
| 147 | // TODO | ||
| 148 | OutResponse::Accepted | ||
| 149 | } | ||
| 150 | _ => OutResponse::Rejected, | ||
| 151 | } | ||
| 152 | } | ||
| 153 | |||
| 154 | fn control_in<'a>(&'a mut self, req: Request, buf: &'a mut [u8]) -> InResponse<'a> { | ||
| 155 | match req.request { | ||
| 156 | REQ_GET_NTB_PARAMETERS => { | ||
| 157 | let res = NtbParameters { | ||
| 158 | length: size_of::<NtbParameters>() as _, | ||
| 159 | formats_supported: 1, // only 16bit, | ||
| 160 | in_params: NtbParametersDir { | ||
| 161 | max_size: NTB_MAX_SIZE as _, | ||
| 162 | divisor: 4, | ||
| 163 | payload_remainder: 0, | ||
| 164 | out_alignment: 4, | ||
| 165 | max_datagram_count: 0, // not used | ||
| 166 | }, | ||
| 167 | out_params: NtbParametersDir { | ||
| 168 | max_size: NTB_MAX_SIZE as _, | ||
| 169 | divisor: 4, | ||
| 170 | payload_remainder: 0, | ||
| 171 | out_alignment: 4, | ||
| 172 | max_datagram_count: 1, // We only decode 1 packet per NTB | ||
| 173 | }, | ||
| 174 | }; | ||
| 175 | InResponse::Accepted(byteify(buf, res)) | ||
| 176 | } | ||
| 177 | _ => InResponse::Rejected, | ||
| 178 | } | ||
| 179 | } | ||
| 180 | |||
| 181 | fn get_string<'a>( | ||
| 182 | &'a mut self, | ||
| 183 | index: StringIndex, | ||
| 184 | _lang_id: u16, | ||
| 185 | buf: &'a mut [u8], | ||
| 186 | ) -> Option<&'a str> { | ||
| 187 | if index == self.mac_addr_string { | ||
| 188 | let mac_addr = self.shared.mac_addr.get(); | ||
| 189 | for i in 0..12 { | ||
| 190 | let n = (mac_addr[i / 2] >> ((1 - i % 2) * 4)) & 0xF; | ||
| 191 | buf[i] = match n { | ||
| 192 | 0x0..=0x9 => b'0' + n, | ||
| 193 | 0xA..=0xF => b'A' + n - 0xA, | ||
| 194 | _ => unreachable!(), | ||
| 195 | } | ||
| 196 | } | ||
| 197 | |||
| 198 | Some(unsafe { core::str::from_utf8_unchecked(&buf[..12]) }) | ||
| 199 | } else { | ||
| 200 | warn!("unknown string index requested"); | ||
| 201 | None | ||
| 202 | } | ||
| 203 | } | ||
| 204 | } | ||
| 205 | |||
| 206 | struct DataControl {} | ||
| 207 | |||
| 208 | impl ControlHandler for DataControl { | ||
| 209 | fn set_alternate_setting(&mut self, alternate_setting: u8) { | ||
| 210 | match alternate_setting { | ||
| 211 | ALTERNATE_SETTING_ENABLED => info!("ncm: interface enabled"), | ||
| 212 | ALTERNATE_SETTING_DISABLED => info!("ncm: interface disabled"), | ||
| 213 | _ => unreachable!(), | ||
| 214 | } | ||
| 215 | } | ||
| 216 | } | ||
| 217 | |||
| 218 | pub struct CdcNcmClass<'d, D: Driver<'d>> { | ||
| 219 | _comm_if: InterfaceNumber, | ||
| 220 | comm_ep: D::EndpointIn, | ||
| 221 | |||
| 222 | data_if: InterfaceNumber, | ||
| 223 | read_ep: D::EndpointOut, | ||
| 224 | write_ep: D::EndpointIn, | ||
| 225 | |||
| 226 | _control: &'d ControlShared, | ||
| 227 | } | ||
| 228 | |||
| 229 | impl<'d, D: Driver<'d>> CdcNcmClass<'d, D> { | ||
| 230 | pub fn new( | ||
| 231 | builder: &mut Builder<'d, D>, | ||
| 232 | state: &'d mut State<'d>, | ||
| 233 | mac_address: [u8; 6], | ||
| 234 | max_packet_size: u16, | ||
| 235 | ) -> Self { | ||
| 236 | let control_shared = &state.shared; | ||
| 237 | control_shared.mac_addr.set(mac_address); | ||
| 238 | |||
| 239 | let mut func = builder.function(USB_CLASS_CDC, CDC_SUBCLASS_NCM, CDC_PROTOCOL_NONE); | ||
| 240 | |||
| 241 | // Control interface | ||
| 242 | let mut iface = func.interface(); | ||
| 243 | let mac_addr_string = iface.string(); | ||
| 244 | iface.handler(state.comm_control.write(CommControl { | ||
| 245 | mac_addr_string, | ||
| 246 | shared: &control_shared, | ||
| 247 | })); | ||
| 248 | let comm_if = iface.interface_number(); | ||
| 249 | let mut alt = iface.alt_setting(USB_CLASS_CDC, CDC_SUBCLASS_NCM, CDC_PROTOCOL_NONE); | ||
| 250 | |||
| 251 | alt.descriptor( | ||
| 252 | CS_INTERFACE, | ||
| 253 | &[ | ||
| 254 | CDC_TYPE_HEADER, // bDescriptorSubtype | ||
| 255 | 0x10, | ||
| 256 | 0x01, // bcdCDC (1.10) | ||
| 257 | ], | ||
| 258 | ); | ||
| 259 | alt.descriptor( | ||
| 260 | CS_INTERFACE, | ||
| 261 | &[ | ||
| 262 | CDC_TYPE_UNION, // bDescriptorSubtype | ||
| 263 | comm_if.into(), // bControlInterface | ||
| 264 | u8::from(comm_if) + 1, // bSubordinateInterface | ||
| 265 | ], | ||
| 266 | ); | ||
| 267 | alt.descriptor( | ||
| 268 | CS_INTERFACE, | ||
| 269 | &[ | ||
| 270 | CDC_TYPE_ETHERNET, // bDescriptorSubtype | ||
| 271 | mac_addr_string.into(), // iMACAddress | ||
| 272 | 0, // bmEthernetStatistics | ||
| 273 | 0, // | | ||
| 274 | 0, // | | ||
| 275 | 0, // | | ||
| 276 | 0xea, // wMaxSegmentSize = 1514 | ||
| 277 | 0x05, // | | ||
| 278 | 0, // wNumberMCFilters | ||
| 279 | 0, // | | ||
| 280 | 0, // bNumberPowerFilters | ||
| 281 | ], | ||
| 282 | ); | ||
| 283 | alt.descriptor( | ||
| 284 | CS_INTERFACE, | ||
| 285 | &[ | ||
| 286 | CDC_TYPE_NCM, // bDescriptorSubtype | ||
| 287 | 0x00, // bcdNCMVersion | ||
| 288 | 0x01, // | | ||
| 289 | 0, // bmNetworkCapabilities | ||
| 290 | ], | ||
| 291 | ); | ||
| 292 | |||
| 293 | let comm_ep = alt.endpoint_interrupt_in(8, 255); | ||
| 294 | |||
| 295 | // Data interface | ||
| 296 | let mut iface = func.interface(); | ||
| 297 | iface.handler(state.data_control.write(DataControl {})); | ||
| 298 | let data_if = iface.interface_number(); | ||
| 299 | let _alt = iface.alt_setting(USB_CLASS_CDC_DATA, 0x00, CDC_PROTOCOL_NTB); | ||
| 300 | let mut alt = iface.alt_setting(USB_CLASS_CDC_DATA, 0x00, CDC_PROTOCOL_NTB); | ||
| 301 | let read_ep = alt.endpoint_bulk_out(max_packet_size); | ||
| 302 | let write_ep = alt.endpoint_bulk_in(max_packet_size); | ||
| 303 | |||
| 304 | CdcNcmClass { | ||
| 305 | _comm_if: comm_if, | ||
| 306 | comm_ep, | ||
| 307 | data_if, | ||
| 308 | read_ep, | ||
| 309 | write_ep, | ||
| 310 | _control: control_shared, | ||
| 311 | } | ||
| 312 | } | ||
| 313 | |||
| 314 | pub fn split(self) -> (Sender<'d, D>, Receiver<'d, D>) { | ||
| 315 | ( | ||
| 316 | Sender { | ||
| 317 | write_ep: self.write_ep, | ||
| 318 | seq: 0, | ||
| 319 | }, | ||
| 320 | Receiver { | ||
| 321 | data_if: self.data_if, | ||
| 322 | comm_ep: self.comm_ep, | ||
| 323 | read_ep: self.read_ep, | ||
| 324 | }, | ||
| 325 | ) | ||
| 326 | } | ||
| 327 | } | ||
| 328 | |||
| 329 | pub struct Sender<'d, D: Driver<'d>> { | ||
| 330 | write_ep: D::EndpointIn, | ||
| 331 | seq: u16, | ||
| 332 | } | ||
| 333 | |||
| 334 | impl<'d, D: Driver<'d>> Sender<'d, D> { | ||
| 335 | pub async fn write_packet(&mut self, data: &[u8]) -> Result<(), EndpointError> { | ||
| 336 | let seq = self.seq; | ||
| 337 | self.seq = self.seq.wrapping_add(1); | ||
| 338 | |||
| 339 | const MAX_PACKET_SIZE: usize = 64; // TODO unhardcode | ||
| 340 | const OUT_HEADER_LEN: usize = 28; | ||
| 341 | |||
| 342 | let header = NtbOutHeader { | ||
| 343 | nth_sig: SIG_NTH, | ||
| 344 | nth_len: 0x0c, | ||
| 345 | nth_seq: seq, | ||
| 346 | nth_total_len: (data.len() + OUT_HEADER_LEN) as u16, | ||
| 347 | nth_first_index: 0x0c, | ||
| 348 | |||
| 349 | ndp_sig: SIG_NDP_NO_FCS, | ||
| 350 | ndp_len: 0x10, | ||
| 351 | ndp_next_index: 0x00, | ||
| 352 | ndp_datagram_index: OUT_HEADER_LEN as u16, | ||
| 353 | ndp_datagram_len: data.len() as u16, | ||
| 354 | ndp_term1: 0x00, | ||
| 355 | ndp_term2: 0x00, | ||
| 356 | }; | ||
| 357 | |||
| 358 | // Build first packet on a buffer, send next packets straight from `data`. | ||
| 359 | let mut buf = [0; MAX_PACKET_SIZE]; | ||
| 360 | let n = byteify(&mut buf, header); | ||
| 361 | assert_eq!(n.len(), OUT_HEADER_LEN); | ||
| 362 | |||
| 363 | if OUT_HEADER_LEN + data.len() < MAX_PACKET_SIZE { | ||
| 364 | // First packet is not full, just send it. | ||
| 365 | // No need to send ZLP because it's short for sure. | ||
| 366 | buf[OUT_HEADER_LEN..][..data.len()].copy_from_slice(data); | ||
| 367 | self.write_ep | ||
| 368 | .write(&buf[..OUT_HEADER_LEN + data.len()]) | ||
| 369 | .await?; | ||
| 370 | } else { | ||
| 371 | let (d1, d2) = data.split_at(MAX_PACKET_SIZE - OUT_HEADER_LEN); | ||
| 372 | |||
| 373 | buf[OUT_HEADER_LEN..].copy_from_slice(d1); | ||
| 374 | self.write_ep.write(&buf).await?; | ||
| 375 | |||
| 376 | for chunk in d2.chunks(MAX_PACKET_SIZE) { | ||
| 377 | self.write_ep.write(&chunk).await?; | ||
| 378 | } | ||
| 379 | |||
| 380 | // Send ZLP if needed. | ||
| 381 | if d2.len() % MAX_PACKET_SIZE == 0 { | ||
| 382 | self.write_ep.write(&[]).await?; | ||
| 383 | } | ||
| 384 | } | ||
| 385 | |||
| 386 | Ok(()) | ||
| 387 | } | ||
| 388 | } | ||
| 389 | |||
| 390 | pub struct Receiver<'d, D: Driver<'d>> { | ||
| 391 | data_if: InterfaceNumber, | ||
| 392 | comm_ep: D::EndpointIn, | ||
| 393 | read_ep: D::EndpointOut, | ||
| 394 | } | ||
| 395 | |||
| 396 | impl<'d, D: Driver<'d>> Receiver<'d, D> { | ||
| 397 | /// Reads a single packet from the OUT endpoint. | ||
| 398 | pub async fn read_packet(&mut self, buf: &mut [u8]) -> Result<usize, EndpointError> { | ||
| 399 | // Retry loop | ||
| 400 | loop { | ||
| 401 | // read NTB | ||
| 402 | let mut ntb = [0u8; NTB_MAX_SIZE]; | ||
| 403 | let mut pos = 0; | ||
| 404 | loop { | ||
| 405 | let n = self.read_ep.read(&mut ntb[pos..]).await?; | ||
| 406 | pos += n; | ||
| 407 | if n < self.read_ep.info().max_packet_size as usize || pos == NTB_MAX_SIZE { | ||
| 408 | break; | ||
| 409 | } | ||
| 410 | } | ||
| 411 | |||
| 412 | let ntb = &ntb[..pos]; | ||
| 413 | |||
| 414 | // Process NTB header (NTH) | ||
| 415 | let nth = match ntb.get(..12) { | ||
| 416 | Some(x) => x, | ||
| 417 | None => { | ||
| 418 | warn!("Received too short NTB"); | ||
| 419 | continue; | ||
| 420 | } | ||
| 421 | }; | ||
| 422 | let sig = u32::from_le_bytes(nth[0..4].try_into().unwrap()); | ||
| 423 | if sig != SIG_NTH { | ||
| 424 | warn!("Received bad NTH sig."); | ||
| 425 | continue; | ||
| 426 | } | ||
| 427 | let ndp_idx = u16::from_le_bytes(nth[10..12].try_into().unwrap()) as usize; | ||
| 428 | |||
| 429 | // Process NTB Datagram Pointer (NDP) | ||
| 430 | let ndp = match ntb.get(ndp_idx..ndp_idx + 12) { | ||
| 431 | Some(x) => x, | ||
| 432 | None => { | ||
| 433 | warn!("NTH has an NDP pointer out of range."); | ||
| 434 | continue; | ||
| 435 | } | ||
| 436 | }; | ||
| 437 | let sig = u32::from_le_bytes(ndp[0..4].try_into().unwrap()); | ||
| 438 | if sig != SIG_NDP_NO_FCS && sig != SIG_NDP_WITH_FCS { | ||
| 439 | warn!("Received bad NDP sig."); | ||
| 440 | continue; | ||
| 441 | } | ||
| 442 | let datagram_index = u16::from_le_bytes(ndp[8..10].try_into().unwrap()) as usize; | ||
| 443 | let datagram_len = u16::from_le_bytes(ndp[10..12].try_into().unwrap()) as usize; | ||
| 444 | |||
| 445 | if datagram_index == 0 || datagram_len == 0 { | ||
| 446 | // empty, ignore. This is allowed by the spec, so don't warn. | ||
| 447 | continue; | ||
| 448 | } | ||
| 449 | |||
| 450 | // Process actual datagram, finally. | ||
| 451 | let datagram = match ntb.get(datagram_index..datagram_index + datagram_len) { | ||
| 452 | Some(x) => x, | ||
| 453 | None => { | ||
| 454 | warn!("NDP has a datagram pointer out of range."); | ||
| 455 | continue; | ||
| 456 | } | ||
| 457 | }; | ||
| 458 | buf[..datagram_len].copy_from_slice(datagram); | ||
| 459 | |||
| 460 | return Ok(datagram_len); | ||
| 461 | } | ||
| 462 | } | ||
| 463 | |||
| 464 | /// Waits for the USB host to enable this interface | ||
| 465 | pub async fn wait_connection(&mut self) -> Result<(), EndpointError> { | ||
| 466 | loop { | ||
| 467 | self.read_ep.wait_enabled().await; | ||
| 468 | self.comm_ep.wait_enabled().await; | ||
| 469 | |||
| 470 | let buf = [ | ||
| 471 | 0xA1, //bmRequestType | ||
| 472 | 0x00, //bNotificationType = NETWORK_CONNECTION | ||
| 473 | 0x01, // wValue = connected | ||
| 474 | 0x00, | ||
| 475 | self.data_if.into(), // wIndex = interface | ||
| 476 | 0x00, | ||
| 477 | 0x00, // wLength | ||
| 478 | 0x00, | ||
| 479 | ]; | ||
| 480 | match self.comm_ep.write(&buf).await { | ||
| 481 | Ok(()) => break, // Done! | ||
| 482 | Err(EndpointError::Disabled) => {} // Got disabled again, wait again. | ||
| 483 | Err(e) => return Err(e), | ||
| 484 | } | ||
| 485 | } | ||
| 486 | |||
| 487 | Ok(()) | ||
| 488 | } | ||
| 489 | } | ||
diff --git a/examples/nrf/Cargo.toml b/examples/nrf/Cargo.toml index e944c171a..4258544f0 100644 --- a/examples/nrf/Cargo.toml +++ b/examples/nrf/Cargo.toml | |||
| @@ -6,14 +6,16 @@ version = "0.1.0" | |||
| 6 | 6 | ||
| 7 | [features] | 7 | [features] |
| 8 | default = ["nightly"] | 8 | default = ["nightly"] |
| 9 | nightly = ["embassy-nrf/nightly", "embassy-nrf/unstable-traits", "embassy-usb", "embassy-usb-serial", "embassy-usb-hid"] | 9 | nightly = ["embassy-nrf/nightly", "embassy-nrf/unstable-traits", "embassy-usb", "embassy-usb-serial", "embassy-usb-hid", "embassy-usb-ncm"] |
| 10 | 10 | ||
| 11 | [dependencies] | 11 | [dependencies] |
| 12 | embassy = { version = "0.1.0", path = "../../embassy", features = ["defmt", "defmt-timestamp-uptime"] } | 12 | embassy = { version = "0.1.0", path = "../../embassy", features = ["defmt", "defmt-timestamp-uptime"] } |
| 13 | embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac"] } | 13 | embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac"] } |
| 14 | embassy-net = { version = "0.1.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", "pool-16"] } | ||
| 14 | embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"], optional = true } | 15 | embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"], optional = true } |
| 15 | embassy-usb-serial = { version = "0.1.0", path = "../../embassy-usb-serial", features = ["defmt"], optional = true } | 16 | embassy-usb-serial = { version = "0.1.0", path = "../../embassy-usb-serial", features = ["defmt"], optional = true } |
| 16 | embassy-usb-hid = { version = "0.1.0", path = "../../embassy-usb-hid", features = ["defmt"], optional = true } | 17 | embassy-usb-hid = { version = "0.1.0", path = "../../embassy-usb-hid", features = ["defmt"], optional = true } |
| 18 | embassy-usb-ncm = { version = "0.1.0", path = "../../embassy-usb-ncm", features = ["defmt"], optional = true } | ||
| 17 | 19 | ||
| 18 | defmt = "0.3" | 20 | defmt = "0.3" |
| 19 | defmt-rtt = "0.3" | 21 | defmt-rtt = "0.3" |
diff --git a/examples/nrf/src/bin/usb_ethernet.rs b/examples/nrf/src/bin/usb_ethernet.rs new file mode 100644 index 000000000..70460d23c --- /dev/null +++ b/examples/nrf/src/bin/usb_ethernet.rs | |||
| @@ -0,0 +1,277 @@ | |||
| 1 | #![no_std] | ||
| 2 | #![no_main] | ||
| 3 | #![feature(generic_associated_types)] | ||
| 4 | #![feature(type_alias_impl_trait)] | ||
| 5 | |||
| 6 | use core::mem; | ||
| 7 | use core::sync::atomic::{AtomicBool, Ordering}; | ||
| 8 | use core::task::Waker; | ||
| 9 | use defmt::*; | ||
| 10 | use embassy::blocking_mutex::raw::ThreadModeRawMutex; | ||
| 11 | use embassy::channel::Channel; | ||
| 12 | use embassy::executor::Spawner; | ||
| 13 | use embassy::io::{AsyncBufReadExt, AsyncWriteExt}; | ||
| 14 | use embassy::util::Forever; | ||
| 15 | use embassy_net::{PacketBox, PacketBoxExt, PacketBuf, TcpSocket}; | ||
| 16 | use embassy_nrf::pac; | ||
| 17 | use embassy_nrf::usb::Driver; | ||
| 18 | use embassy_nrf::Peripherals; | ||
| 19 | use embassy_nrf::{interrupt, peripherals}; | ||
| 20 | use embassy_usb::{Builder, Config, UsbDevice}; | ||
| 21 | use embassy_usb_ncm::{CdcNcmClass, Receiver, Sender, State}; | ||
| 22 | |||
| 23 | use defmt_rtt as _; // global logger | ||
| 24 | use panic_probe as _; | ||
| 25 | |||
| 26 | type MyDriver = Driver<'static, peripherals::USBD>; | ||
| 27 | |||
| 28 | #[embassy::task] | ||
| 29 | async fn usb_task(mut device: UsbDevice<'static, MyDriver>) -> ! { | ||
| 30 | device.run().await | ||
| 31 | } | ||
| 32 | |||
| 33 | #[embassy::task] | ||
| 34 | async fn usb_ncm_rx_task(mut class: Receiver<'static, MyDriver>) { | ||
| 35 | loop { | ||
| 36 | warn!("WAITING for connection"); | ||
| 37 | LINK_UP.store(false, Ordering::Relaxed); | ||
| 38 | |||
| 39 | class.wait_connection().await.unwrap(); | ||
| 40 | |||
| 41 | warn!("Connected"); | ||
| 42 | LINK_UP.store(true, Ordering::Relaxed); | ||
| 43 | |||
| 44 | loop { | ||
| 45 | let mut p = unwrap!(PacketBox::new(embassy_net::Packet::new())); | ||
| 46 | let n = match class.read_packet(&mut p[..]).await { | ||
| 47 | Ok(n) => n, | ||
| 48 | Err(e) => { | ||
| 49 | warn!("error reading packet: {:?}", e); | ||
| 50 | break; | ||
| 51 | } | ||
| 52 | }; | ||
| 53 | |||
| 54 | let buf = p.slice(0..n); | ||
| 55 | if RX_CHANNEL.try_send(buf).is_err() { | ||
| 56 | warn!("Failed pushing rx'd packet to channel."); | ||
| 57 | } | ||
| 58 | } | ||
| 59 | } | ||
| 60 | } | ||
| 61 | |||
| 62 | #[embassy::task] | ||
| 63 | async fn usb_ncm_tx_task(mut class: Sender<'static, MyDriver>) { | ||
| 64 | loop { | ||
| 65 | let pkt = TX_CHANNEL.recv().await; | ||
| 66 | if let Err(e) = class.write_packet(&pkt[..]).await { | ||
| 67 | warn!("Failed to TX packet: {:?}", e); | ||
| 68 | } | ||
| 69 | } | ||
| 70 | } | ||
| 71 | |||
| 72 | #[embassy::task] | ||
| 73 | async fn net_task() -> ! { | ||
| 74 | embassy_net::run().await | ||
| 75 | } | ||
| 76 | |||
| 77 | #[embassy::main] | ||
| 78 | async fn main(spawner: Spawner, p: Peripherals) { | ||
| 79 | let clock: pac::CLOCK = unsafe { mem::transmute(()) }; | ||
| 80 | let power: pac::POWER = unsafe { mem::transmute(()) }; | ||
| 81 | |||
| 82 | info!("Enabling ext hfosc..."); | ||
| 83 | clock.tasks_hfclkstart.write(|w| unsafe { w.bits(1) }); | ||
| 84 | while clock.events_hfclkstarted.read().bits() != 1 {} | ||
| 85 | |||
| 86 | info!("Waiting for vbus..."); | ||
| 87 | while !power.usbregstatus.read().vbusdetect().is_vbus_present() {} | ||
| 88 | info!("vbus OK"); | ||
| 89 | |||
| 90 | // Create the driver, from the HAL. | ||
| 91 | let irq = interrupt::take!(USBD); | ||
| 92 | let driver = Driver::new(p.USBD, irq); | ||
| 93 | |||
| 94 | // Create embassy-usb Config | ||
| 95 | let mut config = Config::new(0xc0de, 0xcafe); | ||
| 96 | config.manufacturer = Some("Embassy"); | ||
| 97 | config.product = Some("USB-Ethernet example"); | ||
| 98 | config.serial_number = Some("12345678"); | ||
| 99 | config.max_power = 100; | ||
| 100 | config.max_packet_size_0 = 64; | ||
| 101 | |||
| 102 | // Required for Windows support. | ||
| 103 | config.composite_with_iads = true; | ||
| 104 | config.device_class = 0xEF; | ||
| 105 | config.device_sub_class = 0x02; | ||
| 106 | config.device_protocol = 0x01; | ||
| 107 | |||
| 108 | struct Resources { | ||
| 109 | device_descriptor: [u8; 256], | ||
| 110 | config_descriptor: [u8; 256], | ||
| 111 | bos_descriptor: [u8; 256], | ||
| 112 | control_buf: [u8; 128], | ||
| 113 | serial_state: State<'static>, | ||
| 114 | } | ||
| 115 | static RESOURCES: Forever<Resources> = Forever::new(); | ||
| 116 | let res = RESOURCES.put(Resources { | ||
| 117 | device_descriptor: [0; 256], | ||
| 118 | config_descriptor: [0; 256], | ||
| 119 | bos_descriptor: [0; 256], | ||
| 120 | control_buf: [0; 128], | ||
| 121 | serial_state: State::new(), | ||
| 122 | }); | ||
| 123 | |||
| 124 | // Create embassy-usb DeviceBuilder using the driver and config. | ||
| 125 | let mut builder = Builder::new( | ||
| 126 | driver, | ||
| 127 | config, | ||
| 128 | &mut res.device_descriptor, | ||
| 129 | &mut res.config_descriptor, | ||
| 130 | &mut res.bos_descriptor, | ||
| 131 | &mut res.control_buf, | ||
| 132 | None, | ||
| 133 | ); | ||
| 134 | |||
| 135 | // WARNINGS for Android ethernet tethering: | ||
| 136 | // - On Pixel 4a, it refused to work on Android 11, worked on Android 12. | ||
| 137 | // - if the host's MAC address has the "locally-administered" bit set (bit 1 of first byte), | ||
| 138 | // it doesn't work! The "Ethernet tethering" option in settings doesn't get enabled. | ||
| 139 | // This is due to regex spaghetti: https://android.googlesource.com/platform/frameworks/base/+/refs/tags/android-mainline-12.0.0_r84/core/res/res/values/config.xml#417 | ||
| 140 | // and this nonsense in the linux kernel: https://github.com/torvalds/linux/blob/c00c5e1d157bec0ef0b0b59aa5482eb8dc7e8e49/drivers/net/usb/usbnet.c#L1751-L1757 | ||
| 141 | |||
| 142 | // Our MAC addr. | ||
| 143 | let our_mac_addr = [0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC]; | ||
| 144 | // Host's MAC addr. This is the MAC the host "thinks" its USB-to-ethernet adapter has. | ||
| 145 | let host_mac_addr = [0x88, 0x88, 0x88, 0x88, 0x88, 0x88]; | ||
| 146 | |||
| 147 | // Create classes on the builder. | ||
| 148 | let class = CdcNcmClass::new(&mut builder, &mut res.serial_state, host_mac_addr, 64); | ||
| 149 | |||
| 150 | // Build the builder. | ||
| 151 | let usb = builder.build(); | ||
| 152 | |||
| 153 | unwrap!(spawner.spawn(usb_task(usb))); | ||
| 154 | |||
| 155 | let (tx, rx) = class.split(); | ||
| 156 | unwrap!(spawner.spawn(usb_ncm_rx_task(rx))); | ||
| 157 | unwrap!(spawner.spawn(usb_ncm_tx_task(tx))); | ||
| 158 | |||
| 159 | // Init embassy-net | ||
| 160 | struct NetResources { | ||
| 161 | resources: embassy_net::StackResources<1, 2, 8>, | ||
| 162 | configurator: embassy_net::DhcpConfigurator, | ||
| 163 | //configurator: StaticConfigurator, | ||
| 164 | device: Device, | ||
| 165 | } | ||
| 166 | static NET_RESOURCES: Forever<NetResources> = Forever::new(); | ||
| 167 | let res = NET_RESOURCES.put(NetResources { | ||
| 168 | resources: embassy_net::StackResources::new(), | ||
| 169 | configurator: embassy_net::DhcpConfigurator::new(), | ||
| 170 | //configurator: embassy_net::StaticConfigurator::new(embassy_net::Config { | ||
| 171 | // address: Ipv4Cidr::new(Ipv4Address::new(10, 42, 0, 1), 24), | ||
| 172 | // dns_servers: Default::default(), | ||
| 173 | // gateway: None, | ||
| 174 | //}), | ||
| 175 | device: Device { | ||
| 176 | mac_addr: our_mac_addr, | ||
| 177 | }, | ||
| 178 | }); | ||
| 179 | embassy_net::init(&mut res.device, &mut res.configurator, &mut res.resources); | ||
| 180 | unwrap!(spawner.spawn(net_task())); | ||
| 181 | |||
| 182 | // And now we can use it! | ||
| 183 | |||
| 184 | let mut rx_buffer = [0; 4096]; | ||
| 185 | let mut tx_buffer = [0; 4096]; | ||
| 186 | let mut buf = [0; 4096]; | ||
| 187 | |||
| 188 | loop { | ||
| 189 | let mut socket = TcpSocket::new(&mut rx_buffer, &mut tx_buffer); | ||
| 190 | socket.set_timeout(Some(embassy_net::SmolDuration::from_secs(10))); | ||
| 191 | |||
| 192 | info!("Listening on TCP:1234..."); | ||
| 193 | if let Err(e) = socket.accept(1234).await { | ||
| 194 | warn!("accept error: {:?}", e); | ||
| 195 | continue; | ||
| 196 | } | ||
| 197 | |||
| 198 | info!("Received connection from {:?}", socket.remote_endpoint()); | ||
| 199 | |||
| 200 | loop { | ||
| 201 | let n = match socket.read(&mut buf).await { | ||
| 202 | Ok(0) => { | ||
| 203 | warn!("read EOF"); | ||
| 204 | break; | ||
| 205 | } | ||
| 206 | Ok(n) => n, | ||
| 207 | Err(e) => { | ||
| 208 | warn!("read error: {:?}", e); | ||
| 209 | break; | ||
| 210 | } | ||
| 211 | }; | ||
| 212 | |||
| 213 | info!("rxd {:02x}", &buf[..n]); | ||
| 214 | |||
| 215 | match socket.write_all(&buf[..n]).await { | ||
| 216 | Ok(()) => {} | ||
| 217 | Err(e) => { | ||
| 218 | warn!("write error: {:?}", e); | ||
| 219 | break; | ||
| 220 | } | ||
| 221 | }; | ||
| 222 | } | ||
| 223 | } | ||
| 224 | } | ||
| 225 | |||
| 226 | static TX_CHANNEL: Channel<ThreadModeRawMutex, PacketBuf, 8> = Channel::new(); | ||
| 227 | static RX_CHANNEL: Channel<ThreadModeRawMutex, PacketBuf, 8> = Channel::new(); | ||
| 228 | static LINK_UP: AtomicBool = AtomicBool::new(false); | ||
| 229 | |||
| 230 | struct Device { | ||
| 231 | mac_addr: [u8; 6], | ||
| 232 | } | ||
| 233 | |||
| 234 | impl embassy_net::Device for Device { | ||
| 235 | fn register_waker(&mut self, waker: &Waker) { | ||
| 236 | // loopy loopy wakey wakey | ||
| 237 | waker.wake_by_ref() | ||
| 238 | } | ||
| 239 | |||
| 240 | fn link_state(&mut self) -> embassy_net::LinkState { | ||
| 241 | match LINK_UP.load(Ordering::Relaxed) { | ||
| 242 | true => embassy_net::LinkState::Up, | ||
| 243 | false => embassy_net::LinkState::Down, | ||
| 244 | } | ||
| 245 | } | ||
| 246 | |||
| 247 | fn capabilities(&mut self) -> embassy_net::DeviceCapabilities { | ||
| 248 | let mut caps = embassy_net::DeviceCapabilities::default(); | ||
| 249 | caps.max_transmission_unit = 1514; // 1500 IP + 14 ethernet header | ||
| 250 | caps.medium = embassy_net::Medium::Ethernet; | ||
| 251 | caps | ||
| 252 | } | ||
| 253 | |||
| 254 | fn is_transmit_ready(&mut self) -> bool { | ||
| 255 | true | ||
| 256 | } | ||
| 257 | |||
| 258 | fn transmit(&mut self, pkt: PacketBuf) { | ||
| 259 | if TX_CHANNEL.try_send(pkt).is_err() { | ||
| 260 | warn!("TX failed") | ||
| 261 | } | ||
| 262 | } | ||
| 263 | |||
| 264 | fn receive<'a>(&mut self) -> Option<PacketBuf> { | ||
| 265 | RX_CHANNEL.try_recv().ok() | ||
| 266 | } | ||
| 267 | |||
| 268 | fn ethernet_address(&mut self) -> [u8; 6] { | ||
| 269 | self.mac_addr | ||
| 270 | } | ||
| 271 | } | ||
| 272 | |||
| 273 | #[no_mangle] | ||
| 274 | fn _embassy_rand(buf: &mut [u8]) { | ||
| 275 | // TODO | ||
| 276 | buf.fill(0x42) | ||
| 277 | } | ||
diff --git a/examples/nrf/src/bin/usb_hid_keyboard.rs b/examples/nrf/src/bin/usb_hid_keyboard.rs index 9fa7ab334..3852dd8da 100644 --- a/examples/nrf/src/bin/usb_hid_keyboard.rs +++ b/examples/nrf/src/bin/usb_hid_keyboard.rs | |||
| @@ -59,8 +59,8 @@ async fn main(_spawner: Spawner, p: Peripherals) { | |||
| 59 | 59 | ||
| 60 | // Create embassy-usb Config | 60 | // Create embassy-usb Config |
| 61 | let mut config = Config::new(0xc0de, 0xcafe); | 61 | let mut config = Config::new(0xc0de, 0xcafe); |
| 62 | config.manufacturer = Some("Tactile Engineering"); | 62 | config.manufacturer = Some("Embassy"); |
| 63 | config.product = Some("Testy"); | 63 | config.product = Some("HID keyboard example"); |
| 64 | config.serial_number = Some("12345678"); | 64 | config.serial_number = Some("12345678"); |
| 65 | config.max_power = 100; | 65 | config.max_power = 100; |
| 66 | config.max_packet_size_0 = 64; | 66 | config.max_packet_size_0 = 64; |
diff --git a/examples/nrf/src/bin/usb_hid_mouse.rs b/examples/nrf/src/bin/usb_hid_mouse.rs index 92aeffda2..e70dc51a5 100644 --- a/examples/nrf/src/bin/usb_hid_mouse.rs +++ b/examples/nrf/src/bin/usb_hid_mouse.rs | |||
| @@ -39,10 +39,11 @@ async fn main(_spawner: Spawner, p: Peripherals) { | |||
| 39 | 39 | ||
| 40 | // Create embassy-usb Config | 40 | // Create embassy-usb Config |
| 41 | let mut config = Config::new(0xc0de, 0xcafe); | 41 | let mut config = Config::new(0xc0de, 0xcafe); |
| 42 | config.manufacturer = Some("Tactile Engineering"); | 42 | config.manufacturer = Some("Embassy"); |
| 43 | config.product = Some("Testy"); | 43 | config.product = Some("HID mouse example"); |
| 44 | config.serial_number = Some("12345678"); | 44 | config.serial_number = Some("12345678"); |
| 45 | config.max_power = 100; | 45 | config.max_power = 100; |
| 46 | config.max_packet_size_0 = 64; | ||
| 46 | 47 | ||
| 47 | // Create embassy-usb DeviceBuilder using the driver and config. | 48 | // Create embassy-usb DeviceBuilder using the driver and config. |
| 48 | // It needs some buffers for building the descriptors. | 49 | // It needs some buffers for building the descriptors. |
diff --git a/examples/nrf/src/bin/usb_serial.rs b/examples/nrf/src/bin/usb_serial.rs index 6081ee917..bc41c2acf 100644 --- a/examples/nrf/src/bin/usb_serial.rs +++ b/examples/nrf/src/bin/usb_serial.rs | |||
| @@ -36,7 +36,12 @@ async fn main(_spawner: Spawner, p: Peripherals) { | |||
| 36 | let driver = Driver::new(p.USBD, irq); | 36 | let driver = Driver::new(p.USBD, irq); |
| 37 | 37 | ||
| 38 | // Create embassy-usb Config | 38 | // Create embassy-usb Config |
| 39 | let config = Config::new(0xc0de, 0xcafe); | 39 | let mut config = Config::new(0xc0de, 0xcafe); |
| 40 | config.manufacturer = Some("Embassy"); | ||
| 41 | config.product = Some("USB-serial example"); | ||
| 42 | config.serial_number = Some("12345678"); | ||
| 43 | config.max_power = 100; | ||
| 44 | config.max_packet_size_0 = 64; | ||
| 40 | 45 | ||
| 41 | // Create embassy-usb DeviceBuilder using the driver and config. | 46 | // Create embassy-usb DeviceBuilder using the driver and config. |
| 42 | // It needs some buffers for building the descriptors. | 47 | // It needs some buffers for building the descriptors. |
diff --git a/examples/nrf/src/bin/usb_serial_multitask.rs b/examples/nrf/src/bin/usb_serial_multitask.rs index d4b3000e7..31e0af483 100644 --- a/examples/nrf/src/bin/usb_serial_multitask.rs +++ b/examples/nrf/src/bin/usb_serial_multitask.rs | |||
| @@ -53,7 +53,12 @@ async fn main(spawner: Spawner, p: Peripherals) { | |||
| 53 | let driver = Driver::new(p.USBD, irq); | 53 | let driver = Driver::new(p.USBD, irq); |
| 54 | 54 | ||
| 55 | // Create embassy-usb Config | 55 | // Create embassy-usb Config |
| 56 | let config = Config::new(0xc0de, 0xcafe); | 56 | let mut config = Config::new(0xc0de, 0xcafe); |
| 57 | config.manufacturer = Some("Embassy"); | ||
| 58 | config.product = Some("USB-serial example"); | ||
| 59 | config.serial_number = Some("12345678"); | ||
| 60 | config.max_power = 100; | ||
| 61 | config.max_packet_size_0 = 64; | ||
| 57 | 62 | ||
| 58 | struct Resources { | 63 | struct Resources { |
| 59 | device_descriptor: [u8; 256], | 64 | device_descriptor: [u8; 256], |
