main
John Lauer Publish 1.4.0 892200b
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
// SPDX-License-Identifier: MIT
// Self-mixing interferometer digitizer and board controller for the Raspberry
// Pi Pico (RP2040), board v1.2.
//
// ADC0 (GPIO26) = channel 1, laser monitor photodiode after the analog chain.
// ADC1 (GPIO27) = channel 2, external photodiode.
// ADC2 (GPIO28) = main board 5.3 V analog rail through a 1:2 divider (monitor).
// Laser current: ADS1115 on the laser head (I2C), AIN0 across the 2 ohm shunt.
// GPIO15        = SYNC from the motion stage (SN74LVC1G17 buffer, non-inverting).
// I2C0, across the cable to the laser head: the head's DAC121C085 (laser
// set-point, written then read back), MCP23008 (monitor TIA gain, monitor
// bias) and ADS1115 (laser current); on the main board the DAC7574 (both
// offsets). GPIO6 carries the laser enable as a 10 kHz carrier, started only
// after a verified nonzero set-point; while armed the firmware reads the head
// DAC back every 2 ms, which also keeps the head's I2C watchdog fed. Pico GPIOs: laser enable and the other
// gain switches. All from the control map (controls/control-map.json ->
// smi_controls_gen.h via controls/gen_controls.py).
//
// The ADC free-runs in round-robin over inputs 0 and 1 at 48 MHz / 96 = 500 ksps
// total (250 ksps per channel). DMA moves samples into a ring of buffers (two
// channels chained ping-pong). The main loop packs each finished buffer into a
// DATA frame (delta-encoded 64-sample blocks with a per-block bit width,
// CRC-16) and writes it to USB CDC. SYNC edges are captured by a GPIO interrupt
// that reads the live DMA position, so each edge carries the sample-pair index
// it landed on.
//
// The laser current is read from the head's ADS1115 over I2C isense_hz times a
// second (50 by default; the ADS1115 converts continuously at 128 SPS), so the
// sampling is not disturbed. The analog rail on ADC2 is read once a second by
// pausing the round robin at a pair boundary for about 14 us; pair indices stay
// contiguous and the pause count and rail voltage are in STATUS.
//
// Commands: binary CMD frames (smi_ctl.h), or text lines: "start", "stop",
// "info", and the board contract's "laser CODE", "laser off", "laser current",
// "head MASK", "gain MASK", "offset B CODE", "offset C CODE" (plus "hb MS").
// Safety: the laser is off at boot, after a watchdog reset, when the host closes
// the port or USB goes away, when no command arrives for hb_timeout_ms, on
// overcurrent, and on a DAC write failure.

#include <stdio.h>
#include <string.h>
#include "pico/stdlib.h"
#include "hardware/adc.h"
#include "hardware/dma.h"
#include "hardware/gpio.h"
#include "hardware/i2c.h"
#include "hardware/pwm.h"
#include "hardware/clocks.h"
#include "hardware/irq.h"
#include "hardware/sync.h"
#include "hardware/watchdog.h"
#include "tusb.h"
#include "smi_frame.h"
#include "smi_ctl.h"
#include "smi_controls_gen.h"
#include "smi_text.h"
#include "smi_stage.h"

#define FW_VERSION "1.4.0"
#define DATA_VBUS_GPIO 24u
#define SYNC_GPIO 15
#define RAIL_GPIO 28
#define PAIRS_PER_BUF 1024
#define SAMPLES_PER_BUF (PAIRS_PER_BUF * 2)
#define NBUF 16
#define TOTAL_SPS 500000u
#define SYNC_QUEUE 64
#define WATCHDOG_MS 300
#define I2C_TIMEOUT_US 750u   // per transfer, as in the board's 1.2 controller patch

static uint16_t bufs[NBUF][SAMPLES_PER_BUF] __attribute__((aligned(4)));
static int dma_a, dma_b;

// Written by the DMA IRQ, read by the main loop.
static volatile uint32_t bufs_done;        // buffers completed since start
static volatile uint32_t buf_done_us[NBUF];
static volatile uint32_t dropped_bufs;
static volatile uint32_t bufs_sent;                // buffers handed to USB (main loop only)
static volatile bool running;
static uint32_t isense_pauses;
static uint16_t rail_mv;
static bool ads_ok;

typedef struct { uint64_t pair; uint32_t t_us; uint8_t level; } sync_evt_t;
static sync_evt_t sync_q[SYNC_QUEUE];
static volatile uint32_t sync_head, sync_tail, sync_count, sync_lost;

static uint8_t frame[SMI_HDR_LEN + 13 + (PAIRS_PER_BUF / SMI_BLOCK) * 2 * SMI_MAX_BLOCK_BYTES + 2];
static uint16_t seq;
static smi_ctl_t ctl;
static smi_stage_t stage;

#define I2C_INST (SMI_I2C_BUS ? i2c1 : i2c0)

// ---------------------------------------------------------------- hardware --

static bool ads_prepare(void);

// Read the DAC121C085's register: two bytes, high first; bits 13:12 the
// power-down mode (0 = normal), bits 11:0 the code.
static bool head_dac_read(uint8_t addr, uint16_t *reg) {
    uint8_t r[2];
    if (i2c_read_timeout_us(I2C_INST, addr, r, 2, false, I2C_TIMEOUT_US) != 2) return false;
    *reg = (uint16_t)((r[0] << 8) | r[1]);
    return true;
}

// part 1, DAC7574 (TI, quad 12-bit, I2C, outputs reset to zero at power-up).
// Control byte: L1 L0 = 01 (update the selected channel), Sel1 Sel0 =
// channel, PD0 = 0; then D11..D4 and D3..D0 left-aligned in the second byte.
// part 2, DAC121C085 (TI, 12-bit, on the laser head, powers up at code 0):
// two bytes, high first, power-down bits 13:12 = 00, then the code; the write
// only counts if the register read straight back matches exactly.
static bool dac_write(void *ctx, uint8_t dev, uint8_t ch, uint16_t code) {
    (void)ctx;
    if (dev >= SMI_NUM_DACS) return false;
    const smi_dac_def_t *d = &smi_dacs[dev];
    if (d->part == 1) {
        uint8_t b[3] = { (uint8_t)(0x10 | ((ch & 3) << 1)), (uint8_t)(code >> 4), (uint8_t)((code & 0x0F) << 4) };
        return i2c_write_timeout_us(I2C_INST, d->addr, b, 3, false, I2C_TIMEOUT_US) == 3;
    }
    if (d->part == 2) {
        // The core has already dropped GP6 and waited disarm_us. Before arming at
        // a nonzero code, (re)configure the head ADC: its config and pointer may
        // only be written while disarmed; armed access to it is read-only.
        if (code && !(ads_ok = ads_prepare())) return false;
        uint8_t b[2] = { (uint8_t)((code >> 8) & 0x0F), (uint8_t)code };
        if (i2c_write_timeout_us(I2C_INST, d->addr, b, 2, false, I2C_TIMEOUT_US) != 2) return false;
        uint16_t reg;
        return head_dac_read(d->addr, &reg) && reg == (code & 0x0FFF);
    }
    return false;
}

// MCP23008 on the laser head: the switch bits. Its pins reset to inputs and the
// head's pull-downs hold every selector at its power-on default (code 0); the
// firmware writes OLAT first, then makes only the mapped bits outputs.
#define MCP_IODIR 0x00
#define MCP_OLAT 0x0A
static uint8_t exp_olat, exp_mask;
static bool exp_ok;

static bool exp_write(uint8_t reg, uint8_t v) {
    uint8_t b[2] = { reg, v };
    return i2c_write_timeout_us(I2C_INST, SMI_EXP_ADDR, b, 2, false, I2C_TIMEOUT_US) == 2;
}

static bool exp_read(uint8_t reg, uint8_t *v) {
    return i2c_write_timeout_us(I2C_INST, SMI_EXP_ADDR, &reg, 1, true, I2C_TIMEOUT_US) == 1 &&
           i2c_read_timeout_us(I2C_INST, SMI_EXP_ADDR, v, 1, false, I2C_TIMEOUT_US) == 1;
}

static void exp_init(void) {
    exp_mask = 0;
    for (int i = 0; i < SMI_NUM_CONTROLS; i++)
        for (int b = 0; b < smi_controls[i].ngpio; b++)
            if (smi_controls[i].gpio[b] >= SMI_EXP_BASE) exp_mask |= (uint8_t)(1u << (smi_controls[i].gpio[b] - SMI_EXP_BASE));
    exp_olat = 0;
    uint8_t dir = 0;
    // Verify the head interface: the IODIR read-back must match what was written.
    exp_ok = !SMI_EXP_PRESENT || (exp_write(MCP_OLAT, 0) && exp_write(MCP_IODIR, (uint8_t)~exp_mask) &&
                                  exp_read(MCP_IODIR, &dir) && dir == (uint8_t)~exp_mask);
}

// Laser enable: with a carrier the "on" state is a 10 kHz square wave from the
// pin's PWM slice; "off" returns the pin to a plain output driven inactive.
static void laser_enable_out(bool on) {
#if SMI_LASER_EN_CARRIER_HZ
    uint slice = pwm_gpio_to_slice_num(SMI_LASER_EN_GPIO);
    if (on) {
        uint32_t wrap = clock_get_hz(clk_sys) / SMI_LASER_EN_CARRIER_HZ - 1u;
        pwm_set_wrap(slice, (uint16_t)wrap);
        pwm_set_gpio_level(SMI_LASER_EN_GPIO, (uint16_t)((wrap + 1u) / 2u));
        pwm_set_enabled(slice, true);
        gpio_set_function(SMI_LASER_EN_GPIO, GPIO_FUNC_PWM);
    } else {
        gpio_set_function(SMI_LASER_EN_GPIO, GPIO_FUNC_SIO);
        gpio_put(SMI_LASER_EN_GPIO, SMI_LASER_EN_ACTIVE_HIGH ? 0 : 1);
        gpio_set_dir(SMI_LASER_EN_GPIO, GPIO_OUT);
        pwm_set_enabled(slice, false);
    }
#else
    gpio_put(SMI_LASER_EN_GPIO, on == (bool)SMI_LASER_EN_ACTIVE_HIGH);
#endif
}

static void hal_wait_us(void *ctx, uint32_t us) {
    (void)ctx;
    busy_wait_us_32(us);
}

static bool hal_dac_read(void *ctx, uint8_t dev, uint16_t *reg) {
    (void)ctx;
    return dev < SMI_NUM_DACS && smi_dacs[dev].part == 2 && head_dac_read(smi_dacs[dev].addr, reg);
}

static bool gpio_out(void *ctx, uint8_t pin, bool level) {
    (void)ctx;
    if (pin == SMI_LASER_EN_GPIO) {
        laser_enable_out(level == (bool)SMI_LASER_EN_ACTIVE_HIGH);
        return true;
    }
    if (pin < SMI_EXP_BASE) {
        gpio_put(pin, level);
        return true;
    }
    if (!SMI_EXP_PRESENT || !exp_ok) return false;
    uint8_t bit = (uint8_t)(1u << (pin - SMI_EXP_BASE));
    uint8_t v = level ? (exp_olat | bit) : (exp_olat & (uint8_t)~bit);
    if (!exp_write(MCP_OLAT, v)) return false;
    exp_olat = v;
    return true;
}

// ADS1115 on the laser head: continuous conversion of the shunt voltage.
#define ADS_REG_CONV 0x00
#define ADS_REG_CONFIG 0x01

// Write the config, check it, then leave the pointer on the conversion
// register so that every later read is a plain two-byte read. Only while the
// laser is disarmed (board contract: armed access is read-only).
static bool ads_prepare(void) {
    uint8_t w[3] = { ADS_REG_CONFIG, (uint8_t)(SMI_ADS_CONFIG >> 8), (uint8_t)SMI_ADS_CONFIG };
    if (i2c_write_timeout_us(I2C_INST, SMI_ADS_ADDR, w, 3, false, I2C_TIMEOUT_US) != 3) return false;
    uint8_t reg = ADS_REG_CONFIG, r[2];
    if (i2c_write_timeout_us(I2C_INST, SMI_ADS_ADDR, &reg, 1, true, I2C_TIMEOUT_US) != 1) return false;
    if (i2c_read_timeout_us(I2C_INST, SMI_ADS_ADDR, r, 2, false, I2C_TIMEOUT_US) != 2) return false;
    // Read-back check, ignoring the OS (conversion status) bit.
    if ((((r[0] << 8) | r[1]) & 0x7FFF) != (SMI_ADS_CONFIG & 0x7FFF)) return false;
    reg = ADS_REG_CONV;
    return i2c_write_timeout_us(I2C_INST, SMI_ADS_ADDR, &reg, 1, false, I2C_TIMEOUT_US) == 1;
}

// A plain read of the conversion register (the pointer was left there).
static bool ads_read(int32_t *v) {
    uint8_t r[2];
    if (i2c_read_timeout_us(I2C_INST, SMI_ADS_ADDR, r, 2, false, I2C_TIMEOUT_US) != 2) return false;
    *v = (int16_t)((r[0] << 8) | r[1]);
    return true;
}


// ------------------------------------------------------------------- stage --
// TMC2209 stage on J4 (smi_stage.c). STEP, DIR and EN_N are plain outputs; HOME
// has the board's 10 k pull-up. PDN_UART is one wire, bit-banged at 115200 8N1:
// the Pico drives it only while it sends and releases it right after the stop
// bit, then listens for the reply. Each byte runs with interrupts off (87 us);
// the ADC DMA keeps running and its completion IRQ is only delayed.
#define STAGE_BIT_US (1000000.0f / 115200.0f)

static void stage_put(void *ctx, uint8_t g, bool v) { (void)ctx; gpio_put(g, v); }
static bool stage_home(void *ctx) { (void)ctx; return gpio_get(SMI_STAGE_HOME_GPIO); }
static void stage_wait(void *ctx, uint32_t us) { (void)ctx; busy_wait_us_32(us); }

static void wait_until(uint32_t t0, float off_us) {
    while ((float)(time_us_32() - t0) < off_us) tight_loop_contents();
}

static void uart_tx_byte(uint8_t b) {
    uint32_t irq = save_and_disable_interrupts();
    uint32_t t0 = time_us_32();
    uint16_t frame = (uint16_t)(0x200u | ((uint16_t)b << 1));   // start 0, 8 data LSB first, stop 1
    for (int i = 0; i < 10; i++) {
        gpio_put(SMI_STAGE_UART_GPIO, (frame >> i) & 1u);
        wait_until(t0, STAGE_BIT_US * (float)(i + 1));
    }
    restore_interrupts(irq);
}

static bool uart_rx_byte(uint8_t *b, uint32_t timeout_us) {
    uint32_t t = time_us_32();
    while (gpio_get(SMI_STAGE_UART_GPIO)) {                      // wait for the start bit
        if (time_us_32() - t > timeout_us) return false;
    }
    uint32_t irq = save_and_disable_interrupts();
    uint32_t t0 = time_us_32();
    uint8_t v = 0;
    for (int i = 0; i < 8; i++) {
        wait_until(t0, STAGE_BIT_US * (1.5f + (float)i));         // middle of data bit i
        v |= (uint8_t)(gpio_get(SMI_STAGE_UART_GPIO) << i);
    }
    wait_until(t0, STAGE_BIT_US * 9.5f);
    bool stop_ok = gpio_get(SMI_STAGE_UART_GPIO);
    restore_interrupts(irq);
    *b = v;
    return stop_ok;
}

static bool stage_uart(void *ctx, const uint8_t *tx, size_t ntx, uint8_t *rxb, size_t nrx) {
    (void)ctx;
    gpio_put(SMI_STAGE_UART_GPIO, 1);
    gpio_set_dir(SMI_STAGE_UART_GPIO, GPIO_OUT);
    for (size_t i = 0; i < ntx; i++) uart_tx_byte(tx[i]);
    gpio_set_dir(SMI_STAGE_UART_GPIO, GPIO_IN);                 // release the line after the stop bit
    busy_wait_us_32(200);                                       // writes need a gap before the next datagram
    for (size_t i = 0; i < nrx; i++) {
        if (!uart_rx_byte(&rxb[i], i == 0 ? 2000u : 300u)) return false;
        watchdog_update();
    }
    return true;
}

static void stage_init(void) {
    // EN_N high (driver off) before anything else touches the stage port.
    gpio_init(SMI_STAGE_EN_N_GPIO);
    gpio_put(SMI_STAGE_EN_N_GPIO, 1);
    gpio_set_dir(SMI_STAGE_EN_N_GPIO, GPIO_OUT);
    gpio_init(SMI_STAGE_STEP_GPIO);
    gpio_put(SMI_STAGE_STEP_GPIO, 0);
    gpio_set_dir(SMI_STAGE_STEP_GPIO, GPIO_OUT);
    gpio_init(SMI_STAGE_DIR_GPIO);
    gpio_set_dir(SMI_STAGE_DIR_GPIO, GPIO_OUT);
    gpio_init(SMI_STAGE_HOME_GPIO);
    gpio_set_dir(SMI_STAGE_HOME_GPIO, GPIO_IN);
    gpio_disable_pulls(SMI_STAGE_HOME_GPIO);                    // 10 k to 3V3 on the board
    gpio_init(SMI_STAGE_UART_GPIO);
    gpio_set_dir(SMI_STAGE_UART_GPIO, GPIO_IN);
    gpio_pull_up(SMI_STAGE_UART_GPIO);                          // idle high while released
    smi_stage_hal_t h = { .ctx = NULL, .put = stage_put, .home_in = stage_home, .wait_us = stage_wait, .uart = stage_uart };
    smi_stage_init(&stage, &h);
}

static void stage_service(void) { smi_stage_tick(&stage, time_us_32()); }

static void outputs_init(void) {
    // Laser enable first, driven off, before anything else can happen.
    gpio_init(SMI_LASER_EN_GPIO);
    gpio_put(SMI_LASER_EN_GPIO, SMI_LASER_EN_ACTIVE_HIGH ? 0 : 1);
    gpio_set_dir(SMI_LASER_EN_GPIO, GPIO_OUT);
    stage_init();                      // stage driver disabled on boot
    for (int i = 0; i < SMI_NUM_CONTROLS; i++) {
        const smi_control_def_t *d = &smi_controls[i];
        for (int b = 0; b < d->ngpio; b++) {
            if (d->gpio[b] >= SMI_EXP_BASE) continue;
            gpio_init(d->gpio[b]);
            gpio_put(d->gpio[b], 0);
            gpio_set_dir(d->gpio[b], GPIO_OUT);
        }
    }
    i2c_init(I2C_INST, SMI_I2C_HZ);
    gpio_set_function(SMI_I2C_SDA, GPIO_FUNC_I2C);
    gpio_set_function(SMI_I2C_SCL, GPIO_FUNC_I2C);
    gpio_pull_up(SMI_I2C_SDA);
    gpio_pull_up(SMI_I2C_SCL);
    // DAC channel A (laser set-point) to zero before configuring anything else.
    for (int i = 0; i < SMI_NUM_CONTROLS; i++)
        if (smi_controls[i].is_laser) dac_write(NULL, smi_controls[i].dac, smi_controls[i].ch, 0);
    exp_init();
    ads_ok = ads_prepare();
}

// ------------------------------------------------------------- acquisition --

static void dma_irq(void) {
    uint32_t mask = dma_hw->ints0;
    // Handle in completion order: the even buffer channel (A) finishes before B.
    for (int k = 0; k < 2; k++) {
        int ch = ((bufs_done & 1) == 0) ? dma_a : dma_b;
        if (!(mask & (1u << ch))) break;
        dma_hw->ints0 = 1u << ch;
        mask &= ~(1u << ch);
        uint32_t idx = bufs_done % NBUF;
        buf_done_us[idx] = time_us_32();
        bufs_done++;
        // This channel's next target is two buffers ahead. If the main loop has
        // not packed that buffer yet it is overwritten and counted as dropped.
        uint32_t next = bufs_done + 1;
        if (next - bufs_sent >= NBUF) dropped_bufs++;
        dma_channel_set_write_addr(ch, bufs[next % NBUF], false);
        dma_channel_set_trans_count(ch, SAMPLES_PER_BUF, false);
    }
    if (mask) dma_hw->ints0 = mask;
}

static void sync_irq(uint gpio, uint32_t events) {
    (void)gpio;
    uint32_t now = time_us_32();
    // Locate the DMA write position: the busy channel holds buffer bufs_done,
    // unless a completion is pending, in which case it holds bufs_done + 1.
    uint32_t done = bufs_done;
    int expect = (done & 1) == 0 ? dma_a : dma_b;
    int other = expect == dma_a ? dma_b : dma_a;
    uint32_t base, remaining;
    if (dma_channel_is_busy(expect)) {
        base = done; remaining = dma_hw->ch[expect].transfer_count;
    } else {
        base = done + 1; remaining = dma_hw->ch[other].transfer_count;
    }
    uint64_t sample = (uint64_t)base * SAMPLES_PER_BUF + (SAMPLES_PER_BUF - remaining);
    if (sync_count >= SYNC_QUEUE) { sync_lost++; return; }
    sync_evt_t *e = &sync_q[sync_head];
    e->pair = sample / 2;
    e->t_us = now;
    e->level = (events & GPIO_IRQ_EDGE_RISE) ? 1 : 0;
    sync_head = (sync_head + 1) % SYNC_QUEUE;
    sync_count++;
}

static void dma_setup(void) {
    dma_a = dma_claim_unused_channel(true);
    dma_b = dma_claim_unused_channel(true);
    int chans[2] = {dma_a, dma_b};
    for (int i = 0; i < 2; i++) {
        dma_channel_config c = dma_channel_get_default_config(chans[i]);
        channel_config_set_transfer_data_size(&c, DMA_SIZE_16);
        channel_config_set_read_increment(&c, false);
        channel_config_set_write_increment(&c, true);
        channel_config_set_dreq(&c, DREQ_ADC);
        channel_config_set_chain_to(&c, chans[1 - i]);
        dma_channel_configure(chans[i], &c, bufs[i], &adc_hw->fifo, SAMPLES_PER_BUF, false);
    }
    dma_channel_set_irq0_enabled(dma_a, true);
    dma_channel_set_irq0_enabled(dma_b, true);
    irq_set_exclusive_handler(DMA_IRQ_0, dma_irq);
    irq_set_priority(DMA_IRQ_0, 0x40);
    irq_set_enabled(DMA_IRQ_0, true);
}

static void acq_start(void) {
    if (running) return;
    adc_run(false);
    dma_channel_abort(dma_a);
    dma_channel_abort(dma_b);
    adc_fifo_drain();
    bufs_done = 0; bufs_sent = 0; dropped_bufs = 0; isense_pauses = 0;
    sync_head = sync_tail = sync_count = 0;
    dma_channel_set_write_addr(dma_a, bufs[0], false);
    dma_channel_set_trans_count(dma_a, SAMPLES_PER_BUF, false);
    dma_channel_set_write_addr(dma_b, bufs[1], false);
    dma_channel_set_trans_count(dma_b, SAMPLES_PER_BUF, false);
    adc_select_input(0);               // round robin begins at ADC0, so even samples are ch0
    adc_set_round_robin(0x3);
    dma_channel_start(dma_a);
    running = true;
    adc_run(true);
}

static void acq_stop(void) {
    adc_run(false);
    running = false;
    dma_channel_abort(dma_a);
    dma_channel_abort(dma_b);
    adc_fifo_drain();
}

static void adc_wait_ready(void) {
    while (!(adc_hw->cs & ADC_CS_READY_BITS)) tight_loop_contents();
}

// Four ADC2 conversions with the FIFO off, so nothing lands in the sample ring.
static uint16_t adc2_convert(void) {
    adc_fifo_setup(false, false, 1, false, false);
    adc_set_round_robin(0);
    adc_select_input(2);
    uint32_t sum = 0;
    for (int i = 0; i < 4; i++) sum += adc_read();
    adc_select_input(0);
    adc_fifo_setup(true, true, 1, false, false);
    return (uint16_t)((sum + 2) / 4);
}

// Read ADC2 (the analog rail). While streaming, stop the round robin after a
// complete ch0/ch1 pair so the even/odd interleave in the ring is preserved.
static uint16_t adc2_read(void) {
    if (!running) {
        uint16_t v = adc2_convert();
        adc_set_round_robin(0x3);
        return v;
    }
    adc_run(false);
    busy_wait_us_32(3);                 // let a conversion already started finish
    adc_wait_ready();
    while (adc_fifo_get_level()) tight_loop_contents();   // DMA takes the last sample
    if (adc_get_selected_input() == 1) {
        // The last stored sample was ch0: convert ch1 once to complete the pair.
        hw_set_bits(&adc_hw->cs, ADC_CS_START_ONCE_BITS);
        busy_wait_us_32(1);
        adc_wait_ready();
        while (adc_fifo_get_level()) tight_loop_contents();
    }
    uint16_t v = adc2_convert();
    adc_set_round_robin(0x3);
    isense_pauses++;
    adc_run(true);
    return v;
}

// ----------------------------------------------------------------- USB out --

// Laser upkeep, called from every loop that can take time (the main loop,
// between DATA frames, and while waiting on USB): the ramp tick and, while
// armed, the head DAC readback every 2 ms. The readback is also the I2C
// traffic that keeps the head's watchdog from dropping the laser gate.
static void laser_service(void) {
    static uint32_t next_poll;
    uint32_t now = time_us_32();
    smi_ctl_tick(&ctl, now);
#if SMI_LASER_READBACK_POLL_MS
    if (ctl.laser_on && (int32_t)(now - next_poll) >= 0) {
        next_poll = now + SMI_LASER_READBACK_POLL_MS * 1000u;
        int li = 0;
        for (int i = 0; i < SMI_NUM_CONTROLS; i++)
            if (smi_controls[i].is_laser) li = i;
        uint16_t reg = 0;
        bool ok = head_dac_read(smi_dacs[smi_controls[li].dac].addr, &reg);
        smi_ctl_laser_readback(&ctl, ok, reg, time_us_32());
    }
#endif
}

// Write a whole frame to CDC; gives up if the host stops reading for 50 ms.
static bool cdc_write_all(const uint8_t *p, size_t n) {
    uint32_t t0 = time_us_32();
    while (n) {
        watchdog_update();
        if (!gpio_get(DATA_VBUS_GPIO) || !tud_cdc_connected()) return false;
        uint32_t avail = tud_cdc_write_available();
        if (avail == 0) {
            tud_task();
            laser_service();
            stage_service();
            if (time_us_32() - t0 > 50000u) return false;
            continue;
        }
        uint32_t k = n < avail ? (uint32_t)n : avail;
        k = tud_cdc_write(p, k);
        p += k; n -= k;
        t0 = time_us_32();
        tud_cdc_write_flush();
        tud_task();
    }
    return true;
}

static void send_data(uint32_t b) {
    const uint16_t *s = bufs[b % NBUF];
    uint8_t *pl = frame + SMI_HDR_LEN;
    smi_put_u64(pl, (uint64_t)b * PAIRS_PER_BUF);
    smi_put_u32(pl + 8, buf_done_us[b % NBUF]);
    pl[12] = PAIRS_PER_BUF / SMI_BLOCK;
    size_t o = 13;
    for (int g = 0; g < PAIRS_PER_BUF / SMI_BLOCK; g++) {
        const uint16_t *base = s + g * SMI_BLOCK * 2;
        o += smi_pack_block(base, 2, pl + o);       // ch0: even samples
        o += smi_pack_block(base + 1, 2, pl + o);   // ch1: odd samples
    }
    smi_begin_frame(frame, SMI_T_DATA, (uint16_t)o, seq++);
    size_t n = smi_finish_frame(frame, (uint16_t)o);
    cdc_write_all(frame, n);
}

static void send_small(uint8_t type, const uint8_t *payload, uint16_t len) {
    uint8_t f[SMI_HDR_LEN + 240 + 2];
    if (len > 240) return;
    memcpy(f + SMI_HDR_LEN, payload, len);
    smi_begin_frame(f, type, len, seq++);
    cdc_write_all(f, smi_finish_frame(f, len));
}

static void send_sync(const sync_evt_t *e) {
    uint8_t pl[13];
    smi_put_u64(pl, e->pair);
    smi_put_u32(pl + 8, e->t_us);
    pl[12] = e->level;
    send_small(SMI_T_SYNC, pl, 13);
}

static void send_status(void) {
    uint8_t pl[30];
    smi_put_u64(pl, (uint64_t)bufs_done * PAIRS_PER_BUF);
    smi_put_u32(pl + 8, dropped_bufs);
    smi_put_u32(pl + 12, sync_lost);
    smi_put_u32(pl + 16, TOTAL_SPS);
    smi_put_u32(pl + 20, time_us_32());
    smi_put_u32(pl + 24, isense_pauses);
    smi_put_u16(pl + 28, rail_mv);
    send_small(SMI_T_STATUS, pl, 30);
}

static void send_state(void) {
    uint8_t pl[30 + 6 * SMI_MAX_CONTROLS];
    size_t n = smi_ctl_state(&ctl, time_us_32(), pl);
    send_small(SMI_T_STATE, pl, (uint16_t)n);
}

static void send_stage(void) {
    uint8_t pl[32];
    size_t n = smi_stage_state(&stage, pl);
    smi_put_u64(pl + n, (uint64_t)bufs_done * PAIRS_PER_BUF);
    send_small(SMI_T_STAGE, pl, (uint16_t)(n + 8));
}

static void send_info(void) {
    char txt[240];
    int n = snprintf(txt, sizeof txt,
        "smi-pico fw " FW_VERSION "; total_sps=%u; per_channel_sps=%u; pairs_per_frame=%u; block=%u; sync_gpio=%u; "
        "map=" SMI_MAP_VERSION "; map_hash=%08lx; controls=%u; head_io=%s; head_adc=%s; boot=%s; stage=J4 GP10-14",
        TOTAL_SPS, TOTAL_SPS / 2, PAIRS_PER_BUF, SMI_BLOCK, SYNC_GPIO, (unsigned long)SMI_MAP_HASH,
        (unsigned)SMI_NUM_CONTROLS, exp_ok ? "ok" : "not answering", ads_ok ? "ok" : "not answering", ctl.boot_reason == SMI_OFF_WATCHDOG ? "watchdog" : "power-on");
    send_small(SMI_T_INFO, (const uint8_t *)txt, (uint16_t)n);
}

// -------------------------------------------------------------- commands in --

static uint8_t rx[8 + 160 + 2];
// Set by the first binary command after a connect (a dashboard host, which sends
// heartbeats). Text-only sessions rely on the USB disconnect rule alone.
static bool stage_host_watch;
static int rx_len;

static void handle_cmd_frame(void) {
    uint16_t len = (uint16_t)(rx[4] | (rx[5] << 8));
    uint16_t crc = (uint16_t)(rx[8 + len] | (rx[9 + len] << 8));
    if (smi_crc16(rx + 2, 6u + len, 0xFFFF) != crc || rx[2] != SMI_T_CMD) return;   // host retries on timeout
    uint16_t cseq = (uint16_t)(rx[6] | (rx[7] << 8));
    uint8_t resp[160];
    // Any binary command is host activity; from the first one on, the stage
    // also stops if the host goes quiet (see the main loop).
    ctl.last_host_us = time_us_32();
    stage_host_watch = true;
    size_t n = (len >= 1 && rx[8] == SMI_OP_STAGE) ? smi_stage_command(&stage, rx + 8, len, cseq, time_us_32(), resp)
                                                   : smi_ctl_command(&ctl, rx + 8, len, cseq, time_us_32(), resp);
    send_small(SMI_T_ACK, resp, (uint16_t)n);
}

// Text commands (board contract): smi_text.c, wired to this firmware.
static uint32_t text_now(void *ctx) { (void)ctx; return time_us_32(); }
static void text_send(void *ctx, const char *t) { (void)ctx; send_small(SMI_T_INFO, (const uint8_t *)t, (uint16_t)strlen(t)); }
static void text_start(void *ctx) { (void)ctx; acq_start(); }
static void text_stop(void *ctx) { (void)ctx; acq_stop(); }
static void text_info(void *ctx) { (void)ctx; send_info(); }
static void text_stage(void *ctx, const char *c) {
    (void)ctx;
    char r[200];
    smi_stage_text(&stage, c, time_us_32(), r, sizeof r);
    send_small(SMI_T_INFO, (const uint8_t *)r, (uint16_t)strlen(r));
}
static smi_text_t textcmd = { .ctl = &ctl, .now_us = text_now, .reply = text_send, .start = text_start,
                              .stop = text_stop, .info = text_info, .stage = text_stage, .exp_base = SMI_EXP_BASE, .gain_base = 7 };

static void poll_commands(void) {
    while (tud_cdc_available()) {
        int c = tud_cdc_read_char();
        if (c < 0) break;
        if (rx_len > 0 || (c == SMI_SYNC0 && textcmd.len == 0)) {
            rx[rx_len++] = (uint8_t)c;
            if (rx_len == 2 && c != SMI_SYNC1) { rx_len = 0; continue; }
            if (rx_len >= 6) {
                uint16_t len = (uint16_t)(rx[4] | (rx[5] << 8));
                if (len > 160) { rx_len = 0; continue; }
                if (rx_len == 8 + len + 2) { handle_cmd_frame(); rx_len = 0; }
            }
            continue;
        }
        smi_text_feed(&textcmd, (char)c);
    }
}

static volatile bool usb_gone;
void tud_umount_cb(void) { usb_gone = true; }
void tud_suspend_cb(bool remote_wakeup_en) { (void)remote_wakeup_en; usb_gone = true; }

// -------------------------------------------------------------------- main --

int main(void) {
    bool wdt = watchdog_caused_reboot();
    outputs_init();
    smi_hal_t hal = { .ctx = NULL, .dac_write = dac_write, .wait_us = hal_wait_us, .dac_read = hal_dac_read, .gpio_put = gpio_out };
    smi_ctl_init(&ctl, smi_controls, SMI_NUM_CONTROLS, &smi_isense, SMI_MAP_HASH, SMI_MAP_VERSION,
                 SMI_LASER_EN_GPIO, SMI_LASER_EN_ACTIVE_HIGH, &hal, wdt ? SMI_OFF_WATCHDOG : SMI_OFF_BOOT, time_us_32());

    gpio_init(DATA_VBUS_GPIO);
    gpio_disable_pulls(DATA_VBUS_GPIO);
    bool data_attached = gpio_get(DATA_VBUS_GPIO);
    bool usb_initialized = false;
    if (data_attached) {
        tusb_init();
        usb_initialized = true;
    }

    adc_init();
    adc_gpio_init(26);
    adc_gpio_init(27);
    adc_gpio_init(RAIL_GPIO);
    // FIFO on, DREQ on, DREQ threshold 1, no error bit, no byte shift (12-bit samples).
    adc_fifo_setup(true, true, 1, false, false);
    adc_set_clkdiv(0);                 // back-to-back: 96 ADC clocks = 2 us per conversion
    dma_setup();

    gpio_init(SYNC_GPIO);
    gpio_set_dir(SYNC_GPIO, GPIO_IN);
    gpio_disable_pulls(SYNC_GPIO);     // R151 on the board holds the buffer input low
    gpio_set_irq_enabled_with_callback(SYNC_GPIO, GPIO_IRQ_EDGE_RISE | GPIO_IRQ_EDGE_FALL, true, sync_irq);

    watchdog_enable(WATCHDOG_MS, true);

    bool was_connected = false;
    uint32_t last_stage = 0, last_status = 0, last_state = 0, next_isense = time_us_32(), next_rail = time_us_32();
    while (true) {
        watchdog_update();
        bool vbus = gpio_get(DATA_VBUS_GPIO);
        if (vbus != data_attached) {
            data_attached = vbus;
            if (vbus) {
                if (usb_initialized) tud_connect();
                else {
                    tusb_init();
                    usb_initialized = true;
                }
            } else {
                tud_disconnect();
                acq_stop();
                smi_ctl_link_lost(&ctl, SMI_OFF_USB);
                smi_stage_link_lost(&stage);
                stage_host_watch = false;
                was_connected = false;
            }
        }
        if (!data_attached) {
            tight_loop_contents();
            continue;
        }
        tud_task();
        uint32_t now = time_us_32();
        bool conn = tud_cdc_connected();
        if (usb_gone) {
            usb_gone = false;
            smi_ctl_link_lost(&ctl, SMI_OFF_USB);
            smi_stage_link_lost(&stage);
        }
        if (conn && !was_connected) { send_info(); acq_start(); }
        if (!conn && was_connected) { acq_stop(); smi_ctl_link_lost(&ctl, SMI_OFF_USB); smi_stage_link_lost(&stage); stage_host_watch = false; }
        // A dashboard host that stops sending (crash, hang) for the heartbeat
        // timeout also disables the stage driver; the position becomes invalid.
        if (stage_host_watch && stage.enabled && ctl.hb_timeout_ms &&
            (uint32_t)(now - ctl.last_host_us) > (uint32_t)ctl.hb_timeout_ms * 1000u)
            smi_stage_link_lost(&stage);
        was_connected = conn;

        if ((int32_t)(now - next_isense) >= 0) {
            next_isense += 1000000u / (ctl.isense_hz ? ctl.isense_hz : 10);
            if ((int32_t)(now - next_isense) > 0) next_isense = now;   // fell behind: no burst
            int32_t raw;
            if (!ads_ok && !ctl.laser_on) ads_ok = ads_prepare();     // the head may be plugged in late; only while disarmed
            if (ads_ok && ads_read(&raw)) smi_ctl_isense(&ctl, raw, time_us_32());
            else { ads_ok = false; smi_ctl_isense_failed(&ctl, time_us_32()); }
        }
        if ((int32_t)(now - next_rail) >= 0) {
            next_rail = now + 1000000u;
            rail_mv = (uint16_t)(adc2_read() * SMI_RAIL_SCALE * 1000.0f + 0.5f);
        }
        laser_service();
        stage_service();
        if (!conn) continue;
        poll_commands();

        while (sync_count) {
            sync_evt_t e = sync_q[sync_tail];
            sync_tail = (sync_tail + 1) % SYNC_QUEUE;
            uint32_t irq = save_and_disable_interrupts();
            sync_count--;
            restore_interrupts(irq);
            send_sync(&e);
        }

        while (running && bufs_sent < bufs_done) {
            uint32_t done = bufs_done;
            if (done - bufs_sent >= NBUF - 1) {
                // Fell behind: skip to the newest complete buffers. The host sees the
                // gap in first_pair and the STATUS frame counts it.
                bufs_sent = done - 2;
            }
            send_data(bufs_sent);
            bufs_sent++;
            poll_commands();               // commands are answered between frames
            laser_service();
            stage_service();
        }

        now = time_us_32();
        if (now - last_status > 500000) { last_status = now; send_status(); }
        if (now - last_state > 250000) { last_state = now; send_state(); }
        if (now - last_stage > (stage.enabled ? 50000u : 500000u)) { last_stage = now; send_stage(); }
    }
}