diff --git a/mongoose.c b/mongoose.c index 7f4374ba..d3215b3b 100644 --- a/mongoose.c +++ b/mongoose.c @@ -39005,13 +39005,20 @@ static uint8_t s_mgi_usb_rp_req[16]; // SETUP packet, then its OUT data static bool s_mgi_usb_rp_req_out; // Waiting for that OUT data stage static uint8_t s_mgi_usb_rp_address; // Address to set after the status stage +// Per-byte memcpy variant to avoid alignment issues +static void mgi_bcopy(void *dst, const void *src, size_t n) { + volatile uint8_t *d = (volatile uint8_t *) dst; + const volatile uint8_t *s = (const volatile uint8_t *) src; + while (n--) *d++ = *s++; +} + // Hand one packet buffer to the controller. OUT: accept up to len bytes static void mgi_usb_rp_packet(unsigned ep, bool in, const void *data, unsigned len) { struct mgi_usb_rp_ep *e = &s_mgi_usb_rp_ep[ep][in]; uint32_t v = len | (e->pid ? USB_BUF_CTRL_DATA1_PID : 0) | (in ? USB_BUF_CTRL_FULL : 0); - if (in && len) memcpy(e->buf, data, len); + if (in && len) mgi_bcopy(e->buf, data, len); e->pid ^= 1; *e->ctrl = v; // RP2040 datasheet: allow at least 12 cycles between writing buffer @@ -39107,7 +39114,7 @@ static void mgi_usb_rp_request(MGI_USB_RP_FN) { static void mgi_usb_rp_setup(MGI_USB_RP_FN) { uint8_t *r = s_mgi_usb_rp_req; unsigned wlen; - memcpy(r, (const void *) usb_dpram->setup_packet, 8); + mgi_bcopy(r, (const void *) usb_dpram->setup_packet, 8); wlen = MG_LOAD_LE16(r + 6); // A SETUP cancels the preceding control transfer. Both its data and // status stages start with DATA1 @@ -39141,12 +39148,14 @@ static void mgi_usb_rp_complete(unsigned ep, bool in, MGI_USB_RP_FN) { if (n != MG_LOAD_LE16(r + 6)) { mgi_usb_rp_stall(); } else { - memcpy(r + 8, e->buf, n); + mgi_bcopy(r + 8, e->buf, n); mgi_usb_rp_request(fn); } #if MG_ENABLE_USB_ETHERNET } else if (ep == MG_USB_EP_ETH_DATA && !in) { - fn(MG_USB_EV_OUT, MG_USB_EP_ETH_DATA, e->buf, n); + uint8_t pkt[64]; // usb.c copies it with memcpy(): give it RAM, not DPRAM + mgi_bcopy(pkt, e->buf, n); + fn(MG_USB_EV_OUT, MG_USB_EP_ETH_DATA, pkt, n); mgi_usb_rp_packet(ep, false, NULL, 64); #endif #if MG_ENABLE_USB_SERIAL diff --git a/src/drivers/usb_rp.c b/src/drivers/usb_rp.c index f1bea115..9fee8474 100644 --- a/src/drivers/usb_rp.c +++ b/src/drivers/usb_rp.c @@ -23,13 +23,20 @@ static uint8_t s_mgi_usb_rp_req[16]; // SETUP packet, then its OUT data static bool s_mgi_usb_rp_req_out; // Waiting for that OUT data stage static uint8_t s_mgi_usb_rp_address; // Address to set after the status stage +// Per-byte memcpy variant to avoid alignment issues +static void mgi_bcopy(void *dst, const void *src, size_t n) { + volatile uint8_t *d = (volatile uint8_t *) dst; + const volatile uint8_t *s = (const volatile uint8_t *) src; + while (n--) *d++ = *s++; +} + // Hand one packet buffer to the controller. OUT: accept up to len bytes static void mgi_usb_rp_packet(unsigned ep, bool in, const void *data, unsigned len) { struct mgi_usb_rp_ep *e = &s_mgi_usb_rp_ep[ep][in]; uint32_t v = len | (e->pid ? USB_BUF_CTRL_DATA1_PID : 0) | (in ? USB_BUF_CTRL_FULL : 0); - if (in && len) memcpy(e->buf, data, len); + if (in && len) mgi_bcopy(e->buf, data, len); e->pid ^= 1; *e->ctrl = v; // RP2040 datasheet: allow at least 12 cycles between writing buffer @@ -125,7 +132,7 @@ static void mgi_usb_rp_request(MGI_USB_RP_FN) { static void mgi_usb_rp_setup(MGI_USB_RP_FN) { uint8_t *r = s_mgi_usb_rp_req; unsigned wlen; - memcpy(r, (const void *) usb_dpram->setup_packet, 8); + mgi_bcopy(r, (const void *) usb_dpram->setup_packet, 8); wlen = MG_LOAD_LE16(r + 6); // A SETUP cancels the preceding control transfer. Both its data and // status stages start with DATA1 @@ -159,12 +166,14 @@ static void mgi_usb_rp_complete(unsigned ep, bool in, MGI_USB_RP_FN) { if (n != MG_LOAD_LE16(r + 6)) { mgi_usb_rp_stall(); } else { - memcpy(r + 8, e->buf, n); + mgi_bcopy(r + 8, e->buf, n); mgi_usb_rp_request(fn); } #if MG_ENABLE_USB_ETHERNET } else if (ep == MG_USB_EP_ETH_DATA && !in) { - fn(MG_USB_EV_OUT, MG_USB_EP_ETH_DATA, e->buf, n); + uint8_t pkt[64]; // usb.c copies it with memcpy(): give it RAM, not DPRAM + mgi_bcopy(pkt, e->buf, n); + fn(MG_USB_EV_OUT, MG_USB_EP_ETH_DATA, pkt, n); mgi_usb_rp_packet(ep, false, NULL, 64); #endif #if MG_ENABLE_USB_SERIAL diff --git a/tutorials/rp/usb-w/CMakeLists.txt b/tutorials/rp/usb-w/CMakeLists.txt new file mode 100644 index 00000000..204aa973 --- /dev/null +++ b/tutorials/rp/usb-w/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 3.13) +set(PICO_BOARD pico2_w 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 dashboard.c file_data.c ../../../mongoose.c) +target_include_directories(firmware PRIVATE . ../../..) +target_link_libraries(firmware pico_stdlib pico_unique_id pico_rand hardware_resets pico_cyw43_driver pico_cyw43_arch_none) +pico_enable_stdio_usb(firmware 0) +pico_enable_stdio_uart(firmware 0) +pico_add_extra_outputs(firmware) diff --git a/tutorials/rp/usb-w/Makefile b/tutorials/rp/usb-w/Makefile new file mode 100644 index 00000000..faae28d6 --- /dev/null +++ b/tutorials/rp/usb-w/Makefile @@ -0,0 +1,20 @@ +PICO_SDK_PATH ?= $(HOME)/src/pico-sdk +PICO_BOARD ?= pico2_w +BUILD ?= build/$(PICO_BOARD) +.PHONY: all build flash clean + +all: build + +build: file_data.c + 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 + +file_data.c: dashboard.html + node ../../../resources/html2c.js dashboard.html -o $@ + +clean: + rm -rf build file_data.c diff --git a/tutorials/rp/usb-w/dashboard.c b/tutorials/rp/usb-w/dashboard.c new file mode 100644 index 00000000..881a6c2c --- /dev/null +++ b/tutorials/rp/usb-w/dashboard.c @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: 2026 Cesanta Software Limited +// SPDX-License-Identifier: GPL-2.0-only or commercial + +#include "mongoose.h" + +static struct mg_dash s_dash; + +// WiFi settings and logic are in main.c. This is the "wifi" object in +// dashboard.html +extern char g_wifi_ssid[33], g_wifi_pass[64]; +extern bool g_wifi_enable, g_wifi_changed; +extern uint32_t wifi_ip(void); +static char s_wifi_status[40]; // Read-only, regenerated on every read + +static bool wifi_fn(enum mg_dash_op op, struct mg_dash_user *u) { + (void) u; + if (op == MG_DASH_READ) { + uint32_t ip = wifi_ip(); + if (ip != 0) { + mg_snprintf(s_wifi_status, sizeof(s_wifi_status), "enabled, IP: %M", + mg_print_ip4, &ip); + } else { + mg_snprintf(s_wifi_status, sizeof(s_wifi_status), "not connected"); + } + return true; + } + // Called twice: before the fields are updated (permission check), and + // after. main() reconnects once, later + if (op == MG_DASH_WRITE) g_wifi_changed = true; + return op == MG_DASH_WRITE; +} + +static struct mg_field fields_wifi[] = { + {"ssid", MG_VAL_STR, g_wifi_ssid, sizeof(g_wifi_ssid)}, + {"pass", MG_VAL_STR, g_wifi_pass, sizeof(g_wifi_pass)}, + {"enable", MG_VAL_BOOL, &g_wifi_enable, sizeof(g_wifi_enable)}, + {"status", MG_VAL_STR, s_wifi_status, 0}, // value_size 0: read-only + {NULL, MG_VAL_INT, NULL, 0}, +}; +static struct mg_field_set set_wifi = {"wifi", fields_wifi, wifi_fn, NULL, + NULL}; + +// 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" + +void mg_dash_init(struct mg_mgr *mgr) { + s_dash.tls_cert = mg_str(TLS_CERT); // HTTPS listener, see MG_HTTPS_ADDR + s_dash.tls_key = mg_str(TLS_KEY); + MG_DASH_ADD_FIELD_SET(&s_dash, &set_wifi); + mg_mem_files = mg_packed_files; + mg_http_listen(mgr, MG_HTTP_ADDR, mg_dash_ev_handler, &s_dash); + mg_http_listen(mgr, MG_HTTPS_ADDR, mg_dash_ev_handler, &s_dash); +} + +void mg_dash_poll(struct mg_mgr *mgr) { + static uint32_t prev_ip; + if (wifi_ip() != prev_ip) { // Got or lost an address: update the status + prev_ip = wifi_ip(); + mg_dash_send_change(mgr, &set_wifi); + } +} diff --git a/tutorials/rp/usb-w/dashboard.html b/tutorials/rp/usb-w/dashboard.html new file mode 100644 index 00000000..267dcb53 --- /dev/null +++ b/tutorials/rp/usb-w/dashboard.html @@ -0,0 +1,123 @@ + + + + WiFi Settings + + + + + + + + +
+ +
+ ${__status.online ? 'live' : 'offline'} + +
+
+ +
+
+
WiFi settings
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+ + + + + diff --git a/tutorials/rp/usb-w/main.c b/tutorials/rp/usb-w/main.c new file mode 100644 index 00000000..32fcc9bc --- /dev/null +++ b/tutorials/rp/usb-w/main.c @@ -0,0 +1,96 @@ +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved + +#include "hardware/clocks.h" +#include "mongoose.h" +#include "pico/stdlib.h" + +static void blink_task(void) { + static uint64_t blink_timer = 0; + static bool on; // Kept here: reading the CYW43 LED pin back is unreliable + if (mg_timer_expired(&blink_timer, 500, mg_millis())) { + on = !on; + cyw43_arch_gpio_put(CYW43_WL_GPIO_LED_PIN, on); + } +} + +// 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)); +} + +// WiFi settings, edited in the dashboard, see dashboard.c +char g_wifi_ssid[33]; // Network name, up to 32 bytes +char g_wifi_pass[64]; // WPA2 passphrase, up to 63 characters +bool g_wifi_enable; // Connect, and poll s_wifi_mgr, if true +bool g_wifi_changed; // Settings saved: reconnect in main() +static struct mg_mgr s_wifi_mgr; // WiFi network, polled while enabled + +// WiFi IP address, 0 if WiFi is disabled or has no address yet +uint32_t wifi_ip(void) { + struct mg_tcpip_if *ifp = s_wifi_mgr.ifp; + bool up = g_wifi_enable && ifp != NULL && ifp->state >= MG_TCPIP_STATE_IP; + return up ? ifp->ip : 0; +} + +// HTTP server on the WiFi interface: one plain text page +static void wifi_http_fn(struct mg_connection *c, int ev, void *ev_data) { + if (ev == MG_EV_HTTP_MSG) { + (void) ev_data; + mg_http_reply(c, 200, "Content-Type: text/plain\r\n", + "Hi from Mongoose over WiFi, uptime %llu ms\n", mg_millis()); + } +} + +int main(void) { + struct mg_mgr mgr; // USB network, always polled + mg_mgr_init(&mgr); + MG_TCPIP_DRIVER_USB_RP_INIT(&mgr); // Static IP, DHCP server for the host + mg_dash_init(&mgr); // WiFi settings dashboard, see dashboard.c + + // WiFi interface: a DHCP client. The driver starts the CYW43 chip, so the + // LED works from here on, and reads the MAC from OTP. It connects when + // WiFi is enabled in the dashboard + static struct mg_tcpip_driver_pico_w_data wifi_data; + static struct mg_tcpip_if wifi_if; + wifi_if.driver = &mg_tcpip_driver_pico_w; + wifi_if.driver_data = &wifi_data; + wifi_if.recv_queue.size = 8192; + wifi_if.mac[0] = 2; // Non-zero: keep mg_tcpip_init() from making one up + mg_mgr_init(&s_wifi_mgr); + mg_tcpip_init(&s_wifi_mgr, &wifi_if); + mg_http_listen(&s_wifi_mgr, "http://0.0.0.0:80", wifi_http_fn, 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 + WiFi")); + + for (;;) { + mg_mgr_poll(&mgr, 0); + mg_dash_poll(&mgr); + if (g_wifi_changed) { // Settings saved in the dashboard: reconnect + g_wifi_changed = false; + mg_wifi_disconnect(); + if (g_wifi_enable && g_wifi_ssid[0] != '\0') { + struct mg_wifi_data wifi; + memset(&wifi, 0, sizeof(wifi)); + wifi.ssid = g_wifi_ssid, wifi.pass = g_wifi_pass; + mg_wifi_connect(&wifi); + } + } + if (g_wifi_enable) mg_mgr_poll(&s_wifi_mgr, 0); + blink_task(); + } + + return 0; +} diff --git a/tutorials/rp/usb-w/mongoose_config.h b/tutorials/rp/usb-w/mongoose_config.h new file mode 100644 index 00000000..31db091f --- /dev/null +++ b/tutorials/rp/usb-w/mongoose_config.h @@ -0,0 +1,27 @@ +#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 +#define MG_ENABLE_DRIVER_PICO_W 1 // WiFi on the CYW43 chip + +// Two interfaces, each in its own manager: main.c starts them, not +// mg_mgr_init(). The WiFi one ignores the static address below, uses DHCP +#define MG_ENABLE_TCPIP_DRIVER_INIT 0 + +// 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)