main
Drew Owens Publish Microgoose Rev A full-stack hardware, CAD, datasheet, and 7-stage RL stack e843249
/*
 * test_firmware_host.c
 * Native gcc host verification suite for Microgoose STM32G431CB Spine firmware:
 *   1. Netlist pin map & connector DXL ID assertions (J1=1..5, J2=6..10, J3=11..15,
 *      PB10/PB11/PB12, PA2/PA3, PB6/PB7, PA0, PA1, PB0/PB1/PB2, PA8)
 *   2. Dynamixel Protocol 2.0 CRC-16 (0x8005) table vs bitwise + official ROBOTIS Ping vector
 *   3. SyncWrite Goal Position (0x83, addr 116) & SyncRead Telemetry (0x82, addr 126..135)
 *   4. Protocol 2.0 [FF FF FD] -> [FF FF FD FD] byte stuffing and status packet unstuffing
 *   5. COBS + CRC-16 host_frame pack/unpack and bit-error rejection
 *   6. INA226 (R20 Bourns CSS2H-2512R-L300F 0.30 mOhm, CAL=17067) + PA0 (100k/33k) fixed-point math
 *   7. BMI270 12-byte burst conversion (0x68 torso, 0x69 head)
 *   8. 200 Hz Spine supervisor: 100 ms host watchdog, >4.2 A overcurrent, <6.1 V undervolt, estop
 */

#include "board_pins.h"
#include "bmi270_min.h"
#include "dxl_protocol2.h"
#include "host_frame.h"
#include "ina226.h"
#include "spine_controller.h"

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int g_tests_run = 0;
static int g_tests_failed = 0;

#define CHECK(cond, msg) do { \
    g_tests_run++; \
    if (!(cond)) { \
        fprintf(stderr, "FAIL [%s:%d]: %s\n", __FILE__, __LINE__, (msg)); \
        g_tests_failed++; \
    } \
} while (0)

static void test_pin_map_and_topology(void) {
    CHECK(MG_PIN_HOST_TX_PORT == 'A' && MG_PIN_HOST_TX_NUM == 2U, "PA2 USART2_TX (J4.4)");
    CHECK(MG_PIN_HOST_RX_PORT == 'A' && MG_PIN_HOST_RX_NUM == 3U, "PA3 USART2_RX (J4.5)");
    CHECK(MG_PIN_DXL_TX_PORT == 'B' && MG_PIN_DXL_TX_NUM == 10U, "PB10 USART3_TX");
    CHECK(MG_PIN_DXL_RX_PORT == 'B' && MG_PIN_DXL_RX_NUM == 11U, "PB11 USART3_RX");
    CHECK(MG_PIN_DXL_DIR_PORT == 'B' && MG_PIN_DXL_DIR_NUM == 12U, "PB12 DXL_DIR");
    CHECK(MG_PIN_I2C1_SCL_PORT == 'B' && MG_PIN_I2C1_SCL_NUM == 6U, "PB6 I2C1_SCL");
    CHECK(MG_PIN_I2C1_SDA_PORT == 'B' && MG_PIN_I2C1_SDA_NUM == 7U, "PB7 I2C1_SDA");
    CHECK(MG_PIN_VBAT_DIV_PORT == 'A' && MG_PIN_VBAT_DIV_NUM == 0U, "PA0 ADC1_IN1 VBAT_ADC");
    CHECK(MG_PIN_WS2812_PORT == 'A' && MG_PIN_WS2812_NUM == 1U, "PA1 TIM2_CH2 LED_PWM_3V3");
    CHECK(MG_PIN_BUCK_PG_PORT == 'B' && MG_PIN_BUCK_PG_NUM == 0U, "PB0 BUCK_PG input");
    CHECK(MG_PIN_IMU_INT1_PORT == 'B' && MG_PIN_IMU_INT1_NUM == 1U, "PB1 IMU_INT1 input");
    CHECK(MG_PIN_INA_ALERT_PORT == 'B' && MG_PIN_INA_ALERT_NUM == 2U, "PB2 INA_ALERT input");
    CHECK(MG_PIN_HEAD_INT_PORT == 'A' && MG_PIN_HEAD_INT_NUM == 8U, "PA8 HEAD_INT input");

    /* Verify J1 Left Leg = 1..5, J2 Right Leg = 6..10, J3 Neck/Head = 11..14, Beak = 15 */
    CHECK(MG_SERVO_DXL_IDS[0] == 1U && MG_SERVO_DXL_IDS[4] == 5U, "Left Leg (J1) DXL IDs 1..5");
    CHECK(MG_SERVO_DXL_IDS[9] == 6U && MG_SERVO_DXL_IDS[13] == 10U, "Right Leg (J2) DXL IDs 6..10");
    CHECK(MG_SERVO_DXL_IDS[5] == 11U && MG_SERVO_DXL_IDS[8] == 14U, "Neck/Head (J3) DXL IDs 11..14");
    CHECK(MG_SERVO_DXL_IDS[14] == 15U, "Beak (J3) DXL ID 15");

    CHECK(MG_TOTAL_SERVO_COUNT == 15U, "15 XL330 servos");
    CHECK(sizeof(mg_telemetry_payload_t) == MG_TELEMETRY_PAYLOAD_BYTES, "Packed telemetry struct is 194 bytes");
    CHECK(sizeof(mg_cmd_joints_payload_t) == MG_CMD_JOINTS_PAYLOAD_BYTES, "Packed command struct is 38 bytes");
}

static void test_dxl_crc16_and_ping_vector(void) {
    uint8_t pkt[16];
    size_t len = dxl_build_ping(1U, pkt, sizeof(pkt));
    const uint8_t expected[10] = {
        0xFFU, 0xFFU, 0xFDU, 0x00U, 0x01U, 0x03U, 0x00U, 0x01U, 0x19U, 0x4EU
    };
    CHECK(len == 10U, "Ping packet length is 10 bytes");
    CHECK(memcmp(pkt, expected, 10U) == 0, "Ping packet matches ROBOTIS e-Manual byte-for-byte");

    uint8_t buf[256];
    for (size_t i = 0U; i < sizeof(buf); i++) {
        buf[i] = (uint8_t)((i * 73U + 19U) & 0xFFU);
    }
    uint16_t c_tbl = dxl_crc16(0x0000U, buf, sizeof(buf));
    uint16_t c_ref = dxl_crc16_bitwise_ref(0x0000U, buf, sizeof(buf));
    CHECK(c_tbl == c_ref, "Lookup table CRC-16 matches bitwise 0x8005 reference");
}

static void test_dxl_sync_write_and_sync_read_packets(void) {
    uint8_t sw_buf[DXL_MAX_PACKET_BYTES];
    size_t sw_len = dxl_build_sync_write_goal_rad(
        MG_SERVO_DXL_IDS,
        MG_SERVO_DEFAULT_RAD,
        MG_TOTAL_SERVO_COUNT,
        sw_buf,
        sizeof(sw_buf)
    );
    CHECK(sw_len == 89U, "15-servo SyncWrite Goal Position is 89 bytes");
    CHECK(sw_buf[0] == 0xFFU && sw_buf[1] == 0xFFU && sw_buf[2] == 0xFDU && sw_buf[3] == 0x00U, "SyncWrite header");
    CHECK(sw_buf[4] == DXL_BROADCAST_ID, "SyncWrite uses broadcast ID 0xFE");
    uint16_t sw_pkt_len = (uint16_t)sw_buf[5] | ((uint16_t)sw_buf[6] << 8);
    CHECK(sw_pkt_len == 82U, "SyncWrite Length field == 82");
    CHECK(sw_buf[7] == DXL_INST_SYNC_WRITE, "SyncWrite instruction == 0x83");
    CHECK(sw_buf[8] == 116U && sw_buf[9] == 0U, "SyncWrite start address == 116 (Goal Position)");
    CHECK(sw_buf[10] == 4U && sw_buf[11] == 0U, "SyncWrite per-servo data length == 4");

    CHECK(sw_buf[12] == 1U, "First servo ID in SyncWrite is 1");
    int32_t id1_ticks = (int32_t)((uint32_t)sw_buf[13] | ((uint32_t)sw_buf[14] << 8) |
                                  ((uint32_t)sw_buf[15] << 16) | ((uint32_t)sw_buf[16] << 24));
    CHECK(id1_ticks == 2048, "0.0 rad maps to center tick 2048");

    uint16_t sw_crc = (uint16_t)sw_buf[87] | ((uint16_t)sw_buf[88] << 8);
    CHECK(sw_crc == dxl_crc16_bitwise_ref(0U, sw_buf, 87U), "SyncWrite CRC-16 valid");

    uint8_t sr_buf[DXL_MAX_PACKET_BYTES];
    size_t sr_len = dxl_build_sync_read_telemetry(
        MG_SERVO_DXL_IDS,
        MG_TOTAL_SERVO_COUNT,
        sr_buf,
        sizeof(sr_buf)
    );
    CHECK(sr_len == 29U, "15-servo SyncRead telemetry request is 29 bytes");
    CHECK(sr_buf[7] == DXL_INST_SYNC_READ, "SyncRead instruction == 0x82");
    CHECK(sr_buf[8] == 126U && sr_buf[9] == 0U, "SyncRead start address == 126");
    CHECK(sr_buf[10] == 10U && sr_buf[11] == 0U, "SyncRead byte length == 10");
    uint16_t sr_crc = (uint16_t)sr_buf[27] | ((uint16_t)sr_buf[28] << 8);
    CHECK(sr_crc == dxl_crc16_bitwise_ref(0U, sr_buf, 27U), "SyncRead CRC-16 valid");

    uint8_t stream[512];
    size_t stream_len = 0U;
    for (size_t i = 0U; i < MG_TOTAL_SERVO_COUNT; i++) {
        uint8_t id = MG_SERVO_DXL_IDS[i];
        int16_t load_ma = (int16_t)(-120 + (int16_t)(i * 25));
        int32_t vel_raw = (i == 7U) ? (int32_t)0x00FDFFFF : (int32_t)(-20 + (int32_t)(i * 3));
        int32_t pos_ticks = dxl_rad_to_ticks(MG_SERVO_DEFAULT_RAD[i]);
        size_t n = dxl_build_status_telemetry(
            id, 0U, load_ma, vel_raw, pos_ticks,
            &stream[stream_len], sizeof(stream) - stream_len
        );
        CHECK(n >= 21U, "Status packet built");
        if (i == 7U) {
            CHECK(n == 22U, "Byte stuffing inserted extra 0xFD escape byte");
        }
        stream_len += n;
    }

    size_t offset = 0U;
    for (size_t i = 0U; i < MG_TOTAL_SERVO_COUNT; i++) {
        dxl_servo_feedback_t fb;
        size_t consumed = 0U;
        bool ok = dxl_parse_status_telemetry(&stream[offset], stream_len - offset, &fb, &consumed);
        CHECK(ok && consumed > 0U, "Parsed streamed servo status packet");
        CHECK(fb.id == MG_SERVO_DXL_IDS[i], "Parsed servo ID matches");
        CHECK(fb.present_load_ma == (int16_t)(-120 + (int16_t)(i * 25)), "Parsed load mA matches");
        if (i != 7U) {
            CHECK(fabsf(fb.present_pos_rad - MG_SERVO_DEFAULT_RAD[i]) < 0.002f, "Parsed pos rad matches");
        } else {
            CHECK(fb.present_vel_raw == (int32_t)0x00FDFFFF, "Unstuffed velocity matches exact raw pattern");
        }
        offset += consumed;
    }
    CHECK(offset == stream_len, "Entire 15-servo status stream consumed cleanly");
}

static void test_host_cobs_frames(void) {
    mg_spine_state_t st;
    mg_spine_init(&st);
    st.vbat_mv        = 7580U;
    st.bus_5v_mv      = 5010U;
    st.bus_current_ma = 1420;
    st.bus_power_mw   = 7114U;

    mg_telemetry_payload_t telem;
    mg_spine_fill_telemetry(&st, &telem);

    uint8_t wire[HOST_FRAME_MAX_COBS_LEN];
    size_t wire_len = host_frame_pack(HOST_MSG_TELEMETRY, 0x1234U, &telem, sizeof(telem), wire, sizeof(wire));
    CHECK(wire_len > sizeof(telem) && wire_len <= sizeof(wire), "Telemetry COBS frame packed");
    CHECK(wire[wire_len - 1U] == 0x00U, "COBS frame ends with 0x00 delimiter");
    for (size_t i = 0U; i + 1U < wire_len; i++) {
        CHECK(wire[i] != 0x00U, "Zero byte never appears inside COBS body");
    }

    mg_host_decoded_frame_t dec;
    CHECK(host_frame_unpack(wire, wire_len, &dec), "Valid COBS telemetry frame unpacked");
    CHECK(dec.msg_type == HOST_MSG_TELEMETRY && dec.seq == 0x1234U, "Header fields preserved");
    CHECK(dec.payload_len == sizeof(telem), "Payload length preserved");
    CHECK(memcmp(dec.payload, &telem, sizeof(telem)) == 0, "194-byte telemetry payload exact match");

    wire[17] ^= 0x04U;
    CHECK(!host_frame_unpack(wire, wire_len, &dec), "Single-bit corruption rejected by CRC-16");
}

static void test_ina226_and_vbat_adc_fixed_point(void) {
    uint16_t cal = ina226_compute_cal_1ma_lsb_uohm(MG_INA226_SHUNT_UOHM);
    CHECK(MG_INA226_SHUNT_UOHM == 300U, "MG_INA226_SHUNT_UOHM == 300 uOhm (0.30 mOhm)");
    CHECK(cal == MG_INA226_CAL_0P3MOHM_1MA && cal == 17067U,
          "INA226 CAL register == 17067 (0x42AB) for 0.30 mOhm Bourns CSS2H-2512R-L300F");

    /* 4.200 A across 0.30 mOhm (300 uOhm) = 1,260 uV -> raw shunt = 1260 / 2.5 = 504 */
    int16_t raw_shunt = 504;
    CHECK(ina226_shunt_raw_to_uv(raw_shunt) == 1260, "Shunt raw 504 -> 1260 uV");
    CHECK(ina226_shunt_and_cal_to_ma(raw_shunt, cal) == 4200, "Shunt + CAL=17067 -> exact 4200 mA");

    /* 5.000 V 5V_BUS -> raw bus = 5000 / 1.25 = 4000 */
    CHECK(ina226_bus_raw_to_mv(4000U) == 5000U, "Bus raw 4000 -> exact 5000 mV");
    CHECK(ina226_power_raw_to_mw(840U) == 21000U, "Power raw 840 -> 21000 mW");

    /* PA0 VBAT_ADC (R11=100k / R12=33k): at VBAT = 7400 mV, ADC = 2278 -> ~7399 mV */
    uint16_t adc_mv = mg_adc_vbat_div_to_mv(2278U);
    CHECK(adc_mv >= 7395U && adc_mv <= 7405U, "PA0 100k/33k ADC conversion within 5 mV at 7.40 V");
}

static void test_bmi270_burst_conversion(void) {
    uint8_t raw12[12] = {
        0x00U, 0x00U,
        0x00U, 0x00U,
        0x00U, 0x20U, /* acc_z = +8192 (+1g) */
        0xCDU, 0x0CU, /* gyr_x = 3277 (~1.745 rad/s) */
        0x00U, 0x00U,
        0x00U, 0x00U
    };
    bmi270_sample_t s;
    bmi270_convert_burst12(raw12, &s);
    CHECK(s.accel_mg[2] == 1000, "BMI270 +8192 LSB -> +1000 mg");
    CHECK(fabsf(s.projected_gravity[2] + 1.0f) < 0.001f, "Level upright projected_gravity.z == -1.0");
    CHECK(fabsf(s.gyro_rad_s[0] - 1.7453f) < 0.01f, "BMI270 gyro +100 dps -> ~1.745 rad/s");
}

static void test_spine_watchdogs_and_faults(void) {
    mg_spine_state_t st;
    mg_spine_init(&st);

    mg_cmd_joints_payload_t cmd;
    memset(&cmd, 0, sizeof(cmd));
    cmd.cmd_flags = HOST_CMD_FLAG_TORQUE_ENABLE;
    for (size_t i = 0U; i < MG_TOTAL_SERVO_COUNT; i++) {
        cmd.goal_pos_0p1mrad[i] = host_rad_to_0p1mrad(MG_SERVO_DEFAULT_RAD[i]);
    }
    uint8_t wire[HOST_FRAME_MAX_COBS_LEN];
    size_t wlen = host_frame_pack(HOST_MSG_CMD_JOINTS, 1U, &cmd, sizeof(cmd), wire, sizeof(wire));
    mg_host_decoded_frame_t dec;
    CHECK(host_frame_unpack(wire, wlen, &dec), "Command frame unpacked");
    mg_spine_handle_host_frame(&st, &dec, 10000U);
    CHECK(st.torque_enabled, "Torque enabled after valid host command");

    mg_spine_supervise(&st, 90000U, 5000U);
    CHECK(st.torque_enabled && (st.status_flags & SPINE_STATUS_WATCHDOG_TRIPPED) == 0U,
          "Torque still active at 80 ms silence");

    mg_spine_supervise(&st, 115000U, 5000U);
    CHECK(!st.torque_enabled && (st.status_flags & SPINE_STATUS_WATCHDOG_TRIPPED) != 0U,
          "100 ms host watchdog tripped and disabled torque");

    mg_spine_handle_host_frame(&st, &dec, 120000U);
    CHECK(st.torque_enabled, "Torque re-enabled when host resumes");
    st.bus_current_ma = 4500;
    for (uint32_t tick = 1U; tick <= 20U; tick++) {
        mg_spine_supervise(&st, 120000U + tick * 5000U, 5000U);
        mg_spine_handle_host_frame(&st, &dec, 120000U + tick * 5000U);
    }
    CHECK(st.torque_enabled, "Torque still active at exactly 100 ms overcurrent boundary");
    mg_spine_supervise(&st, 225000U, 5000U);
    CHECK(!st.torque_enabled && st.estop_latched &&
          (st.status_flags & SPINE_STATUS_OVERCURRENT_FAULT) != 0U,
          "Sustained >4.2 A overcurrent for >100 ms latched fault and disabled torque");

    st.bus_current_ma = 900;
    cmd.cmd_flags = HOST_CMD_FLAG_TORQUE_ENABLE | HOST_CMD_FLAG_CLEAR_FAULTS;
    wlen = host_frame_pack(HOST_MSG_CMD_JOINTS, 2U, &cmd, sizeof(cmd), wire, sizeof(wire));
    (void)host_frame_unpack(wire, wlen, &dec);
    mg_spine_handle_host_frame(&st, &dec, 230000U);
    CHECK(st.torque_enabled && !st.estop_latched, "Faults cleared and torque restored");

    st.vbat_mv = 5950U;
    mg_spine_supervise(&st, 235000U, 5000U);
    CHECK(!st.torque_enabled && st.estop_latched &&
          (st.status_flags & SPINE_STATUS_UNDERVOLT_FAULT) != 0U,
          "Undervoltage (<6.1 V) latched fault and disabled torque");
}

int main(void) {
    test_pin_map_and_topology();
    test_dxl_crc16_and_ping_vector();
    test_dxl_sync_write_and_sync_read_packets();
    test_host_cobs_frames();
    test_ina226_and_vbat_adc_fixed_point();
    test_bmi270_burst_conversion();
    test_spine_watchdogs_and_faults();

    if (g_tests_failed == 0) {
        printf("OK: Passed all %d Microgoose STM32G431CB firmware host checks.\n", g_tests_run);
        return 0;
    }
    fprintf(stderr, "ERROR: %d of %d firmware checks failed.\n", g_tests_failed, g_tests_run);
    return 1;
}