firmware: document every RP2040, USB and Bluetooth function

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013PRsUCpxazyipPn5UGGkF8
This commit is contained in:
Claude committed 2026-10-18 21:16:34 +00:00
1 parent f47d285163
commit bada4f832b
7 files changed
+139 -7

No files matched your search

+57 -1
View File
@@ -76,8 +76,10 @@ static bool s_spp_pending;
// LEDs
static uint8_t s_wl_leds = 0xFF; // RD/SD as last written to the RM2
// Whether a phone may pair now (SPEC-W 4.5); outside the window only bonded phones get in.
static bool pairing_open(void) { return s_pair_until != 0; }
// Milliseconds since boot (wraps after 49 days; compare with subtraction).
static uint32_t now_ms(void) { return to_ms_since_boot(get_absolute_time()); }
// ---------------------------------------------------------------------------
@@ -87,6 +89,9 @@ static uint32_t now_ms(void) { return to_ms_since_boot(get_absolute_time()); }
static uint8_t s_adv[3 + 18];
static uint8_t s_scan[2 + sizeof s_name];
// (Re)starts LE advertising with the current name and discoverable flag.
// Called once the stack is up and whenever the pairing window opens or
// closes; does nothing before then.
static void advertise(void) {
if (!s_working) return;
static const uint8_t nus[16] = {0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0,
@@ -112,6 +117,9 @@ static void advertise(void) {
gap_advertisements_enable(1);
}
// Opens the pairing window for `seconds` (0 closes it): classic inquiry
// scan and the LE discoverable flag follow it. s_pair_until never holds 0
// for an open window, even when the deadline wraps to it.
static void set_window(uint32_t seconds) {
if (seconds) {
uint32_t t = now_ms() + seconds * 1000u;
@@ -124,8 +132,11 @@ static void set_window(uint32_t seconds) {
advertise();
}
// See bt.h.
void bt_pairing_window(uint16_t seconds) { set_window(seconds); }
// Whether any phone is bonded, LE or classic. At power-up this decides
// whether the pairing window opens by itself.
static bool have_bonds(void) {
if (le_device_db_count() > 0) return true;
btstack_link_key_iterator_t it;
@@ -140,6 +151,8 @@ static bool have_bonds(void) {
return any;
}
// See bt.h. Deletes classic link keys and LE bonds from flash, then opens
// the pairing window, as at power-up with nothing bonded.
void bt_forget_all(void) {
if (!s_working) return;
gap_delete_all_link_keys();
@@ -150,6 +163,9 @@ void bt_forget_all(void) {
// ---------------------------------------------------------------------------
// HCI, security manager
// ---------------------------------------------------------------------------
// The BLE link counts as up (a host link that can own the port) only once
// the connection is encrypted, so an unpaired phone can't take the port.
// Called on encryption changes and on disconnect.
static void le_link(bool up) {
if (up == s_le_secure) return;
s_le_secure = up;
@@ -157,6 +173,9 @@ static void le_link(bool up) {
link_up(&g_links, &g_core, LINK_BLE, up);
}
// BTstack HCI events: the stack coming up (name from our address, pairing
// window if nothing is bonded), classic pairing requests (accepted only in
// the window; legacy PIN pairing never), and LE encryption and disconnects.
static void hci_handler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size) {
(void)channel; (void)size;
if (type != HCI_EVENT_PACKET) return;
@@ -197,6 +216,8 @@ static void hci_handler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_
}
}
// Security manager events (LE pairing): Just Works and numeric comparison
// are confirmed inside the pairing window and declined outside it.
static void sm_handler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size) {
(void)channel; (void)size;
if (type != HCI_EVENT_PACKET) return;
@@ -220,6 +241,10 @@ static void sm_handler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t
// ---------------------------------------------------------------------------
// SPP (RFCOMM)
// ---------------------------------------------------------------------------
// RFCOMM events for the SPP server: data from the phone (into the links
// layer; each frame used one credit, granted only with room for it), one
// connection at a time, "can send now" (sends what the RS-232 side has),
// and channel open/close (the SPP link going up or down).
static void spp_handler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size) {
if (type == RFCOMM_DATA_PACKET) {
if (channel != s_spp) return;
@@ -261,6 +286,9 @@ static void spp_handler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_
}
}
// From bt_service(): grants the phone RFCOMM credits while the RS-232
// buffer has room for a whole frame per credit (that's the flow control),
// and asks to send when SPP owns the port and there's data for the phone.
static void spp_service(void) {
if (!s_spp) return;
// give the phone credits while there's room for a whole frame per credit
@@ -278,10 +306,16 @@ static void spp_service(void) {
// ---------------------------------------------------------------------------
// GATT
// ---------------------------------------------------------------------------
// Answers an ATT read from a value of n bytes: BTstack's helper for long
// (offset) reads; with buf NULL it returns the length only.
static uint16_t blob(const void *p, uint16_t n, uint16_t offset, uint8_t *buf, uint16_t size) {
return att_read_callback_handle_blob(p, n, offset, buf, size);
}
// ATT read callback (att_server_init): the value of a dynamic characteristic
// (name, line coding, outputs, inputs, mode, flow, credits, info, and the
// notification switches), little-endian as in pico_serial_w.gatt. Returns
// the bytes copied, or the length when buf is NULL; 0 for anything else.
static uint16_t att_read(hci_con_handle_t con, uint16_t h, uint16_t offset, uint8_t *buf, uint16_t size) {
(void)con;
core_t *c = &g_core;
@@ -325,6 +359,10 @@ static uint16_t att_read(hci_con_handle_t con, uint16_t h, uint16_t offset, uint
}
}
// ATT write callback: NUS data to the RS-232 port, notification switches,
// and the control service's settings. Writes that would change the port
// are refused (Write Not Permitted) unless BLE owns it; line coding is kept
// either way, for when it does. Returns 0 or an ATT error code.
static int att_write(hci_con_handle_t con, uint16_t h, uint16_t mode, uint16_t offset, uint8_t *buf, uint16_t size) {
(void)mode;
if (con != s_le) return 0;
@@ -371,7 +409,10 @@ static int att_write(hci_con_handle_t con, uint16_t h, uint16_t mode, uint16_t o
}
}
// what the phone should hear about next, if anything
// What the phone should hear about next, if anything, in priority order:
// changed inputs, a credits update (free space moved by CREDITS_NOTIFY_STEP,
// or the RS-232 buffer just drained), then RS-232 data (only *len, at most max; the caller reads it).
// Fills data/len and returns the characteristic's handle, or 0 for nothing.
static int le_next(uint8_t *data, uint16_t *len, uint16_t max) {
core_t *c = &g_core;
if (s_inputs_notify) {
@@ -400,6 +441,8 @@ static int le_next(uint8_t *data, uint16_t *len, uint16_t max) {
return 0;
}
// ATT server events: a new LE connection (asks for pairing/encryption at
// once) and "can send now" (sends one notification chosen by le_next()).
static void att_handler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size) {
(void)channel; (void)size;
if (type != HCI_EVENT_PACKET) return;
@@ -431,6 +474,8 @@ static void att_handler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_
}
}
// From bt_service(): on an encrypted LE link with nothing in flight, asks
// BTstack for a "can send now" event when le_next() has something to send.
static void le_service(void) {
if (s_le == HCI_CON_HANDLE_INVALID || !s_le_secure || s_le_pending) return;
uint8_t tmp[sizeof(ps_inputs_t)];
@@ -444,6 +489,9 @@ static void le_service(void) {
// ---------------------------------------------------------------------------
// Button, LEDs
// ---------------------------------------------------------------------------
// Polls the PAIR button (active low) from bt_service(): a press of 50 ms
// opens the pairing window; held 10 s, it forgets every bonded phone.
// Each fires once per press.
static void button(uint32_t now) {
bool down = !gpio_get(PIN_PAIR_BTN);
if (!down) {
@@ -474,6 +522,8 @@ static void bt_led(uint32_t now) {
gpio_put(PIN_LED_BT, on);
}
// See bt.h. Writes to the radio only on a change: each write is a bus
// transaction to the CYW43.
void bt_leds(uint8_t core_leds) {
if (!s_ok) return;
uint8_t m = core_leds & (CORE_LED_RD | CORE_LED_SD);
@@ -485,6 +535,9 @@ void bt_leds(uint8_t core_leds) {
}
// ---------------------------------------------------------------------------
// See bt.h. Sets up the button and BT LED, starts the radio (loads its
// firmware: blocking), then BTstack: security manager, SPP server and its
// SDP record, GATT server, and powers HCI on; the rest follows in hci_handler.
bool bt_init(void) {
gpio_init(PIN_LED_BT);
gpio_set_dir(PIN_LED_BT, GPIO_OUT);
@@ -531,6 +584,9 @@ bool bt_init(void) {
return true;
}
// See bt.h. Polls the radio and BTstack (its callbacks run from here),
// closes an expired pairing window, then the button, SPP and LE senders and
// the BT LED. The LED runs even without a radio (steady on: power).
void bt_service(void) {
uint32_t now = now_ms();
if (s_ok) {
+17 -5
View File
@@ -8,8 +8,20 @@
#include <stdbool.h>
#include <stdint.h>
bool bt_init(void); // after core_init/links_init; false: no radio
void bt_service(void); // call from the main loop
void bt_pairing_window(uint16_t seconds); // 0 closes it
void bt_forget_all(void); // forget every bonded phone
void bt_leds(uint8_t core_leds); // CORE_LED_RD/SD to the RM2's GPIOs
// Starts the radio and BTstack: SPP server, GATT server, pairing rules.
// Call once, after core_init() and links_init(), and before USB and the
// watchdog start: loading the radio's firmware blocks for a while. Returns
// false if the radio didn't start; the board then works over USB only.
bool bt_init(void);
// Polls the radio and runs every Bluetooth callback, the pairing button and
// the BT LED. Call from the main loop, never from an interrupt.
void bt_service(void);
// Opens the pairing window for `seconds` (0 closes it). From the USB
// request PS_REQ_BT_PAIRING; the button opens it for 2 minutes.
void bt_pairing_window(uint16_t seconds);
// Forgets every bonded phone (classic and LE) and opens the pairing window.
// From the USB request PS_REQ_BT_FORGET, or holding the button 10 s.
void bt_forget_all(void);
// Shows the core's RD and SD LED bits (CORE_LED_*) on the LEDs wired to the
// RM2's own GPIOs; the other LED bits are ignored. Called from hal_leds().
void bt_leds(uint8_t core_leds);
+24
View File
@@ -37,12 +37,14 @@ static uint8_t s_route = PS_ROLE_NONE;
static const uint8_t LED_PINS[6] = {LED_PIN_PWR, LED_PIN_TR, LED_PIN_CD, LED_PIN_SD, LED_PIN_RD, LED_PIN_RI};
// Makes pin a GPIO output at `level`, set before the driver turns on so it never glitches.
static void out_pin(uint pin, bool level) {
gpio_init(pin);
gpio_put(pin, level);
gpio_set_dir(pin, GPIO_OUT);
}
// Makes pin a GPIO input, with the pull-up or with no pull at all.
static void in_pin(uint pin, bool pull_up) {
gpio_init(pin);
gpio_set_dir(pin, GPIO_IN);
@@ -59,6 +61,10 @@ static void park(const uart_pins_t *p) {
out_pin(p->rts, true); // deasserted
}
// UART0 interrupt (RX, RX timeout, TX): hands every received byte, with its
// framing/parity/break/overrun flags, to the core, then refills the TX FIFO
// from the core; the TX interrupt is masked once the core has nothing left
// (hal_uart_kick_tx() unmasks it).
static void uart_irq(void) {
uart_hw_t *hw = uart_get_hw(UART);
while (!(hw->fr & UART_UARTFR_RXFE_BITS)) {
@@ -85,6 +91,9 @@ static void uart_irq(void) {
static uint s_ab_sm, s_ab_offset;
static pio_sm_config s_ab_cfg;
// PIO0 interrupt, RX FIFO not empty: each word from autobaud.pio is one run
// of the RX line: its level in bit 31, and 0x7FFFFFFF minus its length in
// bits 30..0. Passed to the core as (level, length in ticks).
static void ab_irq(void) {
while (!pio_sm_is_rx_fifo_empty(AB_PIO, s_ab_sm)) {
uint32_t raw = pio_sm_get(AB_PIO, s_ab_sm);
@@ -92,6 +101,8 @@ static void ab_irq(void) {
}
}
// From hal_init(): claims a state machine on PIO0, loads autobaud.pio and
// hooks its interrupt. The machine stays off until hal_autobaud() picks a pin.
static void ab_init(void) {
s_ab_sm = (uint)pio_claim_unused_sm(AB_PIO, true);
s_ab_offset = pio_add_program(AB_PIO, &autobaud_program);
@@ -116,6 +127,7 @@ void hal_autobaud(uint8_t role) {
pio_sm_set_enabled(AB_PIO, s_ab_sm, true);
}
// The PIO counts once per two system clocks (one loop of two instructions).
uint32_t hal_autobaud_hz(void) { return clock_get_hz(clk_sys) / 2u; }
void hal_init(void) {
@@ -153,6 +165,7 @@ void hal_init(void) {
ab_init();
}
// Milliseconds since boot, from the RP2040's 64-bit timer.
uint32_t hal_millis(void) { return to_ms_since_boot(get_absolute_time()); }
void hal_xcvr_power(uint8_t role) {
@@ -190,6 +203,7 @@ void hal_uart_route(uint8_t role) {
restore_interrupts(irq);
}
// Baud rate (the nearest the UART's divider can make), data bits, stop bits, parity.
void hal_uart_format(const uart_format_t *f) {
uart_set_baudrate(UART, f->baud);
uart_parity_t par = f->parity == 1 ? UART_PARITY_ODD : f->parity == 2 ? UART_PARITY_EVEN : UART_PARITY_NONE;
@@ -201,9 +215,12 @@ void hal_uart_rx_flush(void) {
while (!(hw->fr & UART_UARTFR_RXFE_BITS)) (void)hw->dr;
}
// The UART's own CTS gating: it stops sending while the far end's line is off.
void hal_uart_hw_cts(bool on) { uart_set_hw_flow(UART, on, false); }
void hal_uart_break(bool on) { uart_set_break(UART, on); }
// Starts transmitting what the core queued: fills the FIFO, and leaves the
// TX interrupt on if there's more than fits.
void hal_uart_kick_tx(void) {
uint32_t irq = save_and_disable_interrupts();
uart_hw_t *hw = uart_get_hw(UART);
@@ -244,6 +261,8 @@ uint8_t hal_lines_in(uint8_t role) {
return r;
}
// One GPIO per LED where the board has it (LED_NONE: not fitted); on the W
// board RD and SD hang off the radio module instead.
void hal_leds(uint8_t mask) {
for (unsigned i = 0; i < 6; i++)
if (LED_PINS[i] != LED_NONE) gpio_put(LED_PINS[i], (mask >> i) & 1);
@@ -260,6 +279,9 @@ bool hal_settings_load(void *buf, uint32_t len) {
return true; // the core checks the magic and checksum
}
// Erases the settings sector and writes the blob (at most one 256-byte
// page) with interrupts off: code runs from this flash, so nothing may
// fetch from it meanwhile. Takes some tens of milliseconds.
void hal_settings_save(const void *buf, uint32_t len) {
static uint8_t page[FLASH_PAGE_SIZE];
memset(page, 0xFF, sizeof page);
@@ -270,5 +292,7 @@ void hal_settings_save(const void *buf, uint32_t len) {
restore_interrupts(irq);
}
// Masks interrupts on this core; returns the previous state for hal_irq_restore().
uint32_t hal_irq_save(void) { return save_and_disable_interrupts(); }
// Puts back the interrupt state hal_irq_save() returned.
void hal_irq_restore(uint32_t s) { restore_interrupts(s); }
+3
View File
@@ -3,4 +3,7 @@
* Copyright (C) 2026 Neo-Desktop
*/
#pragma once
// Sets every board pin to a safe state (transceivers shut down, outputs
// deasserted, LEDs off), starts the UART and its interrupt, and loads the
// baud-learning PIO program. Call first in main(), before core_init().
void hal_init(void);
+4
View File
@@ -14,6 +14,10 @@
#include "bt.h"
#endif
// Brings up the hardware, the core and the host links (Bluetooth first on
// the W board), then runs everything from one loop: USB, Bluetooth and the
// core are polled in turn, so their callbacks never interrupt each other.
// The watchdog resets the board if the loop stalls for a second.
int main(void) {
hal_init();
core_init(&g_core);
+28
View File
@@ -57,11 +57,17 @@ static const uint8_t desc_config[] = {
};
TU_VERIFY_STATIC(sizeof desc_config == CONFIG_LEN, "config descriptor length");
// TinyUSB, on GET_DESCRIPTOR(DEVICE): the device descriptor above.
const uint8_t *tud_descriptor_device_cb(void) { return (const uint8_t *)&desc_device; }
// TinyUSB, on GET_DESCRIPTOR(CONFIGURATION): the one configuration (index is always 0).
const uint8_t *tud_descriptor_configuration_cb(uint8_t index) { (void)index; return desc_config; }
static uint16_t desc_str[33];
// TinyUSB, on GET_DESCRIPTOR(STRING): string `index` as a USB string
// descriptor (UTF-16, ASCII only, at most 32 characters) built in desc_str,
// valid until the next call. The serial number is the flash chip's unique ID.
// NULL for an index we don't have, which TinyUSB answers with a STALL.
const uint16_t *tud_descriptor_string_cb(uint8_t index, uint16_t langid) {
(void)langid;
char serial[2 * PICO_UNIQUE_BOARD_ID_SIZE_BYTES + 1];
@@ -92,9 +98,15 @@ const uint16_t *tud_descriptor_string_cb(uint8_t index, uint16_t langid) {
static uint8_t s_control_itf = 0xFF;
static uint8_t s_control_buf[64];
// Class driver init, at tusb_init(): nothing to set up.
static void psd_init(void) {}
// Class driver reset, on bus reset or unplug: forget our interface number until opened again.
static void psd_reset(uint8_t rhport) { (void)rhport; s_control_itf = 0xFF; }
// Class driver open, once per interface when the host sets the configuration:
// claims the "pico-serial control" interface (vendor class, our subclass and
// protocol) and remembers its number. Returns the descriptor bytes used, or 0
// to leave the interface to another driver.
static uint16_t psd_open(uint8_t rhport, const tusb_desc_interface_t *d, uint16_t max_len) {
(void)rhport;
TU_VERIFY(d->bInterfaceClass == TUSB_CLASS_VENDOR_SPECIFIC && d->bInterfaceSubClass == PS_ITF_SUBCLASS &&
@@ -104,6 +116,11 @@ static uint16_t psd_open(uint8_t rhport, const tusb_desc_interface_t *d, uint16_
return sizeof(tusb_desc_interface_t);
}
// A vendor request to the control interface (protocol.h), at each control
// stage. IN requests answer with core_vendor_in()'s data; OUT requests carry
// no data stage, only wValue, and go to core_vendor_out() (or, on the W
// board, the two Bluetooth requests). false stalls the request: not ours, an
// unknown request, or a bad argument.
static bool psd_control_xfer_cb(uint8_t rhport, uint8_t stage, const tusb_control_request_t *r) {
if (r->bmRequestType_bit.type != TUSB_REQ_TYPE_VENDOR || r->bmRequestType_bit.recipient != TUSB_REQ_RCPT_INTERFACE ||
(r->wIndex & 0xFF) != s_control_itf)
@@ -130,6 +147,8 @@ bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, const tusb_contro
return psd_control_xfer_cb(rhport, stage, r);
}
// Class driver transfer-complete callback: the interface has no endpoints,
// so it never fires; TinyUSB requires one.
static bool psd_xfer_cb(uint8_t rhport, uint8_t ep, xfer_result_t res, uint32_t n) {
(void)rhport; (void)ep; (void)res; (void)n;
return true;
@@ -148,6 +167,8 @@ static const usbd_class_driver_t ps_control_driver = {
static usbd_class_driver_t s_drivers[2];
// TinyUSB, at init: the application's own class drivers, tried before the
// built-in ones (our control interface and Raspberry Pi's reset interface).
const usbd_class_driver_t *usbd_app_driver_get_cb(uint8_t *count) {
s_drivers[0] = ps_control_driver;
s_drivers[1] = usb_reset_interface_driver;
@@ -162,18 +183,24 @@ const usbd_class_driver_t *usbd_app_driver_get_cb(uint8_t *count) {
// the RS-232 port (link.h): on the wired boards it always does.
void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts) { (void)itf; link_lines(&g_links, &g_core, LINK_USB, dtr, rts); }
// CDC SET_LINE_CODING (the host opened the port or changed baud/format).
void tud_cdc_line_coding_cb(uint8_t itf, const cdc_line_coding_t *lc) {
(void)itf;
link_format(&g_links, &g_core, LINK_USB, lc->bit_rate, lc->stop_bits, lc->parity, lc->data_bits);
}
// CDC SEND_BREAK: hold a break on the RS-232 line for ms milliseconds
// (0xFFFF: until the next SEND_BREAK, 0: end it).
void tud_cdc_send_break_cb(uint8_t itf, uint16_t ms) { (void)itf; link_break(&g_links, &g_core, LINK_USB, ms); }
// The host configured the device: USB is up as a link.
void tud_mount_cb(void) {
g_core.serial_state_valid = false; // re-announce the lines
link_up(&g_links, &g_core, LINK_USB, true);
}
// Unplugged or deconfigured: USB is down as a link.
void tud_umount_cb(void) { link_up(&g_links, &g_core, LINK_USB, false); }
// Bus suspended (host asleep): treat the port as closed (DTR and RTS off).
void tud_suspend_cb(bool remote_wakeup_en) {
(void)remote_wakeup_en;
link_lines(&g_links, &g_core, LINK_USB, false, false);
@@ -182,6 +209,7 @@ void tud_suspend_cb(bool remote_wakeup_en) {
static uint16_t s_pending_state;
static bool s_pending;
// See usb.h. Full-speed device on the RP2040's only USB port.
void usb_init(void) {
const tusb_rhport_init_t init = {.role = TUSB_ROLE_DEVICE, .speed = TUSB_SPEED_FULL};
tusb_init(0, &init);
+6 -1
View File
@@ -3,5 +3,10 @@
* Copyright (C) 2026 Neo-Desktop
*/
#pragma once
// Starts the USB device stack (descriptors and callbacks in usb.c). Call
// once, after core_init() and links_init(): callbacks feed the core at once.
void usb_init(void);
void usb_service(void); // call from the main loop
// Runs TinyUSB, then moves data both ways between the CDC port and the core
// (only while USB owns the RS-232 port) and sends the host modem-line changes.
// Call from the main loop; never from an interrupt.
void usb_service(void);