diff --git a/.github/workflows/firmware.yml b/.github/workflows/firmware.yml index 7836c6b..0818489 100644 --- a/.github/workflows/firmware.yml +++ b/.github/workflows/firmware.yml @@ -32,6 +32,13 @@ jobs: cmake -S firmware -B firmware/build-hood -G Ninja -DPS_BOARD=hood ninja -C firmware/build-hood + - name: Build (W board, Bluetooth) + run: | + cmake -S firmware -B firmware/build-w -G Ninja -DPS_BOARD=w \ + -DPICO_SDK_PATH=$PWD/firmware/build-hood/_deps/pico_sdk-src \ + -DPICO_TINYUSB_PATH=$PWD/firmware/build-hood/_deps/tinyusb-src + ninja -C firmware/build-w + - name: Build (Pico bench rig) run: | cmake -S firmware -B firmware/build-pico -G Ninja -DPS_BOARD=pico \ @@ -51,4 +58,5 @@ jobs: name: pico-serial-firmware path: | firmware/build-hood/pico-serial-hood.uf2 + firmware/build-w/pico-serial-w.uf2 firmware/build-pico/pico-serial-pico.uf2 diff --git a/.gitignore b/.gitignore index 4ccc6b4..f3af13e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ __pycache__/ firmware/build*/ firmware/test/test_core firmware/test/test_autobaud +firmware/test/test_link firmware/test/emu/node_modules/ firmware/test/emu/vendor/ hardware/kicad/*.kicad_prl diff --git a/firmware/CMakeLists.txt b/firmware/CMakeLists.txt index fc2133f..55de908 100644 --- a/firmware/CMakeLists.txt +++ b/firmware/CMakeLists.txt @@ -2,16 +2,20 @@ # Copyright (C) 2026 Neo-Desktop cmake_minimum_required(VERSION 3.13) -# Which board: "hood" (the DB25 hood board) or "pico" (bench rig: a Raspberry -# Pi Pico wired to the transceivers as SPEC.md 4.5). -set(PS_BOARD hood CACHE STRING "pico-serial board: hood | pico") +# Which board: "hood" (the DB25 hood board), "w" (pico-serial W, with the +# RM2 Bluetooth module, SPEC-W.md) or "pico" (bench rig: a Raspberry Pi Pico +# wired to the transceivers as SPEC.md 4.5). +set(PS_BOARD hood CACHE STRING "pico-serial board: hood | w | pico") if (PS_BOARD STREQUAL "hood") set(PICO_BOARD pico_serial_hood) set(PICO_BOARD_HEADER_DIRS ${CMAKE_CURRENT_LIST_DIR}/boards) +elseif (PS_BOARD STREQUAL "w") + set(PICO_BOARD pico_serial_w) + set(PICO_BOARD_HEADER_DIRS ${CMAKE_CURRENT_LIST_DIR}/boards) elseif (PS_BOARD STREQUAL "pico") set(PICO_BOARD pico) else () - message(FATAL_ERROR "PS_BOARD must be hood or pico") + message(FATAL_ERROR "PS_BOARD must be hood, w or pico") endif () # Pico SDK: PICO_SDK_PATH, or fetched at this tag. @@ -48,6 +52,7 @@ add_executable(pico_serial src/rp2040/usb.c src/core/core.c src/core/autobaud.c + src/core/link.c ) pico_generate_pio_header(pico_serial ${CMAKE_CURRENT_LIST_DIR}/src/rp2040/autobaud.pio) target_include_directories(pico_serial PRIVATE src src/core src/rp2040) @@ -55,6 +60,7 @@ target_compile_options(pico_serial PRIVATE -Wall -Wextra) target_compile_definitions(pico_serial PRIVATE PS_FW_MAJOR=${PS_FW_MAJOR} PS_FW_MINOR=${PS_FW_MINOR} PS_FW_PATCH=${PS_FW_PATCH} $<$:PS_BOARD_PICO> + $<$:PS_BOARD_W> # picotool can reboot it (into BOOTSEL or the app) through the reset interface; # no "1200 baud means reboot": 1200 baud is a real modem speed PICO_ENABLE_USB_RESET_VIA_VENDOR_INTERFACE=1 @@ -67,5 +73,13 @@ target_link_libraries(pico_serial PRIVATE hardware_uart hardware_flash hardware_watchdog hardware_irq hardware_pio hardware_clocks tinyusb_device ) +if (PS_BOARD STREQUAL "w") + # Bluetooth: BTstack (classic SPP + LE GATT) on the RM2, polled from the main loop + target_sources(pico_serial PRIVATE src/rp2040/bt.c) + pico_btstack_make_gatt_header(pico_serial PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src/rp2040/pico_serial_w.gatt) + target_link_libraries(pico_serial PRIVATE + pico_cyw43_arch_poll pico_btstack_cyw43 pico_btstack_ble pico_btstack_classic) + target_compile_definitions(pico_serial PRIVATE CYW43_LWIP=0) # no Wi-Fi networking (yet) +endif () pico_add_extra_outputs(pico_serial) set_target_properties(pico_serial PROPERTIES OUTPUT_NAME pico-serial-${PS_BOARD}) diff --git a/firmware/PROTOCOL.md b/firmware/PROTOCOL.md index 94eb9c8..e441080 100644 --- a/firmware/PROTOCOL.md +++ b/firmware/PROTOCOL.md @@ -34,6 +34,8 @@ An unknown request or an out-of-range value stalls. | 7 | CLEAR_STATS | OUT | 0 | — | | 8 | SET_BAUD_MODE | OUT | 0 auto, 1 host, 2 learn | — (saved) | | 9 | AUTOBAUD_RESTART | OUT | 0 | — (no effect unless learning is in use) | +| 10 | BT_PAIRING | OUT | seconds (0 closes) | — W board only: open the Bluetooth pairing window | +| 11 | BT_FORGET | OUT | 0 | — W board only: forget every bonded phone, then open the window | All multi-byte fields are little-endian. @@ -126,3 +128,30 @@ this protocol for the common lines: - **as DCE:** DSR = the computer's DTR; DCD = a computer is attached; - **as DTE:** the modem's DCD, DSR and RI; - **both roles:** break, framing, parity and overrun events. + +## Bluetooth (W board) + +The W board offers the same controls over BLE, in the **pico-serial +control** service, `50530001-5C6F-4E2B-9A6B-1D2C0E5F7A10`. Its +characteristics share that UUID with the second field changed (`5053000N`). +Every one needs an encrypted (bonded) link. Writes other than line coding +are refused (`Write Not Permitted`) unless this BLE link owns the RS-232 +port. + +| UUID | Name | Access | Content | +|---|---|---|---| +| `50530002` | Line coding | read, write | baud (u32), data bits, parity (0 none, 1 odd, 2 even), stop bits (1, 2): 7 bytes. Kept for this link and used whenever it owns the port | +| `50530003` | Outputs | read, write | write: mask, value (as SET_OUTPUTS); read: override mask, lines driven now | +| `50530004` | Inputs | read, notify | `ps_inputs_t`; notified when it changes | +| `50530005` | Mode | read, write | write: the setting (as SET_MODE); read: setting, role now | +| `50530006` | Break | write | u16 ms; 0 ends it, `0xFFFF` until 0 | +| `50530007` | Flow | read, write | as SET_FLOW | +| `50530008` | Credits | read, notify | u16: free bytes in the buffer to the DB25. Notified when it moves by 256 or more, and when it empties | +| `50530009` | Info | read | `ps_info_t` | + +Data goes through the Nordic UART Service (`6E400001-B5A3-F393-E0A9-E50E24DCCA9E`): +write to RX `6E400002…`, subscribe to TX `6E400003…`. A BLE write can't be +held back, so an app sending more than the buffer holds (4 KB) should +watch Credits. + +Classic Bluetooth (SPP) carries data only; there are no controls on it. diff --git a/firmware/README.md b/firmware/README.md index d2cbfd8..640b0af 100644 --- a/firmware/README.md +++ b/firmware/README.md @@ -5,12 +5,16 @@ bridged to the DB25. It works out by itself whether a computer (DCE role) or a modem (DTE role) is attached, and switches on the matching RS-232 chip. As DCE it also learns the computer's baud rate from its typing. +The same firmware runs pico-serial W (SPEC-W.md), which adds Bluetooth: BLE +for iPhone and classic Bluetooth serial (SPP) for Android. See +[Bluetooth (W board)](#bluetooth-w-board). + ## Build Needs CMake 3.13+, Ninja or Make, and the Arm GNU toolchain (`arm-none-eabi-gcc`). ```sh -cmake -S firmware -B firmware/build -G Ninja # -DPS_BOARD=hood (default) or pico +cmake -S firmware -B firmware/build -G Ninja # -DPS_BOARD=hood (default), w or pico ninja -C firmware/build # -> firmware/build/pico-serial-hood.uf2 ``` @@ -23,6 +27,9 @@ ninja -C firmware/build - **Boards:** - `hood`: the real board, with 16 MB flash and the slow-crystal start-up margin. + - `w`: pico-serial W, the hood board's circuit plus the RM2 radio wired as + on Pico W. Adds BTstack and the radio's firmware (the `.uf2` is about + 900 KB). - `pico`: a bench rig built on a Raspberry Pi Pico wired to the two transceivers as SPEC.md §4.5. Same GPIOs. The LEDs move off GP23/24, which belong to the Pico. @@ -53,6 +60,32 @@ ninja -C firmware/build | Safety | Both transceivers start off (as do the board's pull-downs) and are never on together. Watchdog 1 s | | USB IDs | `1209:0001`, pid.codes' shared **test** PID. Get a real PID before giving boards to others (`src/rp2040/board_config.h`) | +## Bluetooth (W board) + +`src/rp2040/bt.c`, BTstack on the RM2 (CYW43439), polled from the main loop +like the USB code, so nothing runs in an interrupt. + +| | | +|---|---| +| Name | `pico-serial-XXXX`, XXXX = the end of the Bluetooth address | +| Android, desktops | Classic **SPP** server on RFCOMM channel 1, "pico-serial". dmodem-android's "paired device" mode works unchanged | +| iPhone, anything BLE | **Nordic UART Service**: write to RX (`6E400002…`), notifications from TX (`6E400003…`). Generic BLE UART apps work | +| Control | The pico-serial control service over BLE: line coding, outputs, inputs (notify), mode, break, flow, credits (notify), info. See [PROTOCOL.md](PROTOCOL.md#bluetooth-w-board) | +| Who owns the port | USB while its port is open (DTR set); otherwise the wireless link that connected first; the others stay connected but read-only (BLE writes are refused, SPP data is dropped). `src/core/link.c` | +| Modem lines | A wireless link counts as DTR and RTS on, so as DCE the computer sees DCD and DSR while a phone is connected. Over SPP, DCD instead follows the phone's `CONNECT` / `NO CARRIER` result codes (Android can't send modem lines) | +| Pairing | Only inside a **pairing window**: 2 minutes after power-up while nothing is bonded, 2 minutes after a press of the PAIR button, or on request over USB (`BT_PAIRING`). Outside it, only bonded phones connect. Up to 4 bonds, kept in flash. Holding PAIR for 10 s forgets them all (also `BT_FORGET` over USB) | +| Security | LE Secure Connections and classic Secure Simple Pairing, "Just Works". Data and control need an encrypted link; a phone that isn't bonded and connects outside the window can't use either | +| Flow control | SPP: RFCOMM credits, given only while the buffer to the DB25 has room for a whole frame. BLE: GATT writes can't be held back, so apps should pace them with the Credits characteristic | +| LEDs | BT: slow blink while advertising, fast blink while the pairing window is open, on while a phone is connected. TR, CD on GPIOs; RD, SD on the RM2's own GPIOs | +| Flash | Settings in the last sector as before; Bluetooth bonds in the two sectors below it | + +**Not done yet** (SPEC-W.md §4): +- the BLE L2CAP channel for a dedicated iOS app (§4.2); +- the optional static passkey (§4.5), and the name change over USB (§4.1); +- DTR drop → `ATH` hang-up over SPP (§4.4, off by default anyway); +- asking iOS for the 2M PHY (data length extension is on); +- Wi-Fi. + ## Automatic baud rate As DCE, the computer types at whatever speed its terminal is set to, and @@ -112,11 +145,13 @@ one and holds back what it receives. ``` src/core/ portable: role detection, line mapping, flow control, baud-rate - learning, settings (no SDK) + learning, settings, which host link owns the port (no SDK) src/rp2040/ HAL (GPIO, UART + IRQ, PIO line timing, flash), USB descriptors - and callbacks, main -src/generated/ board_pins.h, written by hardware/netlist/build_netlist.py -boards/ SDK board header for the hood board + and callbacks, Bluetooth (W board: bt.c, the GATT database, + BTstack config), main +src/generated/ board_pins.h and board_pins_w.h, written by + hardware/netlist/build_netlist.py +boards/ SDK board headers for the hood and W boards test/ host tests for the core (fake HAL) and the emulator test ``` @@ -126,10 +161,14 @@ there, and the pin header follows. ## Tests ```sh -make -C firmware/test run # core and baud detector, sanitizers on +make -C firmware/test run # core, baud detector, host links; sanitizers on firmware/test/emu/run.sh firmware/build/pico-serial-hood.bin # whole firmware in an emulator ``` +- **Host link tests** (`test_link.c`): who owns the port as USB, BLE and + SPP come and go; line coding kept for a link until it owns the port; + DCD from `CONNECT` / `NO CARRIER`, split across writes, and not from + text inside longer lines. - **Host tests:** the core's logic against a fake board (27 tests). The tests were checked by breaking the core on purpose: removing DCE detection, the buffer hysteresis, the DSR mapping, the one-shot error @@ -179,7 +218,12 @@ firmware/test/emu/run.sh firmware/build/pico-serial-hood.bin # whole firmware the bench. - **Real host drivers:** Windows' usbser, macOS and Linux cdc_acm, and Android's usb-serial-for-android haven't been tried. +- **Bluetooth:** the W firmware builds, but nothing about the radio has + run: the emulator has no CYW43, and there's no W board or Pico W rig + yet. A Pico W wired to the transceivers (SPEC-W.md §9) is the first test: + pairing from an iPhone and from Android, dmodem-android over SPP, the + ownership rules, and throughput. - **Not built yet:** - - the Bluetooth (W) board's BLE/SPP links, SPEC-W.md §4–5; + - the rest of SPEC-W.md §4 listed under [Bluetooth](#bluetooth-w-board); - Microsoft OS descriptors, so Windows binds WinUSB to the control interface without Zadig. diff --git a/firmware/boards/pico_serial_w.h b/firmware/boards/pico_serial_w.h new file mode 100644 index 0000000..ea92877 --- /dev/null +++ b/firmware/boards/pico_serial_w.h @@ -0,0 +1,70 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 Neo-Desktop + */ +// pico-serial W (SPEC-W.md): the hood board's circuit plus a Raspberry Pi +// RM2 (CYW43439) wired exactly as on Pico W, so the SDK's CYW43 defaults apply. +#ifndef _BOARDS_PICO_SERIAL_W_H +#define _BOARDS_PICO_SERIAL_W_H + +pico_board_cmake_set(PICO_PLATFORM, rp2040) +pico_board_cmake_set(PICO_CYW43_SUPPORTED, 1) + +#define PICO_SERIAL_W + +// No UART/I2C/SPI defaults: every UART pin belongs to the RS-232 transceivers. + +// W25Q128JV works with the generic W25Q080 boot stage 2 +#define PICO_BOOT_STAGE2_CHOOSE_W25Q080 1 +#ifndef PICO_FLASH_SPI_CLKDIV +#define PICO_FLASH_SPI_CLKDIV 2 +#endif +pico_board_cmake_set_default(PICO_FLASH_SIZE_BYTES, (16 * 1024 * 1024)) +#ifndef PICO_FLASH_SIZE_BYTES +#define PICO_FLASH_SIZE_BYTES (16 * 1024 * 1024) +#endif + +// SPEC.md 4.2: margin for the crystal to start +#ifndef PICO_XOSC_STARTUP_DELAY_MULTIPLIER +#define PICO_XOSC_STARTUP_DELAY_MULTIPLIER 64 +#endif + +#ifndef PICO_RP2040_B0_SUPPORTED +#define PICO_RP2040_B0_SUPPORTED 0 +#endif +#ifndef PICO_RP2040_B1_SUPPORTED +#define PICO_RP2040_B1_SUPPORTED 0 +#endif + +// Bluetooth bonds (BTstack's flash bank): the two sectors below the last +// one, which holds the firmware's settings. +#ifndef PICO_FLASH_BANK_STORAGE_OFFSET +#define PICO_FLASH_BANK_STORAGE_OFFSET (PICO_FLASH_SIZE_BYTES - 3 * 4096) +#endif + +// RM2: SPEC-W.md 3.1 (same pins as Pico W) +#ifndef CYW43_WL_GPIO_COUNT +#define CYW43_WL_GPIO_COUNT 3 +#endif +#ifndef CYW43_PIN_WL_DYNAMIC +#define CYW43_PIN_WL_DYNAMIC 0 +#endif +#ifndef CYW43_DEFAULT_PIN_WL_REG_ON +#define CYW43_DEFAULT_PIN_WL_REG_ON 23u +#endif +#ifndef CYW43_DEFAULT_PIN_WL_DATA_OUT +#define CYW43_DEFAULT_PIN_WL_DATA_OUT 24u +#endif +#ifndef CYW43_DEFAULT_PIN_WL_DATA_IN +#define CYW43_DEFAULT_PIN_WL_DATA_IN 24u +#endif +#ifndef CYW43_DEFAULT_PIN_WL_HOST_WAKE +#define CYW43_DEFAULT_PIN_WL_HOST_WAKE 24u +#endif +#ifndef CYW43_DEFAULT_PIN_WL_CLOCK +#define CYW43_DEFAULT_PIN_WL_CLOCK 29u +#endif +#ifndef CYW43_DEFAULT_PIN_WL_CS +#define CYW43_DEFAULT_PIN_WL_CS 25u +#endif +#endif diff --git a/firmware/src/core/core.c b/firmware/src/core/core.c index c826fd8..2bdd033 100644 --- a/firmware/src/core/core.c +++ b/firmware/src/core/core.c @@ -135,6 +135,7 @@ void core_init(core_t *c) { ring_init(&c->to_rs232); c->format = c->uart = DEFAULT_FORMAT; c->rx_room = true; + c->host_dcd = -1; uint8_t blob[CORE_SETTINGS_BLOB]; if (!(hal_settings_load(blob, sizeof blob) && core_settings_unpack(&c->settings, blob))) { c->settings.mode = PS_MODE_AUTO; @@ -179,6 +180,7 @@ static uint8_t outputs_for(core_t *c) { // as a null-modem cable would: the host's DTR is the computer's DCD and DSR if (dtr) out |= PS_LINE_DCD | PS_LINE_DSR; if (rts) out |= PS_LINE_CTS; + if (c->host_dcd >= 0) out = (uint8_t)((out & ~PS_LINE_DCD) | (c->host_dcd ? PS_LINE_DCD : 0)); flow_line = PS_LINE_CTS; out = (uint8_t)((out & ~c->override_mask) | (c->override_value & c->override_mask)); out &= PS_LINE_DCD | PS_LINE_DSR | PS_LINE_RI | PS_LINE_CTS; @@ -343,6 +345,8 @@ void core_host_lines(core_t *c, bool dtr, bool rts) { c->host_lines = (uint8_t)((dtr ? PS_LINE_DTR : 0) | (rts ? PS_LINE_RTS : 0)); } +void core_host_dcd(core_t *c, int8_t dcd) { c->host_dcd = dcd; } + void core_host_format(core_t *c, uint32_t baud, uint8_t stop_cdc, uint8_t parity_cdc, uint8_t data_bits) { uart_format_t f = {baud ? baud : c->format.baud, data_bits, 1, 0}; uint8_t flags = 0; diff --git a/firmware/src/core/core.h b/firmware/src/core/core.h index 3e210c4..cd4e2db 100644 --- a/firmware/src/core/core.h +++ b/firmware/src/core/core.h @@ -68,6 +68,7 @@ typedef struct { uint32_t t_lost; // peer missing since (0 = present) uint8_t host_lines; // PS_LINE_DTR / RTS from the host + int8_t host_dcd; // DCE: -1 = DCD follows the host's DTR; 0/1 = set by the link (link.h) uint8_t override_mask, override_value; uint8_t outputs, inputs; bool rx_room; // hysteresis on the to-host buffer @@ -117,6 +118,7 @@ void core_poll(core_t *c); // Host link events void core_host_lines(core_t *c, bool dtr, bool rts); +void core_host_dcd(core_t *c, int8_t dcd); // -1: follow DTR (the default) void core_host_format(core_t *c, uint32_t baud, uint8_t stop_bits_cdc, uint8_t parity_cdc, uint8_t data_bits); void core_host_break(core_t *c, uint16_t duration_ms); uint32_t core_host_write(core_t *c, const uint8_t *data, uint32_t len); // returns bytes accepted diff --git a/firmware/src/core/link.c b/firmware/src/core/link.c new file mode 100644 index 0000000..5950580 --- /dev/null +++ b/firmware/src/core/link.c @@ -0,0 +1,141 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 Neo-Desktop + */ +// Host links and port ownership. See link.h and SPEC-W.md 4.4, 4.6. +#include "link.h" +#include + +links_t g_links; + +static uint8_t pick_owner(const links_t *s) { + const link_t *usb = &s->l[LINK_USB]; + if (usb->up && usb->dtr) return LINK_USB; + uint8_t best = LINK_NONE; + for (uint8_t i = LINK_BLE; i < LINK_COUNT; i++) + if (s->l[i].up && (best == LINK_NONE || s->l[i].order < s->l[best].order)) best = i; + if (best != LINK_NONE) return best; + return usb->up ? LINK_USB : LINK_NONE; +} + +// Hand the core the owner's lines and DCD, and on a change of owner its coding. +static void apply(links_t *s, core_t *c, bool coding) { + if (s->owner == LINK_NONE) { + core_host_lines(c, false, false); + core_host_dcd(c, -1); + return; + } + const link_t *l = &s->l[s->owner]; + core_host_lines(c, l->dtr, l->rts); + core_host_dcd(c, l->rc_dcd ? l->dcd : -1); + if (coding && l->has_format) core_host_format(c, l->baud, l->stop_cdc, l->parity_cdc, l->data_bits); +} + +static void update(links_t *s, core_t *c) { + uint8_t o = pick_owner(s); + bool changed = o != s->owner; + if (changed) { + s->owner = o; + s->owner_changes++; + if (c->break_on) core_host_break(c, 0); // the old owner's break ends with it + } + apply(s, c, changed); +} + +void links_init(links_t *s, core_t *c) { + memset(s, 0, sizeof *s); + s->owner = LINK_NONE; + for (uint8_t i = 0; i < LINK_COUNT; i++) s->l[i].dcd = -1; + s->l[LINK_SPP].rc_dcd = true; + apply(s, c, false); +} + +void link_up(links_t *s, core_t *c, uint8_t id, bool up) { + link_t *l = &s->l[id]; + if (l->up == up) return; + l->up = up; + l->n = 0; + l->overflow = false; + l->dcd = l->rc_dcd ? 0 : -1; // no call yet + if (up) { + l->order = ++s->order; + bool wireless = id != LINK_USB; + l->dtr = l->rts = wireless; + l->has_format = false; + } else { + l->dtr = l->rts = false; + } + update(s, c); +} + +void link_lines(links_t *s, core_t *c, uint8_t id, bool dtr, bool rts) { + s->l[id].dtr = dtr; + s->l[id].rts = rts; + update(s, c); +} + +void link_format(links_t *s, core_t *c, uint8_t id, uint32_t baud, uint8_t stop_cdc, uint8_t parity_cdc, + uint8_t data_bits) { + link_t *l = &s->l[id]; + l->has_format = true; + l->baud = baud; + l->stop_cdc = stop_cdc; + l->parity_cdc = parity_cdc; + l->data_bits = data_bits; + if (s->owner == id) core_host_format(c, baud, stop_cdc, parity_cdc, data_bits); +} + +bool link_break(links_t *s, core_t *c, uint8_t id, uint16_t ms) { + if (s->owner != id) return false; + core_host_break(c, ms); + return true; +} + +void link_rc_dcd(links_t *s, core_t *c, uint8_t id, bool on) { + link_t *l = &s->l[id]; + l->rc_dcd = on; + l->dcd = on ? 0 : -1; + l->n = 0; + if (s->owner == id) apply(s, c, false); +} + +// A complete line from the phone: is it a result code that changes DCD? +static void rc_line(links_t *s, core_t *c, uint8_t id, link_t *l) { + int8_t dcd = l->dcd; + if (l->n >= 7 && memcmp(l->line, "CONNECT", 7) == 0 && (l->n == 7 || l->line[7] == ' ' || l->line[7] == '/')) + dcd = 1; + else if (l->n == 10 && memcmp(l->line, "NO CARRIER", 10) == 0) + dcd = 0; + if (dcd != l->dcd) { + l->dcd = dcd; + if (s->owner == id) core_host_dcd(c, dcd); + } +} + +static void rc_scan(links_t *s, core_t *c, uint8_t id, const uint8_t *p, uint32_t n) { + link_t *l = &s->l[id]; + for (uint32_t i = 0; i < n; i++) { + uint8_t b = p[i]; + if (b == '\r' || b == '\n') { + if (l->n && !l->overflow) rc_line(s, c, id, l); + l->n = 0; + l->overflow = false; + } else if (l->n < sizeof l->line) { + l->line[l->n++] = (char)b; + } else { + l->overflow = true; // too long to be a result code + } + } +} + +uint32_t link_write(links_t *s, core_t *c, uint8_t id, const uint8_t *data, uint32_t len) { + if (s->owner != id) return len; + uint32_t n = core_host_write(c, data, len); + if (s->l[id].rc_dcd) rc_scan(s, c, id, data, n); + return n; +} + +uint32_t link_read(links_t *s, core_t *c, uint8_t id, uint8_t *data, uint32_t max) { + if (s->owner != id) return 0; + return core_host_read(c, data, max); +} diff --git a/firmware/src/core/link.h b/firmware/src/core/link.h new file mode 100644 index 0000000..70e7473 --- /dev/null +++ b/firmware/src/core/link.h @@ -0,0 +1,62 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 Neo-Desktop + */ +// Host links (USB CDC, and on the W board BLE and classic Bluetooth SPP) and +// which one owns the RS-232 port (SPEC-W.md 4.6): +// 1. USB, while its port is open (DTR set); +// 2. otherwise the wireless link that connected first; +// 3. otherwise USB, if it's plugged into a host (the wired boards: always). +// Only the owner's lines, line coding, break and data reach the core; the +// others stay connected but their data is dropped. Portable, like core.c. +#pragma once +#include +#include +#include "core.h" + +enum link_id { LINK_USB = 0, LINK_BLE = 1, LINK_SPP = 2, LINK_COUNT = 3, LINK_NONE = 0xFF }; + +#define LINK_RC_LINE 24u // longest result-code line looked at + +typedef struct { + bool up; // connected (USB: mounted) + bool dtr, rts; + uint32_t order; // when it connected (lower = earlier) + bool has_format; + uint32_t baud; + uint8_t stop_cdc, parity_cdc, data_bits; + // DCD from result codes: the phone is the modem and says CONNECT / NO CARRIER + bool rc_dcd; + int8_t dcd; // -1: DCD follows DTR; 0/1: from result codes + char line[LINK_RC_LINE]; + uint8_t n; + bool overflow; +} link_t; + +typedef struct { + link_t l[LINK_COUNT]; + uint8_t owner; // link_id, LINK_NONE + uint32_t order; + uint32_t owner_changes; +} links_t; + +extern links_t g_links; + +void links_init(links_t *s, core_t *c); +// Connection events. Wireless links come up with DTR and RTS asserted, so a +// plain terminal app gets DCD and DSR while connected (SPEC-W 4.3). +void link_up(links_t *s, core_t *c, uint8_t id, bool up); +void link_lines(links_t *s, core_t *c, uint8_t id, bool dtr, bool rts); +// CDC-style line coding (stop: 0 = 1, 1 = 1.5, 2 = 2; parity 0 none 1 odd 2 even ...) +void link_format(links_t *s, core_t *c, uint8_t id, uint32_t baud, uint8_t stop_cdc, uint8_t parity_cdc, + uint8_t data_bits); +bool link_break(links_t *s, core_t *c, uint8_t id, uint16_t ms); // false: not the owner +// DCD from CONNECT / NO CARRIER in this link's data (SPEC-W 4.4). Default: on for SPP. +void link_rc_dcd(links_t *s, core_t *c, uint8_t id, bool on); + +static inline bool link_owns(const links_t *s, uint8_t id) { return s->owner == id; } +// Data from the link toward the RS-232 port: returns bytes accepted. A link +// that doesn't own the port has its data dropped (returns len). +uint32_t link_write(links_t *s, core_t *c, uint8_t id, const uint8_t *data, uint32_t len); +// Data from the RS-232 port for the link; nothing unless it owns the port. +uint32_t link_read(links_t *s, core_t *c, uint8_t id, uint8_t *data, uint32_t max); diff --git a/firmware/src/core/protocol.h b/firmware/src/core/protocol.h index 3247e84..dee4a9d 100644 --- a/firmware/src/core/protocol.h +++ b/firmware/src/core/protocol.h @@ -24,6 +24,9 @@ enum ps_request { PS_REQ_CLEAR_STATS = 0x07, // OUT PS_REQ_SET_BAUD_MODE = 0x08, // OUT wValue = ps_baud (saved) PS_REQ_AUTOBAUD_RESTART = 0x09, // OUT: learn the baud rate again now + // W board only (stall elsewhere): + PS_REQ_BT_PAIRING = 0x0A, // OUT wValue = seconds to allow pairing (0 = close the window) + PS_REQ_BT_FORGET = 0x0B, // OUT: forget every bonded phone }; enum ps_mode { PS_MODE_AUTO = 0, PS_MODE_DCE = 1, PS_MODE_DTE = 2 }; diff --git a/firmware/src/rp2040/board_config.h b/firmware/src/rp2040/board_config.h index 2531496..32a7012 100644 --- a/firmware/src/rp2040/board_config.h +++ b/firmware/src/rp2040/board_config.h @@ -4,7 +4,11 @@ */ // Per-board choices the netlist doesn't decide: LEDs, names, IDs. #pragma once +#if defined(PS_BOARD_W) +#include "generated/board_pins_w.h" +#else #include "generated/board_pins.h" +#endif // USB IDs. 1209:0001 is pid.codes' shared *test* PID: fine on the bench, // not for boards given to other people. Apply for a PID (Raspberry Pi's @@ -27,6 +31,18 @@ #define LED_PIN_SD 27 #define LED_PIN_RD 28 #define LED_PIN_RI LED_NONE +#elif defined(PS_BOARD_W) +// pico-serial W (SPEC-W.md). LEDs fitted. PWR/BT shows the Bluetooth state +// (bt.c); RD and SD are on the RM2's own GPIOs (WLGPIO_LED_*), driven +// through the radio; there's no RI LED. +#define PS_BOARD_ID 1 +#define PS_PRODUCT "pico-serial W" +#define LED_PIN_PWR LED_NONE +#define LED_PIN_TR PIN_LED_TR +#define LED_PIN_CD PIN_LED_CD +#define LED_PIN_SD LED_NONE +#define LED_PIN_RD LED_NONE +#define LED_PIN_RI LED_NONE #else // DB25 hood board. LEDs are optional (not fitted by default); driving the // pins does no harm either way. diff --git a/firmware/src/rp2040/bt.c b/firmware/src/rp2040/bt.c new file mode 100644 index 0000000..18f31ed --- /dev/null +++ b/firmware/src/rp2040/bt.c @@ -0,0 +1,544 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 Neo-Desktop + */ +// Bluetooth on pico-serial W (SPEC-W.md 4). BTstack on the RM2 (CYW43439), +// polled from the main loop (pico_cyw43_arch_poll), so every callback here +// runs in the same context as the USB code and the core. +// +// classic: an SPP server on RFCOMM ("pico-serial"), for Android and desktops; +// LE: the Nordic UART Service for data, and the pico-serial control +// service (pico_serial_w.gatt) for lines and settings. +// +// Both are host links (link.h): whichever connected first owns the RS-232 +// port unless USB has its port open. Pairing only inside a pairing window. +#include +#include +#include "pico/stdlib.h" +#include "pico/cyw43_arch.h" +#include "btstack.h" +#include "board_config.h" +#include "core.h" +#include "link.h" +#include "bt.h" +#include "pico_serial_w.h" // GATT database, generated from pico_serial_w.gatt + +#define PAIR_WINDOW_S 120u // SPEC-W 4.5: 2 minutes +#define FORGET_HOLD_MS 10000u // hold the button this long to forget all phones +#define BUTTON_DEBOUNCE_MS 50u +#define RFCOMM_CHANNEL 1 +#define SPP_MAX_FRAME 1000u // RFCOMM frame size we offer +#define SPP_MAX_CREDITS 3u // frames the phone may send ahead +#define CREDITS_NOTIFY_STEP 256u // notify the free space when it moves this much + +// handles from the generated GATT database +#define H_NAME ATT_CHARACTERISTIC_GAP_DEVICE_NAME_01_VALUE_HANDLE +#define H_NUS_RX ATT_CHARACTERISTIC_6E400002_B5A3_F393_E0A9_E50E24DCCA9E_01_VALUE_HANDLE +#define H_NUS_TX ATT_CHARACTERISTIC_6E400003_B5A3_F393_E0A9_E50E24DCCA9E_01_VALUE_HANDLE +#define H_NUS_TX_CCC ATT_CHARACTERISTIC_6E400003_B5A3_F393_E0A9_E50E24DCCA9E_01_CLIENT_CONFIGURATION_HANDLE +#define H_CODING ATT_CHARACTERISTIC_50530002_5C6F_4E2B_9A6B_1D2C0E5F7A10_01_VALUE_HANDLE +#define H_OUTPUTS ATT_CHARACTERISTIC_50530003_5C6F_4E2B_9A6B_1D2C0E5F7A10_01_VALUE_HANDLE +#define H_INPUTS ATT_CHARACTERISTIC_50530004_5C6F_4E2B_9A6B_1D2C0E5F7A10_01_VALUE_HANDLE +#define H_INPUTS_CCC ATT_CHARACTERISTIC_50530004_5C6F_4E2B_9A6B_1D2C0E5F7A10_01_CLIENT_CONFIGURATION_HANDLE +#define H_MODE ATT_CHARACTERISTIC_50530005_5C6F_4E2B_9A6B_1D2C0E5F7A10_01_VALUE_HANDLE +#define H_BREAK ATT_CHARACTERISTIC_50530006_5C6F_4E2B_9A6B_1D2C0E5F7A10_01_VALUE_HANDLE +#define H_FLOW ATT_CHARACTERISTIC_50530007_5C6F_4E2B_9A6B_1D2C0E5F7A10_01_VALUE_HANDLE +#define H_CREDITS ATT_CHARACTERISTIC_50530008_5C6F_4E2B_9A6B_1D2C0E5F7A10_01_VALUE_HANDLE +#define H_CREDITS_CCC ATT_CHARACTERISTIC_50530008_5C6F_4E2B_9A6B_1D2C0E5F7A10_01_CLIENT_CONFIGURATION_HANDLE +#define H_INFO ATT_CHARACTERISTIC_50530009_5C6F_4E2B_9A6B_1D2C0E5F7A10_01_VALUE_HANDLE + +static bool s_ok; // radio up +static bool s_working; // HCI running +static char s_name[20] = "pico-serial"; +static btstack_packet_callback_registration_t s_hci_cb, s_sm_cb; +static uint8_t s_spp_sdp[150]; + +// pairing window +static uint32_t s_pair_until; // 0 = closed +static uint32_t s_btn_down; // when the button went down (0 = up) +static bool s_btn_handled, s_btn_forgot; + +// BLE +static hci_con_handle_t s_le = HCI_CON_HANDLE_INVALID; +static bool s_le_secure; // encrypted: counts as a link +static bool s_nus_notify, s_inputs_notify, s_credits_notify; +static bool s_le_pending; // asked for a "can send now" +static uint8_t s_inputs_sent[sizeof(ps_inputs_t)]; +static bool s_inputs_valid; +static uint32_t s_credits_sent; + +// SPP +static uint16_t s_spp; // RFCOMM channel id, 0 = none +static uint16_t s_spp_frame; +static uint8_t s_spp_credits; // frames the phone may still send +static bool s_spp_pending; + +// LEDs +static uint8_t s_wl_leds = 0xFF; // RD/SD as last written to the RM2 + +static bool pairing_open(void) { return s_pair_until != 0; } + +static uint32_t now_ms(void) { return to_ms_since_boot(get_absolute_time()); } + +// --------------------------------------------------------------------------- +// Advertising: NUS UUID in the advertisement, the name in the scan response. +// Discoverable flag only while the pairing window is open. +// --------------------------------------------------------------------------- +static uint8_t s_adv[3 + 18]; +static uint8_t s_scan[2 + sizeof s_name]; + +static void advertise(void) { + if (!s_working) return; + static const uint8_t nus[16] = {0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, + 0x93, 0xF3, 0xA3, 0xB5, 0x01, 0x00, 0x40, 0x6E}; + uint8_t n = 0; + s_adv[n++] = 2; + s_adv[n++] = BLUETOOTH_DATA_TYPE_FLAGS; + s_adv[n++] = pairing_open() ? 0x06 : 0x04; // LE general discoverable (window only); no BR/EDR on LE + s_adv[n++] = 17; + s_adv[n++] = BLUETOOTH_DATA_TYPE_COMPLETE_LIST_OF_128_BIT_SERVICE_CLASS_UUIDS; + memcpy(s_adv + n, nus, sizeof nus); + n = (uint8_t)(n + sizeof nus); + gap_advertisements_set_data(n, s_adv); + + uint8_t len = (uint8_t)strlen(s_name); + s_scan[0] = (uint8_t)(len + 1); + s_scan[1] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME; + memcpy(s_scan + 2, s_name, len); + gap_scan_response_set_data((uint8_t)(len + 2), s_scan); + + bd_addr_t none = {0}; + gap_advertisements_set_params(0x00A0, 0x0140, 0 /* ADV_IND */, 0, none, 0x07, 0); + gap_advertisements_enable(1); +} + +static void set_window(uint32_t seconds) { + if (seconds) { + uint32_t t = now_ms() + seconds * 1000u; + s_pair_until = t ? t : 1; + } else { + s_pair_until = 0; + } + if (!s_working) return; + gap_discoverable_control(pairing_open() ? 1 : 0); + advertise(); +} + +void bt_pairing_window(uint16_t seconds) { set_window(seconds); } + +static bool have_bonds(void) { + if (le_device_db_count() > 0) return true; + btstack_link_key_iterator_t it; + bool any = false; + if (gap_link_key_iterator_init(&it)) { + bd_addr_t a; + link_key_t k; + link_key_type_t t; + any = gap_link_key_iterator_get_next(&it, a, k, &t) != 0; + gap_link_key_iterator_done(&it); + } + return any; +} + +void bt_forget_all(void) { + if (!s_working) return; + gap_delete_all_link_keys(); + for (int i = 0; i < le_device_db_max_count(); i++) le_device_db_remove(i); + set_window(PAIR_WINDOW_S); // nothing bonded now: let a phone pair +} + +// --------------------------------------------------------------------------- +// HCI, security manager +// --------------------------------------------------------------------------- +static void le_link(bool up) { + if (up == s_le_secure) return; + s_le_secure = up; + s_inputs_valid = false; + link_up(&g_links, &g_core, LINK_BLE, up); +} + +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; + bd_addr_t addr; + switch (hci_event_packet_get_type(packet)) { + case BTSTACK_EVENT_STATE: + if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) return; + s_working = true; + gap_local_bd_addr(addr); + snprintf(s_name, sizeof s_name, "pico-serial-%02X%02X", addr[4], addr[5]); + gap_set_local_name(s_name); + set_window(have_bonds() ? 0 : PAIR_WINDOW_S); // SPEC-W 4.5: open at power-up until bonded + break; + case HCI_EVENT_USER_CONFIRMATION_REQUEST: // classic Secure Simple Pairing, Just Works + hci_event_user_confirmation_request_get_bd_addr(packet, addr); + if (pairing_open()) gap_ssp_confirmation_response(addr); + else gap_ssp_confirmation_negative(addr); + break; + case HCI_EVENT_PIN_CODE_REQUEST: // legacy pairing: never + hci_event_pin_code_request_get_bd_addr(packet, addr); + gap_pin_code_negative(addr); + break; + case HCI_EVENT_ENCRYPTION_CHANGE: + case HCI_EVENT_ENCRYPTION_CHANGE_V2: + if (hci_event_encryption_change_get_connection_handle(packet) == s_le) + le_link(hci_event_encryption_change_get_status(packet) == 0 && + hci_event_encryption_change_get_encryption_enabled(packet)); + break; + case HCI_EVENT_DISCONNECTION_COMPLETE: + if (hci_event_disconnection_complete_get_connection_handle(packet) == s_le) { + s_le = HCI_CON_HANDLE_INVALID; + s_nus_notify = s_inputs_notify = s_credits_notify = s_le_pending = false; + le_link(false); + } + break; + default: + break; + } +} + +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; + hci_con_handle_t h; + switch (hci_event_packet_get_type(packet)) { + case SM_EVENT_JUST_WORKS_REQUEST: + h = sm_event_just_works_request_get_handle(packet); + if (pairing_open()) sm_just_works_confirm(h); + else sm_bonding_decline(h); + break; + case SM_EVENT_NUMERIC_COMPARISON_REQUEST: + h = sm_event_numeric_comparison_request_get_handle(packet); + if (pairing_open()) sm_numeric_comparison_confirm(h); + else sm_bonding_decline(h); + break; + default: + break; + } +} + +// --------------------------------------------------------------------------- +// SPP (RFCOMM) +// --------------------------------------------------------------------------- +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; + if (s_spp_credits) s_spp_credits--; + link_write(&g_links, &g_core, LINK_SPP, packet, size); // room was reserved by the credit + return; + } + if (type != HCI_EVENT_PACKET) return; + switch (hci_event_packet_get_type(packet)) { + case RFCOMM_EVENT_INCOMING_CONNECTION: { + uint16_t cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet); + if (s_spp) rfcomm_decline_connection(cid); // one SPP link at a time + else rfcomm_accept_connection(cid); + break; + } + case RFCOMM_EVENT_CHANNEL_OPENED: + if (rfcomm_event_channel_opened_get_status(packet)) break; + s_spp = rfcomm_event_channel_opened_get_rfcomm_cid(packet); + s_spp_frame = rfcomm_event_channel_opened_get_max_frame_size(packet); + s_spp_credits = 1; // the initial credit given at registration + s_spp_pending = false; + link_up(&g_links, &g_core, LINK_SPP, true); + break; + case RFCOMM_EVENT_CAN_SEND_NOW: { + s_spp_pending = false; + static uint8_t buf[SPP_MAX_FRAME]; + uint16_t max = s_spp_frame < sizeof buf ? s_spp_frame : (uint16_t)sizeof buf; + uint32_t n = link_read(&g_links, &g_core, LINK_SPP, buf, max); + if (n) rfcomm_send(s_spp, buf, (uint16_t)n); + break; + } + case RFCOMM_EVENT_CHANNEL_CLOSED: + if (rfcomm_event_channel_closed_get_rfcomm_cid(packet) != s_spp) break; + s_spp = 0; + link_up(&g_links, &g_core, LINK_SPP, false); + break; + default: + break; + } +} + +static void spp_service(void) { + if (!s_spp) return; + // give the phone credits while there's room for a whole frame per credit + uint32_t frame = s_spp_frame ? s_spp_frame : 1u; + while (s_spp_credits < SPP_MAX_CREDITS && ring_free(&g_core.to_rs232) >= (s_spp_credits + 1u) * frame) { + rfcomm_grant_credits(s_spp, 1); + s_spp_credits++; + } + if (!s_spp_pending && link_owns(&g_links, LINK_SPP) && ring_count(&g_core.to_host)) { + s_spp_pending = true; + rfcomm_request_can_send_now_event(s_spp); + } +} + +// --------------------------------------------------------------------------- +// GATT +// --------------------------------------------------------------------------- +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); +} + +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; + uint8_t tmp[sizeof(ps_info_t)]; + switch (h) { + case H_NAME: + return blob(s_name, (uint16_t)strlen(s_name), offset, buf, size); + case H_CODING: + little_endian_store_32(tmp, 0, c->format.baud); + tmp[4] = c->format.data_bits; + tmp[5] = c->format.parity; + tmp[6] = c->format.stop_bits; + return blob(tmp, 7, offset, buf, size); + case H_OUTPUTS: + tmp[0] = c->override_mask; + tmp[1] = c->outputs; + return blob(tmp, 2, offset, buf, size); + case H_INPUTS: + return blob(tmp, (uint16_t)core_vendor_in(c, PS_REQ_GET_INPUTS, 0, tmp, sizeof tmp), offset, buf, size); + case H_INFO: + return blob(tmp, (uint16_t)core_vendor_in(c, PS_REQ_GET_INFO, 0, tmp, sizeof tmp), offset, buf, size); + case H_MODE: + tmp[0] = c->settings.mode; + tmp[1] = c->role; + return blob(tmp, 2, offset, buf, size); + case H_FLOW: + tmp[0] = c->settings.flow; + return blob(tmp, 1, offset, buf, size); + case H_CREDITS: { + uint32_t f = ring_free(&c->to_rs232); + little_endian_store_16(tmp, 0, (uint16_t)(f > 0xFFFF ? 0xFFFF : f)); + return blob(tmp, 2, offset, buf, size); + } + case H_NUS_TX_CCC: case H_INPUTS_CCC: case H_CREDITS_CCC: { + bool on = h == H_NUS_TX_CCC ? s_nus_notify : h == H_INPUTS_CCC ? s_inputs_notify : s_credits_notify; + little_endian_store_16(tmp, 0, on ? GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION : 0); + return blob(tmp, 2, offset, buf, size); + } + default: + return 0; + } +} + +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; + if (offset) return ATT_ERROR_INVALID_OFFSET; + core_t *c = &g_core; + bool owner = link_owns(&g_links, LINK_BLE); + switch (h) { + case H_NUS_RX: + // another link owns the port: read-only (SPEC-W 4.6) + if (!owner) return ATT_ERROR_WRITE_NOT_PERMITTED; + link_write(&g_links, c, LINK_BLE, buf, size); + return 0; + case H_NUS_TX_CCC: case H_INPUTS_CCC: case H_CREDITS_CCC: { + if (size < 2) return ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH; + bool on = (little_endian_read_16(buf, 0) & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) != 0; + if (h == H_NUS_TX_CCC) s_nus_notify = on; + else if (h == H_INPUTS_CCC) { s_inputs_notify = on; s_inputs_valid = false; } + else { s_credits_notify = on; s_credits_sent = 0; } + return 0; + } + case H_CODING: + if (size != 7) return ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH; + // kept for when this link owns the port; CDC encoding for stop bits (0 = 1, 2 = 2) + link_format(&g_links, c, LINK_BLE, little_endian_read_32(buf, 0), buf[6] == 2 ? 2 : 0, buf[5], buf[4]); + return 0; + case H_OUTPUTS: + if (size != 2) return ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH; + if (!owner) return ATT_ERROR_WRITE_NOT_PERMITTED; + core_vendor_out(c, PS_REQ_SET_OUTPUTS, (uint16_t)(buf[0] << 8 | buf[1])); + return 0; + case H_MODE: + case H_FLOW: + if (size != 1) return ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH; + if (!owner) return ATT_ERROR_WRITE_NOT_PERMITTED; + if (!core_vendor_out(c, h == H_MODE ? PS_REQ_SET_MODE : PS_REQ_SET_FLOW, buf[0])) + return ATT_ERROR_VALUE_NOT_ALLOWED; + return 0; + case H_BREAK: + if (size != 2) return ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH; + if (!link_break(&g_links, c, LINK_BLE, little_endian_read_16(buf, 0))) return ATT_ERROR_WRITE_NOT_PERMITTED; + return 0; + default: + return 0; + } +} + +// what the phone should hear about next, if anything +static int le_next(uint8_t *data, uint16_t *len, uint16_t max) { + core_t *c = &g_core; + if (s_inputs_notify) { + uint8_t now[sizeof(ps_inputs_t)]; + core_vendor_in(c, PS_REQ_GET_INPUTS, 0, now, sizeof now); + if (!s_inputs_valid || memcmp(now, s_inputs_sent, sizeof now) != 0) { + memcpy(data, now, sizeof now); + *len = sizeof now; + return H_INPUTS; + } + } + if (s_credits_notify) { + uint32_t f = ring_free(&c->to_rs232); + uint32_t d = f > s_credits_sent ? f - s_credits_sent : s_credits_sent - f; + if (d >= CREDITS_NOTIFY_STEP || (f == RING_SIZE && s_credits_sent != RING_SIZE)) { + little_endian_store_16(data, 0, (uint16_t)(f > 0xFFFF ? 0xFFFF : f)); + *len = 2; + return H_CREDITS; + } + } + if (s_nus_notify && link_owns(&g_links, LINK_BLE) && ring_count(&c->to_host)) { + *len = (uint16_t)ring_count(&c->to_host); + if (*len > max) *len = max; + return H_NUS_TX; + } + return 0; +} + +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; + switch (hci_event_packet_get_type(packet)) { + case ATT_EVENT_CONNECTED: + s_le = att_event_connected_get_handle(packet); + sm_request_pairing(s_le); // bonded phones re-encrypt at once; others pair (window only) + break; + case ATT_EVENT_CAN_SEND_NOW: { + s_le_pending = false; + static uint8_t buf[256]; + uint16_t mtu = att_server_get_mtu(s_le), max = (uint16_t)(mtu > 3 ? mtu - 3 : 20); + if (max > sizeof buf) max = sizeof buf; + uint16_t len = 0; + int h = le_next(buf, &len, max); + if (h == H_NUS_TX) { + len = (uint16_t)link_read(&g_links, &g_core, LINK_BLE, buf, len); + } else if (h == H_INPUTS) { + memcpy(s_inputs_sent, buf, sizeof s_inputs_sent); + s_inputs_valid = true; + } else if (h == H_CREDITS) { + s_credits_sent = little_endian_read_16(buf, 0); + } + if (h && len) att_server_notify(s_le, (uint16_t)h, buf, len); + break; + } + default: + break; + } +} + +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)]; + uint16_t len; + if (le_next(tmp, &len, sizeof tmp)) { + s_le_pending = true; + att_server_request_can_send_now_event(s_le); + } +} + +// --------------------------------------------------------------------------- +// Button, LEDs +// --------------------------------------------------------------------------- +static void button(uint32_t now) { + bool down = !gpio_get(PIN_PAIR_BTN); + if (!down) { + s_btn_down = 0; + s_btn_handled = s_btn_forgot = false; + return; + } + if (!s_btn_down) { s_btn_down = now ? now : 1; return; } + uint32_t held = now - s_btn_down; + if (!s_btn_handled && held >= BUTTON_DEBOUNCE_MS) { + s_btn_handled = true; + set_window(PAIR_WINDOW_S); + } + if (!s_btn_forgot && held >= FORGET_HOLD_MS) { + s_btn_forgot = true; + bt_forget_all(); + } +} + +// PWR/BT: slow blink advertising, fast blink pairing window, on while connected +static void bt_led(uint32_t now) { + bool on; + if (!s_ok) on = true; // no radio: just power + else if (g_links.l[LINK_BLE].up || g_links.l[LINK_SPP].up) on = true; + else if (s_btn_forgot) on = (now / 50u) & 1u; // forgetting: very fast + else if (pairing_open()) on = (now / 125u) & 1u; + else on = (now % 1000u) < 100u; + gpio_put(PIN_LED_BT, on); +} + +void bt_leds(uint8_t core_leds) { + if (!s_ok) return; + uint8_t m = core_leds & (CORE_LED_RD | CORE_LED_SD); + if (m == s_wl_leds) return; + uint8_t changed = (uint8_t)(m ^ s_wl_leds); + if (changed & CORE_LED_RD) cyw43_arch_gpio_put(WLGPIO_LED_RD, (m & CORE_LED_RD) != 0); + if (changed & CORE_LED_SD) cyw43_arch_gpio_put(WLGPIO_LED_SD, (m & CORE_LED_SD) != 0); + s_wl_leds = m; +} + +// --------------------------------------------------------------------------- +bool bt_init(void) { + gpio_init(PIN_LED_BT); + gpio_set_dir(PIN_LED_BT, GPIO_OUT); + gpio_put(PIN_LED_BT, 1); + gpio_init(PIN_PAIR_BTN); + gpio_set_dir(PIN_PAIR_BTN, GPIO_IN); + gpio_pull_up(PIN_PAIR_BTN); + + if (cyw43_arch_init()) return false; // also starts BTstack, with bonds kept in flash + s_ok = true; + s_wl_leds = 0xFF; + bt_leds(0); + + l2cap_init(); + sm_init(); + sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT); + sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING); + s_sm_cb.callback = sm_handler; + sm_add_event_handler(&s_sm_cb); + + // classic: SPP, Secure Simple Pairing (Just Works), encryption required + rfcomm_init(); + rfcomm_register_service_with_initial_credits(spp_handler, RFCOMM_CHANNEL, SPP_MAX_FRAME, 1); + sdp_init(); + memset(s_spp_sdp, 0, sizeof s_spp_sdp); + spp_create_sdp_record(s_spp_sdp, sdp_create_service_record_handle(), RFCOMM_CHANNEL, "pico-serial"); + sdp_register_service(s_spp_sdp); + gap_set_class_of_device(0x001F00); // uncategorised + gap_ssp_set_io_capability(SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT); + gap_ssp_set_authentication_requirement(SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING); + gap_ssp_set_auto_accept(0); + gap_set_security_level(LEVEL_2); + gap_discoverable_control(0); + gap_connectable_control(1); + gap_set_local_name(s_name); + + // LE: GATT server + att_server_init(profile_data, att_read, att_write); + att_server_register_packet_handler(att_handler); + + s_hci_cb.callback = hci_handler; + hci_add_event_handler(&s_hci_cb); + hci_power_control(HCI_POWER_ON); + return true; +} + +void bt_service(void) { + uint32_t now = now_ms(); + if (s_ok) { + cyw43_arch_poll(); + if (s_pair_until && (int32_t)(now - s_pair_until) >= 0) set_window(0); + button(now); + spp_service(); + le_service(); + } + bt_led(now); +} diff --git a/firmware/src/rp2040/bt.h b/firmware/src/rp2040/bt.h new file mode 100644 index 0000000..d737fa5 --- /dev/null +++ b/firmware/src/rp2040/bt.h @@ -0,0 +1,15 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 Neo-Desktop + */ +// Bluetooth on pico-serial W (SPEC-W.md 4): classic SPP and BLE (Nordic UART +// Service plus the pico-serial control service) as host links (link.h). +#pragma once +#include +#include + +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 diff --git a/firmware/src/rp2040/btstack_config.h b/firmware/src/rp2040/btstack_config.h new file mode 100644 index 0000000..31e88c5 --- /dev/null +++ b/firmware/src/rp2040/btstack_config.h @@ -0,0 +1,64 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 Neo-Desktop + */ +// BTstack configuration for pico-serial W: classic (SPP) and LE (GATT) at once. +#pragma once + +// Roles and features (pico_btstack_classic / _ble also define the first two) +#ifndef ENABLE_CLASSIC +#define ENABLE_CLASSIC +#endif +#ifndef ENABLE_BLE +#define ENABLE_BLE +#endif +#define ENABLE_LE_PERIPHERAL +#define ENABLE_LE_SECURE_CONNECTIONS +#define ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS +#define ENABLE_SOFTWARE_AES128 +#define ENABLE_LE_DATA_LENGTH_EXTENSION +#define ENABLE_LOG_ERROR +#define ENABLE_PRINTF_HEXDUMP // the SDK always builds BTstack's stdout HCI dump + +// Buffers +#define HCI_OUTGOING_PRE_BUFFER_SIZE 4 +#define HCI_ACL_PAYLOAD_SIZE (1691 + 4) +#define HCI_ACL_CHUNK_SIZE_ALIGNMENT 4 +#define MAX_NR_AVDTP_CONNECTIONS 0 +#define MAX_NR_AVDTP_STREAM_ENDPOINTS 0 +#define MAX_NR_BNEP_CHANNELS 0 +#define MAX_NR_BNEP_SERVICES 0 +#define MAX_NR_BTSTACK_LINK_KEY_DB_MEMORY_ENTRIES 4 +#define MAX_NR_GATT_CLIENTS 0 +#define MAX_NR_HCI_CONNECTIONS 3 +#define MAX_NR_HID_HOST_CONNECTIONS 0 +#define MAX_NR_HIDS_CLIENTS 0 +#define MAX_NR_HFP_CONNECTIONS 0 +#define MAX_NR_L2CAP_CHANNELS 6 +#define MAX_NR_L2CAP_SERVICES 4 +#define MAX_NR_RFCOMM_CHANNELS 1 +#define MAX_NR_RFCOMM_MULTIPLEXERS 1 +#define MAX_NR_RFCOMM_SERVICES 1 +#define MAX_NR_SERVICE_RECORD_ITEMS 2 +#define MAX_NR_SM_LOOKUP_ENTRIES 3 +#define MAX_NR_WHITELIST_ENTRIES 4 +#define MAX_NR_LE_DEVICE_DB_ENTRIES 4 +#define MAX_ATT_DB_SIZE 32 // runtime GATT builder: unused (the database is compiled), but built by the SDK + +// Bonds kept in flash (TLV), SPEC-W.md 4.5: up to 4 phones +#define NVM_NUM_DEVICE_DB_ENTRIES 4 +#define NVM_NUM_LINK_KEYS 4 + +// The CYW43 controller's own buffers +#define MAX_NR_CONTROLLER_ACL_BUFFERS 3 +#define MAX_NR_CONTROLLER_SCO_PACKETS 3 +#define ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL +#define HCI_HOST_ACL_PACKET_LEN (255 + 4) +#define HCI_HOST_ACL_PACKET_NUM 3 +#define HCI_HOST_SCO_PACKET_LEN 120 +#define HCI_HOST_SCO_PACKET_NUM 3 + +// Platform +#define HAVE_EMBEDDED_TIME_MS +#define HAVE_ASSERT +#define HCI_RESET_RESEND_TIMEOUT_MS 1000 diff --git a/firmware/src/rp2040/hal_rp2040.c b/firmware/src/rp2040/hal_rp2040.c index d77125e..fc3da67 100644 --- a/firmware/src/rp2040/hal_rp2040.c +++ b/firmware/src/rp2040/hal_rp2040.c @@ -18,6 +18,9 @@ #include "core.h" #include "hal_rp2040.h" #include "autobaud.pio.h" +#if defined(PS_BOARD_W) +#include "bt.h" +#endif #define UART uart0 #define UART_IRQ UART0_IRQ @@ -244,6 +247,9 @@ uint8_t hal_lines_in(uint8_t role) { 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); +#if defined(PS_BOARD_W) + bt_leds(mask); // RD and SD are on the radio module +#endif } // Settings live in the last flash sector. diff --git a/firmware/src/rp2040/main.c b/firmware/src/rp2040/main.c index a45939d..8003559 100644 --- a/firmware/src/rp2040/main.c +++ b/firmware/src/rp2040/main.c @@ -2,20 +2,32 @@ * SPDX-License-Identifier: AGPL-3.0-only * Copyright (C) 2026 Neo-Desktop */ -// pico-serial firmware: USB CDC serial port <-> RS-232 DB25, DCE/DTE auto-detect. +// pico-serial firmware: USB CDC serial port (and on the W board, Bluetooth) +// <-> RS-232 DB25, DCE/DTE auto-detect. #include "pico/stdlib.h" #include "hardware/watchdog.h" #include "core.h" #include "hal_rp2040.h" +#include "link.h" #include "usb.h" +#if defined(PS_BOARD_W) +#include "bt.h" +#endif int main(void) { hal_init(); core_init(&g_core); + links_init(&g_links, &g_core); +#if defined(PS_BOARD_W) + bt_init(); // loads the radio's firmware (blocking): before USB and the watchdog start +#endif usb_init(); watchdog_enable(1000, true); for (;;) { usb_service(); +#if defined(PS_BOARD_W) + bt_service(); +#endif core_poll(&g_core); watchdog_update(); } diff --git a/firmware/src/rp2040/pico_serial_w.gatt b/firmware/src/rp2040/pico_serial_w.gatt new file mode 100644 index 0000000..5dda16a --- /dev/null +++ b/firmware/src/rp2040/pico_serial_w.gatt @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +// pico-serial W GATT database (SPEC-W.md 4.2-4.3). Compiled into +// pico_serial_w.h by BTstack's compile_gatt.py at build time. + +PRIMARY_SERVICE, GAP_SERVICE +// "pico-serial-XXXX", from the Bluetooth address: served by bt.c +CHARACTERISTIC, GAP_DEVICE_NAME, READ | DYNAMIC, + +PRIMARY_SERVICE, GATT_SERVICE +CHARACTERISTIC, GATT_SERVICE_CHANGED, READ, + +// Nordic UART Service: the de facto serial-over-BLE, so generic apps work +PRIMARY_SERVICE, 6E400001-B5A3-F393-E0A9-E50E24DCCA9E +// RX: phone -> RS-232 +CHARACTERISTIC, 6E400002-B5A3-F393-E0A9-E50E24DCCA9E, DYNAMIC | WRITE | WRITE_WITHOUT_RESPONSE | ENCRYPTION_KEY_SIZE_16, +// TX: RS-232 -> phone +CHARACTERISTIC, 6E400003-B5A3-F393-E0A9-E50E24DCCA9E, DYNAMIC | NOTIFY | ENCRYPTION_KEY_SIZE_16, + +// pico-serial control (firmware/PROTOCOL.md "Bluetooth") +PRIMARY_SERVICE, 50530001-5C6F-4E2B-9A6B-1D2C0E5F7A10 +// line coding: baud u32, data bits, parity (0 none 1 odd 2 even), stop bits (1, 2) +CHARACTERISTIC, 50530002-5C6F-4E2B-9A6B-1D2C0E5F7A10, DYNAMIC | READ | WRITE | ENCRYPTION_KEY_SIZE_16, +// outputs: mask, value (PS_LINE_*), as SET_OUTPUTS +CHARACTERISTIC, 50530003-5C6F-4E2B-9A6B-1D2C0E5F7A10, DYNAMIC | READ | WRITE | ENCRYPTION_KEY_SIZE_16, +// inputs: ps_inputs_t (5 bytes) +CHARACTERISTIC, 50530004-5C6F-4E2B-9A6B-1D2C0E5F7A10, DYNAMIC | READ | NOTIFY | ENCRYPTION_KEY_SIZE_16, +// mode: write the setting (0 auto, 1 DCE, 2 DTE); read setting, role +CHARACTERISTIC, 50530005-5C6F-4E2B-9A6B-1D2C0E5F7A10, DYNAMIC | READ | WRITE | ENCRYPTION_KEY_SIZE_16, +// break: duration in ms, u16 (0 ends it, 0xFFFF until 0) +CHARACTERISTIC, 50530006-5C6F-4E2B-9A6B-1D2C0E5F7A10, DYNAMIC | WRITE | ENCRYPTION_KEY_SIZE_16, +// flow: 0 auto, 1 on, 2 off +CHARACTERISTIC, 50530007-5C6F-4E2B-9A6B-1D2C0E5F7A10, DYNAMIC | READ | WRITE | ENCRYPTION_KEY_SIZE_16, +// credits: free bytes in the board's RS-232 transmit buffer, u16 +CHARACTERISTIC, 50530008-5C6F-4E2B-9A6B-1D2C0E5F7A10, DYNAMIC | READ | NOTIFY | ENCRYPTION_KEY_SIZE_16, +// info: ps_info_t (14 bytes) +CHARACTERISTIC, 50530009-5C6F-4E2B-9A6B-1D2C0E5F7A10, DYNAMIC | READ | ENCRYPTION_KEY_SIZE_16, diff --git a/firmware/src/rp2040/usb.c b/firmware/src/rp2040/usb.c index ad5c375..50f24b8 100644 --- a/firmware/src/rp2040/usb.c +++ b/firmware/src/rp2040/usb.c @@ -10,7 +10,11 @@ #include "pico/usb_reset.h" #include "board_config.h" #include "core.h" +#include "link.h" #include "usb.h" +#if defined(PS_BOARD_W) +#include "bt.h" +#endif enum { ITF_CDC_COMM, ITF_CDC_DATA, ITF_CONTROL, ITF_RESET, ITF_COUNT }; enum { STR_LANG, STR_MANUFACTURER, STR_PRODUCT, STR_SERIAL, STR_CDC, STR_CONTROL, STR_RESET }; @@ -111,7 +115,12 @@ static bool psd_control_xfer_cb(uint8_t rhport, uint8_t stage, const tusb_contro if (n < 0) return false; return tud_control_xfer(rhport, r, s_control_buf, (uint16_t)n); } - if (r->wLength != 0 || !core_vendor_out(&g_core, r->bRequest, r->wValue)) return false; + if (r->wLength != 0) return false; +#if defined(PS_BOARD_W) + if (r->bRequest == PS_REQ_BT_PAIRING) { bt_pairing_window(r->wValue); return tud_control_status(rhport, r); } + if (r->bRequest == PS_REQ_BT_FORGET) { bt_forget_all(); return tud_control_status(rhport, r); } +#endif + if (!core_vendor_out(&g_core, r->bRequest, r->wValue)) return false; return tud_control_status(rhport, r); } @@ -149,18 +158,26 @@ const usbd_class_driver_t *usbd_app_driver_get_cb(uint8_t *count) { // --------------------------------------------------------------------------- // CDC serial port // --------------------------------------------------------------------------- -void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts) { (void)itf; core_host_lines(&g_core, dtr, rts); } +// Everything goes through the links layer, which decides whether USB owns +// 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); } void tud_cdc_line_coding_cb(uint8_t itf, const cdc_line_coding_t *lc) { (void)itf; - core_host_format(&g_core, lc->bit_rate, lc->stop_bits, lc->parity, lc->data_bits); + link_format(&g_links, &g_core, LINK_USB, lc->bit_rate, lc->stop_bits, lc->parity, lc->data_bits); } -void tud_cdc_send_break_cb(uint8_t itf, uint16_t ms) { (void)itf; core_host_break(&g_core, ms); } +void tud_cdc_send_break_cb(uint8_t itf, uint16_t ms) { (void)itf; link_break(&g_links, &g_core, LINK_USB, ms); } -void tud_mount_cb(void) { g_core.serial_state_valid = false; } // re-announce the lines -void tud_umount_cb(void) { core_host_lines(&g_core, false, false); } -void tud_suspend_cb(bool remote_wakeup_en) { (void)remote_wakeup_en; core_host_lines(&g_core, false, false); } +void tud_mount_cb(void) { + g_core.serial_state_valid = false; // re-announce the lines + link_up(&g_links, &g_core, LINK_USB, true); +} +void tud_umount_cb(void) { link_up(&g_links, &g_core, LINK_USB, false); } +void tud_suspend_cb(bool remote_wakeup_en) { + (void)remote_wakeup_en; + link_lines(&g_links, &g_core, LINK_USB, false, false); +} static uint16_t s_pending_state; static bool s_pending; @@ -174,20 +191,33 @@ void usb_service(void) { tud_task(); if (!tud_mounted()) return; - // host -> RS-232: take only what fits, so the host is held back (NAK) when we're full + // Not the owner (a wireless link has the port and ours isn't open): drop + // what the host sends, send it nothing. + static bool was_owner; + bool owner = link_owns(&g_links, LINK_USB); + if (owner != was_owner) { + was_owner = owner; + g_core.serial_state_valid = false; + } uint8_t buf[64]; + if (!owner) { + while (tud_cdc_available()) tud_cdc_read(buf, sizeof buf); + return; + } + + // host -> RS-232: take only what fits, so the host is held back (NAK) when we're full uint32_t room = ring_free(&g_core.to_rs232); while (room && tud_cdc_available()) { uint32_t n = tud_cdc_read(buf, room < sizeof buf ? room : sizeof buf); if (!n) break; - core_host_write(&g_core, buf, n); + link_write(&g_links, &g_core, LINK_USB, buf, n); room -= n; } // RS-232 -> host uint32_t space = tud_cdc_write_available(); if (space && ring_count(&g_core.to_host)) { - uint32_t n = core_host_read(&g_core, buf, space < sizeof buf ? space : sizeof buf); + uint32_t n = link_read(&g_links, &g_core, LINK_USB, buf, space < sizeof buf ? space : sizeof buf); tud_cdc_write(buf, n); tud_cdc_write_flush(); } diff --git a/firmware/test/Makefile b/firmware/test/Makefile index 46d4cb7..e2987d0 100644 --- a/firmware/test/Makefile +++ b/firmware/test/Makefile @@ -5,7 +5,7 @@ CFLAGS ?= -std=c11 -O1 -g -Wall -Wextra -Werror -Wconversion -Wno-sign-conversio CORE = ../src/core/core.c ../src/core/autobaud.c DEPS = $(CORE) $(wildcard ../src/core/*.h) fake_hal.h wave.h wave.c -all: test_core test_autobaud +all: test_core test_autobaud test_link test_core: test_core.c fake_hal.c $(DEPS) $(CC) $(CFLAGS) -o $@ test_core.c fake_hal.c wave.c $(CORE) -lm @@ -13,10 +13,14 @@ test_core: test_core.c fake_hal.c $(DEPS) test_autobaud: test_autobaud.c $(DEPS) $(CC) $(CFLAGS) -o $@ test_autobaud.c wave.c ../src/core/autobaud.c -lm +test_link: test_link.c fake_hal.c ../src/core/link.c $(DEPS) + $(CC) $(CFLAGS) -o $@ test_link.c fake_hal.c ../src/core/link.c $(CORE) -lm + .PHONY: all run clean run: all ./test_core ./test_autobaud + ./test_link clean: - rm -f test_core test_autobaud + rm -f test_core test_autobaud test_link diff --git a/firmware/test/test_link.c b/firmware/test/test_link.c new file mode 100644 index 0000000..ef21889 --- /dev/null +++ b/firmware/test/test_link.c @@ -0,0 +1,134 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 Neo-Desktop + */ +// Host tests for the host links: who owns the RS-232 port (SPEC-W.md 4.6) +// and DCD from result codes (SPEC-W.md 4.4). +#include +#include +#include "../src/core/link.h" +#include "fake_hal.h" + +static int failures, checks; +#define CHECK(cond) do { checks++; if (!(cond)) { failures++; \ + printf(" FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); } } while (0) +#define TEST(name) static void name(void) +#define RUN(name) do { printf("%s\n", #name); fake_reset(); setup(); name(); } while (0) + +static core_t c; +static links_t s; + +static void run_ms(uint32_t ms) { + for (uint32_t t = 0; t < ms; t += 5) { hw.now += 5; core_poll(&c); } +} + +static void setup(void) { + core_init(&c); + links_init(&s, &c); + CHECK(core_vendor_out(&c, PS_REQ_SET_BAUD_MODE, PS_BAUD_HOST)); + hw.peer_dce = true; + run_ms(500); + CHECK(c.role == PS_ROLE_DCE); +} + +static uint32_t wr(uint8_t id, const char *t) { return link_write(&s, &c, id, (const uint8_t *)t, (uint32_t)strlen(t)); } + +TEST(usb_alone_is_like_before) { + CHECK(s.owner == LINK_NONE); + link_up(&s, &c, LINK_USB, true); + CHECK(s.owner == LINK_USB); // mounted, port not yet open: still the owner + CHECK(c.host_lines == 0); + link_lines(&s, &c, LINK_USB, true, true); + run_ms(10); + CHECK(c.outputs == (PS_LINE_DCD | PS_LINE_DSR | PS_LINE_CTS)); + CHECK(wr(LINK_USB, "hi") == 2); + CHECK(ring_count(&c.to_rs232) == 2); + link_up(&s, &c, LINK_USB, false); + CHECK(s.owner == LINK_NONE && c.host_lines == 0); +} + +TEST(first_wireless_link_owns) { + link_up(&s, &c, LINK_USB, true); // plugged in for power only, port closed + link_up(&s, &c, LINK_BLE, true); + CHECK(s.owner == LINK_BLE); + run_ms(10); + CHECK(c.outputs & PS_LINE_DCD); // a plain NUS app gets DCD and DSR + CHECK(c.outputs & PS_LINE_DSR); + link_up(&s, &c, LINK_SPP, true); + CHECK(s.owner == LINK_BLE); // the second one is read-only + CHECK(wr(LINK_SPP, "xyz") == 3); // accepted and dropped + CHECK(ring_count(&c.to_rs232) == 0); + CHECK(wr(LINK_BLE, "ab") == 2); + CHECK(ring_count(&c.to_rs232) == 2); + uint8_t buf[8]; + ring_put(&c.to_host, 'Q'); + CHECK(link_read(&s, &c, LINK_SPP, buf, sizeof buf) == 0); + CHECK(link_read(&s, &c, LINK_BLE, buf, sizeof buf) == 1 && buf[0] == 'Q'); + link_up(&s, &c, LINK_BLE, false); + CHECK(s.owner == LINK_SPP); // passes to the one still connected + link_up(&s, &c, LINK_SPP, false); + CHECK(s.owner == LINK_USB); +} + +TEST(usb_port_open_takes_over) { + link_up(&s, &c, LINK_USB, true); + link_up(&s, &c, LINK_BLE, true); + link_format(&s, &c, LINK_BLE, 9600, 0, 0, 8); + CHECK(c.format.baud == 9600); + link_format(&s, &c, LINK_USB, 19200, 0, 2, 7); + CHECK(c.format.baud == 9600); // not the owner yet: kept for later + link_lines(&s, &c, LINK_USB, true, false); + CHECK(s.owner == LINK_USB); + CHECK(c.format.baud == 19200 && c.format.parity == 2 && c.format.data_bits == 7); + CHECK(!link_break(&s, &c, LINK_BLE, 100)); + CHECK(link_break(&s, &c, LINK_USB, 100) && hw.brk); + link_lines(&s, &c, LINK_USB, false, false); // port closed: back to the wireless link + CHECK(s.owner == LINK_BLE); + CHECK(!hw.brk); // the old owner's break ended + CHECK(c.format.baud == 9600); +} + +TEST(spp_dcd_from_result_codes) { + link_up(&s, &c, LINK_SPP, true); + run_ms(10); + CHECK(!(c.outputs & PS_LINE_DCD)); // no call yet + CHECK(c.outputs & PS_LINE_DSR); + wr(LINK_SPP, "ATDT5551234\r"); + wr(LINK_SPP, "\r\nCONN"); // split across writes + wr(LINK_SPP, "ECT 33600\r\n"); + run_ms(10); + CHECK(c.outputs & PS_LINE_DCD); + wr(LINK_SPP, "data with NO CARRIER inside\r\n"); // not a whole line + run_ms(10); + CHECK(c.outputs & PS_LINE_DCD); + wr(LINK_SPP, "\r\nNO CARRIER\r\n"); + run_ms(10); + CHECK(!(c.outputs & PS_LINE_DCD)); + link_rc_dcd(&s, &c, LINK_SPP, false); // off: DCD follows "DTR" (connected) + run_ms(10); + CHECK(c.outputs & PS_LINE_DCD); +} + +TEST(long_lines_are_not_result_codes) { + link_up(&s, &c, LINK_SPP, true); + char big[64]; + memset(big, 'x', sizeof big - 1); + big[sizeof big - 1] = 0; + wr(LINK_SPP, big); + wr(LINK_SPP, "CONNECT\r\n"); // same line as the x's + run_ms(10); + CHECK(!(c.outputs & PS_LINE_DCD)); + wr(LINK_SPP, "CONNECT\r"); + run_ms(10); + CHECK(c.outputs & PS_LINE_DCD); +} + +int main(void) { + RUN(usb_alone_is_like_before); + RUN(first_wireless_link_owns); + RUN(usb_port_open_takes_over); + RUN(spp_dcd_from_result_codes); + RUN(long_lines_are_not_result_codes); + printf("%d checks, %d failed\n", checks, failures); + return failures ? 1 : 0; +}