aboutsummaryrefslogtreecommitdiff
path: root/examples/nrf
diff options
context:
space:
mode:
Diffstat (limited to 'examples/nrf')
-rw-r--r--examples/nrf/Cargo.toml4
-rw-r--r--examples/nrf/src/bin/usb_ethernet.rs277
-rw-r--r--examples/nrf/src/bin/usb_hid_keyboard.rs4
-rw-r--r--examples/nrf/src/bin/usb_hid_mouse.rs5
-rw-r--r--examples/nrf/src/bin/usb_serial.rs7
-rw-r--r--examples/nrf/src/bin/usb_serial_multitask.rs7
6 files changed, 297 insertions, 7 deletions
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]
8default = ["nightly"] 8default = ["nightly"]
9nightly = ["embassy-nrf/nightly", "embassy-nrf/unstable-traits", "embassy-usb", "embassy-usb-serial", "embassy-usb-hid"] 9nightly = ["embassy-nrf/nightly", "embassy-nrf/unstable-traits", "embassy-usb", "embassy-usb-serial", "embassy-usb-hid", "embassy-usb-ncm"]
10 10
11[dependencies] 11[dependencies]
12embassy = { version = "0.1.0", path = "../../embassy", features = ["defmt", "defmt-timestamp-uptime"] } 12embassy = { version = "0.1.0", path = "../../embassy", features = ["defmt", "defmt-timestamp-uptime"] }
13embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac"] } 13embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac"] }
14embassy-net = { version = "0.1.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", "pool-16"] }
14embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"], optional = true } 15embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"], optional = true }
15embassy-usb-serial = { version = "0.1.0", path = "../../embassy-usb-serial", features = ["defmt"], optional = true } 16embassy-usb-serial = { version = "0.1.0", path = "../../embassy-usb-serial", features = ["defmt"], optional = true }
16embassy-usb-hid = { version = "0.1.0", path = "../../embassy-usb-hid", features = ["defmt"], optional = true } 17embassy-usb-hid = { version = "0.1.0", path = "../../embassy-usb-hid", features = ["defmt"], optional = true }
18embassy-usb-ncm = { version = "0.1.0", path = "../../embassy-usb-ncm", features = ["defmt"], optional = true }
17 19
18defmt = "0.3" 20defmt = "0.3"
19defmt-rtt = "0.3" 21defmt-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
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}
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],