main
John Lauer software/ 1.2.1 for board 1.2.1: Pico firmware runs the board's controller contract (head DAC121C085 written and read b… 2e755c9
// SPDX-License-Identifier: MIT
// Board control core: laser enable and current set-point, offsets, gains and
// monitor bias, with the firmware's own limits (rated current, ramp rate,
// overcurrent trip, host heartbeat). Portable C99 with a small hardware
// interface, so the same file runs in the Pico firmware, in the host-side test
// and inside the dashboard's simulator.
//
// Command channel, on the same USB link as the sample stream, using the same
// frame (smi_frame.h): the host sends SMI_T_CMD frames, the Pico answers every
// one with an SMI_T_ACK frame carrying the command's seq, and pushes
// SMI_T_STATE frames four times a second while the port is open.
//
// CMD payload: u8 op, then op arguments (little-endian):
//   SMI_OP_GET_STATE     -                       -> ACK carries the state block
//   SMI_OP_LASER_ENABLE  u8 on, u32 key          key must be SMI_LASER_KEY to turn on
//   SMI_OP_SET           u8 control, u8 mode, f32 value
//                        mode 0 = physical units (mA, V, ohm, x), 1 = DAC counts,
//                        2 = setting index (switches)
//                        -> ACK: u8 control, u16 code, f32 applied, f32 target
//   SMI_OP_READ_ISENSE   -                       -> ACK: f32 mA, u16 raw, u16 age_ms
//   SMI_OP_HEARTBEAT     -                       keeps the laser on (see hb_timeout_ms)
//   SMI_OP_CLEAR_FAULT   -
//   SMI_OP_GET_MAP       -                       -> ACK: u32 hash, u8 n, version text
//   SMI_OP_CONFIG        u8 isense_hz, u16 hb_timeout_ms
// ACK payload: u16 cmd_seq, u8 op, u8 status, then the result. On
// SMI_E_RANGE the result is f32 min, f32 max of what is allowed.
#ifndef SMI_CTL_H
#define SMI_CTL_H

#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>

#define SMI_T_CMD 0x10
#define SMI_T_ACK 0x11
#define SMI_T_STATE 0x12

#define SMI_OP_GET_STATE 0x01
#define SMI_OP_LASER_ENABLE 0x02
#define SMI_OP_SET 0x03
#define SMI_OP_READ_ISENSE 0x04
#define SMI_OP_HEARTBEAT 0x05
#define SMI_OP_CLEAR_FAULT 0x06
#define SMI_OP_GET_MAP 0x07
#define SMI_OP_CONFIG 0x08

#define SMI_LASER_KEY 0x4C415345u /* "LASE" */

enum {
    SMI_OK = 0,
    SMI_E_LEN = 1,        // payload too short for the op
    SMI_E_OP = 2,         // unknown op
    SMI_E_CONTROL = 3,    // no such control index
    SMI_E_RANGE = 4,      // value outside the control's limits
    SMI_E_KEY = 5,        // laser enable without the interlock key
    SMI_E_FAULT = 6,      // a fault is latched; clear it first
    SMI_E_HW = 7,         // the DAC did not acknowledge
    SMI_E_MODE = 8,       // unit mode does not apply to this control
    SMI_E_NOT_READY = 9,  // current readback not yet validated at zero (startup rule)
    SMI_E_LASER_ON = 10,  // the map says change this control only with the laser off
};

// Why the laser is off (last_off_reason) and why the Pico booted.
enum {
    SMI_OFF_NONE = 0,
    SMI_OFF_BOOT = 1,
    SMI_OFF_HOST = 2,
    SMI_OFF_USB = 3,
    SMI_OFF_WATCHDOG = 4,
    SMI_OFF_HB_TIMEOUT = 5,
    SMI_OFF_OVERCURRENT = 6,
    SMI_OFF_HW = 7,
};

enum { SMI_FAULT_NONE = 0, SMI_FAULT_OVERCURRENT = 1, SMI_FAULT_HW = 2, SMI_FAULT_CURRENT_WHEN_OFF = 3, SMI_FAULT_ISENSE = 4,
       SMI_FAULT_READBACK = 5 };   // the laser DAC's register no longer matches what was written

#define SMI_FLAG_LASER_ON 0x01
#define SMI_FLAG_RAMPING 0x02
#define SMI_FLAG_FAULT 0x04
#define SMI_FLAG_ISENSE_VALID 0x08
#define SMI_FLAG_TRACK_WARN 0x10

enum { SMI_KIND_DAC = 1, SMI_KIND_SWITCH = 2 };
enum { SMI_UNIT_MA = 0, SMI_UNIT_V = 1, SMI_UNIT_OHM = 2, SMI_UNIT_X = 3 };

#define SMI_MAX_CONTROLS 12
#define SMI_MAX_SETTINGS 8

typedef struct {
    uint8_t part, addr, bits;
    float vref;
} smi_dac_def_t;

// Laser current readback (ADS1115 on the laser head): mA = (code - zero) *
// ma_per_code + offset_ma, with the zero code calibrated with the laser off.
typedef struct {
    float ma_per_code, offset_ma, trip_ma;
    uint8_t rate_hz;
    uint8_t zero_cal;
} smi_isense_def_t;

typedef struct {
    uint8_t kind, unit, is_laser, needs_off;
    float min, max, def;
    // DAC channels: value = at_zero + code * per_code.
    uint8_t dac, ch, bits;
    float per_code, at_zero, ramp_per_s, rated;
    // Laser DAC on the head (board 1.2.1 controller contract), gate = 1: every
    // write drops the enable, waits disarm_us for the head's disable path and
    // soft-start reset, writes and reads back, and re-asserts the enable only on
    // a verified nonzero code, then reads back once more. The head's soft-start
    // ramps the current from zero on every arm, so there is no stepped ramp:
    // the target is written in one step, at most every min_write_us.
    uint8_t gate;
    uint32_t min_write_us, disarm_us;
    // Highest DAC code allowed (0 = full scale). Command codes (counts mode on
    // the laser) map to DAC codes as max(command - guard, 0): the guard band
    // reserves counts for the DAC's positive offset error.
    uint16_t max_code, guard;
    // Switches: GPIO bits (LSB first) take set_code[i] for set_value[i].
    uint8_t ngpio, gpio[4], nset, set_code[SMI_MAX_SETTINGS];
    float set_value[SMI_MAX_SETTINGS];
} smi_control_def_t;

typedef struct {
    void *ctx;
    // Write one DAC channel; return false if the device did not acknowledge.
    // For a write-then-readback DAC (DAC121C085) also false if the register
    // read back does not match exactly.
    bool (*dac_write)(void *ctx, uint8_t dac, uint8_t ch, uint16_t code);
    // Optional (NULL = absent): busy-wait, and read a DAC's raw register back.
    void (*wait_us)(void *ctx, uint32_t us);
    bool (*dac_read)(void *ctx, uint8_t dac, uint16_t *reg);
    // Drive a switch line: Pico GPIO below 32, MCP23008 bit (32 + n) above.
    // Return false if an expander write was not acknowledged.
    bool (*gpio_put)(void *ctx, uint8_t gpio, bool level);
} smi_hal_t;

typedef struct {
    const smi_control_def_t *defs;
    uint8_t n;
    const smi_isense_def_t *isense;
    uint32_t map_hash;
    const char *map_version;
    uint8_t laser_en_gpio, laser_en_active_high;
    smi_hal_t hal;

    uint16_t code[SMI_MAX_CONTROLS];   // what the hardware holds (switches: GPIO code)
    float target[SMI_MAX_CONTROLS];    // requested value, physical units
    float laser_now;                   // ramped laser set-point, mA (= laser_ua / 1000)
    int32_t laser_ua;                  // the ramp runs in integer microamps, exactly at the rate
    uint32_t ramp_rem;                 // remainder of ramp_ua_per_s * dt_us / 1e6
    bool laser_on;
    uint8_t fault, boot_reason, off_reason;
    uint32_t last_host_us, last_tick_us, settled_since_us;
    uint16_t hb_timeout_ms;
    uint8_t isense_hz;
    float isense_ma;
    int16_t isense_raw;
    uint8_t isense_fail_n;             // consecutive failed reads of the head ADC
    uint32_t isense_us;
    bool isense_valid, track_warn;
    uint8_t over_n, offcur_n;
    uint32_t off_since_us;
    float zero_raw;                    // calibrated zero code of the current sense
    uint16_t zero_n;                   // readings that went into it
    uint32_t laser_write_us;           // last laser DAC write
    uint32_t readbacks;                // laser DAC readback polls that matched
} smi_ctl_t;

// boot_reason: SMI_OFF_BOOT for a normal power-up, SMI_OFF_WATCHDOG after a
// watchdog reset. Drives every output to its power-on default, laser off.
void smi_ctl_init(smi_ctl_t *c, const smi_control_def_t *defs, uint8_t n, const smi_isense_def_t *is,
                  uint32_t map_hash, const char *map_version, uint8_t laser_en_gpio, bool laser_en_active_high,
                  const smi_hal_t *hal, uint8_t boot_reason, uint32_t now_us);

// Handle one CMD payload. Writes the ACK payload into resp (at least 96 bytes)
// (at least 128 bytes) and returns its length.
size_t smi_ctl_command(smi_ctl_t *c, const uint8_t *p, size_t n, uint16_t cmd_seq, uint32_t now_us, uint8_t *resp);

// Call often (every loop pass): advances the laser ramp, checks the heartbeat.
void smi_ctl_tick(smi_ctl_t *c, uint32_t now_us);

// A new reading of the laser current sense (signed ADC code).
void smi_ctl_isense(smi_ctl_t *c, int32_t raw, uint32_t now_us);
// The current-sense ADC did not answer. Three in a row with the laser on is a
// fault: the firmware's overcurrent trip cannot work blind.
void smi_ctl_isense_failed(smi_ctl_t *c, uint32_t now_us);

// A poll of the laser DAC's register while armed (every 2 ms on the board:
// the traffic also feeds the head's I2C watchdog). reg is the raw 16-bit
// register: bits 13:12 power-down mode, 11:0 code. A failed read, a mode other
// than normal, or a code other than the one written is a latched fault.
void smi_ctl_laser_readback(smi_ctl_t *c, bool ok, uint16_t reg, uint32_t now_us);

// The host went away (USB unplugged, port closed): laser off, set-point to 0.
void smi_ctl_link_lost(smi_ctl_t *c, uint8_t reason);

// The STATE block (also the GET_STATE result). resp needs 30 + 6 * n bytes:
// 28 bytes of header (isense_raw is a signed i16), 6 per control, then the
// zero code as i16 x 16 (0x8000 = not calibrated).
size_t smi_ctl_state(const smi_ctl_t *c, uint32_t now_us, uint8_t *resp);

// Value <-> code for a DAC control.
uint16_t smi_ctl_code_for(const smi_control_def_t *d, float v);
float smi_ctl_value_of(const smi_control_def_t *d, uint16_t code);

#endif