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
#include "smi_ctl.h"
#include <string.h>

static void put16(uint8_t *p, uint16_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); }
static void put32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i)); }
static void putf(uint8_t *p, float f) { uint32_t u; memcpy(&u, &f, 4); put32(p, u); }
static uint16_t get16(const uint8_t *p) { return (uint16_t)(p[0] | (p[1] << 8)); }
static uint32_t get32(const uint8_t *p) { return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); }
static float getf(const uint8_t *p) { uint32_t u = get32(p); float f; memcpy(&f, &u, 4); return f; }
static float fabsf_(float x) { return x < 0 ? -x : x; }

uint16_t smi_ctl_code_for(const smi_control_def_t *d, float v) {
    float x = (v - d->at_zero) / d->per_code;
    float top = (float)(d->max_code ? d->max_code : (1u << d->bits) - 1u);
    if (x < 0) x = 0;
    if (x > top) x = top;
    return (uint16_t)(x + 0.5f);
}

float smi_ctl_value_of(const smi_control_def_t *d, uint16_t code) {
    return d->at_zero + (float)code * d->per_code;
}

static int laser_index(const smi_ctl_t *c) {
    for (int i = 0; i < c->n; i++)
        if (c->defs[i].is_laser) return i;
    return -1;
}

static void en_pin(smi_ctl_t *c, bool on) {
    (void)c->hal.gpio_put(c->hal.ctx, c->laser_en_gpio, on ? c->laser_en_active_high : !c->laser_en_active_high);
}

static bool put_switch(smi_ctl_t *c, int i, uint8_t code) {
    const smi_control_def_t *d = &c->defs[i];
    bool ok = true;
    for (int b = 0; b < d->ngpio; b++) ok &= c->hal.gpio_put(c->hal.ctx, d->gpio[b], (code >> b) & 1);
    if (ok) c->code[i] = code;
    return ok;
}

static bool put_dac(smi_ctl_t *c, int i, uint16_t code) {
    const smi_control_def_t *d = &c->defs[i];
    if (d->gate) {
        en_pin(c, false);                     // drop the enable before writing
        if (c->hal.wait_us && d->disarm_us) c->hal.wait_us(c->hal.ctx, d->disarm_us);
    }
    bool ok = c->hal.dac_write(c->hal.ctx, d->dac, d->ch, code);
    if (ok) c->code[i] = code;
    // Re-assert only after a verified write of a nonzero code, and only if armed;
    // then read back once more (the head watchdog wants fresh SCL after enable).
    if (d->gate && ok && c->laser_on && code != 0) {
        en_pin(c, true);
        uint16_t reg;
        if (c->hal.dac_read && !(c->hal.dac_read(c->hal.ctx, d->dac, &reg) && ((reg >> 12) & 3u) == 0 && (reg & 0x0FFFu) == code)) {
            en_pin(c, false);
            return false;
        }
    }
    return ok;
}

static void laser_off(smi_ctl_t *c, uint8_t reason) {
    int li = laser_index(c);
    en_pin(c, false);                 // the hardware enable goes first
    if (c->laser_on) c->off_since_us = c->last_tick_us;
    c->laser_on = false;
    c->laser_now = 0;
    c->laser_ua = 0;
    c->ramp_rem = 0;
    c->off_reason = reason;
    if (li >= 0) put_dac(c, li, smi_ctl_code_for(&c->defs[li], 0.0f));
}

static void fault(smi_ctl_t *c, uint8_t f, uint8_t reason) {
    c->fault = f;
    laser_off(c, reason);
}

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) {
    memset(c, 0, sizeof *c);
    c->defs = defs;
    c->n = n > SMI_MAX_CONTROLS ? SMI_MAX_CONTROLS : n;
    c->isense = is;
    c->map_hash = map_hash;
    c->map_version = map_version;
    c->laser_en_gpio = laser_en_gpio;
    c->laser_en_active_high = laser_en_active_high;
    c->hal = *hal;
    c->boot_reason = boot_reason;
    c->hb_timeout_ms = 3000;
    c->isense_hz = is->rate_hz ? is->rate_hz : 10;
    c->last_host_us = c->last_tick_us = now_us;
    en_pin(c, false);
    for (int i = 0; i < c->n; i++) {
        const smi_control_def_t *d = &defs[i];
        c->target[i] = d->def;
        if (d->kind == SMI_KIND_DAC) {
            if (!put_dac(c, i, smi_ctl_code_for(d, d->is_laser ? 0.0f : d->def))) c->fault = SMI_FAULT_HW;
        } else {
            uint8_t code = d->set_code[0];
            for (int k = d->nset - 1; k >= 0; k--)
                if (d->set_value[k] == d->def) code = d->set_code[k];
            if (!put_switch(c, i, code)) c->fault = SMI_FAULT_HW;   // head interface not answering
        }
    }
    c->off_reason = boot_reason;
    c->off_since_us = now_us;
}

static size_t ack(uint8_t *r, uint16_t seq, uint8_t op, uint8_t st) {
    put16(r, seq);
    r[2] = op;
    r[3] = st;
    return 4;
}

static size_t range_err(uint8_t *r, uint16_t seq, uint8_t op, float lo, float hi) {
    size_t o = ack(r, seq, op, SMI_E_RANGE);
    putf(r + o, lo);
    putf(r + o + 4, hi);
    return o + 8;
}

static size_t do_set(smi_ctl_t *c, const uint8_t *p, size_t n, uint16_t seq, uint8_t *r) {
    if (n < 7) return ack(r, seq, SMI_OP_SET, SMI_E_LEN);
    uint8_t i = p[1], mode = p[2];
    float v = getf(p + 3);
    if (i >= c->n) return ack(r, seq, SMI_OP_SET, SMI_E_CONTROL);
    const smi_control_def_t *d = &c->defs[i];
    if (v != v) return range_err(r, seq, SMI_OP_SET, d->min, d->max);   // NaN
    if (d->needs_off && c->laser_on) return ack(r, seq, SMI_OP_SET, SMI_E_LASER_ON);
    if (d->kind == SMI_KIND_DAC) {
        if (mode == 1) {
            float top = (float)((1u << d->bits) - 1u);
            if (v < 0 || v > top) return range_err(r, seq, SMI_OP_SET, 0, top);
            uint16_t cc = (uint16_t)(v + 0.5f);
            if (d->guard) cc = cc > d->guard ? (uint16_t)(cc - d->guard) : 0;   // command code -> DAC code
            v = smi_ctl_value_of(d, cc);
        } else if (mode != 0) {
            return ack(r, seq, SMI_OP_SET, SMI_E_MODE);
        }
        float tol = fabsf_(d->per_code) * 0.5f;
        float hi = d->max;
        if (d->is_laser && d->rated < hi) hi = d->rated;
        if (v < d->min - tol || v > hi + tol) return range_err(r, seq, SMI_OP_SET, d->min, hi);
        if (v > hi) v = hi;
        if (v < d->min) v = d->min;
        c->target[i] = v;
        if (!d->is_laser) {
            if (!put_dac(c, i, smi_ctl_code_for(d, v))) {
                fault(c, SMI_FAULT_HW, SMI_OFF_HW);
                return ack(r, seq, SMI_OP_SET, SMI_E_HW);
            }
        }
        // The laser set-point is applied by smi_ctl_tick at the ramp rate.
    } else {
        int k = -1;
        for (int j = d->nset - 1; j >= 0; j--) {   // first match wins (a map may list a value twice)
            if (mode == 0 && fabsf_(d->set_value[j] - v) <= fabsf_(d->set_value[j]) * 1e-3f) k = j;
            if (mode == 1 && (float)d->set_code[j] == v) k = j;
            if (mode == 2 && (float)j == v) k = j;
        }
        if (mode > 2) return ack(r, seq, SMI_OP_SET, SMI_E_MODE);
        if (k < 0) return range_err(r, seq, SMI_OP_SET, d->min, d->max);
        if (!put_switch(c, i, d->set_code[k])) {
            fault(c, SMI_FAULT_HW, SMI_OFF_HW);
            return ack(r, seq, SMI_OP_SET, SMI_E_HW);
        }
        c->target[i] = d->set_value[k];
    }
    size_t o = ack(r, seq, SMI_OP_SET, SMI_OK);
    r[o] = i;
    put16(r + o + 1, c->code[i]);
    float applied = d->is_laser ? c->laser_now : (d->kind == SMI_KIND_DAC ? smi_ctl_value_of(d, c->code[i]) : c->target[i]);
    putf(r + o + 3, applied);
    putf(r + o + 7, c->target[i]);
    return o + 11;
}

size_t smi_ctl_command(smi_ctl_t *c, const uint8_t *p, size_t n, uint16_t seq, uint32_t now_us, uint8_t *r) {
    if (n < 1) return ack(r, seq, 0, SMI_E_LEN);
    c->last_host_us = now_us;
    uint8_t op = p[0];
    switch (op) {
    case SMI_OP_GET_STATE: {
        size_t o = ack(r, seq, op, SMI_OK);
        return o + smi_ctl_state(c, now_us, r + o);
    }
    case SMI_OP_LASER_ENABLE: {
        if (n < 6) return ack(r, seq, op, SMI_E_LEN);
        if (!p[1]) {
            laser_off(c, SMI_OFF_HOST);
            return ack(r, seq, op, SMI_OK);
        }
        if (get32(p + 2) != SMI_LASER_KEY) return ack(r, seq, op, SMI_E_KEY);
        if (c->fault) return ack(r, seq, op, SMI_E_FAULT);
        // Startup rule: the current readback must have been validated at zero.
        if (c->isense->zero_cal ? c->zero_n < 8 : !c->isense_valid) return ack(r, seq, op, SMI_E_NOT_READY);
        int li = laser_index(c);
        if (li < 0) return ack(r, seq, op, SMI_E_CONTROL);
        if (!c->laser_on) {
            // Set-point to zero before the enable, then ramp up from there.
            if (!put_dac(c, li, smi_ctl_code_for(&c->defs[li], 0.0f))) {
                fault(c, SMI_FAULT_HW, SMI_OFF_HW);
                return ack(r, seq, op, SMI_E_HW);
            }
            c->laser_now = 0;
            c->laser_ua = 0;
            c->ramp_rem = 0;
            c->laser_on = true;
            c->off_reason = SMI_OFF_NONE;
            c->settled_since_us = now_us;
            c->last_tick_us = now_us;
            c->laser_write_us = now_us - c->defs[li].min_write_us;   // first write may go at once
            // A gated laser DAC asserts the enable on its first verified nonzero write.
            if (!c->defs[li].gate) en_pin(c, true);
        }
        return ack(r, seq, op, SMI_OK);
    }
    case SMI_OP_SET:
        return do_set(c, p, n, seq, r);
    case SMI_OP_READ_ISENSE: {
        size_t o = ack(r, seq, op, c->isense_valid ? SMI_OK : SMI_E_HW);
        putf(r + o, c->isense_ma);
        put16(r + o + 4, c->isense_raw);
        uint32_t age = (now_us - c->isense_us) / 1000u;
        put16(r + o + 6, (uint16_t)(age > 65535u ? 65535u : age));
        return o + 8;
    }
    case SMI_OP_HEARTBEAT:
        return ack(r, seq, op, SMI_OK);
    case SMI_OP_CLEAR_FAULT:
        c->fault = SMI_FAULT_NONE;
        c->over_n = c->offcur_n = 0;
        return ack(r, seq, op, SMI_OK);
    case SMI_OP_GET_MAP: {
        size_t o = ack(r, seq, op, SMI_OK);
        put32(r + o, c->map_hash);
        r[o + 4] = c->n;
        size_t l = strlen(c->map_version);
        if (l > 60) l = 60;
        memcpy(r + o + 5, c->map_version, l);
        return o + 5 + l;
    }
    case SMI_OP_CONFIG: {
        if (n < 4) return ack(r, seq, op, SMI_E_LEN);
        uint8_t hz = p[1];
        uint16_t hb = get16(p + 2);
        if (hz < 1 || hz > 50) return range_err(r, seq, op, 1, 50);
        if (hb < 500 || hb > 30000) return range_err(r, seq, op, 500, 30000);
        c->isense_hz = hz;
        c->hb_timeout_ms = hb;
        return ack(r, seq, op, SMI_OK);
    }
    default:
        return ack(r, seq, op, SMI_E_OP);
    }
}

void smi_ctl_tick(smi_ctl_t *c, uint32_t now_us) {
    int li = laser_index(c);
    uint32_t dt = now_us - c->last_tick_us;
    c->last_tick_us = now_us;
    if (dt > 10000u) dt = 10000u;     // a stalled loop slows the ramp, never speeds it
    if (li < 0) return;
    if (c->laser_on && c->hb_timeout_ms && (now_us - c->last_host_us) > (uint32_t)c->hb_timeout_ms * 1000u) {
        laser_off(c, SMI_OFF_HB_TIMEOUT);
        return;
    }
    if (!c->laser_on) return;
    const smi_control_def_t *d = &c->defs[li];
    if (d->gate) {
        // One verified write per set-point change, at most every min_write_us
        // (the latest request wins); the head's soft-start does the ramp.
        uint16_t tc = smi_ctl_code_for(d, c->target[li]);
        if (tc != c->code[li] && (now_us - c->laser_write_us) >= d->min_write_us) {
            c->laser_write_us = now_us;
            if (!put_dac(c, li, tc)) { fault(c, SMI_FAULT_READBACK, SMI_OFF_HW); return; }
            c->laser_now = smi_ctl_value_of(d, tc);
            c->laser_ua = (int32_t)(c->target[li] * 1000.0f);
            c->settled_since_us = now_us;
        } else if (tc == c->code[li]) {
            c->laser_ua = (int32_t)(c->target[li] * 1000.0f);   // nothing to write: arrived
        }
        return;
    }
    int32_t goal = (int32_t)(c->target[li] * 1000.0f);
    // Integer microamps: step = floor(rate * dt) with the remainder carried, so
    // the set-point is never ahead of ramp_per_s, however the loop is timed.
    uint64_t acc = (uint64_t)(uint32_t)(d->ramp_per_s * 1000.0f) * dt + c->ramp_rem;
    int32_t step = (int32_t)(acc / 1000000u);
    c->ramp_rem = (uint32_t)(acc % 1000000u);
    int32_t now = c->laser_ua;
    if (now < goal) now = (goal - now > step) ? now + step : goal;
    else if (now > goal) now = (now - goal > step) ? now - step : goal;
    if (now == goal) c->ramp_rem = 0;
    if (now != c->laser_ua) {
        c->laser_ua = now;
        c->laser_now = (float)now / 1000.0f;
        c->settled_since_us = now_us;
    }
    // The DAC follows the set-point, at most every min_write_us during a ramp
    // (always at once when the ramp arrives), so it never runs ahead of it.
    uint16_t code = smi_ctl_code_for(d, c->laser_now);
    if (code != c->code[li] && (now == goal || (now_us - c->laser_write_us) >= d->min_write_us)) {
        c->laser_write_us = now_us;
        if (!put_dac(c, li, code)) fault(c, SMI_FAULT_HW, SMI_OFF_HW);
    }
}

void smi_ctl_laser_readback(smi_ctl_t *c, bool ok, uint16_t reg, uint32_t now_us) {
    (void)now_us;
    int li = laser_index(c);
    if (li < 0 || !c->laser_on) return;
    if (!ok || ((reg >> 12) & 3u) != 0 || (reg & 0x0FFFu) != c->code[li]) {
        fault(c, SMI_FAULT_READBACK, SMI_OFF_HW);
        return;
    }
    c->readbacks++;
}

void smi_ctl_isense_failed(smi_ctl_t *c, uint32_t now_us) {
    (void)now_us;
    c->isense_valid = false;
    if (++c->isense_fail_n >= 3 && c->laser_on) fault(c, SMI_FAULT_ISENSE, SMI_OFF_HW);
}

void smi_ctl_isense(smi_ctl_t *c, int32_t raw, uint32_t now_us) {
    const smi_isense_def_t *s = c->isense;
    const float ma_per_code = s->ma_per_code;
    c->isense_fail_n = 0;
    // Zero calibration: with the laser off for 300 ms, a reading within about
    // 6 mA of zero is taken as the zero code (mean of the first 8, then a slow
    // average). More than that with the laser off counts towards a fault.
    bool quiet = !c->laser_on && (now_us - c->off_since_us) > 300000u;
    float zero = s->zero_cal ? c->zero_raw : 0.0f;
    if (s->zero_cal && quiet) {
        float m = (float)raw * ma_per_code;
        if (m < 6.0f && m > -6.0f) {
            if (c->zero_n < 8) c->zero_raw = (c->zero_raw * c->zero_n + raw) / (float)(c->zero_n + 1);
            else c->zero_raw += ((float)raw - c->zero_raw) / 16.0f;
            if (c->zero_n < 65535) c->zero_n++;
            zero = c->zero_raw;
        }
    }
    float ma = ((float)raw - zero) * ma_per_code + s->offset_ma;
    c->isense_ma = ma;
    c->isense_raw = (int16_t)(raw > 32767 ? 32767 : raw < -32768 ? -32768 : raw);
    c->isense_us = now_us;
    c->isense_valid = true;
    if (ma > s->trip_ma) {
        if (++c->over_n >= 3) fault(c, SMI_FAULT_OVERCURRENT, SMI_OFF_OVERCURRENT);
    } else {
        c->over_n = 0;
    }
    if (quiet && ma > 5.0f) {
        if (++c->offcur_n >= 5) c->fault = SMI_FAULT_CURRENT_WHEN_OFF;
    } else {
        c->offcur_n = 0;
    }
    int li = laser_index(c);
    bool settled = c->laser_on && li >= 0 && c->laser_ua == (int32_t)(c->target[li] * 1000.0f) && (now_us - c->settled_since_us) > 300000u;
    c->track_warn = settled && fabsf_(ma - c->laser_now) > 5.0f + 0.1f * c->laser_now;
}

void smi_ctl_link_lost(smi_ctl_t *c, uint8_t reason) {
    int li = laser_index(c);
    laser_off(c, reason);
    if (li >= 0) c->target[li] = 0;
}

size_t smi_ctl_state(const smi_ctl_t *c, uint32_t now_us, uint8_t *r) {
    int li = laser_index(c);
    put32(r, c->map_hash);
    uint8_t f = 0;
    if (c->laser_on) f |= SMI_FLAG_LASER_ON;
    if (li >= 0 && c->laser_on && c->laser_ua != (int32_t)(c->target[li] * 1000.0f)) f |= SMI_FLAG_RAMPING;
    if (c->fault) f |= SMI_FLAG_FAULT;
    if (c->isense_valid) f |= SMI_FLAG_ISENSE_VALID;
    if (c->track_warn) f |= SMI_FLAG_TRACK_WARN;
    r[4] = f;
    r[5] = c->fault;
    r[6] = c->boot_reason;
    r[7] = c->off_reason;
    putf(r + 8, li >= 0 ? c->target[li] : 0);
    putf(r + 12, c->laser_now);
    putf(r + 16, c->isense_ma);
    put16(r + 20, (uint16_t)c->isense_raw);
    uint32_t age = c->isense_valid ? (now_us - c->isense_us) / 1000u : 65535u;
    put16(r + 22, (uint16_t)(age > 65535u ? 65535u : age));
    put16(r + 24, c->hb_timeout_ms);
    r[26] = c->isense_hz;
    r[27] = c->n;
    size_t o = 28;
    for (int i = 0; i < c->n; i++) {
        put16(r + o, c->code[i]);
        putf(r + o + 2, c->target[i]);
        o += 6;
    }
    int32_t z = -32768;   // not calibrated
    if (c->zero_n >= 8) {
        float zz = c->zero_raw * 16.0f;
        z = (int32_t)(zz < 0 ? zz - 0.5f : zz + 0.5f);
        if (z > 32767) z = 32767;
        if (z < -32767) z = -32767;
    }
    put16(r + o, (uint16_t)(int16_t)z);
    return o + 2;
}