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
// Host stand-in for the Pico's command channel, for testing the dashboard's
// serial path without hardware: the firmware's control core (smi_ctl.c) and
// frame code (smi_frame.c) behind a pseudo-terminal. It answers CMD frames
// with ACKs, sends STATE frames four times a second, and feeds the core a
// current reading that follows the DAC like the head's ADS1115 would. The
// stage core (smi_stage.c) runs against a mock TMC2209 and screw with a HOME
// switch, answers op 0x09 and "stage ..." lines, and sends STAGE frames.
//   cc -O2 -I../src ctl_pty.c ../src/smi_ctl.c ../src/smi_text.c ../src/smi_frame.c ../src/smi_stage.c -lm -o ctl_pty
//   ./ctl_pty SECONDS     (prints the pty path, then serves it)
#define _XOPEN_SOURCE 600
#define _DEFAULT_SOURCE
#include <fcntl.h>
#include <termios.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "smi_frame.h"
#include "smi_ctl.h"
#include "smi_controls_gen.h"
#include "smi_text.h"
#include "smi_stage.h"

// Mock stage: screw position in pulses (HOME opens at <= 0), TMC2209 registers.
static long mech = 700;
static bool st_step, st_dir = true, st_en_n = true;
static uint32_t tmc[128];
static uint8_t tmc_if;
static void s_put(void *c, uint8_t g, bool v) {
    (void)c;
    if (g == SMI_STAGE_STEP_GPIO) { if (v && !st_step && !st_en_n) mech += st_dir ? 1 : -1; st_step = v; }
    else if (g == SMI_STAGE_DIR_GPIO) st_dir = v;
    else if (g == SMI_STAGE_EN_N_GPIO) st_en_n = v;
}
static bool s_home(void *c) { (void)c; return mech <= 0; }
static bool s_uart(void *c, const uint8_t *tx, size_t ntx, uint8_t *rx, size_t nrx) {
    (void)c;
    if (ntx < 4 || tx[ntx - 1] != smi_tmc_crc(tx, ntx - 1)) return false;
    uint8_t reg = tx[2] & 0x7F;
    if (ntx == 8) { uint32_t v = ((uint32_t)tx[3] << 24) | ((uint32_t)tx[4] << 16) | ((uint32_t)tx[5] << 8) | tx[6]; if (reg == 1) tmc[1] &= ~v; else tmc[reg] = v; tmc_if++; return nrx == 0; }
    uint32_t v = reg == 2 ? tmc_if : reg == 6 ? (0x21u << 24) : tmc[reg];
    rx[0] = 5; rx[1] = 0xFF; rx[2] = reg; rx[3] = (uint8_t)(v >> 24); rx[4] = (uint8_t)(v >> 16); rx[5] = (uint8_t)(v >> 8); rx[6] = (uint8_t)v; rx[7] = smi_tmc_crc(rx, 7);
    return true;
}
static smi_stage_t stage;

static uint16_t dac[4][8];
static bool gp[64];
static bool d_w(void *c, uint8_t d, uint8_t ch, uint16_t code) { (void)c; dac[d][ch] = code; return true; }
static bool g_w(void *c, uint8_t g, bool v) { (void)c; gp[g] = v; return true; }
static uint32_t now_us(void);
static uint32_t text_now(void *x) { (void)x; return now_us(); }
static uint32_t now_us(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint32_t)(t.tv_sec * 1000000ull + t.tv_nsec / 1000); }

static int fd;
static uint16_t seq;
static void send(uint8_t type, const uint8_t *pl, uint16_t n);
static void text_send(void *x, const char *t) { (void)x; send(SMI_T_INFO, (const uint8_t *)t, (uint16_t)strlen(t)); }
static void text_stage(void *x, const char *c) { (void)x; char r[200]; smi_stage_text(&stage, c, now_us(), r, sizeof r); send(SMI_T_INFO, (const uint8_t *)r, (uint16_t)strlen(r)); }
static void send(uint8_t type, const uint8_t *pl, uint16_t n) {
    uint8_t f[256];
    memcpy(f + SMI_HDR_LEN, pl, n);
    smi_begin_frame(f, type, n, seq++);
    size_t len = smi_finish_frame(f, n);
    if (write(fd, f, len) != (ssize_t)len) perror("write");
}

int main(int argc, char **argv) {
    double secs = argc > 1 ? atof(argv[1]) : 30;
    fd = posix_openpt(O_RDWR | O_NOCTTY);
    grantpt(fd); unlockpt(fd);
    {   // Raw from the start, like a USB CDC port: no echo of our own frames back to us.
        int sl = open(ptsname(fd), O_RDWR | O_NOCTTY);
        struct termios t;
        tcgetattr(sl, &t);
        cfmakeraw(&t);
        tcsetattr(sl, TCSANOW, &t);
        close(sl);
    }
    printf("%s\n", ptsname(fd)); fflush(stdout);
    fcntl(fd, F_SETFL, O_NONBLOCK);
    smi_ctl_t c;
    smi_hal_t hal = {.ctx = NULL, .dac_write = d_w, .gpio_put = g_w};
    smi_ctl_init(&c, smi_controls, SMI_NUM_CONTROLS, &smi_isense, SMI_MAP_HASH, SMI_MAP_VERSION, SMI_LASER_EN_GPIO, SMI_LASER_EN_ACTIVE_HIGH, &hal, SMI_OFF_BOOT, now_us());
    smi_stage_hal_t sh = { .ctx = NULL, .put = s_put, .home_in = s_home, .wait_us = NULL, .uart = s_uart };
    smi_stage_init(&stage, &sh);
    bool host_watch = false;
    uint32_t last_stage = 0;
    unsigned stage_acks = 0;
    const char *info = "ctl_pty host stand-in; map=" SMI_MAP_VERSION "; stage=J4 GP10-14";
    send(SMI_T_INFO, (const uint8_t *)info, (uint16_t)strlen(info));
    uint8_t rx[200]; int rl = 0;
    smi_text_t tx = { .ctl = &c, .now_us = text_now, .reply = text_send, .stage = text_stage, .exp_base = SMI_EXP_BASE, .gain_base = 7 };
    uint32_t t0 = now_us(), last_state = 0, last_is = 0, last_poll = 0;
    int li = 0;
    unsigned acks = 0;
    while ((now_us() - t0) < secs * 1e6) {
        uint8_t b;
        while (read(fd, &b, 1) == 1) {
            if (rl == 0 && b != SMI_SYNC0) {
                // Text command lines (board contract), as the firmware takes them.
                smi_text_feed(&tx, (char)b);
                continue;
            }
            rx[rl++] = b;
            if (rl == 2 && b != SMI_SYNC1) { rl = 0; continue; }
            if (rl >= 6) {
                uint16_t len = (uint16_t)(rx[4] | (rx[5] << 8));
                if (len > 160) { rl = 0; continue; }
                if (rl == 8 + len + 2) {
                    uint16_t crc = (uint16_t)(rx[8 + len] | (rx[9 + len] << 8));
                    if (rx[2] == SMI_T_CMD && smi_crc16(rx + 2, 6u + len, 0xFFFF) == crc) {
                        uint8_t r[200];
                        uint16_t cs = (uint16_t)(rx[6] | (rx[7] << 8));
                        c.last_host_us = now_us();   // as main.c: any binary command is host activity
                        host_watch = true;
                        size_t n;
                        if (len >= 1 && rx[8] == SMI_OP_STAGE) { n = smi_stage_command(&stage, rx + 8, len, cs, now_us(), r); stage_acks++; }
                        else n = smi_ctl_command(&c, rx + 8, len, cs, now_us(), r);
                        send(SMI_T_ACK, r, (uint16_t)n);
                        acks++;
                    }
                    rl = 0;
                }
            }
        }
        uint32_t t = now_us();
        smi_ctl_tick(&c, t);
        smi_stage_tick(&stage, t);
        if (host_watch && stage.enabled && c.hb_timeout_ms && (uint32_t)(t - c.last_host_us) > (uint32_t)c.hb_timeout_ms * 1000u)
            smi_stage_link_lost(&stage);
        if (t - last_stage > (stage.enabled ? 50000u : 500000u)) {
            last_stage = t;
            uint8_t sp[40];
            size_t n = smi_stage_state(&stage, sp);
            memset(sp + n, 0, 8);
            send(SMI_T_STAGE, sp, (uint16_t)(n + 8));
        }
        if (t - last_is > 20000) {   // 50 Hz, like the firmware: current follows the DAC, zero code +6
            last_is = t;
            bool on = gp[SMI_LASER_EN_GPIO] == SMI_LASER_EN_ACTIVE_HIGH;
            float ma = on ? smi_ctl_value_of(&smi_controls[li], dac[smi_controls[li].dac][smi_controls[li].ch]) : 0.0f;
            smi_ctl_isense(&c, (int32_t)lroundf(ma / smi_isense.ma_per_code) + 6, t);
        }
        if (SMI_LASER_READBACK_POLL_MS && c.laser_on && t - last_poll >= SMI_LASER_READBACK_POLL_MS * 1000u) {
            last_poll = t;   // the stand-in's head DAC reads back what was written
            smi_ctl_laser_readback(&c, true, dac[smi_controls[li].dac][smi_controls[li].ch] & 0x0FFF, t);
        }
        if (t - last_state > 250000) {
            last_state = t;
            uint8_t st[200];
            send(SMI_T_STATE, st, (uint16_t)smi_ctl_state(&c, t, st));
        }
        usleep(200);
    }
    fprintf(stderr, "ctl_pty: stage %s pos %ld (screw %ld), fault %s, %u stage commands, %lu pulses; ", smi_stage_state_name(stage.state), (long)stage.pos, mech, smi_stage_fault_name(stage.fault), stage_acks, (unsigned long)stage.steps_total);
    fprintf(stderr, "ctl_pty: text laser command %u; answered %u commands; laser %s, off reason %u, fault %u, readback polls %u\n", tx.laser_cmd, acks, c.laser_on ? "on" : "off", c.off_reason, c.fault, (unsigned)c.readbacks);
    return 0;
}