aboutsummaryrefslogtreecommitdiff
path: root/examples/nrf/src/bin
diff options
context:
space:
mode:
authorDario Nieuwenhuis <[email protected]>2022-04-23 05:24:38 +0200
committerDario Nieuwenhuis <[email protected]>2022-04-24 22:44:52 +0200
commitd57fd87ba77f923953e5b4d401c8cf39c45b0842 (patch)
tree496fa80951623ab3b83f57447b4e60c2fa23b357 /examples/nrf/src/bin
parent50e1d257bd192a864a11b6e1edc86298eda7b943 (diff)
Add embassy-usb-ncm. Implements USBB CDC NCM (Ethernet over USB)
Diffstat (limited to 'examples/nrf/src/bin')
-rw-r--r--examples/nrf/src/bin/usb_ethernet.rs277
1 files changed, 277 insertions, 0 deletions
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
6use core::mem;
7use core::sync::atomic::{AtomicBool, Ordering};
8use core::task::Waker;
9use defmt::*;
10use embassy::blocking_mutex::raw::ThreadModeRawMutex;
11use embassy::channel::Channel;
12use embassy::executor::Spawner;
13use embassy::io::{AsyncBufReadExt, AsyncWriteExt};
14use embassy::util::Forever;
15use embassy_net::{PacketBox, PacketBoxExt, PacketBuf, TcpSocket};
16use embassy_nrf::pac;
17use embassy_nrf::usb::Driver;
18use embassy_nrf::Peripherals;
19use embassy_nrf::{interrupt, peripherals};
20use embassy_usb::{Builder, Config, UsbDevice};
21use embassy_usb_ncm::{CdcNcmClass, Receiver, Sender, State};
22
23use defmt_rtt as _; // global logger
24use panic_probe as _;
25
26type MyDriver = Driver<'static, peripherals::USBD>;
27
28#[embassy::task]
29async fn usb_task(mut device: UsbDevice<'static, MyDriver>) -> ! {
30 device.run().await
31}
32
33#[embassy::task]
34async 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]
63async 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]
73async fn net_task() -> ! {
74 embassy_net::run().await
75}
76
77#[embassy::main]
78async 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
226static TX_CHANNEL: Channel<ThreadModeRawMutex, PacketBuf, 8> = Channel::new();
227static RX_CHANNEL: Channel<ThreadModeRawMutex, PacketBuf, 8> = Channel::new();
228static LINK_UP: AtomicBool = AtomicBool::new(false);
229
230struct Device {
231 mac_addr: [u8; 6],
232}
233
234impl 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]
274fn _embassy_rand(buf: &mut [u8]) {
275 // TODO
276 buf.fill(0x42)
277}