main
John Lauer Software 1.3.1: test-stage firmware (J4 TMC2209, HOME, limits, self-test), Stage tab and Calibrate in smi-dash (simulat… c0c5c9b
// SPDX-License-Identifier: MIT
// Test-stage control core (board 1.3.1, STAGE connector J4): a TMC2209 stepper
// driver on STEP/DIR/EN_N with its single-wire PDN_UART, and a normally closed
// HOME switch. Portable C99 behind a small hardware interface, so the same file
// runs in the Pico firmware, in the host-side test and in the dashboard's
// simulator.
//
// Contract: the main board's design/control-map.json "stage" entry (pins) and
// test-stage/design/stage-map.json (motion, UART registers, homing, limits,
// self-test). Rules this core enforces:
//   - Disabled at boot (EN_N high) and on fault, link loss or "stage off".
//     Position becomes invalid whenever the driver is disabled.
//   - The driver is configured over UART with EN_N high; every write is checked
//     against IFCNT; motion is enabled only if all of it verified.
//   - Before homing only the homing search may move the stage. After homing
//     every move must stay inside 0..1600 pulses from HOME.
//   - Steps are rate limited (default 160, at most 640 pulses/s), with the
//     contract's STEP/DIR timing; an unexpected HOME during a normal move
//     disables the driver and invalidates the position.
//   - Moves carry a sequence number: a retried command returns its cached
//     result without issuing new pulses.
#ifndef SMI_STAGE_H
#define SMI_STAGE_H
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>

// Pico GPIOs (control-map.json stage entry: J4 pins 2 to 6).
#define SMI_STAGE_STEP_GPIO 10
#define SMI_STAGE_DIR_GPIO 11
#define SMI_STAGE_EN_N_GPIO 12
#define SMI_STAGE_UART_GPIO 13
#define SMI_STAGE_HOME_GPIO 14

// stage-map.json motion, homing and self-test.
#define SMI_STAGE_TRAVEL_MAX 1600          // pulses from HOME
#define SMI_STAGE_NM_PER_PULSE 15.625f     // nominal; calibrate on the bench
#define SMI_STAGE_RATE_DEFAULT 160         // pulses/s
#define SMI_STAGE_RATE_MAX 640
#define SMI_STAGE_RATE_HOME 80
#define SMI_STAGE_RATE_HOME_SLOW 32
#define SMI_STAGE_HOME_VERIFY_US 5000
#define SMI_STAGE_HOME_BACKOFF 32
#define SMI_STAGE_HOME_MAX_SEARCH 1920
#define SMI_STAGE_HOME_MAX_RELEASE 128
#define SMI_STAGE_STEP_HIGH_US 3           // contract minimum 2 us high and low
#define SMI_STAGE_DIR_SETUP_US 3           // contract minimum 2 us setup and hold
#define SMI_STAGE_SELFTEST_ORIGIN 128
#define SMI_STAGE_SELFTEST_RUNGS 8
#define SMI_STAGE_SELFTEST_DWELL_US 1000000u
// A normal move may see HOME high only this close to zero (the switch opens at 0).
#define SMI_STAGE_HOME_ZONE 4

// TMC2209 (stage-map.json uart.registers).
#define SMI_TMC_ADDR 0
#define SMI_TMC_GCONF 0x00
#define SMI_TMC_GSTAT 0x01
#define SMI_TMC_IFCNT 0x02
#define SMI_TMC_SLAVECONF 0x03
#define SMI_TMC_IOIN 0x06
#define SMI_TMC_IHOLD_IRUN 0x10
#define SMI_TMC_VACTUAL 0x22
#define SMI_TMC_CHOPCONF 0x6C
#define SMI_TMC_DRV_STATUS 0x6F
#define SMI_TMC_GCONF_VAL 0x000000C0u
#define SMI_TMC_SLAVECONF_VAL 0x00000200u
#define SMI_TMC_IHOLD_IRUN_VAL 0x00001B1Bu
#define SMI_TMC_CHOPCONF_VAL 0x040101C3u
#define SMI_TMC_VERSION 0x21

// Pushed by the firmware: SMI_T_STAGE frame = state block (24 bytes) + u64 ADC pair
// index at the time of sending, every 50 ms while the driver is enabled, else every 500 ms.
#define SMI_T_STAGE 0x13

// Binary command (on the existing CMD/ACK channel): op SMI_OP_STAGE, u8 sub, i32 arg.
#define SMI_OP_STAGE 0x09
enum {
    SMI_STAGE_SUB_STATUS = 0,
    SMI_STAGE_SUB_HOME = 1,      // configure the driver, enable and home
    SMI_STAGE_SUB_STEP = 2,      // arg: signed pulse count, relative
    SMI_STAGE_SUB_SPEED = 3,     // arg: pulses/s (0 = report only)
    SMI_STAGE_SUB_STOP = 4,      // stop motion, stay enabled, keep position
    SMI_STAGE_SUB_OFF = 5,       // disable the driver; position becomes invalid
    SMI_STAGE_SUB_CURRENT = 6,   // read DRV_STATUS and report the current set point
    SMI_STAGE_SUB_SELFTEST = 7,  // origin 128, +128 x4, -128 x4, 1 s dwells
    SMI_STAGE_SUB_MOVE_TO = 8,   // arg: absolute pulse position (homed only)
};
enum {
    SMI_STAGE_OK = 0,
    SMI_STAGE_E_LEN = 1,
    SMI_STAGE_E_SUB = 2,
    SMI_STAGE_E_NOT_HOMED = 11,   // only homing may move an unhomed stage
    SMI_STAGE_E_LIMIT = 12,       // outside 0..1600 pulses
    SMI_STAGE_E_BUSY = 13,        // a home, move or self-test is running
    SMI_STAGE_E_DRIVER = 14,      // TMC2209 did not answer, CRC or IFCNT mismatch, wrong version
    SMI_STAGE_E_FAULT = 15,       // a fault is latched: stage off, then home again
    SMI_STAGE_E_RATE = 16,        // speed outside 1..640 pulses/s
};
enum { SMI_STAGE_OFF = 0, SMI_STAGE_IDLE = 1, SMI_STAGE_HOMING = 2, SMI_STAGE_MOVING = 3, SMI_STAGE_SELFTEST = 4, SMI_STAGE_FAULTED = 5 };
enum {
    SMI_STAGE_FAULT_NONE = 0,
    SMI_STAGE_FAULT_DRIVER = 1,        // configuration or status read failed
    SMI_STAGE_FAULT_HOME_STUCK = 2,    // HOME stayed high through the release search
    SMI_STAGE_FAULT_HOME_TIMEOUT = 3,  // no HOME edge within the search limit
    SMI_STAGE_FAULT_HOME_UNEXPECTED = 4, // HOME went high during a normal move
    SMI_STAGE_FAULT_LINK = 5,          // host link lost while enabled
    SMI_STAGE_FAULT_DRV_STATUS = 6,    // over-temperature, short or open load reported
};
#define SMI_STAGE_FLAG_ENABLED 0x01
#define SMI_STAGE_FLAG_HOMED 0x02
#define SMI_STAGE_FLAG_HOME_IN 0x04     // HOME input high now
#define SMI_STAGE_FLAG_MOVING 0x08

typedef struct {
    void *ctx;
    void (*put)(void *ctx, uint8_t gpio, bool level);          // STEP, DIR, EN_N
    bool (*home_in)(void *ctx);                                // HOME level, true = high
    void (*wait_us)(void *ctx, uint32_t us);
    // One half-duplex UART exchange: send ntx bytes, then (nrx > 0) receive
    // exactly nrx bytes. Return false on timeout.
    bool (*uart)(void *ctx, const uint8_t *tx, size_t ntx, uint8_t *rx, size_t nrx);
} smi_stage_hal_t;

typedef struct {
    smi_stage_hal_t hal;
    uint8_t state, fault, home_phase;
    bool enabled, homed, dir_pos;
    int32_t pos;                 // pulses from HOME (valid when homed)
    int32_t target;              // move target
    int32_t phase_count;         // pulses issued in the current homing phase
    uint16_t rate, move_rate;
    uint32_t next_us, high_since_us, dwell_until_us, last_step_us;
    bool high_seen;
    uint8_t st_index;            // self-test rung (0 = going to the origin)
    uint32_t steps_total;
    uint8_t ifcnt;
    uint32_t drv_status, ioin;
    uint32_t last_poll_us;
    // duplicate suppression
    bool have_last;
    uint16_t last_seq;
    uint8_t last_resp[40];
    size_t last_len;
} smi_stage_t;

void smi_stage_init(smi_stage_t *s, const smi_stage_hal_t *hal);
// Call often (every 100 us or faster): issues due pulses and runs homing and
// the self-test.
void smi_stage_tick(smi_stage_t *s, uint32_t now_us);
// Binary command: p = sub, i32 arg. Writes an ACK body (u16 seq, u8 op, u8 status,
// then the state block) to resp and returns its length.
size_t smi_stage_command(smi_stage_t *s, const uint8_t *p, size_t n, uint16_t seq, uint32_t now_us, uint8_t *resp);
// State block (24 bytes): u8 state, u8 flags, u8 fault, u8 home_phase, i32 pos,
// i32 target, u16 rate, u8 st_index, u8 ifcnt, u32 steps_total, u32 drv_status.
size_t smi_stage_state(const smi_stage_t *s, uint8_t *out);
void smi_stage_link_lost(smi_stage_t *s);
// Text command ("stage ..."); writes a one-line reply.
void smi_stage_text(smi_stage_t *s, const char *cmd, uint32_t now_us, char *reply, size_t nreply);
// TMC2209 datagram CRC-8 (polynomial 0x07, LSB first), exported for tests.
uint8_t smi_tmc_crc(const uint8_t *d, size_t n);
const char *smi_stage_state_name(uint8_t st);
const char *smi_stage_fault_name(uint8_t f);
#endif