mirror of
https://github.com/D-Modem/hardware.git
synced 2026-11-28 17:48:05 -08:00
Firmware: learn the far end's baud rate (auto-baud)
As DCE the board now works out the computer's baud rate from what it
types, like a Hayes modem, so the host's speed setting doesn't have to
match the terminal's.
- PIO (autobaud.pio) times each low/high stretch on the RX pin while the
UART keeps the pin.
- src/core/autobaud.c decodes those timings at every standard rate
(110-230400) and picks the one they fit: bit length vs the shortest
stretch, edges on bit boundaries, framing/parity, then the slowest rate
whose edges score near the best.
- The characters it learned from ("AT") are decoded and passed on; the
UART switches only once the line is idle.
- Re-learns on 3 framing errors in 2 s, AUTOBAUD_RESTART, or a new peer.
- Baud mode setting (saved, settings byte 7): auto (learn as DCE, host's
as DTE), host, learn. Vendor requests 8 SET_BAUD_MODE and
9 AUTOBAUD_RESTART; GET_INFO grows to 14 bytes with flags
BAUD_LOCKED/BAUD_LEARNING and the baud mode.
- Tests: detector suite (every rate, 5 formats, jitter, rate error,
glitches, mid-character starts), 5 new core tests, and the emulator
test drives "AT\r" at 9600 and "ATI3\r" at 115200 onto GP1 with PIO
stepped per CPU cycle.
- Docs: firmware README, PROTOCOL.md, SPEC.md 5.7 and 6.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013PRsUCpxazyipPn5UGGkF8
This commit is contained in:
21 files changed
+1181
-44
No files matched your search
@@ -1,5 +1,6 @@
|
||||
__pycache__/
|
||||
firmware/build*/
|
||||
firmware/test/test_core
|
||||
firmware/test/test_autobaud
|
||||
firmware/test/emu/node_modules/
|
||||
firmware/test/emu/vendor/
|
||||
@@ -305,7 +305,8 @@ fitted, GP22–27 become spare pins.
|
||||
> - detection samples every 50 ms and needs 3 matching samples;
|
||||
> - the vendor protocol is in [firmware/PROTOCOL.md](firmware/PROTOCOL.md);
|
||||
> - no 1200-baud reboot, since 1200 baud is a real modem speed;
|
||||
> - TinyUSB 0.21 is used for SERIAL_STATE.
|
||||
> - TinyUSB 0.21 is used for SERIAL_STATE;
|
||||
> - the baud rate is learned from the computer's typing (§5.7).
|
||||
|
||||
### 5.1 USB
|
||||
|
||||
@@ -386,6 +387,25 @@ flow control on or off.
|
||||
- `SET_FLOW(auto|on|off)`
|
||||
- `SET_LEDS` (if LEDs are fitted)
|
||||
|
||||
### 5.7 Baud rate
|
||||
|
||||
As DCE, the board **learns the computer's baud rate** from what it types,
|
||||
as a Hayes modem does, and the host's `SET_LINE_CODING` speed is ignored.
|
||||
So the phone app doesn't need to know what speed the terminal is set to.
|
||||
|
||||
- **How:** a PIO state machine times each low and high stretch on the RX
|
||||
pin (GP1 as DCE, GP13 as DTE) while the UART keeps the pin. The firmware
|
||||
tries every standard rate from 110 to 230 400 baud and picks the one the
|
||||
timings fit (firmware/README.md, "Automatic baud rate").
|
||||
- **Nothing lost:** the characters it learned from (for example "AT") are
|
||||
decoded from the timings and passed on. Two characters are enough.
|
||||
- **Re-learning:** 3 framing errors within 2 s (the computer changed
|
||||
speed), a vendor request, or a new peer on the DB25.
|
||||
- **Data format** (data bits, parity, stop bits) still comes from the host.
|
||||
- **As DTE**, the host's speed is used by default: a modem follows the
|
||||
speed it's spoken to at. Learning can be turned on for DTE too (a device
|
||||
that talks first, such as a GPS), or off for both, with a vendor request.
|
||||
|
||||
---
|
||||
|
||||
## 6. dmodem-android compatibility
|
||||
@@ -396,7 +416,8 @@ Works today with **no app change** (DCE mode):
|
||||
interfaces).
|
||||
- The app's default "its DTR is the modem's carrier" setting becomes the
|
||||
computer's DCD, the same as a null-modem cable on an ordinary adapter.
|
||||
- Data, speed and format pass through.
|
||||
- Data and format pass through. The speed is learned from the computer
|
||||
(§5.7), so the app's speed setting doesn't have to match the terminal's.
|
||||
|
||||
Needs app work:
|
||||
- **Hanging up when the computer drops DTR.** usb-serial-for-android's CDC
|
||||
|
||||
@@ -47,7 +47,9 @@ add_executable(pico_serial
|
||||
src/rp2040/hal_rp2040.c
|
||||
src/rp2040/usb.c
|
||||
src/core/core.c
|
||||
src/core/autobaud.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)
|
||||
target_compile_options(pico_serial PRIVATE -Wall -Wextra)
|
||||
target_compile_definitions(pico_serial PRIVATE
|
||||
@@ -62,7 +64,7 @@ target_compile_definitions(pico_serial PRIVATE
|
||||
)
|
||||
target_link_libraries(pico_serial PRIVATE
|
||||
pico_stdlib pico_unique_id pico_usb_reset
|
||||
hardware_uart hardware_flash hardware_watchdog hardware_irq
|
||||
hardware_uart hardware_flash hardware_watchdog hardware_irq hardware_pio hardware_clocks
|
||||
tinyusb_device
|
||||
)
|
||||
pico_add_extra_outputs(pico_serial)
|
||||
|
||||
+31
-4
@@ -25,13 +25,15 @@ An unknown request or an out-of-range value stalls.
|
||||
|
||||
| bRequest | Name | Dir | wValue | Data |
|
||||
|---|---|---|---|---|
|
||||
| 1 | GET_INFO | IN | 0 | `ps_info_t`, 13 bytes |
|
||||
| 1 | GET_INFO | IN | 0 | `ps_info_t`, 14 bytes |
|
||||
| 2 | SET_MODE | OUT | 0 auto, 1 DCE, 2 DTE | — (saved in flash) |
|
||||
| 3 | SET_OUTPUTS | OUT | `mask << 8 \| value` | — (not saved) |
|
||||
| 4 | GET_INPUTS | IN | 0 | `ps_inputs_t`, 5 bytes |
|
||||
| 5 | SET_FLOW | OUT | 0 auto, 1 on, 2 off | — (saved) |
|
||||
| 6 | GET_STATS | IN | 0 | `ps_stats_t`, 32 bytes |
|
||||
| 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) |
|
||||
|
||||
All multi-byte fields are little-endian.
|
||||
|
||||
@@ -59,9 +61,29 @@ default source, so it needs SET_OUTPUTS. An override of the flow line (CTS
|
||||
as DCE, RTS as DTE) is still held off while the board's buffer to the host
|
||||
is ¾ full.
|
||||
|
||||
## Baud rate
|
||||
|
||||
Where the UART's speed comes from (SET_BAUD_MODE):
|
||||
|
||||
| wValue | Mode | As DCE | As DTE |
|
||||
|---|---|---|---|
|
||||
| 0 | auto (default) | learned | the host's |
|
||||
| 1 | host | the host's | the host's |
|
||||
| 2 | learn | learned | learned |
|
||||
|
||||
"The host's" is the speed in the last CDC SET_LINE_CODING. "Learned" is
|
||||
measured from the far end's characters: see
|
||||
[README.md](README.md#automatic-baud-rate). Data bits, parity and stop
|
||||
bits are always the host's.
|
||||
|
||||
While learning, received bytes are held back. Once the speed is known
|
||||
(GET_INFO flag `0x08`), the characters it was learned from are sent on, and
|
||||
the UART switches to it. GET_INFO's `baud` is the speed the UART runs at,
|
||||
learned or not. AUTOBAUD_RESTART starts learning again.
|
||||
|
||||
## Structures
|
||||
|
||||
`ps_info_t` (13 bytes):
|
||||
`ps_info_t` (14 bytes):
|
||||
|
||||
| Offset | Size | Field |
|
||||
|---|---|---|
|
||||
@@ -71,8 +93,13 @@ is ¾ full.
|
||||
| 5 | 1 | mode setting: 0 auto, 1 DCE, 2 DTE |
|
||||
| 6 | 1 | role now: 0 none, 1 DCE, 2 DTE |
|
||||
| 7 | 1 | flow setting |
|
||||
| 8 | 1 | flags: `0x01` last line coding adjusted, `0x02` baud above 250 kbit/s, `0x04` CTS flow control active |
|
||||
| 9 | 4 | baud now |
|
||||
| 8 | 1 | flags: `0x01` last line coding adjusted, `0x02` baud above 250 kbit/s, `0x04` CTS flow control active, `0x08` baud learned, `0x10` learning the baud now |
|
||||
| 9 | 4 | baud the UART runs at now |
|
||||
| 13 | 1 | baud mode setting: 0 auto, 1 host, 2 learn |
|
||||
|
||||
Fields may be added at the end in later firmware without changing the
|
||||
protocol version. Ask for at least the length you understand and read
|
||||
what comes back.
|
||||
|
||||
`ps_inputs_t` (5 bytes):
|
||||
|
||||
|
||||
+83
-8
@@ -3,6 +3,7 @@
|
||||
RP2040 firmware for the DB25 hood board (SPEC.md §5): a USB CDC serial port
|
||||
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.
|
||||
|
||||
## Build
|
||||
|
||||
@@ -45,17 +46,72 @@ ninja -C firmware/build
|
||||
| DTE lines | Host DTR → modem's DTR; host RTS → modem's RTS (same buffer hold-off) |
|
||||
| To the host | CDC SERIAL_STATE. As DCE: DSR = the computer's DTR, DCD = a computer is attached. As DTE: the modem's DCD, DSR, RI. Framing, parity, overrun and break events also go up |
|
||||
| Flow control | `auto`: obeys the far end's flow line only once it has asserted it, so 3-wire cables still work. `on` and `off` can be forced |
|
||||
| Baud rate | `auto` (default): as DCE, **learned** from the computer's characters; as DTE, the host's. `host` and `learn` (both roles) can be set; saved in flash. See below |
|
||||
| Line coding | 5–8 data bits, none/odd/even parity, 1 or 2 stop bits. Mark/space parity and 1.5 stop bits are mapped to the nearest the UART can do, and flagged in GET_INFO, as are speeds above the transceivers' 250 kbit/s |
|
||||
| Break | CDC SEND_BREAK, timed or until cleared |
|
||||
| LEDs | PWR, TR, CD, SD, RD, RI, as on a modem's front panel (optional on the board) |
|
||||
| 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`) |
|
||||
|
||||
## Automatic baud rate
|
||||
|
||||
As DCE, the computer types at whatever speed its terminal is set to, and
|
||||
the board works out which. The host's SET_LINE_CODING speed is ignored, but
|
||||
its data bits, parity and stop bits still apply. As DTE the host's speed is
|
||||
used, since a modem follows the speed it's spoken to at; `learn` mode turns
|
||||
learning on there too (for a device that talks first, like a GPS).
|
||||
|
||||
**Measuring.** A PIO state machine (`src/rp2040/autobaud.pio`) watches the
|
||||
RX pin while the UART keeps it: PIO reads every pin's input whatever the
|
||||
pin is assigned to. From the first falling edge it times each low and high
|
||||
stretch, in units of 2 system clocks (16 ns at 125 MHz), and an interrupt
|
||||
passes them to the core.
|
||||
|
||||
**Deciding** (`src/core/autobaud.c`). For each standard rate, 110 to
|
||||
230 400 baud, it decodes the timings as a UART would, with the host's
|
||||
format. A rate fits if:
|
||||
- a bit is no longer than the shortest stretch;
|
||||
- the level changes inside each character fall on bit boundaries;
|
||||
- at least 2 characters decode, and at most 1 in 8 has a framing or
|
||||
parity error.
|
||||
|
||||
Of the rates that fit, it takes the slowest whose changes sit about as
|
||||
close to bit boundaries as the best one's. That rules out a rate too fast
|
||||
that happens to decode, and a slower one that fits characters with no
|
||||
1-bit run.
|
||||
|
||||
**Then:**
|
||||
- it waits for the line to go idle for a character's time, so the switch
|
||||
never lands in the middle of one;
|
||||
- the characters it learned from are decoded from the timings and sent to
|
||||
the host, so "AT" isn't lost;
|
||||
- the UART switches to the new speed, and GET_INFO reports it.
|
||||
|
||||
**Learning again:** after 3 framing errors within 2 s (the computer
|
||||
changed speed), on the AUTOBAUD_RESTART request, or when a new peer is
|
||||
detected. Until the new speed is known, the board keeps sending at the old
|
||||
one and holds back what it receives.
|
||||
|
||||
**Limits:**
|
||||
- **Two characters** are enough ("AT"). With only two, very noisy lines
|
||||
can rarely fool it: see the tests below. A wrong guess shows up as
|
||||
framing errors and is re-learned.
|
||||
- **Standard rates only.** A sender up to about 3% off a standard rate is
|
||||
fine.
|
||||
- **Not the format.** 7E1 and 8N1 characters are the same length, so the
|
||||
speed is right either way, but the bytes are only right with the host's
|
||||
format.
|
||||
- **Lost characters:** while it re-learns, characters that came at the old
|
||||
speed are lost; so is anything after more than ~40 characters without
|
||||
a decision (it then starts over from the newest).
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
src/core/ portable: role detection, line mapping, flow control, settings (no SDK)
|
||||
src/rp2040/ HAL (GPIO, UART + IRQ, flash), USB descriptors and callbacks, main
|
||||
src/core/ portable: role detection, line mapping, flow control, baud-rate
|
||||
learning, settings (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
|
||||
test/ host tests for the core (fake HAL) and the emulator test
|
||||
@@ -67,14 +123,25 @@ there, and the pin header follows.
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
make -C firmware/test run # core: 22 tests, sanitizers on
|
||||
make -C firmware/test run # core and baud detector, sanitizers on
|
||||
firmware/test/emu/run.sh firmware/build/pico-serial-hood.bin # whole firmware in an emulator
|
||||
```
|
||||
|
||||
- **Host tests:** the core's logic against a fake board. The tests were
|
||||
checked by breaking the core on purpose: removing DCE detection, the
|
||||
buffer hysteresis, the DSR mapping, the one-shot error events. Each break
|
||||
is caught.
|
||||
- **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
|
||||
events, holding back data while learning, the re-learn on errors. Each
|
||||
break is caught.
|
||||
- **Baud detector tests** (`test_autobaud.c`): waveforms made from text and
|
||||
random bytes at every standard rate, in 8N1, 7E1, 7O1, 8N2 and 8E1, with
|
||||
the sender up to 2.5% off and edges moved by up to 10% of a bit. Also:
|
||||
glitches, a capture starting mid-character, and characters with no
|
||||
single-bit run.
|
||||
- **Stress run** (not in CI): 20 000 random messages per setting, with
|
||||
edges moved by up to 8% of a bit and the sender up to 3% off.
|
||||
- Printable text, 2 to 12 characters: no wrong rate.
|
||||
- Random bytes: no wrong rate from 5 characters up. With only 2
|
||||
characters, 2 in 20 000 were wrong.
|
||||
- **Emulator test:** boots the real `.bin` in
|
||||
[rp2040js](https://github.com/wokwi/rp2040js), which plays the USB host,
|
||||
the transceivers' detect lines and the far end's modem lines. It checks:
|
||||
@@ -85,7 +152,11 @@ firmware/test/emu/run.sh firmware/build/pico-serial-hood.bin # whole firmware
|
||||
- SERIAL_STATE notifications;
|
||||
- GET_INFO and GET_INPUTS;
|
||||
- forcing DTE mode, and its line mapping;
|
||||
- getting through a settings save without a hang or watchdog reset.
|
||||
- getting through a settings save without a hang or watchdog reset;
|
||||
- learning the baud rate: "AT\r" driven onto GP1 at 9600 baud (1% fast)
|
||||
and later "ATI3\r" at 115200 (2% slow) reach the host, the UART
|
||||
switches, and GET_INFO reports it. rp2040js runs PIO on its own timer,
|
||||
so the test steps PIO once per CPU cycle to keep its timing true.
|
||||
|
||||
## Not yet verified
|
||||
|
||||
@@ -96,6 +167,10 @@ firmware/test/emu/run.sh firmware/build/pico-serial-hood.bin # whole firmware
|
||||
- **UART pin routing:** the emulator doesn't model the UART-to-GPIO
|
||||
routing either, so the swap between chip A's and chip B's UART pins is
|
||||
unchecked.
|
||||
- **Baud learning on real lines:** real transceivers make low and high
|
||||
stretches slightly unequal (slew). The detector allows for 5/16 of a
|
||||
bit, which should cover this at 230 400 baud, but it needs checking on
|
||||
the bench.
|
||||
- **Real host drivers:** Windows' usbser, macOS and Linux cdc_acm, and
|
||||
Android's usb-serial-for-android haven't been tried.
|
||||
- **Not built yet:**
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 Neo-Desktop
|
||||
*/
|
||||
// Automatic baud-rate detection. See autobaud.h.
|
||||
//
|
||||
// For each standard rate, decode the runs as a UART would. A rate fits if:
|
||||
// - a bit is no longer than the shortest run (with 25% to spare);
|
||||
// - every level change inside a character lands on a bit boundary
|
||||
// (within 5/16 of a bit, counted from the start bit or from the
|
||||
// previous change), at most 1 in 8 missing it;
|
||||
// - at least AB_MIN_FRAMES characters decode, at most 1 in 8 with a
|
||||
// framing or parity error, and no start bit is a glitch.
|
||||
// Of the rates that fit, take the slowest whose level changes are, on
|
||||
// average, within 1/16 bit as close to boundaries as the best one's.
|
||||
//
|
||||
// A rate too slow fails the first two (a 1-bit run, or changes in the middle
|
||||
// of its bits); with no 1-bit run to go on, 3/4 of the real rate can fit
|
||||
// some characters, but lands a quarter-bit off and scores worse. A rate too
|
||||
// fast decodes a stop bit in the middle of the real character and fails the
|
||||
// third; if it gets away with that, it scores no better and is the faster.
|
||||
#include "autobaud.h"
|
||||
#include <string.h>
|
||||
#include "core.h"
|
||||
|
||||
const uint32_t AB_BAUDS[] = {110, 150, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200,
|
||||
28800, 38400, 57600, 115200, 230400};
|
||||
const uint32_t AB_NBAUDS = sizeof AB_BAUDS / sizeof AB_BAUDS[0];
|
||||
|
||||
#define ALIGN_TOL16 5u // edge within 5/16 of a bit boundary
|
||||
#define AB_SCORE_MARGIN 16u // 1/16 bit, in 1/256 bit
|
||||
|
||||
static uint32_t run_len(uint32_t r) { return r & AB_IDLE; }
|
||||
static bool run_high(uint32_t r) { return (r >> 31) != 0; }
|
||||
|
||||
void ab_reset(ab_t *a) { a->n = 0; }
|
||||
|
||||
bool ab_add(ab_t *a, bool high, uint32_t ticks) {
|
||||
if (ticks > AB_IDLE) ticks = AB_IDLE;
|
||||
if (a->n == 0 && high) return true; // must start low; nothing to time yet
|
||||
if (a->n && run_high(a->run[a->n - 1]) == high) {
|
||||
uint32_t l = run_len(a->run[a->n - 1]);
|
||||
l = l > AB_IDLE - ticks ? AB_IDLE : l + ticks;
|
||||
a->run[a->n - 1] = (high ? 0x80000000u : 0) | l;
|
||||
return true;
|
||||
}
|
||||
if (a->n >= AB_MAX_RUNS) return false;
|
||||
a->run[a->n++] = (high ? 0x80000000u : 0) | ticks;
|
||||
return true;
|
||||
}
|
||||
|
||||
void ab_drop(ab_t *a, uint32_t pairs) {
|
||||
uint32_t k = pairs * 2;
|
||||
if (k >= a->n) { a->n = 0; return; }
|
||||
memmove(a->run, a->run + k, (a->n - k) * sizeof a->run[0]);
|
||||
a->n -= k;
|
||||
}
|
||||
|
||||
// A walk along the runs. Times are ticks from the start of the first run.
|
||||
typedef struct {
|
||||
const ab_t *a;
|
||||
uint32_t i; // current run
|
||||
uint64_t s; // its start
|
||||
bool open_high; // after the last run the line is high (the last run was low)
|
||||
// edge checking, while inside a character
|
||||
bool in_frame;
|
||||
uint64_t t0, prev; // start bit's edge; the last edge
|
||||
uint32_t hz, baud;
|
||||
ab_stats_t *st;
|
||||
} walk_t;
|
||||
|
||||
// How far a time span is from a whole number (at least 1) of bits, in 1/16 bit.
|
||||
static uint32_t off_bits16(const walk_t *w, uint64_t span) {
|
||||
uint64_t b16 = (span * w->baud * 16u + w->hz / 2u) / w->hz;
|
||||
if (b16 < 16) return (uint32_t)(16 - b16);
|
||||
uint32_t frac = (uint32_t)(b16 & 15u);
|
||||
return frac < 8 ? frac : 16 - frac;
|
||||
}
|
||||
|
||||
// A level change inside a character: it should be a whole number of bits
|
||||
// after the start bit's edge, or after the previous change (so a sender a
|
||||
// few percent off doesn't build up an error across the character).
|
||||
static void edge(walk_t *w, uint64_t b) {
|
||||
if (!w->in_frame || b <= w->t0) return;
|
||||
uint32_t abs16 = off_bits16(w, b - w->t0), rel16 = off_bits16(w, b - w->prev);
|
||||
uint32_t d = abs16 < rel16 ? abs16 : rel16;
|
||||
w->st->edges++;
|
||||
w->st->off16 += d;
|
||||
if (d > ALIGN_TOL16) w->st->misaligned++;
|
||||
w->prev = b;
|
||||
}
|
||||
|
||||
// Level at time t (t never goes backwards): 1 high, 0 low, -1 not known yet.
|
||||
static int level_at(walk_t *w, uint64_t t) {
|
||||
while (w->i < w->a->n && t >= w->s + run_len(w->a->run[w->i])) {
|
||||
w->s += run_len(w->a->run[w->i]);
|
||||
w->i++;
|
||||
if (w->i < w->a->n) edge(w, w->s);
|
||||
}
|
||||
if (w->i < w->a->n) return run_high(w->a->run[w->i]);
|
||||
return w->open_high ? 1 : -1;
|
||||
}
|
||||
|
||||
// First time >= t when the line is at level; UINT64_MAX if not known.
|
||||
static uint64_t next_level(walk_t *w, uint64_t t, int level) {
|
||||
int l = level_at(w, t);
|
||||
if (l < 0) return UINT64_MAX;
|
||||
if (l == level) return t;
|
||||
if (w->i >= w->a->n) return UINT64_MAX; // high from here on
|
||||
return w->s + run_len(w->a->run[w->i]); // the next run starts at the other level
|
||||
}
|
||||
|
||||
ab_stats_t ab_decode(const ab_t *a, uint32_t hz, uint32_t baud, const uart_format_t *f, ab_byte_fn fn, void *ctx) {
|
||||
ab_stats_t st = {0};
|
||||
if (!a->n || !baud || !hz) return st;
|
||||
walk_t w = {a, 0, 0, !run_high(a->run[a->n - 1]), false, 0, 0, hz, baud, &st};
|
||||
uint32_t nbits = 1u + f->data_bits + (f->parity ? 1u : 0u) + f->stop_bits;
|
||||
uint64_t pos = 0;
|
||||
for (;;) {
|
||||
uint64_t t0 = next_level(&w, pos, 0);
|
||||
if (t0 == UINT64_MAX) break;
|
||||
w.t0 = w.prev = t0;
|
||||
w.in_frame = true;
|
||||
int bits[13]; // up to 1 + 8 + 1 + 2
|
||||
bool incomplete = false, glitch = false;
|
||||
uint64_t t = t0;
|
||||
for (uint32_t k = 0; k < nbits; k++) {
|
||||
t = t0 + ((uint64_t)(2 * k + 1) * hz) / (2u * baud); // middle of bit k
|
||||
int l = level_at(&w, t);
|
||||
if (l < 0) { incomplete = true; break; }
|
||||
bits[k] = l;
|
||||
if (k == 0 && l) { glitch = true; break; }
|
||||
}
|
||||
w.in_frame = false;
|
||||
if (incomplete) break; // character not finished yet
|
||||
if (glitch) { // the start bit didn't last half a bit
|
||||
st.noise++;
|
||||
pos = t;
|
||||
continue;
|
||||
}
|
||||
uint8_t byte = 0, ones = 0, err = 0;
|
||||
for (uint32_t d = 0; d < f->data_bits; d++)
|
||||
if (bits[1 + d]) { byte |= (uint8_t)(1u << d); ones++; }
|
||||
uint32_t p = 1u + f->data_bits;
|
||||
bool all_low = byte == 0;
|
||||
if (f->parity) {
|
||||
ones = (uint8_t)(ones + bits[p]);
|
||||
if (bits[p]) all_low = false;
|
||||
if ((f->parity == 1) != (ones & 1)) err |= RX_ERR_PARITY; // odd: total ones odd
|
||||
p++;
|
||||
}
|
||||
bool stop_ok = true;
|
||||
for (uint32_t s = 0; s < f->stop_bits; s++)
|
||||
if (!bits[p + s]) stop_ok = false;
|
||||
if (!stop_ok) {
|
||||
err |= RX_ERR_FRAMING;
|
||||
if (all_low && !bits[p]) err |= RX_ERR_BREAK;
|
||||
}
|
||||
st.frames++;
|
||||
if (err) st.errors++;
|
||||
if (fn) fn(ctx, byte, err);
|
||||
pos = t + 1;
|
||||
if (err & RX_ERR_BREAK) { // a break: wait for the line to go high again
|
||||
pos = next_level(&w, pos, 1);
|
||||
if (pos == UINT64_MAX) break;
|
||||
}
|
||||
}
|
||||
return st;
|
||||
}
|
||||
|
||||
uint32_t ab_detect(const ab_t *a, uint32_t hz, const uart_format_t *f) {
|
||||
if (a->n < 3) return 0;
|
||||
uint32_t minrun = AB_IDLE;
|
||||
for (uint32_t i = 0; i < a->n; i++)
|
||||
if (run_len(a->run[i]) < minrun) minrun = run_len(a->run[i]);
|
||||
uint32_t score[sizeof AB_BAUDS / sizeof AB_BAUDS[0]];
|
||||
uint32_t best = UINT32_MAX;
|
||||
for (uint32_t b = 0; b < AB_NBAUDS; b++) {
|
||||
score[b] = UINT32_MAX;
|
||||
uint64_t bit = hz / AB_BAUDS[b];
|
||||
if (bit * 4u > (uint64_t)minrun * 5u) continue; // a bit longer than the shortest run
|
||||
ab_stats_t st = ab_decode(a, hz, AB_BAUDS[b], f, 0, 0);
|
||||
if (st.frames < AB_MIN_FRAMES || st.noise || st.errors * 8u > st.frames ||
|
||||
st.misaligned * 8u > st.edges)
|
||||
continue;
|
||||
score[b] = st.edges ? st.off16 * 16u / st.edges : 0; // mean distance from a boundary, 1/256 bit
|
||||
if (score[b] < best) best = score[b];
|
||||
}
|
||||
for (uint32_t b = 0; b < AB_NBAUDS; b++)
|
||||
if (score[b] != UINT32_MAX && score[b] <= best + AB_SCORE_MARGIN) return AB_BAUDS[b];
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 Neo-Desktop
|
||||
*/
|
||||
// Automatic baud-rate detection, portable part. The HAL times the RX line
|
||||
// (how long it stays low, then high, then low...) starting at the first
|
||||
// falling edge; this works out which standard baud rate those times fit and
|
||||
// decodes the bytes, so the ones it learned from aren't lost.
|
||||
//
|
||||
// The data format (data bits, parity, stop bits) is not detected: it comes
|
||||
// from the host. See firmware/README.md "Automatic baud rate".
|
||||
#pragma once
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include "hal.h"
|
||||
|
||||
#define AB_MAX_RUNS 384u // runs kept while learning (about 40 characters)
|
||||
#define AB_SLIDE_RUNS 32u // past this many without a result, forget the oldest
|
||||
#define AB_MIN_FRAMES 2u // characters needed before deciding ("AT")
|
||||
#define AB_IDLE 0x7FFFFFFFu // run length meaning "a long time"
|
||||
|
||||
// Each run: bit 31 = level (1 high), bits 30..0 = length in HAL ticks.
|
||||
// The first run is always low (the HAL starts on a falling edge), and levels
|
||||
// alternate.
|
||||
typedef struct {
|
||||
uint32_t n;
|
||||
uint32_t run[AB_MAX_RUNS];
|
||||
} ab_t;
|
||||
|
||||
typedef struct {
|
||||
uint32_t frames; // characters decoded
|
||||
uint32_t errors; // ...with a framing or parity error (or a break)
|
||||
uint32_t noise; // start bits shorter than half a bit
|
||||
uint32_t edges; // level changes inside characters
|
||||
uint32_t misaligned; // ...not on a bit boundary
|
||||
uint32_t off16; // total distance of those from a boundary, 1/16 bit
|
||||
} ab_stats_t;
|
||||
|
||||
// The rates tried, lowest first.
|
||||
extern const uint32_t AB_BAUDS[];
|
||||
extern const uint32_t AB_NBAUDS;
|
||||
|
||||
void ab_reset(ab_t *a);
|
||||
// Add a run; merges it into the last if the level didn't change. False if full.
|
||||
bool ab_add(ab_t *a, bool high, uint32_t ticks);
|
||||
// Forget the oldest runs (whole low+high pairs), keeping the first run low.
|
||||
void ab_drop(ab_t *a, uint32_t pairs);
|
||||
|
||||
// The baud rate the runs fit, with this format, or 0 if not sure yet.
|
||||
// hz = HAL ticks per second.
|
||||
uint32_t ab_detect(const ab_t *a, uint32_t hz, const uart_format_t *f);
|
||||
|
||||
// Decode the runs at a baud rate as a UART would, calling fn for each
|
||||
// character (errors = RX_ERR_* bits). Returns the statistics.
|
||||
typedef void (*ab_byte_fn)(void *ctx, uint8_t byte, uint8_t errors);
|
||||
ab_stats_t ab_decode(const ab_t *a, uint32_t hz, uint32_t baud, const uart_format_t *f, ab_byte_fn fn, void *ctx);
|
||||
+159
-8
@@ -42,6 +42,52 @@ static void apply_flow(core_t *c) {
|
||||
}
|
||||
}
|
||||
|
||||
// The UART's format: the host's, with the learned baud rate if there is one.
|
||||
static void apply_format(core_t *c) {
|
||||
c->uart = c->format;
|
||||
if (c->ab_state != AB_OFF && c->ab_baud) c->uart.baud = c->ab_baud;
|
||||
if (c->uart.baud > 250000) c->info_flags |= PS_INFO_BAUD_OVER_RATING;
|
||||
else c->info_flags &= (uint8_t)~PS_INFO_BAUD_OVER_RATING;
|
||||
if (c->role != PS_ROLE_NONE) hal_uart_format(&c->uart);
|
||||
}
|
||||
|
||||
static bool ab_wanted(const core_t *c) {
|
||||
if (c->role == PS_ROLE_NONE) return false;
|
||||
if (c->settings.baud == PS_BAUD_LEARN) return true;
|
||||
return c->settings.baud == PS_BAUD_AUTO && c->role == PS_ROLE_DCE;
|
||||
}
|
||||
|
||||
// Start (or start again) learning the far end's baud rate. Until it's known,
|
||||
// received data is held back (the UART would get it wrong); the characters
|
||||
// it was learned from are decoded from the timings and passed on.
|
||||
static void ab_learn(core_t *c) {
|
||||
hal_autobaud(PS_ROLE_NONE);
|
||||
c->ab_state = AB_LEARNING;
|
||||
ab_reset(&c->ab);
|
||||
c->ab_seen = 0;
|
||||
c->ab_found = 0;
|
||||
c->runs_tail = c->runs_head;
|
||||
c->runs_lost = false;
|
||||
c->t_ab_try = c->t_run = hal_millis();
|
||||
hal_autobaud(c->role);
|
||||
}
|
||||
|
||||
static void ab_stop(core_t *c) {
|
||||
if (c->ab_state != AB_OFF) hal_autobaud(PS_ROLE_NONE);
|
||||
c->ab_state = AB_OFF;
|
||||
c->ab_baud = 0;
|
||||
}
|
||||
|
||||
// After a role or setting change: learn, or go back to the host's rate.
|
||||
static void ab_update(core_t *c) {
|
||||
if (ab_wanted(c)) {
|
||||
if (c->ab_state == AB_OFF) ab_learn(c);
|
||||
} else if (c->ab_state != AB_OFF) {
|
||||
ab_stop(c);
|
||||
apply_format(c);
|
||||
}
|
||||
}
|
||||
|
||||
static void activate(core_t *c, uint8_t role) {
|
||||
c->role = role;
|
||||
c->cts_latched = false;
|
||||
@@ -50,12 +96,16 @@ static void activate(core_t *c, uint8_t role) {
|
||||
hal_uart_hw_cts(false);
|
||||
hal_xcvr_power(role);
|
||||
hal_uart_route(role);
|
||||
hal_uart_format(&c->format);
|
||||
ab_stop(c); // a new far end: its rate is learned afresh
|
||||
apply_format(c);
|
||||
ab_update(c);
|
||||
c->stats.role_changes++;
|
||||
set_state(c, ST_ACTIVE);
|
||||
}
|
||||
|
||||
static void deactivate(core_t *c) {
|
||||
ab_stop(c);
|
||||
apply_format(c); // GET_INFO: back to the host's speed
|
||||
if (c->role != PS_ROLE_NONE) hal_lines_out(c->role, 0);
|
||||
hal_uart_hw_cts(false);
|
||||
c->hw_cts = false;
|
||||
@@ -83,12 +133,13 @@ void core_init(core_t *c) {
|
||||
memset(c, 0, sizeof *c);
|
||||
ring_init(&c->to_host);
|
||||
ring_init(&c->to_rs232);
|
||||
c->format = DEFAULT_FORMAT;
|
||||
c->format = c->uart = DEFAULT_FORMAT;
|
||||
c->rx_room = true;
|
||||
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;
|
||||
c->settings.flow = PS_FLOW_AUTO;
|
||||
c->settings.baud = PS_BAUD_AUTO;
|
||||
}
|
||||
restart(c);
|
||||
}
|
||||
@@ -185,10 +236,94 @@ static void leds(core_t *c, uint32_t now) {
|
||||
hal_leds(m);
|
||||
}
|
||||
|
||||
typedef struct { uint8_t data[AB_MAX_RUNS / 2 + 1]; uint32_t n; uint8_t errors; } ab_out_t;
|
||||
static void ab_collect(void *ctx, uint8_t byte, uint8_t errors) {
|
||||
ab_out_t *o = ctx;
|
||||
if (o->n < sizeof o->data) o->data[o->n++] = byte;
|
||||
o->errors |= errors;
|
||||
}
|
||||
|
||||
static void ab_lock(core_t *c, uint32_t hz, uint32_t baud) {
|
||||
static ab_out_t out;
|
||||
out.n = 0;
|
||||
out.errors = 0;
|
||||
ab_decode(&c->ab, hz, baud, &c->format, ab_collect, &out);
|
||||
hal_autobaud(PS_ROLE_NONE);
|
||||
c->ab_baud = baud;
|
||||
apply_format(c); // still "learning": the interrupt drops anything received meanwhile
|
||||
uint32_t irq = hal_irq_save();
|
||||
hal_uart_rx_flush();
|
||||
for (uint32_t i = 0; i < out.n; i++) {
|
||||
if (!ring_put(&c->to_host, out.data[i])) c->stats.dropped++;
|
||||
else c->stats.from_rs232++;
|
||||
}
|
||||
c->rx_errors |= out.errors;
|
||||
c->ab_state = AB_LOCKED;
|
||||
c->ab_fe_seen = c->ab_fe;
|
||||
c->ab_win_n = 0;
|
||||
hal_irq_restore(irq);
|
||||
}
|
||||
|
||||
static void autobaud(core_t *c, uint32_t now) {
|
||||
if (c->ab_state == AB_LOCKED) {
|
||||
// framing errors coming in: the far end changed speed
|
||||
uint8_t fe = c->ab_fe, d = (uint8_t)(fe - c->ab_fe_seen);
|
||||
c->ab_fe_seen = fe;
|
||||
if (!d) return;
|
||||
if (!c->ab_win_n || elapsed(now, c->t_ab_win, CORE_AB_WINDOW_MS)) {
|
||||
c->t_ab_win = now;
|
||||
c->ab_win_n = 0;
|
||||
}
|
||||
c->ab_win_n = (uint8_t)(c->ab_win_n + d);
|
||||
if (c->ab_win_n >= CORE_AB_ERRORS) ab_learn(c);
|
||||
return;
|
||||
}
|
||||
if (c->ab_state != AB_LEARNING) return;
|
||||
|
||||
while (c->runs_tail != c->runs_head) {
|
||||
uint32_t r = c->runs[c->runs_tail % CORE_RUNS];
|
||||
c->runs_tail++;
|
||||
bool high = (r >> 31) != 0;
|
||||
uint32_t len = r & AB_IDLE;
|
||||
// a high run ends with this arrival: long gaps are just "long". 0 is
|
||||
// the HAL's "too long to count".
|
||||
if (!len || (high && elapsed(now, c->t_run, CORE_AB_LONG_MS))) len = AB_IDLE;
|
||||
c->t_run = now;
|
||||
if (!ab_add(&c->ab, high, len)) {
|
||||
ab_drop(&c->ab, AB_MAX_RUNS / 8);
|
||||
ab_add(&c->ab, high, len);
|
||||
}
|
||||
c->ab_seen++;
|
||||
}
|
||||
if (c->runs_lost) { // timings missed: what's collected no longer adds up
|
||||
c->runs_lost = false;
|
||||
ab_reset(&c->ab);
|
||||
}
|
||||
// look for the rate every CORE_AB_TRY_MS while new timings come in
|
||||
if (c->ab_seen && elapsed(now, c->t_ab_try, CORE_AB_TRY_MS)) {
|
||||
c->ab_seen = 0;
|
||||
c->t_ab_try = now;
|
||||
c->ab_found = ab_detect(&c->ab, hal_autobaud_hz(), &c->format);
|
||||
if (!c->ab_found && c->ab.n > AB_SLIDE_RUNS) {
|
||||
ab_drop(&c->ab, 1); // maybe it began mid-character, or with a glitch
|
||||
c->ab_seen = 1; // try again without it
|
||||
}
|
||||
}
|
||||
if (!c->ab_found) return;
|
||||
// switch the UART over between characters: once the line has been idle
|
||||
// (high) for a character's time, or if the timings are piling up
|
||||
const uart_format_t *f = &c->format;
|
||||
uint32_t bits = 1u + f->data_bits + (f->parity ? 1u : 0u) + f->stop_bits;
|
||||
uint32_t char_ms = (bits * 1000u + c->ab_found - 1) / c->ab_found + 1;
|
||||
bool idle = c->ab.n && !(c->ab.run[c->ab.n - 1] >> 31) && elapsed(now, c->t_run, char_ms);
|
||||
if (idle || c->ab.n >= AB_MAX_RUNS * 3 / 4) ab_lock(c, hal_autobaud_hz(), c->ab_found);
|
||||
}
|
||||
|
||||
void core_poll(core_t *c) {
|
||||
uint32_t now = hal_millis();
|
||||
if (c->settings.mode == PS_MODE_AUTO) detect(c, now);
|
||||
lines(c, now);
|
||||
autobaud(c, now);
|
||||
|
||||
if (c->stats.to_rs232 != c->seen_to_rs232) { c->seen_to_rs232 = c->stats.to_rs232; c->t_sd = now ? now : 1; }
|
||||
if (c->stats.from_rs232 != c->seen_from_rs232) { c->seen_from_rs232 = c->stats.from_rs232; c->t_rd = now ? now : 1; }
|
||||
@@ -217,10 +352,9 @@ void core_host_format(core_t *c, uint32_t baud, uint8_t stop_cdc, uint8_t parity
|
||||
else { f.stop_bits = 2; if (stop_cdc == 1) flags |= PS_INFO_CODING_ADJUSTED; }
|
||||
if (parity_cdc <= 2) f.parity = parity_cdc;
|
||||
else { f.parity = 0; flags |= PS_INFO_CODING_ADJUSTED; }
|
||||
if (f.baud > 250000) flags |= PS_INFO_BAUD_OVER_RATING;
|
||||
c->info_flags = (uint8_t)((c->info_flags & ~(PS_INFO_CODING_ADJUSTED | PS_INFO_BAUD_OVER_RATING)) | flags);
|
||||
c->info_flags = (uint8_t)((c->info_flags & ~PS_INFO_CODING_ADJUSTED) | flags);
|
||||
c->format = f;
|
||||
if (c->role != PS_ROLE_NONE) hal_uart_format(&c->format);
|
||||
apply_format(c); // a learned baud rate stays; data bits, parity and stop bits are the host's
|
||||
}
|
||||
|
||||
void core_host_break(core_t *c, uint16_t ms) {
|
||||
@@ -276,9 +410,12 @@ int core_vendor_in(core_t *c, uint8_t req, uint16_t value, uint8_t *buf, uint16_
|
||||
(void)value;
|
||||
switch (req) {
|
||||
case PS_REQ_GET_INFO: {
|
||||
uint8_t flags = c->info_flags;
|
||||
if (c->hw_cts) flags |= PS_INFO_FLOW_ACTIVE;
|
||||
if (c->ab_state == AB_LOCKED) flags |= PS_INFO_BAUD_LOCKED;
|
||||
if (c->ab_state == AB_LEARNING) flags |= PS_INFO_BAUD_LEARNING;
|
||||
ps_info_t i = {PS_PROTOCOL_VERSION, PS_FW_MAJOR, PS_FW_MINOR, PS_FW_PATCH, PS_BOARD_ID,
|
||||
c->settings.mode, c->role, c->settings.flow,
|
||||
(uint8_t)(c->info_flags | (c->hw_cts ? PS_INFO_FLOW_ACTIVE : 0)), c->format.baud};
|
||||
c->settings.mode, c->role, c->settings.flow, flags, c->uart.baud, c->settings.baud};
|
||||
uint16_t n = max < sizeof i ? max : (uint16_t)sizeof i;
|
||||
memcpy(buf, &i, n);
|
||||
return n;
|
||||
@@ -322,6 +459,17 @@ bool core_vendor_out(core_t *c, uint8_t req, uint16_t value) {
|
||||
apply_flow(c);
|
||||
}
|
||||
return true;
|
||||
case PS_REQ_SET_BAUD_MODE:
|
||||
if (value > PS_BAUD_LEARN) return false;
|
||||
if (value != c->settings.baud) {
|
||||
c->settings.baud = (uint8_t)value;
|
||||
mark_dirty(c);
|
||||
ab_update(c);
|
||||
}
|
||||
return true;
|
||||
case PS_REQ_AUTOBAUD_RESTART:
|
||||
if (c->ab_state != AB_OFF) ab_learn(c); // no effect when not learning baud rates
|
||||
return true;
|
||||
case PS_REQ_SET_OUTPUTS:
|
||||
c->override_mask = (uint8_t)(value >> 8);
|
||||
c->override_value = (uint8_t)value;
|
||||
@@ -353,6 +501,7 @@ void core_settings_pack(const core_settings_t *s, uint8_t out[CORE_SETTINGS_BLOB
|
||||
out[4] = 1; // version
|
||||
out[5] = s->mode;
|
||||
out[6] = s->flow;
|
||||
out[7] = s->baud;
|
||||
uint32_t crc = crc32(out, CORE_SETTINGS_BLOB - 4);
|
||||
memcpy(out + CORE_SETTINGS_BLOB - 4, &crc, 4);
|
||||
}
|
||||
@@ -361,8 +510,10 @@ bool core_settings_unpack(core_settings_t *s, const uint8_t in[CORE_SETTINGS_BLO
|
||||
uint32_t crc;
|
||||
memcpy(&crc, in + CORE_SETTINGS_BLOB - 4, 4);
|
||||
if (memcmp(in, "PSER", 4) != 0 || in[4] != 1 || crc != crc32(in, CORE_SETTINGS_BLOB - 4)) return false;
|
||||
if (in[5] > PS_MODE_DTE || in[6] > PS_FLOW_OFF) return false;
|
||||
// byte 7 was 0 before baud-rate learning existed: PS_BAUD_AUTO
|
||||
if (in[5] > PS_MODE_DTE || in[6] > PS_FLOW_OFF || in[7] > PS_BAUD_LEARN) return false;
|
||||
s->mode = in[5];
|
||||
s->flow = in[6];
|
||||
s->baud = in[7];
|
||||
return true;
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
#pragma once
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include "autobaud.h"
|
||||
#include "hal.h"
|
||||
#include "protocol.h"
|
||||
#include "ring.h"
|
||||
@@ -18,6 +19,11 @@
|
||||
#define CORE_SETTLE_MS 100u // after switching off, before detecting again
|
||||
#define CORE_SAVE_DELAY_MS 500u // settle before writing settings to flash
|
||||
#define CORE_LED_PULSE_MS 30u
|
||||
#define CORE_AB_ERRORS 3u // this many framing errors...
|
||||
#define CORE_AB_WINDOW_MS 2000u // ...this close together: learn the baud rate again
|
||||
#define CORE_AB_TRY_MS 20u // while data keeps coming, look for the rate this often
|
||||
#define CORE_AB_LONG_MS 10000u // a run this long is just "long" (the timer would wrap)
|
||||
#define CORE_RUNS 128u // runs from the interrupt, waiting for core_poll
|
||||
|
||||
// LEDs, in the order of the front panel
|
||||
#define CORE_LED_PWR 0x01
|
||||
@@ -46,9 +52,11 @@
|
||||
typedef struct {
|
||||
uint8_t mode; // ps_mode
|
||||
uint8_t flow; // ps_flow
|
||||
uint8_t baud; // ps_baud
|
||||
} core_settings_t;
|
||||
|
||||
typedef enum { ST_DETECT, ST_ACTIVE, ST_SETTLE } core_state_t;
|
||||
typedef enum { AB_OFF, AB_LEARNING, AB_LOCKED } core_ab_state_t;
|
||||
|
||||
typedef struct {
|
||||
core_settings_t settings;
|
||||
@@ -66,7 +74,8 @@ typedef struct {
|
||||
bool cts_latched; // FLOW_AUTO: the far end has used its flow line
|
||||
bool hw_cts;
|
||||
|
||||
uart_format_t format;
|
||||
uart_format_t format; // as the host set it
|
||||
uart_format_t uart; // what the UART runs at: the host's, or with the learned baud
|
||||
uint8_t info_flags;
|
||||
uint32_t break_until; // 0 = no timed break
|
||||
bool break_on;
|
||||
@@ -82,6 +91,20 @@ typedef struct {
|
||||
uint32_t seen_to_rs232, seen_from_rs232;
|
||||
ps_stats_t stats;
|
||||
|
||||
// baud-rate learning
|
||||
volatile uint8_t ab_state; // core_ab_state_t; read by the UART interrupt
|
||||
uint32_t ab_baud; // learned rate, 0 = none yet
|
||||
ab_t ab; // runs collected while learning
|
||||
uint32_t ab_seen; // runs added since the last try
|
||||
uint32_t ab_found; // the rate they fit, 0 = not sure yet
|
||||
uint32_t t_ab_try, t_run;
|
||||
volatile uint8_t ab_fe; // framing errors while locked (from the interrupt)
|
||||
uint8_t ab_fe_seen, ab_win_n;
|
||||
uint32_t t_ab_win;
|
||||
uint32_t runs[CORE_RUNS]; // from the timing interrupt
|
||||
volatile uint32_t runs_head, runs_tail;
|
||||
volatile bool runs_lost;
|
||||
|
||||
ring_t to_host; // RS-232 -> host
|
||||
ring_t to_rs232; // host -> RS-232
|
||||
} core_t;
|
||||
@@ -108,6 +131,8 @@ bool core_vendor_out(core_t *c, uint8_t req, uint16_t value);
|
||||
|
||||
// From the UART interrupt
|
||||
static inline void core_isr_rx(core_t *c, uint8_t byte, uint8_t errors) {
|
||||
if (c->ab_state == AB_LEARNING) return; // received at a rate that's about to change
|
||||
if (errors & RX_ERR_FRAMING && c->ab_state == AB_LOCKED) c->ab_fe++;
|
||||
if (errors) c->rx_errors |= errors;
|
||||
if (!(errors & RX_ERR_BREAK)) {
|
||||
if (!ring_put(&c->to_host, byte)) c->stats.dropped++;
|
||||
@@ -120,6 +145,14 @@ static inline bool core_isr_tx(core_t *c, uint8_t *byte) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// From the line-timing interrupt (hal_autobaud): one run of a level.
|
||||
static inline void core_isr_run(core_t *c, bool high, uint32_t ticks) {
|
||||
uint32_t h = c->runs_head;
|
||||
if (h - c->runs_tail >= CORE_RUNS) { c->runs_lost = true; return; }
|
||||
c->runs[h % CORE_RUNS] = (high ? 0x80000000u : 0) | (ticks > AB_IDLE ? AB_IDLE : ticks);
|
||||
c->runs_head = h + 1;
|
||||
}
|
||||
|
||||
// Settings blob (for flash), with a checksum.
|
||||
#define CORE_SETTINGS_BLOB 16u
|
||||
void core_settings_pack(const core_settings_t *s, uint8_t out[CORE_SETTINGS_BLOB]);
|
||||
|
||||
@@ -34,6 +34,14 @@ void hal_uart_format(const uart_format_t *f);
|
||||
void hal_uart_hw_cts(bool on); // obey the far end's flow-control line
|
||||
void hal_uart_break(bool on);
|
||||
void hal_uart_kick_tx(void); // data was queued for the UART
|
||||
void hal_uart_rx_flush(void); // drop what the UART has received (call with interrupts off)
|
||||
|
||||
// Baud-rate learning: time the RX line of this role's chip (PS_ROLE_NONE
|
||||
// stops). From the first falling edge after the line is high, report each
|
||||
// run of one level with core_isr_run(), in ticks of hal_autobaud_hz()
|
||||
// (0 = too long to count).
|
||||
void hal_autobaud(uint8_t role);
|
||||
uint32_t hal_autobaud_hz(void);
|
||||
|
||||
// Modem lines for the active role.
|
||||
void hal_lines_out(uint8_t role, uint8_t asserted); // DCE: DCD DSR RI CTS; DTE: DTR RTS
|
||||
|
||||
@@ -22,11 +22,18 @@ enum ps_request {
|
||||
PS_REQ_SET_FLOW = 0x05, // OUT wValue = ps_flow (saved)
|
||||
PS_REQ_GET_STATS = 0x06, // IN ps_stats_t
|
||||
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
|
||||
};
|
||||
|
||||
enum ps_mode { PS_MODE_AUTO = 0, PS_MODE_DCE = 1, PS_MODE_DTE = 2 };
|
||||
enum ps_role { PS_ROLE_NONE = 0, PS_ROLE_DCE = 1, PS_ROLE_DTE = 2 };
|
||||
enum ps_flow { PS_FLOW_AUTO = 0, PS_FLOW_ON = 1, PS_FLOW_OFF = 2 };
|
||||
// Where the UART's baud rate comes from. AUTO: learned from the far end as
|
||||
// DCE (a computer typing at its own speed), the host's as DTE (a modem
|
||||
// follows the speed it's spoken to at). HOST: always the host's (SET_LINE_CODING).
|
||||
// LEARN: always learned. Data bits, parity and stop bits are always the host's.
|
||||
enum ps_baud { PS_BAUD_AUTO = 0, PS_BAUD_HOST = 1, PS_BAUD_LEARN = 2 };
|
||||
|
||||
// Modem lines, 1 = asserted (ON). Which are outputs and which inputs depends
|
||||
// on the role: as DCE the board drives DCD DSR RI CTS and reads DTR RTS; as
|
||||
@@ -42,6 +49,8 @@ enum ps_flow { PS_FLOW_AUTO = 0, PS_FLOW_ON = 1, PS_FLOW_OFF = 2 };
|
||||
#define PS_INFO_CODING_ADJUSTED 0x01 // last SET_LINE_CODING asked for something the UART can't do
|
||||
#define PS_INFO_BAUD_OVER_RATING 0x02 // baud above the transceivers' 250 kbit/s rating
|
||||
#define PS_INFO_FLOW_ACTIVE 0x04 // hardware CTS flow control currently obeyed
|
||||
#define PS_INFO_BAUD_LOCKED 0x08 // the baud rate was learned from the far end
|
||||
#define PS_INFO_BAUD_LEARNING 0x10 // learning it now (received data waits until it's known)
|
||||
|
||||
typedef struct __attribute__((packed)) {
|
||||
uint8_t protocol; // PS_PROTOCOL_VERSION
|
||||
@@ -51,7 +60,8 @@ typedef struct __attribute__((packed)) {
|
||||
uint8_t role; // ps_role now
|
||||
uint8_t flow; // ps_flow setting
|
||||
uint8_t flags; // PS_INFO_*
|
||||
uint32_t baud; // UART baud now
|
||||
uint32_t baud; // UART baud now (learned, or the host's)
|
||||
uint8_t baud_mode; // ps_baud setting
|
||||
} ps_info_t;
|
||||
|
||||
// ps_inputs_t.detect
|
||||
@@ -75,6 +85,6 @@ typedef struct __attribute__((packed)) {
|
||||
uint32_t role_changes;
|
||||
} ps_stats_t;
|
||||
|
||||
_Static_assert(sizeof(ps_info_t) == 13, "ps_info_t is 13 bytes on the wire");
|
||||
_Static_assert(sizeof(ps_info_t) == 14, "ps_info_t is 14 bytes on the wire");
|
||||
_Static_assert(sizeof(ps_inputs_t) == 5, "ps_inputs_t is 5 bytes on the wire");
|
||||
_Static_assert(sizeof(ps_stats_t) == 32, "ps_stats_t is 32 bytes on the wire");
|
||||
@@ -0,0 +1,38 @@
|
||||
; SPDX-License-Identifier: AGPL-3.0-only
|
||||
; Copyright (C) 2026 Neo-Desktop
|
||||
;
|
||||
; Times the RS-232 RX line for baud-rate learning (hal_autobaud). From the
|
||||
; first falling edge after the line is high, pushes one word per run of one
|
||||
; level: bit 31 = the level (1 high), bits 30..0 = 0x7FFFFFFF - length, the
|
||||
; length in counts of 2 system clocks. Reads the pin through the input
|
||||
; synchroniser, so the UART keeps the pin; jmp_pin and in_base = the RX pin.
|
||||
; A run of 2^32 counts or more (68 s) is waited out and reported as 0, which
|
||||
; the core takes as "long".
|
||||
|
||||
.program autobaud
|
||||
wait 1 pin 0 ; idle
|
||||
wait 0 pin 0 ; first start bit
|
||||
low_start:
|
||||
mov x, ~null
|
||||
low_loop:
|
||||
jmp pin low_end ; 2 clocks a count
|
||||
jmp x-- low_loop
|
||||
wait 1 pin 0
|
||||
low_end:
|
||||
set y, 0
|
||||
in x, 31
|
||||
in y, 1
|
||||
push noblock
|
||||
mov x, ~null
|
||||
high_loop:
|
||||
jmp pin high_more ; 2 clocks a count
|
||||
jmp high_end
|
||||
high_more:
|
||||
jmp x-- high_loop
|
||||
wait 0 pin 0
|
||||
high_end:
|
||||
set y, 1
|
||||
in x, 31
|
||||
in y, 1
|
||||
push noblock
|
||||
jmp low_start
|
||||
@@ -8,13 +8,16 @@
|
||||
// reads low on a receiver output.
|
||||
#include <string.h>
|
||||
#include "pico/stdlib.h"
|
||||
#include "hardware/clocks.h"
|
||||
#include "hardware/flash.h"
|
||||
#include "hardware/irq.h"
|
||||
#include "hardware/pio.h"
|
||||
#include "hardware/sync.h"
|
||||
#include "hardware/uart.h"
|
||||
#include "board_config.h"
|
||||
#include "core.h"
|
||||
#include "hal_rp2040.h"
|
||||
#include "autobaud.pio.h"
|
||||
|
||||
#define UART uart0
|
||||
#define UART_IRQ UART0_IRQ
|
||||
@@ -74,6 +77,44 @@ static void uart_irq(void) {
|
||||
}
|
||||
}
|
||||
|
||||
// Baud-rate learning: a PIO state machine times the RX line (autobaud.pio).
|
||||
#define AB_PIO pio0
|
||||
static uint s_ab_sm, s_ab_offset;
|
||||
static pio_sm_config s_ab_cfg;
|
||||
|
||||
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);
|
||||
core_isr_run(&g_core, (raw >> 31) != 0, ~raw & 0x7FFFFFFFu);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
s_ab_cfg = autobaud_program_get_default_config(s_ab_offset);
|
||||
sm_config_set_in_shift(&s_ab_cfg, true, false, 32); // right: "in x, 31; in y, 1" puts y in bit 31
|
||||
sm_config_set_fifo_join(&s_ab_cfg, PIO_FIFO_JOIN_RX);
|
||||
sm_config_set_clkdiv_int_frac(&s_ab_cfg, 1, 0);
|
||||
irq_set_exclusive_handler(PIO0_IRQ_0, ab_irq);
|
||||
pio_set_irq0_source_enabled(AB_PIO, (enum pio_interrupt_source)(pis_sm0_rx_fifo_not_empty + s_ab_sm), true);
|
||||
irq_set_enabled(PIO0_IRQ_0, true);
|
||||
}
|
||||
|
||||
void hal_autobaud(uint8_t role) {
|
||||
pio_sm_set_enabled(AB_PIO, s_ab_sm, false);
|
||||
pio_sm_clear_fifos(AB_PIO, s_ab_sm);
|
||||
if (role != PS_ROLE_DCE && role != PS_ROLE_DTE) return;
|
||||
// the pin stays the UART's: PIO reads every pin's input
|
||||
uint pin = PINS[role].rx;
|
||||
sm_config_set_in_pins(&s_ab_cfg, pin);
|
||||
sm_config_set_jmp_pin(&s_ab_cfg, pin);
|
||||
pio_sm_init(AB_PIO, s_ab_sm, s_ab_offset, &s_ab_cfg);
|
||||
pio_sm_set_enabled(AB_PIO, s_ab_sm, true);
|
||||
}
|
||||
|
||||
uint32_t hal_autobaud_hz(void) { return clock_get_hz(clk_sys) / 2u; }
|
||||
|
||||
void hal_init(void) {
|
||||
// transceivers off until the core decides (the board also pulls these low)
|
||||
out_pin(PIN_A_SHDN_N, false);
|
||||
@@ -105,6 +146,8 @@ void hal_init(void) {
|
||||
irq_set_exclusive_handler(UART_IRQ, uart_irq);
|
||||
irq_set_enabled(UART_IRQ, true);
|
||||
uart_set_irq_enables(UART, true, false); // RX (and RX timeout); TX when there's data
|
||||
|
||||
ab_init();
|
||||
}
|
||||
|
||||
uint32_t hal_millis(void) { return to_ms_since_boot(get_absolute_time()); }
|
||||
@@ -150,6 +193,11 @@ void hal_uart_format(const uart_format_t *f) {
|
||||
uart_set_format(UART, f->data_bits, f->stop_bits, par);
|
||||
}
|
||||
|
||||
void hal_uart_rx_flush(void) {
|
||||
uart_hw_t *hw = uart_get_hw(UART);
|
||||
while (!(hw->fr & UART_UARTFR_RXFE_BITS)) (void)hw->dr;
|
||||
}
|
||||
|
||||
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); }
|
||||
|
||||
|
||||
+13
-5
@@ -2,13 +2,21 @@
|
||||
# Copyright (C) 2026 Neo-Desktop
|
||||
# Host tests for the portable core: make -C firmware/test
|
||||
CFLAGS ?= -std=c11 -O1 -g -Wall -Wextra -Werror -Wconversion -Wno-sign-conversion -fsanitize=address,undefined
|
||||
CORE = ../src/core/core.c ../src/core/autobaud.c
|
||||
DEPS = $(CORE) $(wildcard ../src/core/*.h) fake_hal.h wave.h wave.c
|
||||
|
||||
test_core: test_core.c fake_hal.c ../src/core/core.c ../src/core/core.h ../src/core/hal.h ../src/core/ring.h ../src/core/protocol.h fake_hal.h
|
||||
$(CC) $(CFLAGS) -o $@ test_core.c fake_hal.c ../src/core/core.c
|
||||
all: test_core test_autobaud
|
||||
|
||||
.PHONY: run clean
|
||||
run: test_core
|
||||
test_core: test_core.c fake_hal.c $(DEPS)
|
||||
$(CC) $(CFLAGS) -o $@ test_core.c fake_hal.c wave.c $(CORE) -lm
|
||||
|
||||
test_autobaud: test_autobaud.c $(DEPS)
|
||||
$(CC) $(CFLAGS) -o $@ test_autobaud.c wave.c ../src/core/autobaud.c -lm
|
||||
|
||||
.PHONY: all run clean
|
||||
run: all
|
||||
./test_core
|
||||
./test_autobaud
|
||||
|
||||
clean:
|
||||
rm -f test_core
|
||||
rm -f test_core test_autobaud
|
||||
@@ -3,7 +3,8 @@
|
||||
// End-to-end test of the real firmware image in the rp2040js emulator:
|
||||
// boot, USB enumeration (the emulator plays the host), DCE/DTE detection via
|
||||
// the transceivers' status lines, modem-line mapping on the GPIOs, data both
|
||||
// ways through the UART, CDC SERIAL_STATE notifications and vendor requests.
|
||||
// ways through the UART, CDC SERIAL_STATE notifications, vendor requests, and
|
||||
// learning the baud rate from characters driven onto the RX pin (GP1).
|
||||
//
|
||||
// firmware/test/emu/run.sh <firmware .bin>
|
||||
import { readFileSync } from 'fs';
|
||||
@@ -18,7 +19,9 @@ const P = {
|
||||
B_RTS: 15, A_SHDN_N: 16, B_FORCEOFF_N: 17, RS_FORCEON: 18, A_R1OUTB: 19, A_STATUS: 20, B_INVALID: 21,
|
||||
};
|
||||
const ITF_CONTROL = 2;
|
||||
const REQ = { GET_INFO: 1, SET_MODE: 2, GET_INPUTS: 4 };
|
||||
const REQ = { GET_INFO: 1, SET_MODE: 2, GET_INPUTS: 4, AUTOBAUD_RESTART: 9 };
|
||||
const INFO = { LEN: 14, BAUD_LOCKED: 0x08, BAUD_LEARNING: 0x10 };
|
||||
const A_RX = 1;
|
||||
|
||||
let failures = 0, checks = 0;
|
||||
function check(cond: boolean, what: string) {
|
||||
@@ -61,6 +64,52 @@ mcu.usbCtrl.onEndpointWrite = (ep, buf) => {
|
||||
cdcWrite(ep, buf);
|
||||
};
|
||||
|
||||
// rp2040js runs PIO on its own timer, not the simulated clock. The baud-rate
|
||||
// learning times the RX line with PIO, so step it once per CPU cycle instead
|
||||
// (the firmware runs the system clock at 125 MHz, as the emulator does).
|
||||
const pio0 = mcu.pio[0] as any;
|
||||
pio0.run = () => {};
|
||||
const simAny = sim as any;
|
||||
sim.execute = () => {
|
||||
simAny.executeTimer = null;
|
||||
simAny.stopped = false;
|
||||
for (let i = 0; i < 200000 && !simAny.stopped; i++) {
|
||||
let cycles: number;
|
||||
if (mcu.core.waiting) {
|
||||
const n = sim.clock.nanosToNextAlarm;
|
||||
sim.clock.tick(n);
|
||||
cycles = Math.min(Math.ceil(n / 8), 1 << 20);
|
||||
} else {
|
||||
cycles = mcu.core.executeInstruction();
|
||||
sim.clock.tick(cycles * 8);
|
||||
}
|
||||
if (!pio0.stopped) for (let k = 0; k < cycles; k++) pio0.step();
|
||||
}
|
||||
if (!simAny.stopped) simAny.executeTimer = setTimeout(() => sim.execute(), 0);
|
||||
};
|
||||
|
||||
// A computer typing: drive characters (8N1) onto a receiver output pin, on
|
||||
// the simulated clock. Receiver outputs are inverted RS-232: idle = high.
|
||||
function sendWave(gpio: number, baud: number, text: string, errPct = 0): Promise<void> {
|
||||
const levels: boolean[] = [];
|
||||
for (const ch of Buffer.from(text)) {
|
||||
levels.push(false);
|
||||
for (let d = 0; d < 8; d++) levels.push(((ch >> d) & 1) === 1);
|
||||
levels.push(true, true); // stop bit and a little idle
|
||||
}
|
||||
const bitNs = 1e9 / (baud * (1 + errPct / 100));
|
||||
return new Promise((resolve) => {
|
||||
let k = 0;
|
||||
const alarm = sim.clock.createAlarm(() => {
|
||||
pin(gpio).setInputValue(levels[k]);
|
||||
k++;
|
||||
if (k < levels.length) alarm.schedule(bitNs);
|
||||
else resolve();
|
||||
});
|
||||
alarm.schedule(1000);
|
||||
});
|
||||
}
|
||||
|
||||
sim.rp2040.core.PC = 0x10000000;
|
||||
sim.execute();
|
||||
|
||||
@@ -113,6 +162,25 @@ async function main() {
|
||||
check(!out(P.A_RTS), "host RTS asserts the computer's CTS");
|
||||
check(out(P.A_RI), 'RI stays off');
|
||||
|
||||
console.log('learning the baud rate: the computer types "AT\\r" at 9600 baud (1% fast)');
|
||||
const learning = await vendorIn(REQ.GET_INFO, INFO.LEN);
|
||||
check(!!learning && learning.length === INFO.LEN && (learning[8] & INFO.BAUD_LEARNING) !== 0,
|
||||
'GET_INFO (14 bytes) says it is learning the baud rate');
|
||||
mcu.uart[0].feedByte(0x78); // what the UART makes of it at the wrong rate
|
||||
await runFor(20);
|
||||
check(hostIn.length === 0, 'while learning, the UART\'s bytes are held back');
|
||||
await sendWave(A_RX, 9600, 'AT\r', 1);
|
||||
check(await until(() => hostIn.length >= 3, 500) && Buffer.from(hostIn).toString() === 'AT\r',
|
||||
'the characters it learned from reach the host: "AT\\r"');
|
||||
hostIn.length = 0;
|
||||
const locked = await vendorIn(REQ.GET_INFO, INFO.LEN);
|
||||
if (locked) {
|
||||
const dv = new DataView(locked.buffer, locked.byteOffset);
|
||||
check(dv.getUint32(9, true) === 9600, `UART now at 9600 (got ${dv.getUint32(9, true)})`);
|
||||
check((locked[8] & (INFO.BAUD_LOCKED | INFO.BAUD_LEARNING)) === INFO.BAUD_LOCKED, 'flags: baud locked, not learning');
|
||||
check(locked[13] === 0, 'baud mode AUTO');
|
||||
} else check(false, 'GET_INFO answers');
|
||||
|
||||
console.log('data both ways');
|
||||
for (const ch of Buffer.from('ATZ\r')) cdc.sendSerialByte(ch);
|
||||
check(await until(() => uartOut.length >= 4, 500) && Buffer.from(uartOut).toString() === 'ATZ\r',
|
||||
@@ -126,18 +194,28 @@ async function main() {
|
||||
check(await until(() => (lastState() & 0x03) === 0x03, 500), 'SERIAL_STATE reports DCD (computer attached) + DSR (its DTR)');
|
||||
|
||||
console.log('vendor requests');
|
||||
const info = await vendorIn(REQ.GET_INFO, 13);
|
||||
check(!!info && info.length === 13, 'GET_INFO answers 13 bytes');
|
||||
const info = await vendorIn(REQ.GET_INFO, INFO.LEN);
|
||||
check(!!info && info.length === INFO.LEN, 'GET_INFO answers 14 bytes');
|
||||
if (info) {
|
||||
const dv = new DataView(info.buffer, info.byteOffset);
|
||||
check(info[0] === 1, `protocol version 1 (got ${info[0]})`);
|
||||
check(info[6] === 1, `role DCE (got ${info[6]})`);
|
||||
check(dv.getUint32(9, true) === 115200, `baud 115200 (got ${dv.getUint32(9, true)})`);
|
||||
check(dv.getUint32(9, true) === 9600, `baud still the learned 9600 (got ${dv.getUint32(9, true)})`);
|
||||
}
|
||||
const inputs = await vendorIn(REQ.GET_INPUTS, 5);
|
||||
check(!!inputs && (inputs[1] & 0x01) === 0x01 && (inputs[3] & 0x01) === 0x01,
|
||||
"GET_INPUTS shows the computer's DTR and chip A STATUS");
|
||||
|
||||
console.log('learn again (vendor request): now 115200 baud, 2% slow');
|
||||
vendorOut(REQ.AUTOBAUD_RESTART, 0);
|
||||
await runFor(20);
|
||||
hostIn.length = 0;
|
||||
await sendWave(A_RX, 115200, 'ATI3\r', -2);
|
||||
check(await until(() => hostIn.length >= 5, 500) && Buffer.from(hostIn).toString() === 'ATI3\r',
|
||||
'"ATI3\\r" reaches the host');
|
||||
const again = await vendorIn(REQ.GET_INFO, INFO.LEN);
|
||||
check(!!again && new DataView(again.buffer, again.byteOffset).getUint32(9, true) === 115200, 'UART now at 115200');
|
||||
|
||||
console.log('force DTE mode');
|
||||
vendorOut(REQ.SET_MODE, 2);
|
||||
check(await until(() => !out(P.A_SHDN_N) && out(P.B_FORCEOFF_N), 500), 'chip A off, chip B (DTE) on');
|
||||
@@ -151,8 +229,13 @@ async function main() {
|
||||
// checked here; check the firmware gets through the save (500 ms after the
|
||||
// change) without hanging or a watchdog reset, still in DTE mode.
|
||||
await runFor(1500);
|
||||
const after = await vendorIn(REQ.GET_INFO, 13);
|
||||
const after = await vendorIn(REQ.GET_INFO, INFO.LEN);
|
||||
check(!!after && after[5] === 2 && after[6] === 2, 'still running in DTE mode after the settings save');
|
||||
if (after) {
|
||||
const dv = new DataView(after.buffer, after.byteOffset);
|
||||
check((after[8] & (INFO.BAUD_LOCKED | INFO.BAUD_LEARNING)) === 0 && dv.getUint32(9, true) === 115200,
|
||||
"as DTE the host's baud rate (115200) is used, not learned");
|
||||
}
|
||||
|
||||
sim.stop();
|
||||
console.log(`${checks} checks, ${failures} failed`);
|
||||
|
||||
@@ -28,6 +28,9 @@ void hal_uart_format(const uart_format_t *f) { hw.format = *f; hw.format_calls++
|
||||
void hal_uart_hw_cts(bool on) { hw.hw_cts = on; }
|
||||
void hal_uart_break(bool on) { hw.brk = on; }
|
||||
void hal_uart_kick_tx(void) { hw.kicks++; }
|
||||
void hal_uart_rx_flush(void) { hw.rx_flushes++; }
|
||||
void hal_autobaud(uint8_t role) { hw.ab_role = role; hw.ab_calls++; }
|
||||
uint32_t hal_autobaud_hz(void) { return FAKE_AB_HZ; }
|
||||
void hal_lines_out(uint8_t role, uint8_t asserted) { hw.out_role = role; hw.out = asserted; }
|
||||
uint8_t hal_lines_in(uint8_t role) { (void)role; return hw.in; }
|
||||
void hal_leds(uint8_t mask) { hw.leds = mask; }
|
||||
|
||||
@@ -19,7 +19,11 @@ typedef struct {
|
||||
uint8_t flash[64];
|
||||
bool flash_valid;
|
||||
int saves;
|
||||
uint8_t ab_role; // hal_autobaud: which RX line is being timed
|
||||
int ab_calls, rx_flushes;
|
||||
} fake_hw_t;
|
||||
|
||||
#define FAKE_AB_HZ 62500000u
|
||||
|
||||
extern fake_hw_t hw;
|
||||
void fake_reset(void);
|
||||
@@ -0,0 +1,157 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 Neo-Desktop
|
||||
*/
|
||||
// Host tests for the baud-rate detector: waveforms made from text and random
|
||||
// bytes at every standard rate, with timing jitter, a sender running fast or
|
||||
// slow, other data formats, glitches, and a capture starting mid-character.
|
||||
// Build and run: make -C firmware/test
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "../src/core/autobaud.h"
|
||||
#include "../src/core/core.h"
|
||||
#include "wave.h"
|
||||
|
||||
static int failures, checks;
|
||||
#define CHECK(cond) do { checks++; if (!(cond)) { failures++; \
|
||||
printf(" FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); } } while (0)
|
||||
|
||||
static ab_t a;
|
||||
static wave_t wv;
|
||||
#define rnd wave_rnd
|
||||
|
||||
static void synth(uint32_t hz, uint32_t baud, double err, const uart_format_t *f,
|
||||
const uint8_t *msg, size_t len, double gap_bits, double jitter) {
|
||||
wave_make(&wv, hz, baud, err, f, msg, len, gap_bits, jitter);
|
||||
ab_reset(&a);
|
||||
for (uint32_t i = 0; i < wv.n; i++) ab_add(&a, wv.high[i], wv.ticks[i]);
|
||||
}
|
||||
|
||||
typedef struct { uint8_t buf[512]; uint32_t n; uint32_t errs; } sink_t;
|
||||
static void sink(void *ctx, uint8_t b, uint8_t e) {
|
||||
sink_t *s = ctx;
|
||||
if (s->n < sizeof s->buf) s->buf[s->n++] = b;
|
||||
if (e) s->errs++;
|
||||
}
|
||||
|
||||
static bool decodes_to(uint32_t hz, uint32_t baud, const uart_format_t *f, const uint8_t *msg, size_t len) {
|
||||
sink_t s = {{0}, 0, 0};
|
||||
uint8_t mask = (uint8_t)((1u << f->data_bits) - 1);
|
||||
ab_decode(&a, hz, baud, f, sink, &s);
|
||||
if (s.n != len || s.errs) return false;
|
||||
for (size_t i = 0; i < len; i++)
|
||||
if (s.buf[i] != (msg[i] & mask)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
static const uart_format_t F8N1 = {0, 8, 1, 0}, F7E1 = {0, 7, 1, 2}, F8N2 = {0, 8, 2, 0},
|
||||
F7O1 = {0, 7, 1, 1}, F8E1 = {0, 8, 1, 2};
|
||||
|
||||
static void every_rate(const char *name, const uart_format_t *f, const uint8_t *msg, size_t len,
|
||||
double err, double jitter, double gap, uint32_t hz) {
|
||||
int bad = 0;
|
||||
for (uint32_t b = 0; b < AB_NBAUDS; b++) {
|
||||
synth(hz, AB_BAUDS[b], err, f, msg, len, gap, jitter);
|
||||
uint32_t got = ab_detect(&a, hz, f);
|
||||
bool ok = got == AB_BAUDS[b] && decodes_to(hz, got, f, msg, len);
|
||||
CHECK(ok);
|
||||
if (!ok) { bad++; printf(" %s at %u: got %u\n", name, AB_BAUDS[b], got); }
|
||||
}
|
||||
printf("%-44s %s\n", name, bad ? "FAIL" : "ok");
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
const uint32_t HZ = 62500000; // 125 MHz / 2
|
||||
const uint8_t at[] = "AT\r", at_lc[] = "at", dial[] = "ATDT5551212\r", ok[] = "\r\nOK\r\n";
|
||||
const uint8_t at2[] = "AT";
|
||||
|
||||
every_rate("AT\\r, 8N1, exact", &F8N1, at, 3, 0, 0, 0, HZ);
|
||||
every_rate("AT (just 2 characters), 8N1", &F8N1, at2, 2, 0, 0, 0, HZ);
|
||||
every_rate("at, 8N1, sender 2% fast, jitter 0.08 bit", &F8N1, at_lc, 2, 0.02, 0.08, 0, HZ);
|
||||
every_rate("AT\\r, 8N1, sender 2.5% slow, jitter 0.1", &F8N1, at, 3, -0.025, 0.1, 0, HZ);
|
||||
every_rate("ATDT5551212\\r, 8N1, gaps of 3 bits", &F8N1, dial, 12, 0.01, 0.05, 3, HZ);
|
||||
every_rate("\\r\\nOK\\r\\n, 8N1, back to back", &F8N1, ok, 6, -0.01, 0.05, 0, HZ);
|
||||
every_rate("ATDT5551212\\r, 7E1", &F7E1, dial, 12, 0.015, 0.05, 0, HZ);
|
||||
every_rate("ATDT5551212\\r, 7O1", &F7O1, dial, 12, -0.015, 0.05, 1, HZ);
|
||||
every_rate("ATDT5551212\\r, 8N2", &F8N2, dial, 12, 0.0, 0.05, 0, HZ);
|
||||
every_rate("ATDT5551212\\r, 8E1", &F8E1, dial, 12, 0.0, 0.05, 0, HZ);
|
||||
every_rate("AT\\r, 8N1, 100 MHz ticks (200 MHz clock)", &F8N1, at, 3, 0.01, 0.05, 0, 100000000);
|
||||
|
||||
uint8_t bin[40];
|
||||
int bad = 0;
|
||||
for (int trial = 0; trial < 200; trial++) {
|
||||
for (size_t i = 0; i < sizeof bin; i++) bin[i] = (uint8_t)(rnd() * 256);
|
||||
uint32_t baud = AB_BAUDS[trial % AB_NBAUDS];
|
||||
synth(HZ, baud, (rnd() - 0.5) * 0.04, &F8N1, bin, 16, (double)(trial % 3), 0.06);
|
||||
uint32_t got = ab_detect(&a, HZ, &F8N1);
|
||||
if (got != baud) { bad++; printf(" random bytes at %u: got %u\n", baud, got); }
|
||||
CHECK(got == baud);
|
||||
}
|
||||
printf("%-44s %s (%d/200 wrong)\n", "200 x 16 random bytes, random rates", bad ? "FAIL" : "ok", bad);
|
||||
|
||||
// characters with no 1-bit runs: half the rate is ruled out by the
|
||||
// bit-boundary check, 3/4 of it by the score
|
||||
{
|
||||
const char *tricky[] = {"0>", "<0", "<8", "><", "0>0>", "<0<8", "<8<8<8", "><><><"};
|
||||
int wrong = 0, undecided = 0;
|
||||
for (int t = 0; t < 8; t++)
|
||||
for (uint32_t b = 1; b < AB_NBAUDS; b++)
|
||||
for (int gap = 0; gap < 4; gap++) {
|
||||
size_t len = strlen(tricky[t]);
|
||||
synth(HZ, AB_BAUDS[b], 0, &F8N1, (const uint8_t *)tricky[t], len, gap, 0.03);
|
||||
uint32_t got = ab_detect(&a, HZ, &F8N1);
|
||||
if (!got) undecided++;
|
||||
else if (got != AB_BAUDS[b]) {
|
||||
wrong++;
|
||||
printf(" \"%s\" gap %d at %u: got %u\n", tricky[t], gap, AB_BAUDS[b], got);
|
||||
}
|
||||
}
|
||||
CHECK(wrong == 0);
|
||||
CHECK(undecided == 0);
|
||||
printf("%-44s %s\n", "no 1-bit runs (\"<0\" etc.)", wrong ? "FAIL" : "ok");
|
||||
}
|
||||
|
||||
// one character isn't enough to decide
|
||||
synth(HZ, 9600, 0, &F8N1, (const uint8_t *)"A", 1, 0, 0);
|
||||
CHECK(ab_detect(&a, HZ, &F8N1) == 0);
|
||||
printf("%-44s ok\n", "one character: no decision yet");
|
||||
|
||||
// a glitch before the data stops a decision until it's dropped
|
||||
synth(HZ, 9600, 0, &F8N1, at, 3, 0, 0);
|
||||
{
|
||||
ab_t g;
|
||||
ab_reset(&g);
|
||||
ab_add(&g, false, 300); // 5 us low glitch
|
||||
ab_add(&g, true, HZ / 100); // 10 ms idle
|
||||
for (uint32_t i = 0; i < a.n; i++) ab_add(&g, a.run[i] >> 31, a.run[i] & AB_IDLE);
|
||||
CHECK(ab_detect(&g, HZ, &F8N1) == 0);
|
||||
ab_drop(&g, 1);
|
||||
CHECK(ab_detect(&g, HZ, &F8N1) == 9600);
|
||||
printf("%-44s ok\n", "glitch first: undecided until dropped");
|
||||
}
|
||||
|
||||
// capture starting in the middle of a character: drop runs until it fits
|
||||
{
|
||||
synth(HZ, 19200, 0, &F8N1, dial, 12, 0, 0.03);
|
||||
ab_drop(&a, 2); // starts mid-"A"/"T"
|
||||
uint32_t got = 0;
|
||||
for (int k = 0; k < 6 && !(got = ab_detect(&a, HZ, &F8N1)); k++) ab_drop(&a, 1);
|
||||
CHECK(got == 19200);
|
||||
printf("%-44s %s\n", "capture started mid-character", got == 19200 ? "ok" : "FAIL");
|
||||
}
|
||||
|
||||
// add merges same-level runs and the first run is low
|
||||
ab_reset(&a);
|
||||
CHECK(ab_add(&a, true, 100) && a.n == 0);
|
||||
ab_add(&a, false, 10); ab_add(&a, false, 5); ab_add(&a, true, 7);
|
||||
CHECK(a.n == 2 && (a.run[0] & AB_IDLE) == 15 && (a.run[1] >> 31));
|
||||
ab_add(&a, true, AB_IDLE);
|
||||
CHECK((a.run[1] & AB_IDLE) == AB_IDLE);
|
||||
ab_reset(&a);
|
||||
for (uint32_t i = 0; i < AB_MAX_RUNS; i++) CHECK(ab_add(&a, i & 1, 100));
|
||||
CHECK(!ab_add(&a, AB_MAX_RUNS & 1, 100));
|
||||
|
||||
printf("%d checks, %d failed\n", checks, failures);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
+168
-7
@@ -9,6 +9,7 @@
|
||||
#include <string.h>
|
||||
#include "../src/core/core.h"
|
||||
#include "fake_hal.h"
|
||||
#include "wave.h"
|
||||
|
||||
static int failures, checks;
|
||||
#define CHECK(cond) do { checks++; if (!(cond)) { failures++; \
|
||||
@@ -28,6 +29,14 @@ static void start_auto(void) {
|
||||
CHECK(hw.xcvr == PS_ROLE_NONE);
|
||||
}
|
||||
|
||||
// a computer attached, at the host's baud rate (received bytes go straight through)
|
||||
static void start_dce_host_baud(void) {
|
||||
start_auto();
|
||||
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 && c.ab_state == AB_OFF);
|
||||
}
|
||||
|
||||
TEST(detects_computer_as_dce) {
|
||||
start_auto();
|
||||
hw.peer_dce = true;
|
||||
@@ -88,7 +97,7 @@ TEST(short_loss_recovers) {
|
||||
}
|
||||
|
||||
TEST(forced_mode_ignores_detection) {
|
||||
core_settings_t s = {PS_MODE_DTE, PS_FLOW_AUTO};
|
||||
core_settings_t s = {PS_MODE_DTE, PS_FLOW_AUTO, PS_BAUD_AUTO};
|
||||
uint8_t blob[CORE_SETTINGS_BLOB];
|
||||
core_settings_pack(&s, blob);
|
||||
memcpy(hw.flash, blob, sizeof blob); hw.flash_valid = true;
|
||||
@@ -131,8 +140,7 @@ TEST(overrides) {
|
||||
}
|
||||
|
||||
TEST(full_buffer_holds_the_far_end) {
|
||||
start_auto();
|
||||
hw.peer_dce = true; run_ms(500);
|
||||
start_dce_host_baud();
|
||||
core_host_lines(&c, false, true); run_ms(5);
|
||||
CHECK(hw.out & PS_LINE_CTS);
|
||||
for (uint32_t i = 0; i < RING_SIZE * 3 / 4; i++) core_isr_rx(&c, 'x', 0);
|
||||
@@ -222,8 +230,7 @@ TEST(break_timing) {
|
||||
}
|
||||
|
||||
TEST(data_both_ways) {
|
||||
start_auto();
|
||||
hw.peer_dce = true; run_ms(500);
|
||||
start_dce_host_baud();
|
||||
const uint8_t msg[] = "ATDT5551234\r";
|
||||
CHECK(core_host_write(&c, msg, sizeof msg - 1) == sizeof msg - 1);
|
||||
CHECK(hw.kicks > 0);
|
||||
@@ -259,10 +266,10 @@ TEST(vendor_info_and_mode) {
|
||||
}
|
||||
|
||||
TEST(settings_blob) {
|
||||
core_settings_t a = {PS_MODE_DTE, PS_FLOW_OFF}, b = {0, 0};
|
||||
core_settings_t a = {PS_MODE_DTE, PS_FLOW_OFF, PS_BAUD_LEARN}, b = {0, 0, 0};
|
||||
uint8_t blob[CORE_SETTINGS_BLOB];
|
||||
core_settings_pack(&a, blob);
|
||||
CHECK(core_settings_unpack(&b, blob) && b.mode == PS_MODE_DTE && b.flow == PS_FLOW_OFF);
|
||||
CHECK(core_settings_unpack(&b, blob) && b.mode == PS_MODE_DTE && b.flow == PS_FLOW_OFF && b.baud == PS_BAUD_LEARN);
|
||||
blob[5] ^= 1;
|
||||
CHECK(!core_settings_unpack(&b, blob)); // checksum catches it
|
||||
memset(blob, 0xFF, sizeof blob); // erased flash
|
||||
@@ -286,6 +293,7 @@ TEST(ring_wraps) {
|
||||
|
||||
TEST(leds) {
|
||||
start_auto();
|
||||
core_vendor_out(&c, PS_REQ_SET_BAUD_MODE, PS_BAUD_HOST);
|
||||
run_ms(5);
|
||||
CHECK(hw.leds == CORE_LED_PWR);
|
||||
hw.peer_dce = true; run_ms(500);
|
||||
@@ -297,6 +305,154 @@ TEST(leds) {
|
||||
CHECK(!(hw.leds & CORE_LED_RD));
|
||||
}
|
||||
|
||||
// --- baud-rate learning ---
|
||||
static wave_t wv;
|
||||
static const uart_format_t F8N1 = {0, 8, 1, 0};
|
||||
|
||||
static void send_runs(uint32_t baud, const char *msg, const uart_format_t *f) {
|
||||
wave_make(&wv, FAKE_AB_HZ, baud, 0.01, f, (const uint8_t *)msg, strlen(msg), 1, 0.03);
|
||||
for (uint32_t i = 0; i < wv.n; i++) core_isr_run(&c, wv.high[i], wv.ticks[i]);
|
||||
}
|
||||
static bool host_got(const char *want) {
|
||||
uint8_t buf[128];
|
||||
uint32_t n = core_host_read(&c, buf, sizeof buf);
|
||||
return n == strlen(want) && memcmp(buf, want, n) == 0;
|
||||
}
|
||||
static ps_info_t info(void) {
|
||||
ps_info_t i;
|
||||
uint8_t buf[sizeof i];
|
||||
CHECK(core_vendor_in(&c, PS_REQ_GET_INFO, 0, buf, sizeof buf) == (int)sizeof i);
|
||||
memcpy(&i, buf, sizeof i);
|
||||
return i;
|
||||
}
|
||||
|
||||
TEST(autobaud_learns_as_dce) {
|
||||
start_auto();
|
||||
hw.peer_dce = true; run_ms(500);
|
||||
CHECK(c.ab_state == AB_LEARNING && hw.ab_role == PS_ROLE_DCE);
|
||||
CHECK(info().flags & PS_INFO_BAUD_LEARNING);
|
||||
CHECK(hw.format.baud == 115200); // the host's until learned
|
||||
core_isr_rx(&c, 'x', RX_ERR_FRAMING); // the UART at the wrong rate: dropped
|
||||
CHECK(ring_count(&c.to_host) == 0 && c.rx_errors == 0);
|
||||
send_runs(9600, "AT\r", &F8N1);
|
||||
run_ms(120);
|
||||
CHECK(c.ab_state == AB_LOCKED && hw.ab_role == PS_ROLE_NONE);
|
||||
CHECK(hw.format.baud == 9600 && hw.rx_flushes == 1);
|
||||
CHECK(host_got("AT\r")); // the characters it learned from aren't lost
|
||||
CHECK(c.stats.from_rs232 == 3);
|
||||
ps_info_t i = info();
|
||||
CHECK(i.baud == 9600 && (i.flags & PS_INFO_BAUD_LOCKED) && !(i.flags & PS_INFO_BAUD_LEARNING));
|
||||
CHECK(i.baud_mode == PS_BAUD_AUTO);
|
||||
core_isr_rx(&c, 'Z', 0); // now the UART's bytes go through
|
||||
CHECK(host_got("Z"));
|
||||
// the host changing the format keeps the learned rate
|
||||
core_host_format(&c, 115200, 0, 2, 7);
|
||||
CHECK(hw.format.baud == 9600 && hw.format.data_bits == 7 && hw.format.parity == 2);
|
||||
CHECK(info().baud == 9600);
|
||||
}
|
||||
|
||||
TEST(autobaud_relearns_on_framing_errors) {
|
||||
start_auto();
|
||||
hw.peer_dce = true; run_ms(500);
|
||||
send_runs(2400, "ATZ\r", &F8N1); run_ms(120);
|
||||
CHECK(c.ab_state == AB_LOCKED && hw.format.baud == 2400);
|
||||
host_got("ATZ\r");
|
||||
// scattered errors: not enough
|
||||
core_isr_rx(&c, 0, RX_ERR_FRAMING); run_ms(1500);
|
||||
core_isr_rx(&c, 0, RX_ERR_FRAMING); run_ms(1500);
|
||||
core_isr_rx(&c, 0, RX_ERR_FRAMING); run_ms(1500);
|
||||
CHECK(c.ab_state == AB_LOCKED);
|
||||
// the computer switched to 115200: a burst of errors
|
||||
for (int k = 0; k < 3; k++) { core_isr_rx(&c, 0, RX_ERR_FRAMING); run_ms(10); }
|
||||
CHECK(c.ab_state == AB_LEARNING && hw.ab_role == PS_ROLE_DCE);
|
||||
CHECK(hw.format.baud == 2400); // sends at the old rate until it knows
|
||||
host_got("\0\0\0\0\0\0");
|
||||
send_runs(115200, "AT&F\r", &F8N1); run_ms(120);
|
||||
CHECK(c.ab_state == AB_LOCKED && hw.format.baud == 115200);
|
||||
CHECK(host_got("AT&F\r"));
|
||||
}
|
||||
|
||||
TEST(autobaud_vendor_restart_and_modes) {
|
||||
start_auto();
|
||||
hw.peer_dce = true; run_ms(500);
|
||||
send_runs(19200, "at\r", &F8N1); run_ms(120);
|
||||
CHECK(hw.format.baud == 19200);
|
||||
CHECK(core_vendor_out(&c, PS_REQ_AUTOBAUD_RESTART, 0));
|
||||
CHECK(c.ab_state == AB_LEARNING);
|
||||
send_runs(300, "AT\r", &F8N1); run_ms(120);
|
||||
CHECK(hw.format.baud == 300);
|
||||
// HOST: back to the host's rate, no learning
|
||||
CHECK(core_vendor_out(&c, PS_REQ_SET_BAUD_MODE, PS_BAUD_HOST));
|
||||
CHECK(c.ab_state == AB_OFF && hw.ab_role == PS_ROLE_NONE && hw.format.baud == 115200);
|
||||
CHECK(core_vendor_out(&c, PS_REQ_AUTOBAUD_RESTART, 0) && c.ab_state == AB_OFF); // no effect
|
||||
CHECK(!core_vendor_out(&c, PS_REQ_SET_BAUD_MODE, 3));
|
||||
run_ms(CORE_SAVE_DELAY_MS + 20);
|
||||
core_settings_t st;
|
||||
CHECK(core_settings_unpack(&st, hw.flash) && st.baud == PS_BAUD_HOST);
|
||||
CHECK(info().baud_mode == PS_BAUD_HOST);
|
||||
// AUTO again: learns again
|
||||
CHECK(core_vendor_out(&c, PS_REQ_SET_BAUD_MODE, PS_BAUD_AUTO));
|
||||
CHECK(c.ab_state == AB_LEARNING);
|
||||
}
|
||||
|
||||
TEST(autobaud_dte) {
|
||||
start_auto();
|
||||
hw.peer_dte = true; run_ms(500);
|
||||
CHECK(c.role == PS_ROLE_DTE && c.ab_state == AB_OFF && hw.ab_calls == 0); // AUTO: a modem follows the host
|
||||
core_isr_rx(&c, 'K', 0);
|
||||
CHECK(host_got("K"));
|
||||
CHECK(core_vendor_out(&c, PS_REQ_SET_BAUD_MODE, PS_BAUD_LEARN));
|
||||
CHECK(c.ab_state == AB_LEARNING && hw.ab_role == PS_ROLE_DTE);
|
||||
send_runs(57600, "$GPGGA,", &F8N1); run_ms(120); // a device that just talks
|
||||
CHECK(hw.format.baud == 57600 && host_got("$GPGGA,"));
|
||||
// unplugged: stops, and starts afresh with the next device
|
||||
hw.peer_dte = false; run_ms(CORE_LOST_MS + 200);
|
||||
CHECK(c.role == PS_ROLE_NONE && c.ab_state == AB_OFF && hw.ab_role == PS_ROLE_NONE);
|
||||
hw.peer_dte = true; run_ms(500);
|
||||
CHECK(c.ab_state == AB_LEARNING && hw.format.baud == 115200);
|
||||
}
|
||||
|
||||
TEST(autobaud_rough_starts) {
|
||||
start_auto();
|
||||
hw.peer_dce = true; run_ms(500);
|
||||
// a glitch, then idle, then typing
|
||||
core_isr_run(&c, false, 200); core_isr_run(&c, true, FAKE_AB_HZ / 10);
|
||||
run_ms(120);
|
||||
send_runs(4800, "ATDT5551212\r", &F8N1);
|
||||
run_ms(200);
|
||||
CHECK(c.ab_state == AB_LOCKED && hw.format.baud == 4800);
|
||||
// timings lost (the interrupt's queue overflowed): starts over, still learns
|
||||
CHECK(core_vendor_out(&c, PS_REQ_AUTOBAUD_RESTART, 0));
|
||||
for (uint32_t k = 0; k < CORE_RUNS + 5; k++) core_isr_run(&c, k & 1, 1000);
|
||||
CHECK(c.runs_lost);
|
||||
run_ms(120);
|
||||
CHECK(!c.runs_lost && c.ab_state == AB_LEARNING);
|
||||
core_isr_run(&c, true, FAKE_AB_HZ / 10); // idle
|
||||
send_runs(38400, "AT\r", &F8N1); run_ms(200);
|
||||
CHECK(c.ab_state == AB_LOCKED && hw.format.baud == 38400);
|
||||
// a pause longer than the timer can count, between characters
|
||||
host_got("");
|
||||
uint8_t junk[64]; while (core_host_read(&c, junk, sizeof junk)) {}
|
||||
CHECK(core_vendor_out(&c, PS_REQ_AUTOBAUD_RESTART, 0));
|
||||
send_runs(1200, "A", &F8N1); run_ms(120);
|
||||
CHECK(c.ab_state == AB_LEARNING);
|
||||
run_ms(CORE_AB_LONG_MS + 1000);
|
||||
core_isr_run(&c, true, 5); // the count wrapped: looks short
|
||||
send_runs(1200, "T\r", &F8N1); run_ms(120);
|
||||
CHECK(c.ab_state == AB_LOCKED && hw.format.baud == 1200);
|
||||
CHECK(host_got("AT\r"));
|
||||
// a run the HAL couldn't count (0) is "long" too
|
||||
CHECK(core_vendor_out(&c, PS_REQ_AUTOBAUD_RESTART, 0));
|
||||
send_runs(600, "A", &F8N1); run_ms(30);
|
||||
core_isr_run(&c, true, 0);
|
||||
send_runs(600, "T\r", &F8N1); run_ms(200);
|
||||
CHECK(c.ab_state == AB_LOCKED && hw.format.baud == 600);
|
||||
CHECK(host_got("AT\r"));
|
||||
// unplugged: GET_INFO is back to the host's speed
|
||||
hw.peer_dce = false; run_ms(CORE_LOST_MS + 200);
|
||||
CHECK(info().baud == 115200 && !(info().flags & (PS_INFO_BAUD_LOCKED | PS_INFO_BAUD_LEARNING)));
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
RUN(detects_computer_as_dce);
|
||||
RUN(detects_modem_as_dte);
|
||||
@@ -320,6 +476,11 @@ int main(void) {
|
||||
RUN(settings_blob);
|
||||
RUN(ring_wraps);
|
||||
RUN(leds);
|
||||
RUN(autobaud_learns_as_dce);
|
||||
RUN(autobaud_relearns_on_framing_errors);
|
||||
RUN(autobaud_vendor_restart_and_modes);
|
||||
RUN(autobaud_dte);
|
||||
RUN(autobaud_rough_starts);
|
||||
printf("%d checks, %d failed\n", checks, failures);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 Neo-Desktop
|
||||
*/
|
||||
#include "wave.h"
|
||||
#include <math.h>
|
||||
|
||||
static uint32_t rng = 12345;
|
||||
double wave_rnd(void) {
|
||||
rng = rng * 1103515245u + 12345u;
|
||||
return (double)((rng >> 8) & 0xFFFFFF) / (double)0x1000000;
|
||||
}
|
||||
|
||||
void wave_make(wave_t *w, uint32_t hz, uint32_t baud, double err, const uart_format_t *f,
|
||||
const uint8_t *msg, size_t len, double gap_bits, double jitter) {
|
||||
static bool lv[WAVE_MAX * 2];
|
||||
size_t n = 0;
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
int ones = 0;
|
||||
lv[n++] = false;
|
||||
for (int d = 0; d < f->data_bits; d++) { bool b = (msg[i] >> d) & 1; ones += b; lv[n++] = b; }
|
||||
if (f->parity) lv[n++] = f->parity == 1 ? !(ones & 1) : (ones & 1);
|
||||
for (int s = 0; s < f->stop_bits; s++) lv[n++] = true;
|
||||
for (int g = 0; g < (int)gap_bits; g++) lv[n++] = true;
|
||||
}
|
||||
double bit = (double)hz / (baud * (1.0 + err));
|
||||
double last = (wave_rnd() * 2 - 1) * jitter * bit; // the first start bit's falling edge
|
||||
w->n = 0;
|
||||
for (size_t k = 1; k < n && w->n < WAVE_MAX; k++) {
|
||||
if (lv[k] == lv[k - 1]) continue;
|
||||
double e = (double)k * bit + (wave_rnd() * 2 - 1) * jitter * bit;
|
||||
w->high[w->n] = lv[k - 1];
|
||||
w->ticks[w->n] = (uint32_t)llround(e - last);
|
||||
w->n++;
|
||||
last = e;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 Neo-Desktop
|
||||
*/
|
||||
// Test waveforms: the line timings a capture would see for some characters.
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include "../src/core/hal.h"
|
||||
|
||||
#define WAVE_MAX 8192
|
||||
typedef struct {
|
||||
uint32_t n;
|
||||
bool high[WAVE_MAX];
|
||||
uint32_t ticks[WAVE_MAX];
|
||||
} wave_t;
|
||||
|
||||
// Characters sent at baud * (1 + err), each edge moved by up to +-jitter of
|
||||
// a bit, gap_bits of idle between characters. Starts at the first start bit;
|
||||
// the run still going at the end (the final stop bit and idle) isn't included.
|
||||
void wave_make(wave_t *w, uint32_t hz, uint32_t baud, double err, const uart_format_t *f,
|
||||
const uint8_t *msg, size_t len, double gap_bits, double jitter);
|
||||
double wave_rnd(void); // 0..1, repeatable
|
||||
Reference in new issue
Block a user