Add USB NCM drivers

This commit is contained in:
cpq committed 2026-11-25 13:31:12 +00:00
1 parent bae9e53f00
commit a8d6573ccc
31 files changed
+3057 -175

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 3.13)
set(PICO_BOARD pico2 CACHE STRING "Target board")
include($ENV{PICO_SDK_PATH}/external/pico_sdk_import.cmake)
project(usb_ncm C CXX ASM)
pico_sdk_init()
add_executable(firmware main.c ../../../mongoose.c)
target_include_directories(firmware PRIVATE . ../../..)
target_link_libraries(firmware pico_stdlib pico_unique_id pico_rand hardware_resets)
pico_enable_stdio_usb(firmware 0)
pico_enable_stdio_uart(firmware 0)
pico_add_extra_outputs(firmware)
+13
View File
@@ -0,0 +1,13 @@
PICO_SDK_PATH ?= $(HOME)/src/pico-sdk
PICO_BOARD ?= pico2
BUILD ?= build/$(PICO_BOARD)
.PHONY: all build flash clean
all: build
build:
PICO_SDK_PATH=$(PICO_SDK_PATH) cmake -S . -B $(BUILD) -DPICO_BOARD=$(PICO_BOARD) -DCMAKE_BUILD_TYPE=Release
cmake --build $(BUILD) -j 4
flash: build
picotool load -f $(BUILD)/firmware.uf2
picotool reboot
clean:
rm -rf build
+99
View File
@@ -0,0 +1,99 @@
# Pico 2 / XIAO RP2040: USB Ethernet and serial with Mongoose
One USB cable gives the board a CDC-NCM Ethernet interface and a CDC-ACM
serial port that carries the Mongoose log. The native RP2040/RP2350 USB
controller is driven directly: no PIO, Ethernet PHY, TinyUSB, or lwIP.
Mongoose provides TCP/IP, a DHCP server, and HTTP/HTTPS servers.
The USB code is a Mongoose driver, `src/drivers/usb_rp.c`, enabled by
`MG_ENABLE_DRIVER_USB_RP` in `mongoose_config.h`. `mg_mgr_init()` starts it,
so `main.c` only sets up the LED and the HTTP listeners.
## Build and flash
Install the Pico SDK, CMake, Arm GNU toolchain, and picotool. The Makefile
uses `~/src/pico-sdk`; override `PICO_SDK_PATH` if necessary.
The default target is `PICO_BOARD=pico2` (RP2350, Arm Cortex-M33).
```sh
make # Pico 2
make PICO_BOARD=seeed_xiao_rp2040 # XIAO RP2040
```
Each board has its own build directory, `build/pico2/firmware.uf2` or
`build/seeed_xiao_rp2040/firmware.uf2`, so RP2040 and RP2350 CMake settings
never mix.
On Pico 2, hold BOOTSEL while connecting the USB cable. On XIAO, hold BOOT
while pressing and releasing RESET, then release BOOT. Flash:
```sh
make flash
```
The firmware also enters BOOTSEL when its serial port is opened at 1200 baud
and DTR drops. `picotool -f` alone cannot reboot it: the driver does not
implement the Pico SDK vendor reset interface.
## Use on macOS
Connect with a USB data cable. macOS creates an Ethernet service and a
`/dev/cu.usbmodem*` serial port with built-in drivers. Allow the USB accessory
if prompted, and leave the network service set to DHCP.
`mongoose_config.h` gives the device a static address, and the driver serves
DHCP to the host:
* Device: `192.168.7.1/24`
* HTTP: <http://192.168.7.1/>
* HTTPS: <https://192.168.7.1/> (self-signed demonstration certificate)
* JSON tick: <http://192.168.7.1/api/tick>
Change `MG_TCPIP_IP` and `MG_TCPIP_MASK` if the subnet conflicts with another
network. Remove them to make the board a DHCP client instead, for example
behind macOS Internet Sharing.
```sh
curl --noproxy '*' http://192.168.7.1/api/tick
curl --noproxy '*' -k https://192.168.7.1/api/tick
screen /dev/cu.usbmodemXXXX 115200
```
Use the actual serial device path. The baud rate is ignored, except that
1200 baud followed by DTR dropping requests BOOTSEL. To exit screen, press
Ctrl-A, then backslash, and confirm. The serial port is an output console;
received bytes are discarded.
Linux normally provides NCM and ACM drivers. Windows 11 provides NCM and ACM;
the driver includes Microsoft OS 2.0 compatible ID descriptors for driver
binding. Linux and Windows have not been tested here. Windows 10 has no
built-in NCM driver.
## Implementation
* `main.c`: LED blink task and the HTTP/HTTPS handler.
* `../../../src/drivers/usb_rp.c`: RP2040/RP2350 USB device controller.
* `../../../src/drivers/usb.c`: controller independent NCM + ACM:
descriptors, control requests, NTB16 negotiation, framing, parser, and the
serial log buffer. Shared with the SAMD21 driver, `usb_samd21.c`.
* Network control/data interfaces 0/1; ACM control/data interfaces 2/3.
* Network endpoints: interrupt IN 0x81, bulk OUT/IN 0x02/0x82.
* Serial endpoints: interrupt IN 0x83, bulk OUT/IN 0x04/0x84.
* Full-speed USB, 64-byte packets. Transfers span multiple packets and end
with short packets or ZLPs. Ethernet FCS is not sent on USB.
* NTB16 with no CRC, 4 KiB maximum IN/OUT blocks, and up to 16 incoming
datagrams per block, including chained NDPs. The whole block is validated
before any frame is delivered. NTB32 and CRC mode are not advertised.
* One Ethernet frame per outgoing block, within the host's negotiated input
size. Outgoing frames are not aggregated.
* Host and device MAC addresses and the USB serial number come from the
board's flash ID. One outgoing block can be in flight; incoming frames go
to Mongoose's 8 KiB queue. The serial log is a nonblocking 2 KiB ring; old
logs are overwritten when the host is not reading.
* Buffer sizes can be changed with `MG_USB_NCM_NTB_SIZE`,
`MG_USB_NCM_LOG_SIZE` and `MG_USB_NCM_QUEUE_SIZE`.
* Single core, polled from `mg_mgr_poll()`. No host mode, RNDIS, suspend,
remote wake, or Ethernet bridging.
The development VID/PID is `CAFE:40E4`, not an allocation for shipped
products. Get a legitimate VID/PID before distributing hardware.
+96
View File
@@ -0,0 +1,96 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
#include "hardware/clocks.h"
#include "mongoose.h"
#include "pico/stdlib.h"
#define LED1 PICO_DEFAULT_LED_PIN // User LED, active low
//#define LED1 16 // User LED, active low
static void blink_task(void) {
static uint64_t blink_timer = 0;
if (mg_timer_expired(&blink_timer, 500, mg_millis())) {
gpio_xor_mask(1u << LED1);
}
}
// Match MG24's heap-extent measurements. The Pico SDK's newlib _sbrk(0)
// returns the current heap break without allocating. Its linker reserves
// stacks separately, so free space ends at __HeapLimit, not the current SP.
// These figures exclude globals/stacks and reusable blocks inside malloc.
extern void *_sbrk(int incr);
extern char __end__, __HeapLimit;
static size_t hal_ram_used(void) {
return (size_t) ((uintptr_t) _sbrk(0) - (uintptr_t) &__end__);
}
static size_t hal_ram_free(void) {
return (size_t) ((uintptr_t) &__HeapLimit - (uintptr_t) _sbrk(0));
}
// Self-signed P-256 certificate and key for the HTTPS listener. Created by:
// openssl ecparam -genkey -name prime256v1 -noout -out key.pem
// openssl req -x509 -key key.pem -out cert.pem -days 3650 -subj /CN=mg
#define TLS_CERT \
"-----BEGIN CERTIFICATE-----\n" \
"MIIBgjCCASegAwIBAgIUIJOq77Qn7lHbH6WseMemeqorR50wCgYIKoZIzj0EAwIw\n" \
"FjEUMBIGA1UEAwwLbnVjbGVvLWg3MjMwHhcNMjYxMDEyMTUwMjE5WhcNMzYxMDA5\n" \
"MTUwMjE5WjAWMRQwEgYDVQQDDAtudWNsZW8taDcyMzBZMBMGByqGSM49AgEGCCqG\n" \
"SM49AwEHA0IABB6IQJNmzrsdQL+2BnZYS7GYOaj7sz8f6cjBmz3n8D9Em19XodlU\n" \
"uy4ybIvyhr766lL0ERoTmMUivb/lGmzx9C+jUzBRMB0GA1UdDgQWBBQqxMuc4gj7\n" \
"MTMzreWlRMNI3QMqTzAfBgNVHSMEGDAWgBQqxMuc4gj7MTMzreWlRMNI3QMqTzAP\n" \
"BgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0kAMEYCIQDY4xaJpuxq6b3rHK3b\n" \
"lOIQyfkQX+orCRqQUkseplqpqwIhAKswZFNn+2zUNRRNY8+cHmdIwmdpsmxtoWYP\n" \
"BCjX++LI\n" \
"-----END CERTIFICATE-----\n"
#define TLS_KEY \
"-----BEGIN EC PRIVATE KEY-----\n" \
"MHcCAQEEIJ/GBl0TlD52q9PMg1KWaNIdXqp8b/HyIsABmBpqC+O1oAoGCCqGSM49\n" \
"AwEHoUQDQgAEHohAk2bOux1Av7YGdlhLsZg5qPuzPx/pyMGbPefwP0SbX1eh2VS7\n" \
"LjJsi/KGvvrqUvQRGhOYxSK9v+UabPH0Lw==\n" \
"-----END EC PRIVATE KEY-----\n"
static void http_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_ACCEPT && c->is_tls) { // Accepted on the https:// listener
struct mg_tls_opts opts = {.cert = mg_str(TLS_CERT),
.key = mg_str(TLS_KEY)};
mg_tls_init(c, &opts);
} else if (ev == MG_EV_HTTP_MSG) {
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
if (mg_match(hm->uri, mg_str("/api/tick"), NULL)) {
mg_http_reply(c, 200, "", "{%m:%llu}\n", MG_ESC("tick"), mg_millis());
} else {
mg_http_reply(c, 200, "",
"Hi from Mongoose!\n"
"tick: %llu\n"
"ram used: %zu\n"
"ram free: %zu\n",
mg_millis(), hal_ram_used(), hal_ram_free());
}
}
}
int main(void) {
gpio_init(LED1);
gpio_put(LED1, 1);
gpio_set_dir(LED1, GPIO_OUT);
struct mg_mgr mgr;
mg_mgr_init(&mgr); // Also starts the USB driver, see mongoose_config.h
mg_http_listen(&mgr, "http://0.0.0.0", http_ev_handler, NULL);
mg_http_listen(&mgr, "https://0.0.0.0", http_ev_handler, NULL);
MG_INFO(("Initialised. CPU clock: %lu MHz", clock_get_hz(clk_sys) / 1000000));
MG_INFO(("RAM used: %zu, free: %zu", hal_ram_used(), hal_ram_free()));
MG_INFO(("USB Ethernet + serial"));
for (;;) {
mg_mgr_poll(&mgr, 0);
blink_task();
}
return 0;
}
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#define MG_ARCH MG_ARCH_PICOSDK
#define MG_TLS MG_TLS_BUILTIN
#define MG_ENABLE_TCPIP 1
#define MG_ENABLE_DRIVER_USB_RP 1 // RP2040 / RP2350 USB controller
#define MG_ENABLE_USB_ETHERNET 1 // USB NCM Ethernet interface
#define MG_ENABLE_USB_SERIAL 1 // USB serial log console
// Static device address; the driver serves DHCP to the USB host. Remove
// these to get an address over DHCP instead, e.g. from Internet Sharing
#define MG_TCPIP_IP MG_IPV4(192, 168, 7, 1)
#define MG_TCPIP_MASK MG_IPV4(255, 255, 255, 0)
#define MG_SET_MAC_ADDRESS(mac) \
do { \
mac[0] = 2; \
mac[1] = 3; \
mac[2] = 4; \
mac[3] = 5; \
mac[4] = 6; \
mac[5] = 7; \
} while (0)