Compare commits

..

4 Commits

Author SHA1 Message Date
Jason 7cb7688814 chore: add .gitattributes to enforce LF line endings for new files 2026-04-15 13:03:54 +05:45
Jason 86b493a780 feat: CI test suite phases A+B, WaveformConfig separation, dead golden code cleanup
- Phase A: Remove self-blessing golden test from FPGA regression, wire
  MF co-sim (4 scenarios) into run_regression.sh, add opcode count guards
  to cross-layer tests (+3 tests)
- Phase B: Add radar_params.vh parser and architectural param consistency
  tests (+7 tests), add banned stale-value pattern scanner (+1 test)
- Separate WaveformConfig.range_resolution_m (physical, bandwidth-dependent)
  from bin_spacing_m (sample-rate dependent); rename all callers
- Remove 151 lines of dead golden generate/compare code from
  tb_radar_receiver_final.v; testbench now runs structural + bounds only
- Untrack generated MF co-sim CSV files, gitignore tb/golden/ directory

CI: 256 tests total (168 python + 40 cross-layer + 27 FPGA + 21 MCU), all green
2026-04-15 12:45:41 +05:45
Jason c023337949 chore: gitignore sim artifacts (doppler CSV/mem) and MCU test binaries
- Untrack rx_final_doppler_out.csv and golden_doppler.mem (regenerated by tests)
- Add 6 missing MCU test binaries to tests/.gitignore
2026-04-15 10:39:05 +05:45
Jason d259e5c106 fix: align all range/carrier/velocity values to PLFM hardware + FPGA bug fixes
- Correct carrier from 10.525/10 GHz to 10.5 GHz (verified ADF4382 config)
- Correct range-per-bin from 4.8/5.6/781.25 m to 24.0 m (matched-filter)
- Correct velocity resolution from 1.484 to 2.67 m/s/bin (PRI-based)
- Correct processing rate from 4 MSPS to 100 MSPS (post-DDC)
- Correct max range from 307/5000/50000 m to 1536 m (64 bins x 24 m)
- Add WaveformConfig.pri_s field (167 us PRI for velocity calculation)
- Fix short chirp chirp_complete deadlock (Bug A)
- Remove dead short_chirp ports, rename long_chirp to ref_chirp (Bug B)
- Fix stale latency comment 2159 -> 3187 cycles (Bug C)
- Create radar_params.vh as single source of truth for FPGA parameters
- Lower RadarSettings.cpp map_size validation bound from 1000 to 100
- Add PLFM hardware constants to golden_reference.py
- Update all GUI versions, tests, and cross-layer contracts

All 244 tests passing (167 Python + 21 MCU + 29 cross-layer + 27 FPGA)
2026-04-15 10:38:59 +05:45
52 changed files with 1047 additions and 15540 deletions
+21
View File
@@ -0,0 +1,21 @@
# Enforce LF line endings for all text files going forward.
# Existing CRLF files are left as-is to avoid polluting git blame.
* text=auto eol=lf
# Binary files — ensure git doesn't mangle these
*.npy binary
*.h5 binary
*.hdf5 binary
*.png binary
*.jpg binary
*.pdf binary
*.zip binary
*.bin binary
*.mem binary
*.hex binary
*.vvp binary
*.s2p binary
*.s3p binary
*.step binary
*.FCStd binary
*.FCBak binary
+6
View File
@@ -32,6 +32,12 @@
9_Firmware/9_2_FPGA/tb/cosim/rtl_doppler_*.csv
9_Firmware/9_2_FPGA/tb/cosim/compare_doppler_*.csv
9_Firmware/9_2_FPGA/tb/cosim/rtl_multiseg_*.csv
9_Firmware/9_2_FPGA/tb/cosim/rx_final_doppler_out.csv
9_Firmware/9_2_FPGA/tb/cosim/rtl_mf_*.csv
9_Firmware/9_2_FPGA/tb/cosim/compare_mf_*.csv
# Golden reference outputs (regenerated by testbenches)
9_Firmware/9_2_FPGA/tb/golden/
# macOS
.DS_Store
+4 -1
View File
@@ -1,7 +1,10 @@
import numpy as np
# Define parameters
fs = 120e6 # Sampling frequency
# NOTE: This is a standalone LUT generation utility. The production chirp LUT
# is generated by 9_Firmware/9_2_FPGA/tb/cosim/gen_chirp_mem.py with
# CHIRP_BW=20e6 (target: 30e6 Phase 1) and DAC_CLK=120e6.
fs = 120e6 # Sampling frequency (DAC clock from AD9523 OUT10)
Ts = 1 / fs # Sampling time
Tb = 1e-6 # Burst time
Tau = 30e-6 # Pulse repetition time
@@ -6,16 +6,16 @@ RadarSettings::RadarSettings() {
}
void RadarSettings::resetToDefaults() {
system_frequency = 10.0e9; // 10 GHz
chirp_duration_1 = 30.0e-6; // 30 s
chirp_duration_2 = 0.5e-6; // 0.5 s
system_frequency = 10.5e9; // 10.5 GHz (PLFM TX LO, ADF4382 config)
chirp_duration_1 = 30.0e-6; // 30 µs
chirp_duration_2 = 0.5e-6; // 0.5 µs
chirps_per_position = 32;
freq_min = 10.0e6; // 10 MHz
freq_max = 30.0e6; // 30 MHz
prf1 = 1000.0; // 1 kHz
prf2 = 2000.0; // 2 kHz
max_distance = 50000.0; // 50 km
map_size = 50000.0; // 50 km
max_distance = 1536.0; // 1536 m (64 bins × 24 m, 3 km mode)
map_size = 1536.0; // 1536 m
settings_valid = true;
}
@@ -88,7 +88,7 @@ bool RadarSettings::validateSettings() {
if (prf1 < 100 || prf1 > 10000) return false;
if (prf2 < 100 || prf2 > 10000) return false;
if (max_distance < 100 || max_distance > 100000) return false;
if (map_size < 1000 || map_size > 200000) return false;
if (map_size < 100 || map_size > 200000) return false;
return true;
}
@@ -46,9 +46,7 @@ extern "C" {
#include <vector>
#include "stm32_spi.h"
#include "stm32_delay.h"
extern "C" {
#include "um982_gps.h"
}
#include "TinyGPSPlus.h"
extern "C" {
#include "GY_85_HAL.h"
}
@@ -123,8 +121,8 @@ UART_HandleTypeDef huart5;
UART_HandleTypeDef huart3;
/* USER CODE BEGIN PV */
// UM982 dual-antenna GPS receiver
UM982_GPS_t um982;
// The TinyGPSPlus object
TinyGPSPlus gps;
// Global data structures
GPS_Data_t current_gps_data = {0};
@@ -175,7 +173,7 @@ float RADAR_Altitude;
double RADAR_Longitude = 0;
double RADAR_Latitude = 0;
extern uint8_t GUI_start_flag_received; // [STM32-006] Legacy, unused -- kept for linker compat
extern uint8_t GUI_start_flag_received;
//RADAR
@@ -622,8 +620,7 @@ typedef enum {
ERROR_POWER_SUPPLY,
ERROR_TEMPERATURE_HIGH,
ERROR_MEMORY_ALLOC,
ERROR_WATCHDOG_TIMEOUT,
ERROR_COUNT // must be last — used for bounds checking error_strings[]
ERROR_WATCHDOG_TIMEOUT
} SystemError_t;
static SystemError_t last_error = ERROR_NONE;
@@ -634,41 +631,20 @@ static bool system_emergency_state = false;
SystemError_t checkSystemHealth(void) {
SystemError_t current_error = ERROR_NONE;
// 0. Watchdog: detect main-loop stall (checkSystemHealth not called for >60 s).
// Timestamp is captured at function ENTRY and updated unconditionally, so
// any early return from a sub-check below cannot leave a stale value that
// would later trip a spurious ERROR_WATCHDOG_TIMEOUT. A dedicated cold-start
// branch ensures the first call after boot never trips (last_health_check==0
// would otherwise make `HAL_GetTick() - 0 > 60000` true forever after the
// 60-s mark of the init sequence).
static uint32_t last_health_check = 0;
uint32_t now_tick = HAL_GetTick();
if (last_health_check == 0) {
last_health_check = now_tick; // cold start: seed only
} else {
uint32_t elapsed = now_tick - last_health_check;
last_health_check = now_tick; // update BEFORE any early return
if (elapsed > 60000) {
current_error = ERROR_WATCHDOG_TIMEOUT;
DIAG_ERR("SYS", "Health check: Watchdog timeout (>60s since last check)");
return current_error;
}
}
// 1. Check AD9523 Clock Generator
static uint32_t last_clock_check = 0;
if (HAL_GetTick() - last_clock_check > 5000) {
GPIO_PinState s0 = HAL_GPIO_ReadPin(AD9523_STATUS0_GPIO_Port, AD9523_STATUS0_Pin);
GPIO_PinState s1 = HAL_GPIO_ReadPin(AD9523_STATUS1_GPIO_Port, AD9523_STATUS1_Pin);
DIAG_GPIO("CLK", "AD9523 STATUS0", s0);
DIAG_GPIO("CLK", "AD9523 STATUS1", s1);
if (s0 == GPIO_PIN_RESET || s1 == GPIO_PIN_RESET) {
current_error = ERROR_AD9523_CLOCK;
DIAG_ERR("CLK", "AD9523 clock health check FAILED (STATUS0=%d STATUS1=%d)", s0, s1);
return current_error;
}
last_clock_check = HAL_GetTick();
}
if (HAL_GetTick() - last_clock_check > 5000) {
GPIO_PinState s0 = HAL_GPIO_ReadPin(AD9523_STATUS0_GPIO_Port, AD9523_STATUS0_Pin);
GPIO_PinState s1 = HAL_GPIO_ReadPin(AD9523_STATUS1_GPIO_Port, AD9523_STATUS1_Pin);
DIAG_GPIO("CLK", "AD9523 STATUS0", s0);
DIAG_GPIO("CLK", "AD9523 STATUS1", s1);
if (s0 == GPIO_PIN_RESET || s1 == GPIO_PIN_RESET) {
current_error = ERROR_AD9523_CLOCK;
DIAG_ERR("CLK", "AD9523 clock health check FAILED (STATUS0=%d STATUS1=%d)", s0, s1);
return current_error;
}
last_clock_check = HAL_GetTick();
}
// 2. Check ADF4382 Lock Status
bool tx_locked, rx_locked;
@@ -703,34 +679,37 @@ SystemError_t checkSystemHealth(void) {
// 4. Check IMU Communication
static uint32_t last_imu_check = 0;
if (HAL_GetTick() - last_imu_check > 10000) {
if (!GY85_Update(&imu)) {
current_error = ERROR_IMU_COMM;
DIAG_ERR("IMU", "Health check: GY85_Update() FAILED");
return current_error;
}
last_imu_check = HAL_GetTick();
}
if (HAL_GetTick() - last_imu_check > 10000) {
if (!GY85_Update(&imu)) {
current_error = ERROR_IMU_COMM;
DIAG_ERR("IMU", "Health check: GY85_Update() FAILED");
return current_error;
}
last_imu_check = HAL_GetTick();
}
// 5. Check BMP180 Communication
static uint32_t last_bmp_check = 0;
if (HAL_GetTick() - last_bmp_check > 15000) {
double pressure = myBMP.getPressure();
if (pressure < 30000.0 || pressure > 110000.0 || isnan(pressure)) {
current_error = ERROR_BMP180_COMM;
DIAG_ERR("SYS", "Health check: BMP180 pressure out of range: %.0f", pressure);
return current_error;
}
last_bmp_check = HAL_GetTick();
}
if (HAL_GetTick() - last_bmp_check > 15000) {
double pressure = myBMP.getPressure();
if (pressure < 30000.0 || pressure > 110000.0 || isnan(pressure)) {
current_error = ERROR_BMP180_COMM;
DIAG_ERR("SYS", "Health check: BMP180 pressure out of range: %.0f", pressure);
return current_error;
}
last_bmp_check = HAL_GetTick();
}
// 6. Check GPS Communication (30s grace period from boot / last valid fix)
uint32_t gps_fix_age = um982_position_age(&um982);
if (gps_fix_age > 30000) {
current_error = ERROR_GPS_COMM;
DIAG_WARN("SYS", "Health check: GPS no fix for >30s (age=%lu ms)", (unsigned long)gps_fix_age);
return current_error;
}
// 6. Check GPS Communication
static uint32_t last_gps_fix = 0;
if (gps.location.isUpdated()) {
last_gps_fix = HAL_GetTick();
}
if (HAL_GetTick() - last_gps_fix > 30000) {
current_error = ERROR_GPS_COMM;
DIAG_WARN("SYS", "Health check: GPS no fix for >30s");
return current_error;
}
// 7. Check RF Power Amplifier Current
if (PowerAmplifier) {
@@ -755,7 +734,14 @@ SystemError_t checkSystemHealth(void) {
return current_error;
}
// 9. Watchdog check is performed at function entry (see step 0).
// 9. Simple watchdog check
static uint32_t last_health_check = 0;
if (HAL_GetTick() - last_health_check > 60000) {
current_error = ERROR_WATCHDOG_TIMEOUT;
DIAG_ERR("SYS", "Health check: Watchdog timeout (>60s since last check)");
return current_error;
}
last_health_check = HAL_GetTick();
if (current_error != ERROR_NONE) {
DIAG_ERR("SYS", "checkSystemHealth returning error code %d", current_error);
@@ -867,7 +853,7 @@ void handleSystemError(SystemError_t error) {
DIAG_ERR("SYS", "handleSystemError: error=%d error_count=%lu", error, error_count);
char error_msg[100];
static const char* const error_strings[] = {
const char* error_strings[] = {
"No error",
"AD9523 Clock failure",
"ADF4382 TX LO unlocked",
@@ -887,16 +873,9 @@ void handleSystemError(SystemError_t error) {
"Watchdog timeout"
};
static_assert(sizeof(error_strings) / sizeof(error_strings[0]) == ERROR_COUNT,
"error_strings[] and SystemError_t enum are out of sync");
const char* err_name = (error >= 0 && error < (int)(sizeof(error_strings) / sizeof(error_strings[0])))
? error_strings[error]
: "Unknown error";
snprintf(error_msg, sizeof(error_msg),
"ERROR #%d: %s (Count: %lu)\r\n",
error, err_name, error_count);
error, error_strings[error], error_count);
HAL_UART_Transmit(&huart3, (uint8_t*)error_msg, strlen(error_msg), 1000);
// Blink LED pattern based on error code
@@ -906,23 +885,9 @@ void handleSystemError(SystemError_t error) {
HAL_Delay(200);
}
// Critical errors trigger emergency shutdown.
//
// Safety-critical range: any fault that can damage the PAs or leave the
// system in an undefined state must cut the RF rails via Emergency_Stop().
// This covers:
// ERROR_RF_PA_OVERCURRENT .. ERROR_POWER_SUPPLY (9..13) -- PA/supply faults
// ERROR_TEMPERATURE_HIGH (14) -- >75 C on the PA thermal sensors;
// without cutting bias + 5V/5V5/RFPA rails
// the GaN QPA2962 stage can thermal-runaway.
// ERROR_WATCHDOG_TIMEOUT (16) -- health-check loop has stalled (>60 s);
// transmitter state is unknown, safest to
// latch Emergency_Stop rather than rely on
// IWDG reset (which re-energises the rails).
if ((error >= ERROR_RF_PA_OVERCURRENT && error <= ERROR_POWER_SUPPLY) ||
error == ERROR_TEMPERATURE_HIGH ||
error == ERROR_WATCHDOG_TIMEOUT) {
DIAG_ERR("SYS", "CRITICAL ERROR (code %d: %s) -- initiating Emergency_Stop()", error, err_name);
// Critical errors trigger emergency shutdown
if (error >= ERROR_RF_PA_OVERCURRENT && error <= ERROR_POWER_SUPPLY) {
DIAG_ERR("SYS", "CRITICAL ERROR (code %d: %s) -- initiating Emergency_Stop()", error, error_strings[error]);
snprintf(error_msg, sizeof(error_msg),
"CRITICAL ERROR! Initiating emergency shutdown.\r\n");
HAL_UART_Transmit(&huart3, (uint8_t*)error_msg, strlen(error_msg), 1000);
@@ -1055,7 +1020,20 @@ static inline void delay_ms(uint32_t ms) { HAL_Delay(ms); }
// smartDelay removed -- replaced by non-blocking um982_process() in main loop
// This custom version of delay() ensures that the gps object
// is being "fed".
static void smartDelay(unsigned long ms)
{
uint32_t start = HAL_GetTick();
uint8_t ch;
do {
// While there is new data available in UART (non-blocking)
if (HAL_UART_Receive(&huart5, &ch, 1, 0) == HAL_OK) {
gps.encode(ch); // Pass received byte to TinyGPS++ equivalent parser
}
} while (HAL_GetTick() - start < ms);
}
// Small helper to enable DWT cycle counter for microdelay
static void DWT_Init(void)
@@ -1199,14 +1177,7 @@ static int configure_ad9523(void)
// init ad9523 defaults (fills any missing pdata defaults)
DIAG("CLK", "Calling ad9523_init() -- fills pdata defaults");
{
int32_t init_ret = ad9523_init(&init_param);
DIAG("CLK", "ad9523_init() returned %ld", (long)init_ret);
if (init_ret != 0) {
DIAG_ERR("CLK", "ad9523_init() FAILED (ret=%ld)", (long)init_ret);
return -1;
}
}
ad9523_init(&init_param);
/* [Bug #2 FIXED] Removed first ad9523_setup() call that was here.
* It wrote to the chip while still in reset — writes were lost.
@@ -1595,12 +1566,6 @@ int main(void)
Yaw_Sensor = (180*atan2(magRawY,magRawX)/PI) - Mag_Declination;
if(Yaw_Sensor<0)Yaw_Sensor+=360;
// Override magnetometer heading with UM982 dual-antenna heading when available
if (um982_is_heading_valid(&um982)) {
Yaw_Sensor = um982_get_heading(&um982);
}
RxEst_0 = RxEst_1;
RyEst_0 = RyEst_1;
RzEst_0 = RzEst_1;
@@ -1776,38 +1741,14 @@ int main(void)
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////GPS/////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
DIAG_SECTION("GPS INIT (UM982)");
DIAG("GPS", "Initializing UM982 on UART5 @ 115200 (baseline=50cm, tol=3cm)");
if (!um982_init(&um982, &huart5, 50.0f, 3.0f)) {
DIAG_WARN("GPS", "UM982 init: no VERSIONA response -- module may need more time");
// Not fatal: module may still start sending NMEA data after boot
} else {
DIAG("GPS", "UM982 init OK -- VERSIONA received");
for(int i=0; i<10;i++){
smartDelay(1000);
RADAR_Longitude = gps.location.lng();
RADAR_Latitude = gps.location.lat();
}
// Collect GPS data for a few seconds (non-blocking pump)
DIAG("GPS", "Pumping GPS for 5 seconds to acquire initial fix...");
{
uint32_t gps_start = HAL_GetTick();
while (HAL_GetTick() - gps_start < 5000) {
um982_process(&um982);
HAL_Delay(10);
}
}
RADAR_Longitude = um982_get_longitude(&um982);
RADAR_Latitude = um982_get_latitude(&um982);
DIAG("GPS", "Initial position: lat=%.6f lon=%.6f fix=%d sats=%d",
RADAR_Latitude, RADAR_Longitude,
um982_get_fix_quality(&um982), um982_get_num_sats(&um982));
// Re-apply heading after GPS init so the north-alignment stepper move uses
// UM982 dual-antenna heading when available.
if (um982_is_heading_valid(&um982)) {
Yaw_Sensor = um982_get_heading(&um982);
}
//move Stepper to position 1 = 0°
HAL_GPIO_WritePin(STEPPER_CW_P_GPIO_Port, STEPPER_CW_P_Pin, GPIO_PIN_RESET);//Set stepper motor spinning direction to CCW
//move Stepper to position 1 = 0°
HAL_GPIO_WritePin(STEPPER_CW_P_GPIO_Port, STEPPER_CW_P_Pin, GPIO_PIN_RESET);//Set stepper motor spinning direction to CCW
//Point Stepper to North
for(int i= 0;i<(int)(Yaw_Sensor*Stepper_steps/360);i++){
HAL_GPIO_WritePin(STEPPER_CLK_P_GPIO_Port, STEPPER_CLK_P_Pin, GPIO_PIN_SET);
@@ -1829,11 +1770,29 @@ int main(void)
HAL_UART_Transmit(&huart3, (uint8_t*)gps_send_error, sizeof(gps_send_error) - 1, 1000);
}
/* [STM32-006 FIXED] Removed blocking do-while loop that waited for
* usbHandler.isStartFlagReceived(). The production V7 PyQt GUI does not
* send the legacy 4-byte start flag [23,46,158,237], so this loop hung
* the MCU at boot indefinitely. The USB settings handshake (if ever
* re-enabled) should be handled non-blocking in the main loop. */
// Check if start flag was received and settings are ready
do{
if (usbHandler.isStartFlagReceived() &&
usbHandler.getState() == USBHandler::USBState::READY_FOR_DATA) {
const RadarSettings& settings = usbHandler.getSettings();
// Use the settings to configure your radar system
/*
settings.getSystemFrequency();
settings.getChirpDuration1();
settings.getChirpDuration2();
settings.getChirpsPerPosition();
settings.getFreqMin();
settings.getFreqMax();
settings.getPRF1();
settings.getPRF2();
settings.getMaxDistance();
*/
}
}while(!usbHandler.isStartFlagReceived());
/***************************************************************/
/************RF Power Amplifier Powering up sequence************/
@@ -2058,18 +2017,6 @@ int main(void)
}
DIAG("SYS", "Exited safe mode blink loop -- system_emergency_state cleared");
}
//////////////////////////////////////////////////////////////////////////////////////
////////////////////////// GPS: Non-blocking NMEA processing ////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
um982_process(&um982);
// Update position globals continuously
if (um982_is_position_valid(&um982)) {
RADAR_Latitude = um982_get_latitude(&um982);
RADAR_Longitude = um982_get_longitude(&um982);
}
//////////////////////////////////////////////////////////////////////////////////////
////////////////////////// Monitor ADF4382A lock status periodically//////////////////
//////////////////////////////////////////////////////////////////////////////////////
@@ -2620,7 +2567,7 @@ static void MX_UART5_Init(void)
/* USER CODE END UART5_Init 1 */
huart5.Instance = UART5;
huart5.Init.BaudRate = 115200;
huart5.Init.BaudRate = 9600;
huart5.Init.WordLength = UART_WORDLENGTH_8B;
huart5.Init.StopBits = UART_STOPBITS_1;
huart5.Init.Parity = UART_PARITY_NONE;
@@ -1,586 +0,0 @@
/*******************************************************************************
* um982_gps.c -- UM982 dual-antenna GNSS receiver driver implementation
*
* See um982_gps.h for API documentation.
* Command syntax per Unicore N4 Command Reference EN R1.14.
******************************************************************************/
#include "um982_gps.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
/* ========================= Internal helpers ========================== */
/**
* Advance to the next comma-delimited field in an NMEA sentence.
* Returns pointer to the start of the next field (after the comma),
* or NULL if no more commas found before end-of-string or '*'.
*
* Handles empty fields (consecutive commas) correctly by returning
* a pointer to the character after the comma (which may be another comma).
*/
static const char *next_field(const char *p)
{
if (p == NULL) return NULL;
while (*p != '\0' && *p != ',' && *p != '*') {
p++;
}
if (*p == ',') return p + 1;
return NULL; /* End of sentence or checksum marker */
}
/**
* Get the length of the current field (up to next comma, '*', or '\0').
*/
static int field_len(const char *p)
{
int len = 0;
if (p == NULL) return 0;
while (p[len] != '\0' && p[len] != ',' && p[len] != '*') {
len++;
}
return len;
}
/**
* Check if a field is non-empty (has at least one character before delimiter).
*/
static bool field_valid(const char *p)
{
return p != NULL && field_len(p) > 0;
}
/**
* Parse a floating-point value from a field, returning 0.0 if empty.
*/
static double field_to_double(const char *p)
{
if (!field_valid(p)) return 0.0;
return strtod(p, NULL);
}
static float field_to_float(const char *p)
{
return (float)field_to_double(p);
}
static int field_to_int(const char *p)
{
if (!field_valid(p)) return 0;
return (int)strtol(p, NULL, 10);
}
/* ========================= Checksum ================================== */
bool um982_verify_checksum(const char *sentence)
{
if (sentence == NULL || sentence[0] != '$') return false;
const char *p = sentence + 1; /* Skip '$' */
uint8_t computed = 0;
while (*p != '\0' && *p != '*') {
computed ^= (uint8_t)*p;
p++;
}
if (*p != '*') return false; /* No checksum marker found */
p++; /* Skip '*' */
/* Parse 2-char hex checksum */
if (p[0] == '\0' || p[1] == '\0') return false;
char hex_str[3] = { p[0], p[1], '\0' };
unsigned long expected = strtoul(hex_str, NULL, 16);
return computed == (uint8_t)expected;
}
/* ========================= Coordinate parsing ======================== */
double um982_parse_coord(const char *field, char hemisphere)
{
if (field == NULL || field[0] == '\0') return NAN;
/* Find the decimal point to determine degree digit count.
* Latitude: ddmm.mmmm (dot at index 4, degrees = 2)
* Longitude: dddmm.mmmm (dot at index 5, degrees = 3)
* General: degree_digits = dot_position - 2
*/
const char *dot = strchr(field, '.');
if (dot == NULL) return NAN;
int dot_pos = (int)(dot - field);
int deg_digits = dot_pos - 2;
if (deg_digits < 1 || deg_digits > 3) return NAN;
/* Extract degree portion */
double degrees = 0.0;
for (int i = 0; i < deg_digits; i++) {
if (field[i] < '0' || field[i] > '9') return NAN;
degrees = degrees * 10.0 + (field[i] - '0');
}
/* Extract minutes portion (everything from deg_digits onward) */
double minutes = strtod(field + deg_digits, NULL);
if (minutes < 0.0 || minutes >= 60.0) return NAN;
double result = degrees + minutes / 60.0;
/* Apply hemisphere sign */
if (hemisphere == 'S' || hemisphere == 'W') {
result = -result;
}
return result;
}
/* ========================= Sentence parsers ========================== */
/**
* Identify the NMEA sentence type by skipping the 2-char talker ID
* and comparing the 3-letter formatter.
*
* "$GNGGA,..." -> talker="GN", formatter="GGA"
* "$GPTHS,..." -> talker="GP", formatter="THS"
*
* Returns pointer to the formatter (3 chars at sentence+3), or NULL
* if sentence is too short.
*/
static const char *get_formatter(const char *sentence)
{
/* sentence starts with '$', followed by 2-char talker + 3-char formatter */
if (sentence == NULL || strlen(sentence) < 6) return NULL;
return sentence + 3; /* Skip "$XX" -> points to formatter */
}
/**
* Parse GGA sentence — position and fix quality.
*
* Format: $--GGA,time,lat,N/S,lon,E/W,quality,numSat,hdop,alt,M,geoidSep,M,dgpsAge,refID*XX
* field: 1 2 3 4 5 6 7 8 9 10 11 12 13 14
*/
static void parse_gga(UM982_GPS_t *gps, const char *sentence)
{
/* Skip to first field (after "$XXGGA,") */
const char *f = strchr(sentence, ',');
if (f == NULL) return;
f++; /* f -> field 1 (time) */
/* Field 1: UTC time — skip for now */
const char *f2 = next_field(f); /* lat */
const char *f3 = next_field(f2); /* N/S */
const char *f4 = next_field(f3); /* lon */
const char *f5 = next_field(f4); /* E/W */
const char *f6 = next_field(f5); /* quality */
const char *f7 = next_field(f6); /* numSat */
const char *f8 = next_field(f7); /* hdop */
const char *f9 = next_field(f8); /* altitude */
const char *f10 = next_field(f9); /* M */
const char *f11 = next_field(f10); /* geoid sep */
uint32_t now = HAL_GetTick();
/* Parse fix quality first — if 0, position is meaningless */
gps->fix_quality = (uint8_t)field_to_int(f6);
/* Parse coordinates */
if (field_valid(f2) && field_valid(f3)) {
char hem = field_valid(f3) ? *f3 : 'N';
double lat = um982_parse_coord(f2, hem);
if (!isnan(lat)) gps->latitude = lat;
}
if (field_valid(f4) && field_valid(f5)) {
char hem = field_valid(f5) ? *f5 : 'E';
double lon = um982_parse_coord(f4, hem);
if (!isnan(lon)) gps->longitude = lon;
}
/* Number of satellites */
gps->num_satellites = (uint8_t)field_to_int(f7);
/* HDOP */
if (field_valid(f8)) {
gps->hdop = field_to_float(f8);
}
/* Altitude */
if (field_valid(f9)) {
gps->altitude = field_to_float(f9);
}
/* Geoid separation */
if (field_valid(f11)) {
gps->geoid_sep = field_to_float(f11);
}
gps->last_gga_tick = now;
if (gps->fix_quality != UM982_FIX_NONE) {
gps->last_fix_tick = now;
}
}
/**
* Parse RMC sentence — recommended minimum (position, speed, date).
*
* Format: $--RMC,time,status,lat,N/S,lon,E/W,speed,course,date,magVar,E/W,mode*XX
* field: 1 2 3 4 5 6 7 8 9 10 11 12
*/
static void parse_rmc(UM982_GPS_t *gps, const char *sentence)
{
const char *f = strchr(sentence, ',');
if (f == NULL) return;
f++; /* f -> field 1 (time) */
const char *f2 = next_field(f); /* status */
const char *f3 = next_field(f2); /* lat */
const char *f4 = next_field(f3); /* N/S */
const char *f5 = next_field(f4); /* lon */
const char *f6 = next_field(f5); /* E/W */
const char *f7 = next_field(f6); /* speed knots */
const char *f8 = next_field(f7); /* course true */
/* Status */
if (field_valid(f2)) {
gps->rmc_status = *f2;
}
/* Position (only if status = A for valid) */
if (field_valid(f2) && *f2 == 'A') {
if (field_valid(f3) && field_valid(f4)) {
double lat = um982_parse_coord(f3, *f4);
if (!isnan(lat)) gps->latitude = lat;
}
if (field_valid(f5) && field_valid(f6)) {
double lon = um982_parse_coord(f5, *f6);
if (!isnan(lon)) gps->longitude = lon;
}
}
/* Speed (knots) */
if (field_valid(f7)) {
gps->speed_knots = field_to_float(f7);
}
/* Course */
if (field_valid(f8)) {
gps->course_true = field_to_float(f8);
}
gps->last_rmc_tick = HAL_GetTick();
}
/**
* Parse THS sentence — true heading and status (UM982-specific).
*
* Format: $--THS,heading,mode*XX
* field: 1 2
*/
static void parse_ths(UM982_GPS_t *gps, const char *sentence)
{
const char *f = strchr(sentence, ',');
if (f == NULL) return;
f++; /* f -> field 1 (heading) */
const char *f2 = next_field(f); /* mode */
/* Heading */
if (field_valid(f)) {
gps->heading = field_to_float(f);
} else {
gps->heading = NAN;
}
/* Mode */
if (field_valid(f2)) {
gps->heading_mode = *f2;
} else {
gps->heading_mode = 'V'; /* Not valid if missing */
}
gps->last_ths_tick = HAL_GetTick();
}
/**
* Parse VTG sentence — course and speed over ground.
*
* Format: $--VTG,courseTrue,T,courseMag,M,speedKnots,N,speedKmh,K,mode*XX
* field: 1 2 3 4 5 6 7 8 9
*/
static void parse_vtg(UM982_GPS_t *gps, const char *sentence)
{
const char *f = strchr(sentence, ',');
if (f == NULL) return;
f++; /* f -> field 1 (course true) */
const char *f2 = next_field(f); /* T */
const char *f3 = next_field(f2); /* course mag */
const char *f4 = next_field(f3); /* M */
const char *f5 = next_field(f4); /* speed knots */
const char *f6 = next_field(f5); /* N */
const char *f7 = next_field(f6); /* speed km/h */
/* Course true */
if (field_valid(f)) {
gps->course_true = field_to_float(f);
}
/* Speed knots */
if (field_valid(f5)) {
gps->speed_knots = field_to_float(f5);
}
/* Speed km/h */
if (field_valid(f7)) {
gps->speed_kmh = field_to_float(f7);
}
gps->last_vtg_tick = HAL_GetTick();
}
/* ========================= Sentence dispatch ========================= */
void um982_parse_sentence(UM982_GPS_t *gps, const char *sentence)
{
if (sentence == NULL || sentence[0] != '$') return;
/* Verify checksum before parsing */
if (!um982_verify_checksum(sentence)) return;
/* Check for VERSIONA response (starts with '#', not '$') -- handled separately */
/* Actually VERSIONA starts with '#', so it won't enter here. We check in feed(). */
/* Identify sentence type */
const char *fmt = get_formatter(sentence);
if (fmt == NULL) return;
if (strncmp(fmt, "GGA", 3) == 0) {
gps->initialized = true;
parse_gga(gps, sentence);
} else if (strncmp(fmt, "RMC", 3) == 0) {
gps->initialized = true;
parse_rmc(gps, sentence);
} else if (strncmp(fmt, "THS", 3) == 0) {
gps->initialized = true;
parse_ths(gps, sentence);
} else if (strncmp(fmt, "VTG", 3) == 0) {
gps->initialized = true;
parse_vtg(gps, sentence);
}
/* Other sentences silently ignored */
}
/* ========================= Command interface ========================= */
bool um982_send_command(UM982_GPS_t *gps, const char *cmd)
{
if (gps == NULL || gps->huart == NULL || cmd == NULL) return false;
/* Build command with \r\n termination */
char buf[UM982_CMD_BUF_SIZE];
int len = snprintf(buf, sizeof(buf), "%s\r\n", cmd);
if (len <= 0 || (size_t)len >= sizeof(buf)) return false;
HAL_StatusTypeDef status = HAL_UART_Transmit(
gps->huart, (const uint8_t *)buf, (uint16_t)len, 100);
return status == HAL_OK;
}
/* ========================= Line assembly + feed ====================== */
/**
* Process a completed line from the line buffer.
*/
static void process_line(UM982_GPS_t *gps, const char *line)
{
if (line == NULL || line[0] == '\0') return;
/* NMEA sentence starts with '$' */
if (line[0] == '$') {
um982_parse_sentence(gps, line);
return;
}
/* Unicore proprietary response starts with '#' (e.g. #VERSIONA) */
if (line[0] == '#') {
if (strncmp(line + 1, "VERSIONA", 8) == 0) {
gps->version_received = true;
gps->initialized = true;
}
return;
}
}
void um982_feed(UM982_GPS_t *gps, const uint8_t *data, uint16_t len)
{
if (gps == NULL || data == NULL || len == 0) return;
for (uint16_t i = 0; i < len; i++) {
uint8_t ch = data[i];
/* End of line: process if we have content */
if (ch == '\n' || ch == '\r') {
if (gps->line_len > 0 && !gps->line_overflow) {
gps->line_buf[gps->line_len] = '\0';
process_line(gps, gps->line_buf);
}
gps->line_len = 0;
gps->line_overflow = false;
continue;
}
/* Accumulate into line buffer */
if (gps->line_len < UM982_LINE_BUF_SIZE - 1) {
gps->line_buf[gps->line_len++] = (char)ch;
} else {
gps->line_overflow = true;
}
}
}
/* ========================= UART process (production) ================= */
void um982_process(UM982_GPS_t *gps)
{
if (gps == NULL || gps->huart == NULL) return;
/* Read all available bytes from the UART one at a time.
* At 115200 baud (~11.5 KB/s) and a typical main-loop period of ~10 ms,
* we expect ~115 bytes per call — negligible overhead on a 168 MHz STM32.
*
* Note: batch reads (HAL_UART_Receive with Size > 1 and Timeout = 0) are
* NOT safe here because the HAL consumes bytes from the data register as
* it reads them. If fewer than Size bytes are available, the consumed
* bytes are lost (HAL_TIMEOUT is returned and the caller has no way to
* know how many bytes were actually placed into the buffer). */
uint8_t ch;
while (HAL_UART_Receive(gps->huart, &ch, 1, 0) == HAL_OK) {
um982_feed(gps, &ch, 1);
}
}
/* ========================= Validity checks =========================== */
bool um982_is_heading_valid(const UM982_GPS_t *gps)
{
if (gps == NULL) return false;
if (isnan(gps->heading)) return false;
/* Mode must be Autonomous or Differential */
if (gps->heading_mode != 'A' && gps->heading_mode != 'D') return false;
/* Check age */
uint32_t age = HAL_GetTick() - gps->last_ths_tick;
return age < UM982_HEADING_TIMEOUT_MS;
}
bool um982_is_position_valid(const UM982_GPS_t *gps)
{
if (gps == NULL) return false;
if (gps->fix_quality == UM982_FIX_NONE) return false;
/* Check age of the last valid fix */
uint32_t age = HAL_GetTick() - gps->last_fix_tick;
return age < UM982_POSITION_TIMEOUT_MS;
}
uint32_t um982_heading_age(const UM982_GPS_t *gps)
{
if (gps == NULL) return UINT32_MAX;
return HAL_GetTick() - gps->last_ths_tick;
}
uint32_t um982_position_age(const UM982_GPS_t *gps)
{
if (gps == NULL) return UINT32_MAX;
return HAL_GetTick() - gps->last_fix_tick;
}
/* ========================= Initialization ============================ */
bool um982_init(UM982_GPS_t *gps, UART_HandleTypeDef *huart,
float baseline_cm, float tolerance_cm)
{
if (gps == NULL || huart == NULL) return false;
/* Zero-init entire structure */
memset(gps, 0, sizeof(UM982_GPS_t));
gps->huart = huart;
gps->heading = NAN;
gps->heading_mode = 'V';
gps->rmc_status = 'V';
gps->speed_knots = 0.0f;
/* Seed fix timestamp so position_age() returns ~0 instead of uptime.
* Gives the module a full 30s grace window from init to acquire a fix
* before the health check fires ERROR_GPS_COMM. */
gps->last_fix_tick = HAL_GetTick();
gps->speed_kmh = 0.0f;
gps->course_true = 0.0f;
/* Step 1: Stop all current output to get a clean slate */
um982_send_command(gps, "UNLOG");
HAL_Delay(100);
/* Step 2: Configure heading mode
* Per N4 Reference 4.18: CONFIG HEADING FIXLENGTH (default mode)
* "The distance between ANT1 and ANT2 is fixed. They move synchronously." */
um982_send_command(gps, "CONFIG HEADING FIXLENGTH");
HAL_Delay(50);
/* Step 3: Set baseline length if specified
* Per N4 Reference: CONFIG HEADING LENGTH <cm> <tolerance_cm>
* "parameter1: Fixed baseline length (cm), valid range >= 0"
* "parameter2: Tolerable error margin (cm), valid range > 0" */
if (baseline_cm > 0.0f) {
char cmd[64];
if (tolerance_cm > 0.0f) {
snprintf(cmd, sizeof(cmd), "CONFIG HEADING LENGTH %.0f %.0f",
baseline_cm, tolerance_cm);
} else {
snprintf(cmd, sizeof(cmd), "CONFIG HEADING LENGTH %.0f",
baseline_cm);
}
um982_send_command(gps, cmd);
HAL_Delay(50);
}
/* Step 4: Enable NMEA output sentences on COM2.
* Per N4 Reference: "When requesting NMEA messages, users should add GP
* before each command name"
*
* We target COM2 because the ELT0213 board (GNSS.STORE) exposes COM2
* (RXD2/TXD2) on its 12-pin JST connector (pins 5 & 6). The STM32
* UART5 (PC12-TX, PD2-RX) connects to these pins via JP8.
* COM2 defaults to 115200 baud — matching our UART5 config. */
um982_send_command(gps, "GPGGA COM2 1"); /* GGA at 1 Hz */
HAL_Delay(50);
um982_send_command(gps, "GPRMC COM2 1"); /* RMC at 1 Hz */
HAL_Delay(50);
um982_send_command(gps, "GPTHS COM2 0.2"); /* THS at 5 Hz (heading primary) */
HAL_Delay(50);
/* Step 5: Skip SAVECONFIG -- NMEA config is re-sent every boot anyway.
* Saving to NVM on every power cycle would wear flash. If persistent
* config is needed, call um982_send_command(gps, "SAVECONFIG") once
* during commissioning. */
/* Step 6: Query version to verify communication */
gps->version_received = false;
um982_send_command(gps, "VERSIONA");
/* Wait for VERSIONA response (non-blocking poll) */
uint32_t start = HAL_GetTick();
while (!gps->version_received &&
(HAL_GetTick() - start) < UM982_INIT_TIMEOUT_MS) {
um982_process(gps);
HAL_Delay(10);
}
gps->initialized = gps->version_received;
return gps->initialized;
}
@@ -1,213 +0,0 @@
/*******************************************************************************
* um982_gps.h -- UM982 dual-antenna GNSS receiver driver
*
* Parses NMEA sentences (GGA, RMC, THS, VTG) from the Unicore UM982 module
* and provides position, heading, and velocity data.
*
* Design principles:
* - Non-blocking: process() reads available UART bytes without waiting
* - Correct NMEA parsing: proper tokenizer handles empty fields
* - Longitude handles 3-digit degrees (dddmm.mmmm) via decimal-point detection
* - Checksum verified on every sentence
* - Command syntax verified against Unicore N4 Command Reference EN R1.14
*
* Hardware: UM982 on UART5 @ 115200 baud, dual-antenna heading mode
******************************************************************************/
#ifndef UM982_GPS_H
#define UM982_GPS_H
#include <stdint.h>
#include <stdbool.h>
#include <math.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Forward-declare the HAL UART handle type. The real definition comes from
* stm32f7xx_hal.h (production) or stm32_hal_mock.h (tests). */
#ifndef STM32_HAL_MOCK_H
#include "stm32f7xx_hal.h"
#else
/* Already included via mock -- nothing to do */
#endif
/* ========================= Constants ================================= */
#define UM982_RX_BUF_SIZE 512 /* Ring buffer for incoming UART bytes */
#define UM982_LINE_BUF_SIZE 96 /* Max NMEA sentence (82 chars + margin) */
#define UM982_CMD_BUF_SIZE 128 /* Outgoing command buffer */
#define UM982_INIT_TIMEOUT_MS 3000 /* Timeout waiting for VERSIONA response */
/* Fix quality values (from GGA field 6) */
#define UM982_FIX_NONE 0
#define UM982_FIX_GPS 1
#define UM982_FIX_DGPS 2
#define UM982_FIX_RTK_FIXED 4
#define UM982_FIX_RTK_FLOAT 5
/* Validity timeout defaults (ms) */
#define UM982_HEADING_TIMEOUT_MS 2000
#define UM982_POSITION_TIMEOUT_MS 5000
/* ========================= Data Types ================================ */
typedef struct {
/* Position */
double latitude; /* Decimal degrees, positive = North */
double longitude; /* Decimal degrees, positive = East */
float altitude; /* Meters above MSL */
float geoid_sep; /* Geoid separation (meters) */
/* Heading (from dual-antenna THS) */
float heading; /* True heading 0-360 degrees, NAN if invalid */
char heading_mode; /* A=autonomous, D=diff, E=est, M=manual, S=sim, V=invalid */
/* Velocity */
float speed_knots; /* Speed over ground (knots) */
float speed_kmh; /* Speed over ground (km/h) */
float course_true; /* Course over ground (degrees true) */
/* Quality */
uint8_t fix_quality; /* 0=none, 1=GPS, 2=DGPS, 4=RTK fixed, 5=RTK float */
uint8_t num_satellites; /* Satellites used in fix */
float hdop; /* Horizontal dilution of precision */
/* RMC status */
char rmc_status; /* A=valid, V=warning */
/* Timestamps (HAL_GetTick() at last update) */
uint32_t last_fix_tick; /* Last valid GGA fix (fix_quality > 0) */
uint32_t last_gga_tick;
uint32_t last_rmc_tick;
uint32_t last_ths_tick;
uint32_t last_vtg_tick;
/* Communication state */
bool initialized; /* VERSIONA or supported NMEA traffic seen */
bool version_received; /* VERSIONA response seen */
/* ---- Internal parser state (not for external use) ---- */
/* Ring buffer */
uint8_t rx_buf[UM982_RX_BUF_SIZE];
uint16_t rx_head; /* Write index */
uint16_t rx_tail; /* Read index */
/* Line assembler */
char line_buf[UM982_LINE_BUF_SIZE];
uint8_t line_len;
bool line_overflow; /* Current line exceeded buffer */
/* UART handle */
UART_HandleTypeDef *huart;
} UM982_GPS_t;
/* ========================= Public API ================================ */
/**
* Initialize the UM982_GPS_t structure and configure the module.
*
* Sends: UNLOG, CONFIG HEADING, optional CONFIG HEADING LENGTH,
* GPGGA, GPRMC, GPTHS
* Queries VERSIONA to verify communication.
*
* @param gps Pointer to UM982_GPS_t instance
* @param huart UART handle (e.g. &huart5)
* @param baseline_cm Distance between antennas in cm (0 = use module default)
* @param tolerance_cm Baseline tolerance in cm (0 = use module default)
* @return true if VERSIONA response received within timeout
*/
bool um982_init(UM982_GPS_t *gps, UART_HandleTypeDef *huart,
float baseline_cm, float tolerance_cm);
/**
* Process available UART data. Call from main loop — non-blocking.
*
* Reads all available bytes from UART, assembles lines, and dispatches
* complete NMEA sentences to the appropriate parser.
*
* @param gps Pointer to UM982_GPS_t instance
*/
void um982_process(UM982_GPS_t *gps);
/**
* Feed raw bytes directly into the parser (useful for testing).
* In production, um982_process() calls this internally after UART read.
*
* @param gps Pointer to UM982_GPS_t instance
* @param data Pointer to byte array
* @param len Number of bytes
*/
void um982_feed(UM982_GPS_t *gps, const uint8_t *data, uint16_t len);
/* ---- Getters ---- */
static inline float um982_get_heading(const UM982_GPS_t *gps) { return gps->heading; }
static inline double um982_get_latitude(const UM982_GPS_t *gps) { return gps->latitude; }
static inline double um982_get_longitude(const UM982_GPS_t *gps) { return gps->longitude; }
static inline float um982_get_altitude(const UM982_GPS_t *gps) { return gps->altitude; }
static inline uint8_t um982_get_fix_quality(const UM982_GPS_t *gps) { return gps->fix_quality; }
static inline uint8_t um982_get_num_sats(const UM982_GPS_t *gps) { return gps->num_satellites; }
static inline float um982_get_hdop(const UM982_GPS_t *gps) { return gps->hdop; }
static inline float um982_get_speed_knots(const UM982_GPS_t *gps) { return gps->speed_knots; }
static inline float um982_get_speed_kmh(const UM982_GPS_t *gps) { return gps->speed_kmh; }
static inline float um982_get_course(const UM982_GPS_t *gps) { return gps->course_true; }
/**
* Check if heading is valid (mode A or D, and within timeout).
*/
bool um982_is_heading_valid(const UM982_GPS_t *gps);
/**
* Check if position is valid (fix_quality > 0, and within timeout).
*/
bool um982_is_position_valid(const UM982_GPS_t *gps);
/**
* Get age of last heading update in milliseconds.
*/
uint32_t um982_heading_age(const UM982_GPS_t *gps);
/**
* Get age of the last valid position fix in milliseconds.
*/
uint32_t um982_position_age(const UM982_GPS_t *gps);
/* ========================= Internal (exposed for testing) ============ */
/**
* Verify NMEA checksum. Returns true if valid.
* Sentence must start with '$' and contain '*XX' before termination.
*/
bool um982_verify_checksum(const char *sentence);
/**
* Parse a complete NMEA line (with $ prefix and *XX checksum).
* Dispatches to GGA/RMC/THS/VTG parsers as appropriate.
*/
void um982_parse_sentence(UM982_GPS_t *gps, const char *sentence);
/**
* Parse NMEA coordinate string to decimal degrees.
* Works for both latitude (ddmm.mmmm) and longitude (dddmm.mmmm)
* by detecting the decimal point position.
*
* @param field NMEA coordinate field (e.g. "4404.14036" or "12118.85961")
* @param hemisphere 'N', 'S', 'E', or 'W'
* @return Decimal degrees (negative for S/W), or NAN on parse error
*/
double um982_parse_coord(const char *field, char hemisphere);
/**
* Send a command to the UM982. Appends \r\n automatically.
* @return true if UART transmit succeeded
*/
bool um982_send_command(UM982_GPS_t *gps, const char *cmd);
#ifdef __cplusplus
}
#endif
#endif /* UM982_GPS_H */
+10 -24
View File
@@ -3,38 +3,24 @@
*.dSYM/
# Test binaries (built by Makefile)
# TESTS_WITH_REAL
test_bug1_timed_sync_init_ordering
test_bug2_ad9523_double_setup
test_bug3_timed_sync_noop
test_bug4_phase_shift_before_check
test_bug5_fine_phase_gpio_only
test_bug9_platform_ops_null
test_bug10_spi_cs_not_toggled
test_bug15_htim3_dangling_extern
# TESTS_MOCK_ONLY
test_bug2_ad9523_double_setup
test_bug6_timer_variable_collision
test_bug7_gpio_pin_conflict
test_bug8_uart_commented_out
test_bug14_diag_section_args
test_gap3_emergency_stop_rails
# TESTS_STANDALONE
test_bug9_platform_ops_null
test_bug10_spi_cs_not_toggled
test_bug11_platform_spi_transmit_only
test_bug12_pa_cal_loop_inverted
test_bug13_dac2_adc_buffer_mismatch
test_bug14_diag_section_args
test_bug15_htim3_dangling_extern
test_agc_outer_loop
test_gap3_emergency_state_ordering
test_gap3_emergency_stop_rails
test_gap3_idq_periodic_reread
test_gap3_iwdg_config
test_gap3_temperature_max
test_gap3_idq_periodic_reread
test_gap3_emergency_state_ordering
test_gap3_overtemp_emergency_stop
test_gap3_health_watchdog_cold_start
# TESTS_WITH_PLATFORM
test_bug11_platform_spi_transmit_only
# TESTS_WITH_CXX
test_agc_outer_loop
# Manual / one-off test builds
test_um982_gps
+3 -39
View File
@@ -27,10 +27,6 @@ CXX_LIB_DIR := ../9_1_1_C_Cpp_Libraries
CXX_SRCS := $(CXX_LIB_DIR)/ADAR1000_AGC.cpp $(CXX_LIB_DIR)/ADAR1000_Manager.cpp
CXX_OBJS := ADAR1000_AGC.o ADAR1000_Manager.o
# GPS driver source
GPS_SRC := ../9_1_3_C_Cpp_Code/um982_gps.c
GPS_OBJ := um982_gps.o
# Real source files compiled against mock headers
REAL_SRC := ../9_1_1_C_Cpp_Libraries/adf4382a_manager.c
@@ -68,9 +64,7 @@ TESTS_STANDALONE := test_bug12_pa_cal_loop_inverted \
test_gap3_iwdg_config \
test_gap3_temperature_max \
test_gap3_idq_periodic_reread \
test_gap3_emergency_state_ordering \
test_gap3_overtemp_emergency_stop \
test_gap3_health_watchdog_cold_start
test_gap3_emergency_state_ordering
# Tests that need platform_noos_stm32.o + mocks
TESTS_WITH_PLATFORM := test_bug11_platform_spi_transmit_only
@@ -78,15 +72,11 @@ TESTS_WITH_PLATFORM := test_bug11_platform_spi_transmit_only
# C++ tests (AGC outer loop)
TESTS_WITH_CXX := test_agc_outer_loop
# GPS driver tests (need mocks + GPS source + -lm)
TESTS_GPS := test_um982_gps
ALL_TESTS := $(TESTS_WITH_REAL) $(TESTS_MOCK_ONLY) $(TESTS_STANDALONE) $(TESTS_WITH_PLATFORM) $(TESTS_WITH_CXX) $(TESTS_GPS)
ALL_TESTS := $(TESTS_WITH_REAL) $(TESTS_MOCK_ONLY) $(TESTS_STANDALONE) $(TESTS_WITH_PLATFORM) $(TESTS_WITH_CXX)
.PHONY: all build test clean \
$(addprefix test_,bug1 bug2 bug3 bug4 bug5 bug6 bug7 bug8 bug9 bug10 bug11 bug12 bug13 bug14 bug15) \
test_gap3_estop test_gap3_iwdg test_gap3_temp test_gap3_idq test_gap3_order \
test_gap3_overtemp test_gap3_wdog
test_gap3_estop test_gap3_iwdg test_gap3_temp test_gap3_idq test_gap3_order
all: build test
@@ -172,12 +162,6 @@ test_gap3_idq_periodic_reread: test_gap3_idq_periodic_reread.c
test_gap3_emergency_state_ordering: test_gap3_emergency_state_ordering.c
$(CC) $(CFLAGS) $< -o $@
test_gap3_overtemp_emergency_stop: test_gap3_overtemp_emergency_stop.c
$(CC) $(CFLAGS) $< -o $@
test_gap3_health_watchdog_cold_start: test_gap3_health_watchdog_cold_start.c
$(CC) $(CFLAGS) $< -o $@
# Tests that need platform_noos_stm32.o + mocks
$(TESTS_WITH_PLATFORM): %: %.c $(MOCK_OBJS) $(PLATFORM_OBJ)
$(CC) $(CFLAGS) $(INCLUDES) $< $(MOCK_OBJS) $(PLATFORM_OBJ) -o $@
@@ -200,20 +184,6 @@ test_agc_outer_loop: test_agc_outer_loop.cpp $(CXX_OBJS) $(MOCK_OBJS)
test_agc: test_agc_outer_loop
./test_agc_outer_loop
# --- GPS driver rules ---
$(GPS_OBJ): $(GPS_SRC)
$(CC) $(CFLAGS) $(INCLUDES) -I../9_1_3_C_Cpp_Code -c $< -o $@
# Note: test includes um982_gps.c directly for white-box testing (static fn access)
test_um982_gps: test_um982_gps.c $(MOCK_OBJS)
$(CC) $(CFLAGS) $(INCLUDES) -I../9_1_3_C_Cpp_Code $< $(MOCK_OBJS) -lm -o $@
# Convenience target
.PHONY: test_gps
test_gps: test_um982_gps
./test_um982_gps
# --- Individual test targets ---
test_bug1: test_bug1_timed_sync_init_ordering
@@ -276,12 +246,6 @@ test_gap3_idq: test_gap3_idq_periodic_reread
test_gap3_order: test_gap3_emergency_state_ordering
./test_gap3_emergency_state_ordering
test_gap3_overtemp: test_gap3_overtemp_emergency_stop
./test_gap3_overtemp_emergency_stop
test_gap3_wdog: test_gap3_health_watchdog_cold_start
./test_gap3_health_watchdog_cold_start
# --- Clean ---
clean:
@@ -21,7 +21,6 @@ SPI_HandleTypeDef hspi4 = { .id = 4 };
I2C_HandleTypeDef hi2c1 = { .id = 1 };
I2C_HandleTypeDef hi2c2 = { .id = 2 };
UART_HandleTypeDef huart3 = { .id = 3 };
UART_HandleTypeDef huart5 = { .id = 5 }; /* GPS UART */
ADC_HandleTypeDef hadc3 = { .id = 3 };
TIM_HandleTypeDef htim3 = { .id = 3 };
@@ -35,26 +34,6 @@ uint32_t mock_tick = 0;
/* ========================= Printf control ========================= */
int mock_printf_enabled = 0;
/* ========================= Mock UART TX capture =================== */
uint8_t mock_uart_tx_buf[MOCK_UART_TX_BUF_SIZE];
uint16_t mock_uart_tx_len = 0;
/* ========================= Mock UART RX buffer ==================== */
#define MOCK_UART_RX_SLOTS 8
static struct {
uint32_t uart_id;
uint8_t buf[MOCK_UART_RX_BUF_SIZE];
uint16_t head;
uint16_t tail;
} mock_uart_rx[MOCK_UART_RX_SLOTS];
void mock_uart_tx_clear(void)
{
mock_uart_tx_len = 0;
memset(mock_uart_tx_buf, 0, sizeof(mock_uart_tx_buf));
}
/* ========================= Mock GPIO read ========================= */
#define GPIO_READ_TABLE_SIZE 32
static struct {
@@ -70,9 +49,6 @@ void spy_reset(void)
mock_tick = 0;
mock_printf_enabled = 0;
memset(gpio_read_table, 0, sizeof(gpio_read_table));
memset(mock_uart_rx, 0, sizeof(mock_uart_rx));
mock_uart_tx_len = 0;
memset(mock_uart_tx_buf, 0, sizeof(mock_uart_tx_buf));
}
const SpyRecord *spy_get(int index)
@@ -209,83 +185,6 @@ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, const uint8_t *pD
.value = Timeout,
.extra = huart
});
/* Capture TX data for test inspection */
for (uint16_t i = 0; i < Size && mock_uart_tx_len < MOCK_UART_TX_BUF_SIZE; i++) {
mock_uart_tx_buf[mock_uart_tx_len++] = pData[i];
}
return HAL_OK;
}
/* ========================= Mock UART RX helpers ====================== */
/* find_rx_slot, mock_uart_rx_load, etc. use the mock_uart_rx declared above */
static int find_rx_slot(UART_HandleTypeDef *huart)
{
if (huart == NULL) return -1;
/* Find existing slot */
for (int i = 0; i < MOCK_UART_RX_SLOTS; i++) {
if (mock_uart_rx[i].uart_id == huart->id && mock_uart_rx[i].head != mock_uart_rx[i].tail) {
return i;
}
if (mock_uart_rx[i].uart_id == huart->id) {
return i;
}
}
/* Find empty slot */
for (int i = 0; i < MOCK_UART_RX_SLOTS; i++) {
if (mock_uart_rx[i].uart_id == 0) {
mock_uart_rx[i].uart_id = huart->id;
return i;
}
}
return -1;
}
void mock_uart_rx_load(UART_HandleTypeDef *huart, const uint8_t *data, uint16_t len)
{
int slot = find_rx_slot(huart);
if (slot < 0) return;
mock_uart_rx[slot].uart_id = huart->id;
for (uint16_t i = 0; i < len; i++) {
uint16_t next = (mock_uart_rx[slot].head + 1) % MOCK_UART_RX_BUF_SIZE;
if (next == mock_uart_rx[slot].tail) break; /* Buffer full */
mock_uart_rx[slot].buf[mock_uart_rx[slot].head] = data[i];
mock_uart_rx[slot].head = next;
}
}
void mock_uart_rx_clear(UART_HandleTypeDef *huart)
{
int slot = find_rx_slot(huart);
if (slot < 0) return;
mock_uart_rx[slot].head = 0;
mock_uart_rx[slot].tail = 0;
}
HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData,
uint16_t Size, uint32_t Timeout)
{
(void)Timeout;
int slot = find_rx_slot(huart);
if (slot < 0) return HAL_TIMEOUT;
for (uint16_t i = 0; i < Size; i++) {
if (mock_uart_rx[slot].head == mock_uart_rx[slot].tail) {
return HAL_TIMEOUT; /* No more data */
}
pData[i] = mock_uart_rx[slot].buf[mock_uart_rx[slot].tail];
mock_uart_rx[slot].tail = (mock_uart_rx[slot].tail + 1) % MOCK_UART_RX_BUF_SIZE;
}
spy_push((SpyRecord){
.type = SPY_UART_RX,
.port = NULL,
.pin = Size,
.value = Timeout,
.extra = huart
});
return HAL_OK;
}
@@ -105,7 +105,6 @@ typedef struct {
extern SPI_HandleTypeDef hspi1, hspi4;
extern I2C_HandleTypeDef hi2c1, hi2c2;
extern UART_HandleTypeDef huart3;
extern UART_HandleTypeDef huart5; /* GPS UART */
extern ADC_HandleTypeDef hadc3;
extern TIM_HandleTypeDef htim3; /* Timer for DELADJ PWM */
@@ -140,7 +139,6 @@ typedef enum {
SPY_TIM_SET_COMPARE,
SPY_SPI_TRANSMIT_RECEIVE,
SPY_SPI_TRANSMIT,
SPY_UART_RX,
} SpyCallType;
typedef struct {
@@ -189,23 +187,6 @@ void HAL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin);
uint32_t HAL_GetTick(void);
void HAL_Delay(uint32_t Delay);
HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size, uint32_t Timeout);
HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout);
/* ========================= Mock UART RX buffer ======================= */
/* Inject bytes into the mock UART RX buffer for a specific UART handle.
* HAL_UART_Receive will return these bytes one at a time. */
#define MOCK_UART_RX_BUF_SIZE 2048
void mock_uart_rx_load(UART_HandleTypeDef *huart, const uint8_t *data, uint16_t len);
void mock_uart_rx_clear(UART_HandleTypeDef *huart);
/* Capture buffer for UART TX data (to verify commands sent to GPS module) */
#define MOCK_UART_TX_BUF_SIZE 2048
extern uint8_t mock_uart_tx_buf[MOCK_UART_TX_BUF_SIZE];
extern uint16_t mock_uart_tx_len;
void mock_uart_tx_clear(void);
/* ========================= SPI stubs ============================== */
@@ -34,25 +34,22 @@ static void Mock_Emergency_Stop(void)
state_was_true_when_estop_called = system_emergency_state;
}
/* Error codes (subset matching main.cpp SystemError_t) */
/* Error codes (subset matching main.cpp) */
typedef enum {
ERROR_NONE = 0,
ERROR_RF_PA_OVERCURRENT = 9,
ERROR_RF_PA_BIAS = 10,
ERROR_STEPPER_MOTOR = 11,
ERROR_STEPPER_FAULT = 11,
ERROR_FPGA_COMM = 12,
ERROR_POWER_SUPPLY = 13,
ERROR_TEMPERATURE_HIGH = 14,
ERROR_MEMORY_ALLOC = 15,
ERROR_WATCHDOG_TIMEOUT = 16,
} SystemError_t;
/* Extracted critical-error handling logic (matches post-fix main.cpp predicate) */
/* Extracted critical-error handling logic (post-fix ordering) */
static void simulate_handleSystemError_critical(SystemError_t error)
{
if ((error >= ERROR_RF_PA_OVERCURRENT && error <= ERROR_POWER_SUPPLY) ||
error == ERROR_TEMPERATURE_HIGH ||
error == ERROR_WATCHDOG_TIMEOUT) {
/* Only critical errors (PA overcurrent through power supply) trigger e-stop */
if (error >= ERROR_RF_PA_OVERCURRENT && error <= ERROR_POWER_SUPPLY) {
/* FIX 5: set flag BEFORE calling Emergency_Stop */
system_emergency_state = true;
Mock_Emergency_Stop();
@@ -96,39 +93,17 @@ int main(void)
assert(state_was_true_when_estop_called == true);
printf("PASS\n");
/* Test 4: Overtemp → MUST trigger e-stop (was incorrectly non-critical before fix) */
printf(" Test 4: Overtemp triggers e-stop... ");
/* Test 4: Non-critical error → no e-stop, flag stays false */
printf(" Test 4: Non-critical error (no e-stop)... ");
system_emergency_state = false;
emergency_stop_called = false;
state_was_true_when_estop_called = false;
simulate_handleSystemError_critical(ERROR_TEMPERATURE_HIGH);
assert(emergency_stop_called == true);
assert(system_emergency_state == true);
assert(state_was_true_when_estop_called == true);
printf("PASS\n");
/* Test 5: Watchdog timeout → MUST trigger e-stop */
printf(" Test 5: Watchdog timeout triggers e-stop... ");
system_emergency_state = false;
emergency_stop_called = false;
state_was_true_when_estop_called = false;
simulate_handleSystemError_critical(ERROR_WATCHDOG_TIMEOUT);
assert(emergency_stop_called == true);
assert(system_emergency_state == true);
assert(state_was_true_when_estop_called == true);
printf("PASS\n");
/* Test 6: Non-critical error (memory alloc) → no e-stop */
printf(" Test 6: Non-critical error (no e-stop)... ");
system_emergency_state = false;
emergency_stop_called = false;
simulate_handleSystemError_critical(ERROR_MEMORY_ALLOC);
assert(emergency_stop_called == false);
assert(system_emergency_state == false);
printf("PASS\n");
/* Test 7: ERROR_NONE → no e-stop */
printf(" Test 7: ERROR_NONE (no action)... ");
/* Test 5: ERROR_NONE → no e-stop */
printf(" Test 5: ERROR_NONE (no action)... ");
system_emergency_state = false;
emergency_stop_called = false;
simulate_handleSystemError_critical(ERROR_NONE);
@@ -136,6 +111,6 @@ int main(void)
assert(system_emergency_state == false);
printf("PASS\n");
printf("\n=== Gap-3 Fix 5: ALL 7 TESTS PASSED ===\n\n");
printf("\n=== Gap-3 Fix 5: ALL TESTS PASSED ===\n\n");
return 0;
}
@@ -1,132 +0,0 @@
/*******************************************************************************
* test_gap3_health_watchdog_cold_start.c
*
* Safety bug: checkSystemHealth()'s internal watchdog (step 9, pre-fix) had two
* linked defects that, once ERROR_WATCHDOG_TIMEOUT was escalated to
* Emergency_Stop() by the overtemp/watchdog PR, would false-latch the radar:
*
* (1) Cold-start false trip:
* static uint32_t last_health_check = 0;
* if (HAL_GetTick() - last_health_check > 60000) { ... }
* On the very first call, last_health_check == 0, so once the MCU has
* been up >60 s (which is typical after the ADAR1000 / AD9523 / ADF4382
* init sequence) the subtraction `now - 0` exceeds 60 000 ms and the
* watchdog trips spuriously.
*
* (2) Stale-timestamp after early returns:
* last_health_check = HAL_GetTick(); // at END of function
* Every earlier sub-check (IMU, BMP180, GPS, PA Idq, temperature) has an
* `if (fault) return current_error;` path that skips the update. After a
* cumulative 60 s of transient faults, the next clean call compares
* `now` against the long-stale `last_health_check` and trips.
*
* After fix: Watchdog logic moved to function ENTRY. A dedicated cold-start
* branch seeds the timestamp on the first call without checking.
* On every subsequent call, the elapsed delta is captured FIRST
* and last_health_check is updated BEFORE any sub-check runs, so
* early returns no longer leave a stale value.
*
* Test strategy:
* Extract the post-fix watchdog predicate into a standalone function that
* takes a simulated HAL_GetTick() value and returns whether the watchdog
* should trip. Walk through boot + fault sequences that would have tripped
* the pre-fix code and assert the post-fix code does NOT trip.
******************************************************************************/
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
/* --- Post-fix watchdog state + predicate, extracted verbatim --- */
static uint32_t last_health_check = 0;
/* Returns 1 iff this call should raise ERROR_WATCHDOG_TIMEOUT.
Updates last_health_check BEFORE returning (matches post-fix behaviour). */
static int health_watchdog_step(uint32_t now_tick)
{
if (last_health_check == 0) {
last_health_check = now_tick; /* cold start: seed only, never trip */
return 0;
}
uint32_t elapsed = now_tick - last_health_check;
last_health_check = now_tick; /* update BEFORE any early return */
return (elapsed > 60000) ? 1 : 0;
}
/* Test helper: reset the static state between scenarios. */
static void reset_state(void) { last_health_check = 0; }
int main(void)
{
printf("=== Safety fix: checkSystemHealth() watchdog cold-start + stale-ts ===\n");
/* ---------- Scenario 1: cold-start after 60 s of init must NOT trip ---- */
printf(" Test 1: first call at t=75000 ms (post-init) does not trip... ");
reset_state();
assert(health_watchdog_step(75000) == 0);
printf("PASS\n");
/* ---------- Scenario 2: first call far beyond 60 s (PRE-FIX BUG) ------- */
printf(" Test 2: first call at t=600000 ms still does not trip... ");
reset_state();
assert(health_watchdog_step(600000) == 0);
printf("PASS\n");
/* ---------- Scenario 3: healthy main-loop pacing (10 ms period) -------- */
printf(" Test 3: 1000 calls at 10 ms intervals never trip... ");
reset_state();
(void)health_watchdog_step(1000); /* seed */
for (int i = 1; i <= 1000; i++) {
assert(health_watchdog_step(1000 + i * 10) == 0);
}
printf("PASS\n");
/* ---------- Scenario 4: stale-timestamp after a burst of early returns -
Pre-fix bug: many early returns skipped the timestamp update, so a
later clean call would compare `now` against a 60+ s old value. Post-fix,
every call (including ones that would have early-returned in the real
function) updates the timestamp at the top, so this scenario is modelled
by calling health_watchdog_step() on every iteration of the main loop. */
printf(" Test 4: 70 s of 100 ms-spaced calls after seed do not trip... ");
reset_state();
(void)health_watchdog_step(50000); /* seed mid-run */
for (int i = 1; i <= 700; i++) { /* 70 s @ 100 ms */
int tripped = health_watchdog_step(50000 + i * 100);
assert(tripped == 0);
}
printf("PASS\n");
/* ---------- Scenario 5: genuine stall MUST trip ------------------------ */
printf(" Test 5: real 60+ s gap between calls does trip... ");
reset_state();
(void)health_watchdog_step(10000); /* seed */
assert(health_watchdog_step(10000 + 60001) == 1);
printf("PASS\n");
/* ---------- Scenario 6: exactly 60 s gap is the boundary -- do NOT trip
Post-fix predicate uses strict >60000, matching the pre-fix comparator. */
printf(" Test 6: exactly 60000 ms gap does not trip (boundary)... ");
reset_state();
(void)health_watchdog_step(10000);
assert(health_watchdog_step(10000 + 60000) == 0);
printf("PASS\n");
/* ---------- Scenario 7: trip, then recover on next paced call ---------- */
printf(" Test 7: after a genuine stall+trip, next paced call does not re-trip... ");
reset_state();
(void)health_watchdog_step(5000); /* seed */
assert(health_watchdog_step(5000 + 70000) == 1); /* stall -> trip */
assert(health_watchdog_step(5000 + 70000 + 10) == 0); /* resume paced */
printf("PASS\n");
/* ---------- Scenario 8: HAL_GetTick() 32-bit wrap (~49.7 days) ---------
Because we subtract unsigned 32-bit values, wrap is handled correctly as
long as the true elapsed time is < 2^32 ms. */
printf(" Test 8: tick wrap from 0xFFFFFF00 -> 0x00000064 (200 ms span) does not trip... ");
reset_state();
(void)health_watchdog_step(0xFFFFFF00u);
assert(health_watchdog_step(0x00000064u) == 0); /* elapsed = 0x164 = 356 ms */
printf("PASS\n");
printf("\n=== Safety fix: ALL TESTS PASSED ===\n\n");
return 0;
}
@@ -1,119 +0,0 @@
/*******************************************************************************
* test_gap3_overtemp_emergency_stop.c
*
* Safety bug: handleSystemError() did not escalate ERROR_TEMPERATURE_HIGH
* (or ERROR_WATCHDOG_TIMEOUT) to Emergency_Stop().
*
* Before fix: The critical-error gate was
* if (error >= ERROR_RF_PA_OVERCURRENT &&
* error <= ERROR_POWER_SUPPLY) { Emergency_Stop(); }
* So overtemp (code 14) and watchdog timeout (code 16) fell
* through to attemptErrorRecovery()'s default branch (log and
* continue), leaving the 10 W GaN PAs biased at >75 °C.
*
* After fix: The gate also matches ERROR_TEMPERATURE_HIGH and
* ERROR_WATCHDOG_TIMEOUT, so thermal and watchdog faults
* latch Emergency_Stop() exactly like PA overcurrent.
*
* Test strategy:
* Replicate the critical-error predicate and assert that every error
* enum value which threatens RF/power safety is accepted, and that the
* non-critical ones (comm, sensor, memory) are not.
******************************************************************************/
#include <assert.h>
#include <stdio.h>
/* Mirror of SystemError_t from main.cpp (keep in lockstep). */
typedef enum {
ERROR_NONE = 0,
ERROR_AD9523_CLOCK,
ERROR_ADF4382_TX_UNLOCK,
ERROR_ADF4382_RX_UNLOCK,
ERROR_ADAR1000_COMM,
ERROR_ADAR1000_TEMP,
ERROR_IMU_COMM,
ERROR_BMP180_COMM,
ERROR_GPS_COMM,
ERROR_RF_PA_OVERCURRENT,
ERROR_RF_PA_BIAS,
ERROR_STEPPER_MOTOR,
ERROR_FPGA_COMM,
ERROR_POWER_SUPPLY,
ERROR_TEMPERATURE_HIGH,
ERROR_MEMORY_ALLOC,
ERROR_WATCHDOG_TIMEOUT
} SystemError_t;
/* Extracted post-fix predicate: returns 1 when Emergency_Stop() must fire. */
static int triggers_emergency_stop(SystemError_t e)
{
return ((e >= ERROR_RF_PA_OVERCURRENT && e <= ERROR_POWER_SUPPLY) ||
e == ERROR_TEMPERATURE_HIGH ||
e == ERROR_WATCHDOG_TIMEOUT);
}
int main(void)
{
printf("=== Safety fix: overtemp / watchdog -> Emergency_Stop() ===\n");
/* --- Errors that MUST latch Emergency_Stop --- */
printf(" Test 1: ERROR_RF_PA_OVERCURRENT triggers... ");
assert(triggers_emergency_stop(ERROR_RF_PA_OVERCURRENT));
printf("PASS\n");
printf(" Test 2: ERROR_RF_PA_BIAS triggers... ");
assert(triggers_emergency_stop(ERROR_RF_PA_BIAS));
printf("PASS\n");
printf(" Test 3: ERROR_STEPPER_MOTOR triggers... ");
assert(triggers_emergency_stop(ERROR_STEPPER_MOTOR));
printf("PASS\n");
printf(" Test 4: ERROR_FPGA_COMM triggers... ");
assert(triggers_emergency_stop(ERROR_FPGA_COMM));
printf("PASS\n");
printf(" Test 5: ERROR_POWER_SUPPLY triggers... ");
assert(triggers_emergency_stop(ERROR_POWER_SUPPLY));
printf("PASS\n");
printf(" Test 6: ERROR_TEMPERATURE_HIGH triggers (regression)... ");
assert(triggers_emergency_stop(ERROR_TEMPERATURE_HIGH));
printf("PASS\n");
printf(" Test 7: ERROR_WATCHDOG_TIMEOUT triggers (regression)... ");
assert(triggers_emergency_stop(ERROR_WATCHDOG_TIMEOUT));
printf("PASS\n");
/* --- Errors that MUST NOT escalate (recoverable / informational) --- */
printf(" Test 8: ERROR_NONE does not trigger... ");
assert(!triggers_emergency_stop(ERROR_NONE));
printf("PASS\n");
printf(" Test 9: ERROR_AD9523_CLOCK does not trigger... ");
assert(!triggers_emergency_stop(ERROR_AD9523_CLOCK));
printf("PASS\n");
printf(" Test 10: ERROR_ADF4382_TX_UNLOCK does not trigger (recoverable)... ");
assert(!triggers_emergency_stop(ERROR_ADF4382_TX_UNLOCK));
printf("PASS\n");
printf(" Test 11: ERROR_ADAR1000_COMM does not trigger... ");
assert(!triggers_emergency_stop(ERROR_ADAR1000_COMM));
printf("PASS\n");
printf(" Test 12: ERROR_IMU_COMM does not trigger... ");
assert(!triggers_emergency_stop(ERROR_IMU_COMM));
printf("PASS\n");
printf(" Test 13: ERROR_GPS_COMM does not trigger... ");
assert(!triggers_emergency_stop(ERROR_GPS_COMM));
printf("PASS\n");
printf(" Test 14: ERROR_MEMORY_ALLOC does not trigger... ");
assert(!triggers_emergency_stop(ERROR_MEMORY_ALLOC));
printf("PASS\n");
printf("\n=== Safety fix: ALL TESTS PASSED ===\n\n");
return 0;
}
@@ -1,853 +0,0 @@
/*******************************************************************************
* test_um982_gps.c -- Unit tests for UM982 GPS driver
*
* Tests NMEA parsing, checksum validation, coordinate parsing, init sequence,
* and validity tracking. Uses the mock HAL infrastructure for UART.
*
* Build: see Makefile target test_um982_gps
* Run: ./test_um982_gps
******************************************************************************/
#include "stm32_hal_mock.h"
#include "../9_1_3_C_Cpp_Code/um982_gps.h"
#include "../9_1_3_C_Cpp_Code/um982_gps.c" /* Include .c directly for white-box testing */
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <math.h>
/* ========================= Test helpers ============================== */
static int tests_passed = 0;
static int tests_failed = 0;
#define TEST(name) \
do { printf(" [TEST] %-55s ", name); } while(0)
#define PASS() \
do { printf("PASS\n"); tests_passed++; } while(0)
#define FAIL(msg) \
do { printf("FAIL: %s\n", msg); tests_failed++; } while(0)
#define ASSERT_TRUE(expr, msg) \
do { if (!(expr)) { FAIL(msg); return; } } while(0)
#define ASSERT_FALSE(expr, msg) \
do { if (expr) { FAIL(msg); return; } } while(0)
#define ASSERT_EQ_INT(a, b, msg) \
do { if ((a) != (b)) { \
char _buf[256]; \
snprintf(_buf, sizeof(_buf), "%s (got %d, expected %d)", msg, (int)(a), (int)(b)); \
FAIL(_buf); return; \
} } while(0)
#define ASSERT_NEAR(a, b, tol, msg) \
do { if (fabs((double)(a) - (double)(b)) > (tol)) { \
char _buf[256]; \
snprintf(_buf, sizeof(_buf), "%s (got %.8f, expected %.8f)", msg, (double)(a), (double)(b)); \
FAIL(_buf); return; \
} } while(0)
#define ASSERT_NAN(val, msg) \
do { if (!isnan(val)) { FAIL(msg); return; } } while(0)
static UM982_GPS_t gps;
static void reset_gps(void)
{
spy_reset();
memset(&gps, 0, sizeof(gps));
gps.huart = &huart5;
gps.heading = NAN;
gps.heading_mode = 'V';
gps.rmc_status = 'V';
}
/* ========================= Checksum tests ============================ */
static void test_checksum_valid(void)
{
TEST("checksum: valid GGA");
ASSERT_TRUE(um982_verify_checksum(
"$GNGGA,001043.00,4404.14036,N,12118.85961,W,1,12,0.98,1113.0,M,-21.3,M*47"),
"should be valid");
PASS();
}
static void test_checksum_valid_ths(void)
{
TEST("checksum: valid THS");
ASSERT_TRUE(um982_verify_checksum("$GNTHS,341.3344,A*1F"),
"should be valid");
PASS();
}
static void test_checksum_invalid(void)
{
TEST("checksum: invalid (wrong value)");
ASSERT_FALSE(um982_verify_checksum("$GNTHS,341.3344,A*FF"),
"should be invalid");
PASS();
}
static void test_checksum_missing_star(void)
{
TEST("checksum: missing * marker");
ASSERT_FALSE(um982_verify_checksum("$GNTHS,341.3344,A"),
"should be invalid");
PASS();
}
static void test_checksum_null(void)
{
TEST("checksum: NULL input");
ASSERT_FALSE(um982_verify_checksum(NULL), "should be false");
PASS();
}
static void test_checksum_no_dollar(void)
{
TEST("checksum: missing $ prefix");
ASSERT_FALSE(um982_verify_checksum("GNTHS,341.3344,A*1F"),
"should be invalid without $");
PASS();
}
/* ========================= Coordinate parsing tests ================== */
static void test_coord_latitude_north(void)
{
TEST("coord: latitude 4404.14036 N");
double lat = um982_parse_coord("4404.14036", 'N');
/* 44 + 04.14036/60 = 44.069006 */
ASSERT_NEAR(lat, 44.069006, 0.000001, "latitude");
PASS();
}
static void test_coord_latitude_south(void)
{
TEST("coord: latitude 3358.92500 S (negative)");
double lat = um982_parse_coord("3358.92500", 'S');
ASSERT_TRUE(lat < 0.0, "should be negative for S");
ASSERT_NEAR(lat, -(33.0 + 58.925/60.0), 0.000001, "latitude");
PASS();
}
static void test_coord_longitude_3digit(void)
{
TEST("coord: longitude 12118.85961 W (3-digit degrees)");
double lon = um982_parse_coord("12118.85961", 'W');
/* 121 + 18.85961/60 = 121.314327 */
ASSERT_TRUE(lon < 0.0, "should be negative for W");
ASSERT_NEAR(lon, -(121.0 + 18.85961/60.0), 0.000001, "longitude");
PASS();
}
static void test_coord_longitude_east(void)
{
TEST("coord: longitude 11614.19729 E");
double lon = um982_parse_coord("11614.19729", 'E');
ASSERT_TRUE(lon > 0.0, "should be positive for E");
ASSERT_NEAR(lon, 116.0 + 14.19729/60.0, 0.000001, "longitude");
PASS();
}
static void test_coord_empty(void)
{
TEST("coord: empty string returns NAN");
ASSERT_NAN(um982_parse_coord("", 'N'), "should be NAN");
PASS();
}
static void test_coord_null(void)
{
TEST("coord: NULL returns NAN");
ASSERT_NAN(um982_parse_coord(NULL, 'N'), "should be NAN");
PASS();
}
static void test_coord_no_dot(void)
{
TEST("coord: no decimal point returns NAN");
ASSERT_NAN(um982_parse_coord("440414036", 'N'), "should be NAN");
PASS();
}
/* ========================= GGA parsing tests ========================= */
static void test_parse_gga_full(void)
{
TEST("GGA: full sentence with all fields");
reset_gps();
mock_set_tick(1000);
um982_parse_sentence(&gps,
"$GNGGA,001043.00,4404.14036,N,12118.85961,W,1,12,0.98,1113.0,M,-21.3,M*47");
ASSERT_NEAR(gps.latitude, 44.069006, 0.0001, "latitude");
ASSERT_NEAR(gps.longitude, -(121.0 + 18.85961/60.0), 0.0001, "longitude");
ASSERT_EQ_INT(gps.fix_quality, 1, "fix quality");
ASSERT_EQ_INT(gps.num_satellites, 12, "num sats");
ASSERT_NEAR(gps.hdop, 0.98, 0.01, "hdop");
ASSERT_NEAR(gps.altitude, 1113.0, 0.1, "altitude");
ASSERT_NEAR(gps.geoid_sep, -21.3, 0.1, "geoid sep");
PASS();
}
static void test_parse_gga_rtk_fixed(void)
{
TEST("GGA: RTK fixed (quality=4)");
reset_gps();
um982_parse_sentence(&gps,
"$GNGGA,023634.00,4004.73871635,N,11614.19729418,E,4,28,0.7,61.0988,M,-8.4923,M,,*5D");
ASSERT_EQ_INT(gps.fix_quality, 4, "RTK fixed");
ASSERT_EQ_INT(gps.num_satellites, 28, "num sats");
ASSERT_NEAR(gps.latitude, 40.0 + 4.73871635/60.0, 0.0000001, "latitude");
ASSERT_NEAR(gps.longitude, 116.0 + 14.19729418/60.0, 0.0000001, "longitude");
PASS();
}
static void test_parse_gga_no_fix(void)
{
TEST("GGA: no fix (quality=0)");
reset_gps();
/* Compute checksum for this sentence */
um982_parse_sentence(&gps,
"$GNGGA,235959.00,,,,,0,00,99.99,,,,,,*79");
ASSERT_EQ_INT(gps.fix_quality, 0, "no fix");
PASS();
}
/* ========================= RMC parsing tests ========================= */
static void test_parse_rmc_valid(void)
{
TEST("RMC: valid position and speed");
reset_gps();
mock_set_tick(2000);
um982_parse_sentence(&gps,
"$GNRMC,001031.00,A,4404.13993,N,12118.86023,W,0.146,,100117,,,A*7B");
ASSERT_EQ_INT(gps.rmc_status, 'A', "status");
ASSERT_NEAR(gps.latitude, 44.0 + 4.13993/60.0, 0.0001, "latitude");
ASSERT_NEAR(gps.longitude, -(121.0 + 18.86023/60.0), 0.0001, "longitude");
ASSERT_NEAR(gps.speed_knots, 0.146, 0.001, "speed");
PASS();
}
static void test_parse_rmc_void(void)
{
TEST("RMC: void status (no valid fix)");
reset_gps();
gps.latitude = 12.34; /* Pre-set to check it doesn't get overwritten */
um982_parse_sentence(&gps,
"$GNRMC,235959.00,V,,,,,,,100117,,,N*64");
ASSERT_EQ_INT(gps.rmc_status, 'V', "void status");
ASSERT_NEAR(gps.latitude, 12.34, 0.001, "lat should not change on void");
PASS();
}
/* ========================= THS parsing tests ========================= */
static void test_parse_ths_autonomous(void)
{
TEST("THS: autonomous heading 341.3344");
reset_gps();
mock_set_tick(3000);
um982_parse_sentence(&gps, "$GNTHS,341.3344,A*1F");
ASSERT_NEAR(gps.heading, 341.3344, 0.001, "heading");
ASSERT_EQ_INT(gps.heading_mode, 'A', "mode");
PASS();
}
static void test_parse_ths_not_valid(void)
{
TEST("THS: not valid mode");
reset_gps();
um982_parse_sentence(&gps, "$GNTHS,,V*10");
ASSERT_NAN(gps.heading, "heading should be NAN when empty");
ASSERT_EQ_INT(gps.heading_mode, 'V', "mode V");
PASS();
}
static void test_parse_ths_zero(void)
{
TEST("THS: heading exactly 0.0000");
reset_gps();
um982_parse_sentence(&gps, "$GNTHS,0.0000,A*19");
ASSERT_NEAR(gps.heading, 0.0, 0.001, "heading zero");
ASSERT_EQ_INT(gps.heading_mode, 'A', "mode A");
PASS();
}
static void test_parse_ths_360_boundary(void)
{
TEST("THS: heading near 360");
reset_gps();
um982_parse_sentence(&gps, "$GNTHS,359.9999,D*13");
ASSERT_NEAR(gps.heading, 359.9999, 0.001, "heading near 360");
ASSERT_EQ_INT(gps.heading_mode, 'D', "mode D");
PASS();
}
/* ========================= VTG parsing tests ========================= */
static void test_parse_vtg(void)
{
TEST("VTG: course and speed");
reset_gps();
um982_parse_sentence(&gps,
"$GPVTG,220.86,T,,M,2.550,N,4.724,K,A*34");
ASSERT_NEAR(gps.course_true, 220.86, 0.01, "course");
ASSERT_NEAR(gps.speed_knots, 2.550, 0.001, "speed knots");
ASSERT_NEAR(gps.speed_kmh, 4.724, 0.001, "speed kmh");
PASS();
}
/* ========================= Talker ID tests =========================== */
static void test_talker_gp(void)
{
TEST("talker: GP prefix parses correctly");
reset_gps();
um982_parse_sentence(&gps, "$GPTHS,123.4567,A*07");
ASSERT_NEAR(gps.heading, 123.4567, 0.001, "heading with GP");
PASS();
}
static void test_talker_gl(void)
{
TEST("talker: GL prefix parses correctly");
reset_gps();
um982_parse_sentence(&gps, "$GLTHS,123.4567,A*1B");
ASSERT_NEAR(gps.heading, 123.4567, 0.001, "heading with GL");
PASS();
}
/* ========================= Feed / line assembly tests ================ */
static void test_feed_single_sentence(void)
{
TEST("feed: single complete sentence with CRLF");
reset_gps();
mock_set_tick(5000);
const char *data = "$GNTHS,341.3344,A*1F\r\n";
um982_feed(&gps, (const uint8_t *)data, (uint16_t)strlen(data));
ASSERT_NEAR(gps.heading, 341.3344, 0.001, "heading");
PASS();
}
static void test_feed_multiple_sentences(void)
{
TEST("feed: multiple sentences in one chunk");
reset_gps();
mock_set_tick(5000);
const char *data =
"$GNTHS,100.0000,A*18\r\n"
"$GNGGA,001043.00,4404.14036,N,12118.85961,W,1,12,0.98,1113.0,M,-21.3,M*47\r\n";
um982_feed(&gps, (const uint8_t *)data, (uint16_t)strlen(data));
ASSERT_NEAR(gps.heading, 100.0, 0.01, "heading from THS");
ASSERT_EQ_INT(gps.fix_quality, 1, "fix from GGA");
PASS();
}
static void test_feed_partial_then_complete(void)
{
TEST("feed: partial bytes then complete");
reset_gps();
mock_set_tick(5000);
const char *part1 = "$GNTHS,200.";
const char *part2 = "5000,A*1E\r\n";
um982_feed(&gps, (const uint8_t *)part1, (uint16_t)strlen(part1));
/* Heading should not be set yet */
ASSERT_NAN(gps.heading, "should be NAN before complete");
um982_feed(&gps, (const uint8_t *)part2, (uint16_t)strlen(part2));
ASSERT_NEAR(gps.heading, 200.5, 0.01, "heading after complete");
PASS();
}
static void test_feed_bad_checksum_rejected(void)
{
TEST("feed: bad checksum sentence is rejected");
reset_gps();
mock_set_tick(5000);
const char *data = "$GNTHS,999.0000,A*FF\r\n";
um982_feed(&gps, (const uint8_t *)data, (uint16_t)strlen(data));
ASSERT_NAN(gps.heading, "heading should remain NAN");
PASS();
}
static void test_feed_versiona_response(void)
{
TEST("feed: VERSIONA response sets flag");
reset_gps();
const char *data = "#VERSIONA,79,GPS,FINE,2326,378237000,15434,0,18,889;\"UM982\"\r\n";
um982_feed(&gps, (const uint8_t *)data, (uint16_t)strlen(data));
ASSERT_TRUE(gps.version_received, "version_received should be true");
ASSERT_TRUE(gps.initialized, "VERSIONA should mark communication alive");
PASS();
}
/* ========================= Validity / age tests ====================== */
static void test_heading_valid_within_timeout(void)
{
TEST("validity: heading valid within timeout");
reset_gps();
mock_set_tick(10000);
um982_parse_sentence(&gps, "$GNTHS,341.3344,A*1F");
/* Still at tick 10000 */
ASSERT_TRUE(um982_is_heading_valid(&gps), "should be valid");
PASS();
}
static void test_heading_invalid_after_timeout(void)
{
TEST("validity: heading invalid after 2s timeout");
reset_gps();
mock_set_tick(10000);
um982_parse_sentence(&gps, "$GNTHS,341.3344,A*1F");
/* Advance past timeout */
mock_set_tick(12500);
ASSERT_FALSE(um982_is_heading_valid(&gps), "should be invalid after 2.5s");
PASS();
}
static void test_heading_invalid_mode_v(void)
{
TEST("validity: heading invalid with mode V");
reset_gps();
mock_set_tick(10000);
um982_parse_sentence(&gps, "$GNTHS,,V*10");
ASSERT_FALSE(um982_is_heading_valid(&gps), "mode V is invalid");
PASS();
}
static void test_position_valid(void)
{
TEST("validity: position valid with fix quality 1");
reset_gps();
mock_set_tick(10000);
um982_parse_sentence(&gps,
"$GNGGA,001043.00,4404.14036,N,12118.85961,W,1,12,0.98,1113.0,M,-21.3,M*47");
ASSERT_TRUE(um982_is_position_valid(&gps), "should be valid");
PASS();
}
static void test_position_invalid_no_fix(void)
{
TEST("validity: position invalid with no fix");
reset_gps();
mock_set_tick(10000);
um982_parse_sentence(&gps,
"$GNGGA,235959.00,,,,,0,00,99.99,,,,,,*79");
ASSERT_FALSE(um982_is_position_valid(&gps), "no fix = invalid");
PASS();
}
static void test_position_age_uses_last_valid_fix(void)
{
TEST("age: position age uses last valid fix, not no-fix GGA");
reset_gps();
mock_set_tick(10000);
um982_parse_sentence(&gps,
"$GNGGA,001043.00,4404.14036,N,12118.85961,W,1,12,0.98,1113.0,M,-21.3,M*47");
mock_set_tick(12000);
um982_parse_sentence(&gps,
"$GNGGA,235959.00,,,,,0,00,99.99,,,,,,*79");
mock_set_tick(12500);
ASSERT_EQ_INT(um982_position_age(&gps), 2500, "age should still be from last valid fix");
ASSERT_FALSE(um982_is_position_valid(&gps), "latest no-fix GGA should invalidate position");
PASS();
}
static void test_heading_age(void)
{
TEST("age: heading age computed correctly");
reset_gps();
mock_set_tick(10000);
um982_parse_sentence(&gps, "$GNTHS,341.3344,A*1F");
mock_set_tick(10500);
uint32_t age = um982_heading_age(&gps);
ASSERT_EQ_INT(age, 500, "age should be 500ms");
PASS();
}
/* ========================= Send command tests ======================== */
static void test_send_command_appends_crlf(void)
{
TEST("send_command: appends \\r\\n");
reset_gps();
um982_send_command(&gps, "GPGGA COM2 1");
/* Check that TX buffer contains "GPGGA COM2 1\r\n" */
const char *expected = "GPGGA COM2 1\r\n";
ASSERT_TRUE(mock_uart_tx_len == strlen(expected), "TX length");
ASSERT_TRUE(memcmp(mock_uart_tx_buf, expected, strlen(expected)) == 0,
"TX content should be 'GPGGA COM2 1\\r\\n'");
PASS();
}
static void test_send_command_null_safety(void)
{
TEST("send_command: NULL gps returns false");
ASSERT_FALSE(um982_send_command(NULL, "RESET"), "should return false");
PASS();
}
/* ========================= Init sequence tests ======================= */
static void test_init_sends_correct_commands(void)
{
TEST("init: sends correct command sequence");
spy_reset();
mock_uart_tx_clear();
/* Pre-load VERSIONA response so init succeeds */
const char *ver_resp = "#VERSIONA,79,GPS,FINE,2326,378237000,15434,0,18,889;\"UM982\"\r\n";
mock_uart_rx_load(&huart5, (const uint8_t *)ver_resp, (uint16_t)strlen(ver_resp));
UM982_GPS_t init_gps;
bool ok = um982_init(&init_gps, &huart5, 50.0f, 3.0f);
ASSERT_TRUE(ok, "init should succeed");
ASSERT_TRUE(init_gps.initialized, "should be initialized");
/* Verify TX buffer contains expected commands */
const char *tx = (const char *)mock_uart_tx_buf;
ASSERT_TRUE(strstr(tx, "UNLOG\r\n") != NULL, "should send UNLOG");
ASSERT_TRUE(strstr(tx, "CONFIG HEADING FIXLENGTH\r\n") != NULL, "should send CONFIG HEADING");
ASSERT_TRUE(strstr(tx, "CONFIG HEADING LENGTH 50 3\r\n") != NULL, "should send LENGTH");
ASSERT_TRUE(strstr(tx, "GPGGA COM2 1\r\n") != NULL, "should enable GGA");
ASSERT_TRUE(strstr(tx, "GPRMC COM2 1\r\n") != NULL, "should enable RMC");
ASSERT_TRUE(strstr(tx, "GPTHS COM2 0.2\r\n") != NULL, "should enable THS at 5Hz");
ASSERT_TRUE(strstr(tx, "SAVECONFIG\r\n") == NULL, "should NOT save config (NVM wear)");
ASSERT_TRUE(strstr(tx, "VERSIONA\r\n") != NULL, "should query version");
/* Verify command order: UNLOG should come before GPGGA */
const char *unlog_pos = strstr(tx, "UNLOG\r\n");
const char *gpgga_pos = strstr(tx, "GPGGA COM2 1\r\n");
ASSERT_TRUE(unlog_pos < gpgga_pos, "UNLOG should precede GPGGA");
PASS();
}
static void test_init_no_baseline(void)
{
TEST("init: baseline=0 skips LENGTH command");
spy_reset();
mock_uart_tx_clear();
const char *ver_resp = "#VERSIONA,79,GPS,FINE,2326,378237000,15434,0,18,889;\"UM982\"\r\n";
mock_uart_rx_load(&huart5, (const uint8_t *)ver_resp, (uint16_t)strlen(ver_resp));
UM982_GPS_t init_gps;
um982_init(&init_gps, &huart5, 0.0f, 0.0f);
const char *tx = (const char *)mock_uart_tx_buf;
ASSERT_TRUE(strstr(tx, "CONFIG HEADING LENGTH") == NULL, "should NOT send LENGTH");
PASS();
}
static void test_init_fails_no_version(void)
{
TEST("init: fails if no VERSIONA response");
spy_reset();
mock_uart_tx_clear();
/* Don't load any RX data — init should timeout */
UM982_GPS_t init_gps;
bool ok = um982_init(&init_gps, &huart5, 50.0f, 3.0f);
ASSERT_FALSE(ok, "init should fail without version response");
ASSERT_FALSE(init_gps.initialized, "should not be initialized");
PASS();
}
static void test_nmea_traffic_sets_initialized_without_versiona(void)
{
TEST("init state: supported NMEA traffic sets initialized");
reset_gps();
ASSERT_FALSE(gps.initialized, "should start uninitialized");
um982_parse_sentence(&gps, "$GNTHS,341.3344,A*1F");
ASSERT_TRUE(gps.initialized, "supported NMEA should mark communication alive");
PASS();
}
/* ========================= Edge case tests =========================== */
static void test_empty_fields_handled(void)
{
TEST("edge: GGA with empty lat/lon fields");
reset_gps();
gps.latitude = 99.99;
gps.longitude = 99.99;
/* GGA with empty position fields (no fix) */
um982_parse_sentence(&gps,
"$GNGGA,235959.00,,,,,0,00,99.99,,,,,,*79");
ASSERT_EQ_INT(gps.fix_quality, 0, "no fix");
/* Latitude/longitude should not be updated (fields are empty) */
ASSERT_NEAR(gps.latitude, 99.99, 0.01, "lat unchanged");
ASSERT_NEAR(gps.longitude, 99.99, 0.01, "lon unchanged");
PASS();
}
static void test_sentence_too_short(void)
{
TEST("edge: sentence too short to have formatter");
reset_gps();
/* Should not crash */
um982_parse_sentence(&gps, "$GN");
um982_parse_sentence(&gps, "$");
um982_parse_sentence(&gps, "");
um982_parse_sentence(&gps, NULL);
PASS();
}
static void test_line_overflow(void)
{
TEST("edge: oversized line is dropped");
reset_gps();
/* Create a line longer than UM982_LINE_BUF_SIZE */
char big[200];
memset(big, 'X', sizeof(big));
big[0] = '$';
big[198] = '\n';
big[199] = '\0';
um982_feed(&gps, (const uint8_t *)big, 199);
/* Should not crash, heading should still be NAN */
ASSERT_NAN(gps.heading, "no valid data from overflow");
PASS();
}
static void test_process_via_mock_uart(void)
{
TEST("process: reads from mock UART RX buffer");
reset_gps();
mock_set_tick(5000);
/* Load data into mock UART RX */
const char *data = "$GNTHS,275.1234,D*18\r\n";
mock_uart_rx_load(&huart5, (const uint8_t *)data, (uint16_t)strlen(data));
/* Call process() which reads from UART */
um982_process(&gps);
ASSERT_NEAR(gps.heading, 275.1234, 0.001, "heading via process()");
ASSERT_EQ_INT(gps.heading_mode, 'D', "mode D");
PASS();
}
/* ========================= PR #68 bug regression tests =============== */
/* These tests specifically verify the bugs found in the reverted PR #68 */
static void test_regression_sentence_id_with_gn_prefix(void)
{
TEST("regression: GN-prefixed GGA is correctly identified");
reset_gps();
/* PR #68 bug: strncmp(sentence, "GGA", 3) compared "GNG" vs "GGA" — never matched.
* Our fix: skip 2-char talker ID, compare at sentence+3. */
um982_parse_sentence(&gps,
"$GNGGA,001043.00,4404.14036,N,12118.85961,W,1,12,0.98,1113.0,M,-21.3,M*47");
ASSERT_EQ_INT(gps.fix_quality, 1, "GGA should parse with GN prefix");
ASSERT_NEAR(gps.latitude, 44.069006, 0.001, "latitude should be parsed");
PASS();
}
static void test_regression_longitude_3digit_degrees(void)
{
TEST("regression: 3-digit longitude degrees parsed correctly");
reset_gps();
/* PR #68 bug: hardcoded 2-digit degrees for longitude.
* 12118.85961 should be 121° 18.85961' = 121.314327° */
um982_parse_sentence(&gps,
"$GNGGA,001043.00,4404.14036,N,12118.85961,W,1,12,0.98,1113.0,M,-21.3,M*47");
ASSERT_NEAR(gps.longitude, -(121.0 + 18.85961/60.0), 0.0001,
"longitude 121° should not be parsed as 12°");
ASSERT_TRUE(gps.longitude < -100.0, "longitude should be > 100 degrees");
PASS();
}
static void test_regression_hemisphere_no_ptr_corrupt(void)
{
TEST("regression: hemisphere parsing doesn't corrupt field pointer");
reset_gps();
/* PR #68 bug: GGA/RMC hemisphere cases manually advanced ptr,
* desynchronizing from field counter. Our parser uses proper tokenizer. */
um982_parse_sentence(&gps,
"$GNGGA,001043.00,4404.14036,N,12118.85961,W,1,12,0.98,1113.0,M,-21.3,M*47");
/* After lat/lon, remaining fields should be correct */
ASSERT_EQ_INT(gps.num_satellites, 12, "sats after hemisphere");
ASSERT_NEAR(gps.hdop, 0.98, 0.01, "hdop after hemisphere");
ASSERT_NEAR(gps.altitude, 1113.0, 0.1, "altitude after hemisphere");
PASS();
}
static void test_regression_rmc_also_parsed(void)
{
TEST("regression: RMC sentence is actually parsed (not dead code)");
reset_gps();
/* PR #68 bug: identifySentence never matched GGA/RMC, so position
* parsing was dead code. */
um982_parse_sentence(&gps,
"$GNRMC,001031.00,A,4404.13993,N,12118.86023,W,0.146,,100117,,,A*7B");
ASSERT_TRUE(gps.latitude > 44.0, "RMC lat should be parsed");
ASSERT_TRUE(gps.longitude < -121.0, "RMC lon should be parsed");
ASSERT_NEAR(gps.speed_knots, 0.146, 0.001, "RMC speed");
PASS();
}
/* ========================= Main ====================================== */
int main(void)
{
printf("=== UM982 GPS Driver Tests ===\n\n");
printf("--- Checksum ---\n");
test_checksum_valid();
test_checksum_valid_ths();
test_checksum_invalid();
test_checksum_missing_star();
test_checksum_null();
test_checksum_no_dollar();
printf("\n--- Coordinate Parsing ---\n");
test_coord_latitude_north();
test_coord_latitude_south();
test_coord_longitude_3digit();
test_coord_longitude_east();
test_coord_empty();
test_coord_null();
test_coord_no_dot();
printf("\n--- GGA Parsing ---\n");
test_parse_gga_full();
test_parse_gga_rtk_fixed();
test_parse_gga_no_fix();
printf("\n--- RMC Parsing ---\n");
test_parse_rmc_valid();
test_parse_rmc_void();
printf("\n--- THS Parsing ---\n");
test_parse_ths_autonomous();
test_parse_ths_not_valid();
test_parse_ths_zero();
test_parse_ths_360_boundary();
printf("\n--- VTG Parsing ---\n");
test_parse_vtg();
printf("\n--- Talker IDs ---\n");
test_talker_gp();
test_talker_gl();
printf("\n--- Feed / Line Assembly ---\n");
test_feed_single_sentence();
test_feed_multiple_sentences();
test_feed_partial_then_complete();
test_feed_bad_checksum_rejected();
test_feed_versiona_response();
printf("\n--- Validity / Age ---\n");
test_heading_valid_within_timeout();
test_heading_invalid_after_timeout();
test_heading_invalid_mode_v();
test_position_valid();
test_position_invalid_no_fix();
test_position_age_uses_last_valid_fix();
test_heading_age();
printf("\n--- Send Command ---\n");
test_send_command_appends_crlf();
test_send_command_null_safety();
printf("\n--- Init Sequence ---\n");
test_init_sends_correct_commands();
test_init_no_baseline();
test_init_fails_no_version();
test_nmea_traffic_sets_initialized_without_versiona();
printf("\n--- Edge Cases ---\n");
test_empty_fields_handled();
test_sentence_too_short();
test_line_overflow();
test_process_via_mock_uart();
printf("\n--- PR #68 Regression ---\n");
test_regression_sentence_id_with_gn_prefix();
test_regression_longitude_3digit_degrees();
test_regression_hemisphere_no_ptr_corrupt();
test_regression_rmc_also_parsed();
printf("\n===============================================\n");
printf(" Results: %d passed, %d failed (of %d total)\n",
tests_passed, tests_failed, tests_passed + tests_failed);
printf("===============================================\n");
return tests_failed > 0 ? 1 : 0;
}
@@ -18,10 +18,9 @@ module matched_filter_multi_segment (
input wire mc_new_elevation, // Toggle for new elevation (32)
input wire mc_new_azimuth, // Toggle for new azimuth (50)
input wire [15:0] long_chirp_real,
input wire [15:0] long_chirp_imag,
input wire [15:0] short_chirp_real,
input wire [15:0] short_chirp_imag,
// Reference chirp (upstream memory loader selects long/short via use_long_chirp)
input wire [15:0] ref_chirp_real,
input wire [15:0] ref_chirp_imag,
// Memory system interface
output reg [1:0] segment_request,
@@ -244,6 +243,7 @@ always @(posedge clk or negedge reset_n) begin
if (!use_long_chirp) begin
if (chirp_samples_collected >= SHORT_CHIRP_SAMPLES - 1) begin
state <= ST_ZERO_PAD;
chirp_complete <= 1; // Bug A fix: mark chirp done so ST_OUTPUT exits to IDLE
`ifdef SIMULATION
$display("[MULTI_SEG_FIXED] Short chirp: collected %d samples, starting zero-pad",
chirp_samples_collected + 1);
@@ -500,11 +500,9 @@ matched_filter_processing_chain m_f_p_c(
// Chirp Selection
.chirp_counter(chirp_counter),
// Reference Chirp Memory Interfaces
.long_chirp_real(long_chirp_real),
.long_chirp_imag(long_chirp_imag),
.short_chirp_real(short_chirp_real),
.short_chirp_imag(short_chirp_imag),
// Reference Chirp Memory Interface (single pair upstream selects long/short)
.ref_chirp_real(ref_chirp_real),
.ref_chirp_imag(ref_chirp_imag),
// Output
.range_profile_i(fft_pc_i),
@@ -15,7 +15,7 @@
* .clk, .reset_n
* .adc_data_i, .adc_data_q, .adc_valid <- from input buffer
* .chirp_counter <- 6-bit frame counter
* .long_chirp_real/imag, .short_chirp_real/imag <- reference (time-domain)
* .ref_chirp_real/imag <- reference (time-domain)
* .range_profile_i, .range_profile_q, .range_profile_valid -> output
* .chain_state -> 4-bit status
*
@@ -48,10 +48,10 @@ module matched_filter_processing_chain (
input wire [5:0] chirp_counter,
// Reference chirp (time-domain, latency-aligned by upstream buffer)
input wire [15:0] long_chirp_real,
input wire [15:0] long_chirp_imag,
input wire [15:0] short_chirp_real,
input wire [15:0] short_chirp_imag,
// Upstream chirp_memory_loader_param selects long/short reference
// via use_long_chirp this single pair carries whichever is active.
input wire [15:0] ref_chirp_real,
input wire [15:0] ref_chirp_imag,
// Output: range profile (pulse-compressed)
output wire signed [15:0] range_profile_i,
@@ -189,8 +189,8 @@ always @(posedge clk or negedge reset_n) begin
// Store first sample (signal + reference)
fwd_buf_i[0] <= $signed(adc_data_i);
fwd_buf_q[0] <= $signed(adc_data_q);
ref_buf_i[0] <= $signed(long_chirp_real);
ref_buf_q[0] <= $signed(long_chirp_imag);
ref_buf_i[0] <= $signed(ref_chirp_real);
ref_buf_q[0] <= $signed(ref_chirp_imag);
fwd_in_count <= 1;
state <= ST_FWD_FFT;
end
@@ -205,8 +205,8 @@ always @(posedge clk or negedge reset_n) begin
if (adc_valid && fwd_in_count < FFT_SIZE) begin
fwd_buf_i[fwd_in_count] <= $signed(adc_data_i);
fwd_buf_q[fwd_in_count] <= $signed(adc_data_q);
ref_buf_i[fwd_in_count] <= $signed(long_chirp_real);
ref_buf_q[fwd_in_count] <= $signed(long_chirp_imag);
ref_buf_i[fwd_in_count] <= $signed(ref_chirp_real);
ref_buf_q[fwd_in_count] <= $signed(ref_chirp_imag);
fwd_in_count <= fwd_in_count + 1;
end
@@ -775,16 +775,16 @@ always @(posedge clk) begin : ref_bram_port
if (adc_valid) begin
we = 1'b1;
addr = 0;
wdata_i = $signed(long_chirp_real);
wdata_q = $signed(long_chirp_imag);
wdata_i = $signed(ref_chirp_real);
wdata_q = $signed(ref_chirp_imag);
end
end
ST_COLLECT: begin
if (adc_valid && collect_count < FFT_SIZE) begin
we = 1'b1;
addr = collect_count[ADDR_BITS-1:0];
wdata_i = $signed(long_chirp_real);
wdata_q = $signed(long_chirp_imag);
wdata_i = $signed(ref_chirp_real);
wdata_q = $signed(ref_chirp_imag);
end
end
ST_REF_FFT: begin
+200
View File
@@ -0,0 +1,200 @@
// ============================================================================
// radar_params.vh — Single Source of Truth for AERIS-10 FPGA Parameters
// ============================================================================
//
// ALL modules in the FPGA processing chain MUST `include this file instead of
// hardcoding range bins, segment counts, chirp samples, or timing values.
//
// This file uses `define macros (not localparam) so it can be included at any
// scope. Each consuming module should include this file inside its body and
// optionally alias macros to localparams for readability.
//
// BOARD VARIANTS:
// SUPPORT_LONG_RANGE = 0 (50T, USB_MODE=1) — 3 km mode only, 64 range bins
// SUPPORT_LONG_RANGE = 1 (200T, USB_MODE=0) — 3 km + 20 km modes, up to 1024 bins
//
// RANGE MODES (runtime, via host_range_mode register, opcode 0x20):
// 2'b00 = 3 km (default on both boards)
// 2'b01 = 20 km (200T only; clamped to 3 km on 50T)
// 2'b10 = Reserved
// 2'b11 = Reserved
//
// USAGE:
// `include "radar_params.vh"
// Then reference `RP_FFT_SIZE, `RP_MAX_OUTPUT_BINS, etc.
//
// PHYSICAL CONSTANTS (derived from hardware):
// ADC clock: 400 MSPS
// CIC decimation: 4x
// Processing rate: 100 MSPS (post-DDC)
// Range per sample: c / (2 * 100e6) = 1.5 m
// Decimation factor: 16 (1024 FFT bins -> 64 output bins per segment)
// Range per dec. bin: 1.5 m * 16 = 24.0 m
// Carrier frequency: 10.5 GHz
//
// CHIRP BANDWIDTH (Phase 1 target — currently 20 MHz, planned 30 MHz):
// Range resolution: c / (2 * BW)
// 20 MHz -> 7.5 m
// 30 MHz -> 5.0 m
// NOTE: Range resolution is independent of range-per-bin. Resolution
// determines the minimum separation between two targets; range-per-bin
// determines the spatial sampling grid.
// ============================================================================
`ifndef RADAR_PARAMS_VH
`define RADAR_PARAMS_VH
// ============================================================================
// BOARD VARIANT — set at synthesis time, NOT runtime
// ============================================================================
// Default to 50T (conservative). Override in top-level or synthesis script:
// +define+SUPPORT_LONG_RANGE
// or via Vivado: set_property verilog_define {SUPPORT_LONG_RANGE} [current_fileset]
// Note: SUPPORT_LONG_RANGE is a flag define (ifdef/ifndef), not a value.
// `ifndef SUPPORT_LONG_RANGE means 50T (no long range).
// `ifdef SUPPORT_LONG_RANGE means 200T (long range supported).
// ============================================================================
// FFT AND PROCESSING CONSTANTS (fixed, both modes)
// ============================================================================
`define RP_FFT_SIZE 1024 // Range FFT points per segment
`define RP_OVERLAP_SAMPLES 128 // Overlap between adjacent segments
`define RP_SEGMENT_ADVANCE 896 // FFT_SIZE - OVERLAP = 1024 - 128
`define RP_DECIMATION_FACTOR 16 // Range bin decimation (1024 -> 64)
`define RP_BINS_PER_SEGMENT 64 // FFT_SIZE / DECIMATION_FACTOR
`define RP_DOPPLER_FFT_SIZE 16 // Per sub-frame Doppler FFT
`define RP_CHIRPS_PER_FRAME 32 // Total chirps (16 long + 16 short)
`define RP_CHIRPS_PER_SUBFRAME 16 // Chirps per Doppler sub-frame
`define RP_NUM_DOPPLER_BINS 32 // 2 sub-frames * 16 = 32
`define RP_DATA_WIDTH 16 // ADC/processing data width
// ============================================================================
// 3 KM MODE PARAMETERS (both 50T and 200T)
// ============================================================================
`define RP_LONG_CHIRP_SAMPLES_3KM 3000 // 30 us at 100 MSPS
`define RP_LONG_SEGMENTS_3KM 4 // ceil((3000-1024)/896) + 1 = 4
`define RP_OUTPUT_RANGE_BINS_3KM 64 // Downstream pipeline expects 64 range bins (NOTE: will become 128 after 2048-pt FFT upgrade)
`define RP_SHORT_CHIRP_SAMPLES 50 // 0.5 us at 100 MSPS (same both modes)
`define RP_SHORT_SEGMENTS 1 // Single segment for short chirp
// Derived 3 km limits
`define RP_MAX_RANGE_3KM 1536 // 64 bins * 24 m = 1536 m
// ============================================================================
// 20 KM MODE PARAMETERS (200T only)
// ============================================================================
`define RP_LONG_CHIRP_SAMPLES_20KM 13700 // 137 us at 100 MSPS (= listen window)
`define RP_LONG_SEGMENTS_20KM 16 // ceil((13700-1024)/896) + 1 = 16
`define RP_OUTPUT_RANGE_BINS_20KM 1024 // 16 segments * 64 dec. bins each
// Derived 20 km limits
`define RP_MAX_RANGE_20KM 24576 // 1024 bins * 24 m = 24576 m
// ============================================================================
// MAX VALUES (for sizing buffers — compile-time, based on board variant)
// ============================================================================
`ifdef SUPPORT_LONG_RANGE
`define RP_MAX_SEGMENTS 16
`define RP_MAX_OUTPUT_BINS 1024
`define RP_MAX_CHIRP_SAMPLES 13700
`else
`define RP_MAX_SEGMENTS 4
`define RP_MAX_OUTPUT_BINS 64
`define RP_MAX_CHIRP_SAMPLES 3000
`endif
// ============================================================================
// BIT WIDTHS (derived from MAX values)
// ============================================================================
// Segment index: ceil(log2(MAX_SEGMENTS))
// 50T: log2(4) = 2 bits
// 200T: log2(16) = 4 bits
`ifdef SUPPORT_LONG_RANGE
`define RP_SEGMENT_IDX_WIDTH 4
`define RP_RANGE_BIN_WIDTH 10
`define RP_CHIRP_MEM_ADDR_W 14 // log2(16*1024) = 14
`define RP_DOPPLER_MEM_ADDR_W 15 // log2(1024*32) = 15
`define RP_CFAR_MAG_ADDR_W 15 // log2(1024*32) = 15
`else
`define RP_SEGMENT_IDX_WIDTH 2
`define RP_RANGE_BIN_WIDTH 6
`define RP_CHIRP_MEM_ADDR_W 12 // log2(4*1024) = 12
`define RP_DOPPLER_MEM_ADDR_W 11 // log2(64*32) = 11
`define RP_CFAR_MAG_ADDR_W 11 // log2(64*32) = 11
`endif
// Derived depths (for memory declarations)
// Usage: reg [15:0] mem [0:`RP_CHIRP_MEM_DEPTH-1];
`define RP_CHIRP_MEM_DEPTH (`RP_MAX_SEGMENTS * `RP_FFT_SIZE)
`define RP_DOPPLER_MEM_DEPTH (`RP_MAX_OUTPUT_BINS * `RP_CHIRPS_PER_FRAME)
`define RP_CFAR_MAG_DEPTH (`RP_MAX_OUTPUT_BINS * `RP_NUM_DOPPLER_BINS)
// ============================================================================
// CHIRP TIMING DEFAULTS (100 MHz clock cycles)
// ============================================================================
// Reset defaults for host-configurable timing registers.
// Match radar_mode_controller.v parameters and main.cpp STM32 defaults.
`define RP_DEF_LONG_CHIRP_CYCLES 3000 // 30 us
`define RP_DEF_LONG_LISTEN_CYCLES 13700 // 137 us
`define RP_DEF_GUARD_CYCLES 17540 // 175.4 us
`define RP_DEF_SHORT_CHIRP_CYCLES 50 // 0.5 us
`define RP_DEF_SHORT_LISTEN_CYCLES 17450 // 174.5 us
`define RP_DEF_CHIRPS_PER_ELEV 32
// ============================================================================
// BLIND ZONE CONSTANTS (informational, for comments and GUI)
// ============================================================================
// Long chirp blind zone: c * 30 us / 2 = 4500 m
// Short chirp blind zone: c * 0.5 us / 2 = 75 m
`define RP_LONG_BLIND_ZONE_M 4500
`define RP_SHORT_BLIND_ZONE_M 75
// ============================================================================
// PHYSICAL CONSTANTS (integer-scaled for Verilog — use in comments/assertions)
// ============================================================================
// Range per ADC sample: 1.5 m (stored as 15 in units of 0.1 m)
// Range per decimated bin: 24.0 m (stored as 240 in units of 0.1 m)
// Processing rate: 100 MSPS
`define RP_RANGE_PER_SAMPLE_DM 15 // 1.5 m in decimeters
`define RP_RANGE_PER_BIN_DM 240 // 24.0 m in decimeters
`define RP_PROCESSING_RATE_MHZ 100
// ============================================================================
// AGC DEFAULTS
// ============================================================================
`define RP_DEF_AGC_TARGET 200
`define RP_DEF_AGC_ATTACK 1
`define RP_DEF_AGC_DECAY 1
`define RP_DEF_AGC_HOLDOFF 4
// ============================================================================
// CFAR DEFAULTS
// ============================================================================
`define RP_DEF_CFAR_GUARD 2
`define RP_DEF_CFAR_TRAIN 8
`define RP_DEF_CFAR_ALPHA 8'h30 // 3.0 in Q4.4
`define RP_DEF_CFAR_MODE 2'b00 // CA-CFAR
// ============================================================================
// DETECTION DEFAULTS
// ============================================================================
`define RP_DEF_DETECT_THRESHOLD 10000
// ============================================================================
// RANGE MODE ENCODING
// ============================================================================
`define RP_RANGE_MODE_3KM 2'b00
`define RP_RANGE_MODE_20KM 2'b01
`define RP_RANGE_MODE_RSVD2 2'b10
`define RP_RANGE_MODE_RSVD3 2'b11
`endif // RADAR_PARAMS_VH
+36 -31
View File
@@ -11,10 +11,8 @@ module radar_receiver_final (
input wire adc_dco_n, // Data Clock Output N (400MHz LVDS)
output wire adc_pwdn,
// Chirp counter from transmitter (for matched filter indexing)
// Chirp counter from transmitter (for frame sync and matched filter)
input wire [5:0] chirp_counter,
// Frame-start pulse from transmitter (CDC-synchronized, 1 clk_100m cycle)
input wire tx_frame_start,
output wire [31:0] doppler_output,
output wire doppler_valid,
@@ -104,9 +102,9 @@ wire [7:0] gc_saturation_count; // Diagnostic: per-frame clipped sample counter
wire [7:0] gc_peak_magnitude; // Diagnostic: per-frame peak magnitude
wire [3:0] gc_current_gain; // Diagnostic: effective gain_shift
// Reference signals for the processing chain
wire [15:0] long_chirp_real, long_chirp_imag;
wire [15:0] short_chirp_real, short_chirp_imag;
// Reference signal for the processing chain (carries long OR short ref
// depending on use_long_chirp selected by chirp_memory_loader_param)
wire [15:0] ref_chirp_real, ref_chirp_imag;
// ========== DOPPLER PROCESSING SIGNALS ==========
wire [31:0] range_data_32bit;
@@ -294,7 +292,8 @@ end
// sample_addr_wire removed was unused implicit wire (synthesis warning)
// 4. CRITICAL: Reference Chirp Latency Buffer
// This aligns reference data with FFT output (2159 cycle delay)
// This aligns reference data with FFT output (3187 cycle delay)
// TODO: verify empirically during hardware bring-up with correlation test
wire [15:0] delayed_ref_i, delayed_ref_q;
wire mem_ready_delayed;
@@ -310,11 +309,10 @@ latency_buffer #(
.valid_out(mem_ready_delayed)
);
// Assign delayed reference signals
assign long_chirp_real = delayed_ref_i;
assign long_chirp_imag = delayed_ref_q;
assign short_chirp_real = delayed_ref_i;
assign short_chirp_imag = delayed_ref_q;
// Assign delayed reference signals (single pair chirp_memory_loader_param
// selects long/short reference upstream via use_long_chirp)
assign ref_chirp_real = delayed_ref_i;
assign ref_chirp_imag = delayed_ref_q;
// 5. Dual Chirp Matched Filter
@@ -338,10 +336,8 @@ matched_filter_multi_segment mf_dual (
.mc_new_chirp(mc_new_chirp),
.mc_new_elevation(mc_new_elevation),
.mc_new_azimuth(mc_new_azimuth),
.long_chirp_real(delayed_ref_i), // From latency buffer
.long_chirp_imag(delayed_ref_q),
.short_chirp_real(delayed_ref_i), // Same for short chirp
.short_chirp_imag(delayed_ref_q),
.ref_chirp_real(delayed_ref_i), // From latency buffer (long or short ref)
.ref_chirp_imag(delayed_ref_q),
.segment_request(segment_request),
.mem_request(mem_request),
.sample_addr_out(sample_addr_from_chain),
@@ -394,31 +390,32 @@ mti_canceller #(
.mti_first_chirp(mti_first_chirp)
);
// ========== FRAME SYNC FROM TRANSMITTER ==========
// [FPGA-001 FIXED] Use the authoritative new_chirp_frame signal from the
// transmitter (via plfm_chirp_controller_enhanced), CDC-synchronized to
// clk_100m in radar_system_top. Previous code tried to derive frame
// boundaries from chirp_counter == 0, but that counter comes from the
// transmitter path (plfm_chirp_controller_enhanced) which does NOT wrap
// at chirps_per_elev it overflows to N and only wraps at 6-bit rollover
// (64). This caused frame pulses at half the expected rate for N=32.
reg tx_frame_start_prev;
// ========== FRAME SYNC USING chirp_counter ==========
reg [5:0] chirp_counter_prev;
reg new_frame_pulse;
always @(posedge clk or negedge reset_n) begin
if (!reset_n) begin
tx_frame_start_prev <= 1'b0;
chirp_counter_prev <= 6'd0;
new_frame_pulse <= 1'b0;
end else begin
// Default: no pulse
new_frame_pulse <= 1'b0;
// Edge detect: tx_frame_start is a toggle-CDC derived pulse that
// may be 1 clock wide. Capture rising edge for clean 1-cycle pulse.
if (tx_frame_start && !tx_frame_start_prev) begin
new_frame_pulse <= 1'b1;
// Dynamic frame detection using host_chirps_per_elev.
// Detect frame boundary when chirp_counter changes AND is a
// multiple of host_chirps_per_elev (0, N, 2N, 3N, ...).
// Uses a modulo counter that resets at host_chirps_per_elev.
if (chirp_counter != chirp_counter_prev) begin
if (chirp_counter == 6'd0 ||
chirp_counter == host_chirps_per_elev ||
chirp_counter == {host_chirps_per_elev, 1'b0}) begin
new_frame_pulse <= 1'b1;
end
end
tx_frame_start_prev <= tx_frame_start;
// Store previous value
chirp_counter_prev <= chirp_counter;
end
end
@@ -484,6 +481,14 @@ always @(posedge clk or negedge reset_n) begin
`endif
chirps_in_current_frame <= 0;
end
// Monitor chirp counter pattern
if (chirp_counter != chirp_counter_prev) begin
`ifdef SIMULATION
$display("[TOP] chirp_counter: %0d ? %0d",
chirp_counter_prev, chirp_counter);
`endif
end
end
end
-2
View File
@@ -505,8 +505,6 @@ radar_receiver_final rx_inst (
// Chirp counter from transmitter (CDC-synchronized from 120 MHz domain)
.chirp_counter(tx_current_chirp_sync),
// Frame-start pulse from transmitter (CDC-synchronized togglepulse)
.tx_frame_start(tx_new_chirp_frame_sync),
// ADC Physical Interface
.adc_d_p(adc_d_p),
+88 -26
View File
@@ -253,6 +253,68 @@ run_lint_static() {
fi
}
# ---------------------------------------------------------------------------
# Helper: compile, run, and compare a matched-filter co-sim scenario
# run_mf_cosim <scenario_name> <define_flag>
# ---------------------------------------------------------------------------
run_mf_cosim() {
local name="$1"
local define="$2"
local vvp="tb/tb_mf_cosim_${name}.vvp"
local scenario_lower="$name"
printf " %-45s " "MF Co-Sim ($name)"
# Compile — build command as string to handle optional define
local cmd="iverilog -g2001 -DSIMULATION"
if [[ -n "$define" ]]; then
cmd="$cmd $define"
fi
cmd="$cmd -o $vvp tb/tb_mf_cosim.v matched_filter_processing_chain.v fft_engine.v chirp_memory_loader_param.v"
if ! eval "$cmd" 2>/tmp/iverilog_err_$$; then
echo -e "${RED}COMPILE FAIL${NC}"
ERRORS="$ERRORS\n MF Co-Sim ($name): compile error ($(head -1 /tmp/iverilog_err_$$))"
FAIL=$((FAIL + 1))
return
fi
# Run TB
local output
output=$(timeout 120 vvp "$vvp" 2>&1) || true
rm -f "$vvp"
# Check TB internal pass/fail
local tb_fail
tb_fail=$(echo "$output" | grep -Ec '^\[FAIL' || true)
if [[ "$tb_fail" -gt 0 ]]; then
echo -e "${RED}FAIL${NC} (TB internal failure)"
ERRORS="$ERRORS\n MF Co-Sim ($name): TB internal failure"
FAIL=$((FAIL + 1))
return
fi
# Run Python compare
if command -v python3 >/dev/null 2>&1; then
local compare_out
local compare_rc=0
compare_out=$(python3 tb/cosim/compare_mf.py "$scenario_lower" 2>&1) || compare_rc=$?
if [[ "$compare_rc" -ne 0 ]]; then
echo -e "${RED}FAIL${NC} (compare_mf.py mismatch)"
ERRORS="$ERRORS\n MF Co-Sim ($name): Python compare failed"
FAIL=$((FAIL + 1))
return
fi
else
echo -e "${YELLOW}SKIP${NC} (RTL passed, python3 not found — compare skipped)"
SKIP=$((SKIP + 1))
return
fi
echo -e "${GREEN}PASS${NC} (RTL + Python compare)"
PASS=$((PASS + 1))
}
# ---------------------------------------------------------------------------
# Helper: compile and run a single testbench
# run_test <name> <vvp_path> <iverilog_args...>
@@ -416,30 +478,14 @@ run_test "Full-Chain Real-Data (decim→Doppler, exact match)" \
doppler_processor.v xfft_16.v fft_engine.v
if [[ "$QUICK" -eq 0 ]]; then
# Golden generate
run_test "Receiver (golden generate)" \
tb/tb_rx_golden_reg.vvp \
-DGOLDEN_GENERATE \
tb/tb_radar_receiver_final.v radar_receiver_final.v \
radar_mode_controller.v tb/ad9484_interface_400m_stub.v \
ddc_400m.v nco_400m_enhanced.v cic_decimator_4x_enhanced.v \
cdc_modules.v fir_lowpass.v ddc_input_interface.v \
chirp_memory_loader_param.v latency_buffer.v \
matched_filter_multi_segment.v matched_filter_processing_chain.v \
range_bin_decimator.v doppler_processor.v xfft_16.v fft_engine.v \
rx_gain_control.v mti_canceller.v
# Golden compare
run_test "Receiver (golden compare)" \
tb/tb_rx_compare_reg.vvp \
tb/tb_radar_receiver_final.v radar_receiver_final.v \
radar_mode_controller.v tb/ad9484_interface_400m_stub.v \
ddc_400m.v nco_400m_enhanced.v cic_decimator_4x_enhanced.v \
cdc_modules.v fir_lowpass.v ddc_input_interface.v \
chirp_memory_loader_param.v latency_buffer.v \
matched_filter_multi_segment.v matched_filter_processing_chain.v \
range_bin_decimator.v doppler_processor.v xfft_16.v fft_engine.v \
rx_gain_control.v mti_canceller.v
# NOTE: The "Receiver golden generate/compare" pair was REMOVED because
# it was self-blessing: both passes ran the same RTL with the same
# deterministic stimulus, so the test always passed regardless of bugs.
# Real co-sim coverage is provided by:
# - tb_doppler_realdata.v (committed Python golden hex, exact match)
# - tb_fullchain_realdata.v (committed Python golden hex, exact match)
# A proper full-pipeline co-sim (DDC→MF→Decim→Doppler vs Python) is
# planned as a replacement (Phase C of CI test plan).
# Full system top (monitoring-only, legacy)
run_test "System Top (radar_system_tb)" \
@@ -469,12 +515,28 @@ if [[ "$QUICK" -eq 0 ]]; then
usb_data_interface.v edge_detector.v radar_mode_controller.v \
rx_gain_control.v cfar_ca.v mti_canceller.v fpga_self_test.v
else
echo " (skipped receiver golden + system top + E2E — use without --quick)"
SKIP=$((SKIP + 4))
echo " (skipped system top + E2E — use without --quick)"
SKIP=$((SKIP + 2))
fi
echo ""
# ===========================================================================
# PHASE 2b: MATCHED FILTER CO-SIMULATION (RTL vs Python golden reference)
# Runs tb_mf_cosim.v for 4 scenarios, then compare_mf.py validates output
# against committed Python golden CSV files. In SIMULATION mode, thresholds
# are generous (behavioral vs fixed-point twiddles differ) — validates
# state machine mechanics, output count, and energy sanity.
# ===========================================================================
echo "--- PHASE 2b: Matched Filter Co-Sim ---"
run_mf_cosim "chirp" ""
run_mf_cosim "dc" "-DSCENARIO_DC"
run_mf_cosim "impulse" "-DSCENARIO_IMPULSE"
run_mf_cosim "tone5" "-DSCENARIO_TONE5"
echo ""
# ===========================================================================
# PHASE 3: UNIT TESTS — Signal Processing
# ===========================================================================
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -2,8 +2,8 @@
"""
golden_reference.py — AERIS-10 FPGA bit-accurate golden reference model
Uses ADI CN0566 Phaser radar data (10.525 GHz X-band FMCW) to validate
the FPGA signal processing pipeline stage by stage:
Uses ADI CN0566 Phaser radar data (10.525 GHz, used as test stimulus only) to
validate the FPGA signal processing pipeline stage by stage:
ADC → DDC (NCO+mixer+CIC+FIR) → Range FFT → Doppler FFT → Detection
@@ -90,7 +90,8 @@ HAMMING_Q15 = [
0x3088, 0x1B6D, 0x0E5C, 0x0A3D,
]
# ADI dataset parameters
# ADI dataset parameters — used ONLY for loading/requantizing ADI Phaser test data.
# These are NOT PLFM hardware parameters. See AERIS-10 constants below.
ADI_SAMPLE_RATE = 4e6 # 4 MSPS
ADI_IF_FREQ = 100e3 # 100 kHz IF
ADI_RF_FREQ = 9.9e9 # 9.9 GHz
@@ -99,9 +100,17 @@ ADI_RAMP_TIME = 300e-6 # 300 us
ADI_NUM_CHIRPS = 256
ADI_SAMPLES_PER_CHIRP = 1079
# AERIS-10 parameters
AERIS_FS = 400e6 # 400 MHz ADC clock
AERIS_IF = 120e6 # 120 MHz IF
# AERIS-10 hardware parameters (from ADF4382/AD9523/main.cpp configuration)
AERIS_FS = 400e6 # 400 MHz ADC clock (AD9523 OUT4)
AERIS_IF = 120e6 # 120 MHz IF (TX 10.5 GHz - RX 10.38 GHz)
AERIS_FS_PROCESSING = 100e6 # Post-DDC rate (400 MSPS / 4x CIC)
AERIS_CARRIER_HZ = 10.5e9 # TX LO (ADF4382, verified)
AERIS_RX_LO_HZ = 10.38e9 # RX LO (ADF4382)
AERIS_CHIRP_BW = 20e6 # Chirp bandwidth (target: 30 MHz Phase 1)
AERIS_LONG_CHIRP_S = 30e-6 # Long chirp duration
AERIS_PRI_S = 167e-6 # Pulse repetition interval
AERIS_DECIMATION = 16 # Range bin decimation (1024 → 64)
AERIS_RANGE_PER_BIN = 24.0 # Meters per decimated bin
# ===========================================================================
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -421,13 +421,13 @@ def test_latency_buffer():
#
# For synthesis: the latency_buffer feeds ref data to the chain via
# chirp_memory_loader_param → latency_buffer → chain.
# But wait — looking at radar_receiver_final.v:
# Looking at radar_receiver_final.v:
# - mem_request drives valid_in on the latency buffer
# - The buffer delays {ref_i, ref_q} by LATENCY valid_in cycles
# - The delayed output feeds long_chirp_real/imag → chain
# - The delayed output feeds ref_chirp_real/imag → chain
#
# The purpose: the chain in the SYNTHESIS branch reads reference data
# via the long_chirp_real/imag ports DURING ST_FWD_FFT (while collecting
# via the ref_chirp_real/imag ports DURING ST_FWD_FFT (while collecting
# input samples). The reference data needs to arrive LATENCY cycles
# after the first mem_request, where LATENCY accounts for:
# - The fft_engine pipeline latency from input to output
File diff suppressed because it is too large Load Diff
@@ -18,10 +18,8 @@ module tb_matched_filter_processing_chain;
reg [15:0] adc_data_q;
reg adc_valid;
reg [5:0] chirp_counter;
reg [15:0] long_chirp_real;
reg [15:0] long_chirp_imag;
reg [15:0] short_chirp_real;
reg [15:0] short_chirp_imag;
reg [15:0] ref_chirp_real;
reg [15:0] ref_chirp_imag;
wire signed [15:0] range_profile_i;
wire signed [15:0] range_profile_q;
wire range_profile_valid;
@@ -83,10 +81,8 @@ module tb_matched_filter_processing_chain;
.adc_data_q (adc_data_q),
.adc_valid (adc_valid),
.chirp_counter (chirp_counter),
.long_chirp_real (long_chirp_real),
.long_chirp_imag (long_chirp_imag),
.short_chirp_real (short_chirp_real),
.short_chirp_imag (short_chirp_imag),
.ref_chirp_real (ref_chirp_real),
.ref_chirp_imag (ref_chirp_imag),
.range_profile_i (range_profile_i),
.range_profile_q (range_profile_q),
.range_profile_valid (range_profile_valid),
@@ -133,10 +129,8 @@ module tb_matched_filter_processing_chain;
adc_data_i = 16'd0;
adc_data_q = 16'd0;
chirp_counter = 6'd0;
long_chirp_real = 16'd0;
long_chirp_imag = 16'd0;
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = 16'd0;
ref_chirp_imag = 16'd0;
cap_enable = 0;
cap_count = 0;
cap_max_abs = 0;
@@ -168,10 +162,8 @@ module tb_matched_filter_processing_chain;
angle = 6.28318530718 * tone_bin * k / (1.0 * FFT_SIZE);
adc_data_i = $rtoi(8000.0 * $cos(angle));
adc_data_q = $rtoi(8000.0 * $sin(angle));
long_chirp_real = $rtoi(8000.0 * $cos(angle));
long_chirp_imag = $rtoi(8000.0 * $sin(angle));
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = $rtoi(8000.0 * $cos(angle));
ref_chirp_imag = $rtoi(8000.0 * $sin(angle));
adc_valid = 1'b1;
@(posedge clk);
#1;
@@ -187,10 +179,8 @@ module tb_matched_filter_processing_chain;
for (k = 0; k < FFT_SIZE; k = k + 1) begin
adc_data_i = 16'sh1000;
adc_data_q = 16'sh0000;
long_chirp_real = 16'sh1000;
long_chirp_imag = 16'sh0000;
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = 16'sh1000;
ref_chirp_imag = 16'sh0000;
adc_valid = 1'b1;
@(posedge clk);
#1;
@@ -233,10 +223,8 @@ module tb_matched_filter_processing_chain;
for (k = 0; k < FFT_SIZE; k = k + 1) begin
adc_data_i = gold_sig_i[k];
adc_data_q = gold_sig_q[k];
long_chirp_real = gold_ref_i[k];
long_chirp_imag = gold_ref_q[k];
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = gold_ref_i[k];
ref_chirp_imag = gold_ref_q[k];
adc_valid = 1'b1;
@(posedge clk);
#1;
@@ -374,10 +362,8 @@ module tb_matched_filter_processing_chain;
for (i = 0; i < FFT_SIZE; i = i + 1) begin
adc_data_i = 16'd0;
adc_data_q = 16'd0;
long_chirp_real = 16'd0;
long_chirp_imag = 16'd0;
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = 16'd0;
ref_chirp_imag = 16'd0;
adc_valid = 1'b1;
@(posedge clk); #1;
end
@@ -449,10 +435,8 @@ module tb_matched_filter_processing_chain;
for (i = 0; i < FFT_SIZE; i = i + 1) begin
adc_data_i = $rtoi(8000.0 * $cos(6.28318530718 * 5 * i / 1024.0));
adc_data_q = $rtoi(8000.0 * $sin(6.28318530718 * 5 * i / 1024.0));
long_chirp_real = $rtoi(8000.0 * $cos(6.28318530718 * 10 * i / 1024.0));
long_chirp_imag = $rtoi(8000.0 * $sin(6.28318530718 * 10 * i / 1024.0));
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = $rtoi(8000.0 * $cos(6.28318530718 * 10 * i / 1024.0));
ref_chirp_imag = $rtoi(8000.0 * $sin(6.28318530718 * 10 * i / 1024.0));
adc_valid = 1'b1;
@(posedge clk); #1;
end
@@ -568,10 +552,8 @@ module tb_matched_filter_processing_chain;
for (i = 0; i < FFT_SIZE; i = i + 1) begin
adc_data_i = 16'sh7FFF;
adc_data_q = 16'sh7FFF;
long_chirp_real = 16'sh7FFF;
long_chirp_imag = 16'sh7FFF;
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = 16'sh7FFF;
ref_chirp_imag = 16'sh7FFF;
adc_valid = 1'b1;
@(posedge clk); #1;
end
@@ -589,10 +571,8 @@ module tb_matched_filter_processing_chain;
for (i = 0; i < FFT_SIZE; i = i + 1) begin
adc_data_i = 16'sh8000;
adc_data_q = 16'sh8000;
long_chirp_real = 16'sh8000;
long_chirp_imag = 16'sh8000;
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = 16'sh8000;
ref_chirp_imag = 16'sh8000;
adc_valid = 1'b1;
@(posedge clk); #1;
end
@@ -611,16 +591,14 @@ module tb_matched_filter_processing_chain;
if (i % 2 == 0) begin
adc_data_i = 16'sh7FFF;
adc_data_q = 16'sh7FFF;
long_chirp_real = 16'sh7FFF;
long_chirp_imag = 16'sh7FFF;
ref_chirp_real = 16'sh7FFF;
ref_chirp_imag = 16'sh7FFF;
end else begin
adc_data_i = 16'sh8000;
adc_data_q = 16'sh8000;
long_chirp_real = 16'sh8000;
long_chirp_imag = 16'sh8000;
ref_chirp_real = 16'sh8000;
ref_chirp_imag = 16'sh8000;
end
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
adc_valid = 1'b1;
@(posedge clk); #1;
end
@@ -641,10 +619,8 @@ module tb_matched_filter_processing_chain;
for (i = 0; i < 512; i = i + 1) begin
adc_data_i = 16'sh1000;
adc_data_q = 16'sh0000;
long_chirp_real = 16'sh1000;
long_chirp_imag = 16'sh0000;
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = 16'sh1000;
ref_chirp_imag = 16'sh0000;
adc_valid = 1'b1;
@(posedge clk); #1;
end
@@ -683,10 +659,8 @@ module tb_matched_filter_processing_chain;
for (i = 0; i < FFT_SIZE; i = i + 1) begin
adc_data_i = 16'sh1000;
adc_data_q = 16'sh0000;
long_chirp_real = 16'sh1000;
long_chirp_imag = 16'sh0000;
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = 16'sh1000;
ref_chirp_imag = 16'sh0000;
adc_valid = 1'b1;
@(posedge clk); #1;
+24 -46
View File
@@ -28,10 +28,8 @@ module tb_mf_chain_synth;
reg [15:0] adc_data_q;
reg adc_valid;
reg [5:0] chirp_counter;
reg [15:0] long_chirp_real;
reg [15:0] long_chirp_imag;
reg [15:0] short_chirp_real;
reg [15:0] short_chirp_imag;
reg [15:0] ref_chirp_real;
reg [15:0] ref_chirp_imag;
wire signed [15:0] range_profile_i;
wire signed [15:0] range_profile_q;
wire range_profile_valid;
@@ -78,10 +76,8 @@ module tb_mf_chain_synth;
.adc_data_q (adc_data_q),
.adc_valid (adc_valid),
.chirp_counter (chirp_counter),
.long_chirp_real (long_chirp_real),
.long_chirp_imag (long_chirp_imag),
.short_chirp_real (short_chirp_real),
.short_chirp_imag (short_chirp_imag),
.ref_chirp_real (ref_chirp_real),
.ref_chirp_imag (ref_chirp_imag),
.range_profile_i (range_profile_i),
.range_profile_q (range_profile_q),
.range_profile_valid (range_profile_valid),
@@ -130,10 +126,8 @@ module tb_mf_chain_synth;
adc_data_i = 16'd0;
adc_data_q = 16'd0;
chirp_counter = 6'd0;
long_chirp_real = 16'd0;
long_chirp_imag = 16'd0;
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = 16'd0;
ref_chirp_imag = 16'd0;
cap_enable = 0;
cap_count = 0;
cap_max_abs = 0;
@@ -177,10 +171,8 @@ module tb_mf_chain_synth;
for (k = 0; k < FFT_SIZE; k = k + 1) begin
adc_data_i = 16'sh1000; // +4096
adc_data_q = 16'sh0000;
long_chirp_real = 16'sh1000;
long_chirp_imag = 16'sh0000;
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = 16'sh1000;
ref_chirp_imag = 16'sh0000;
adc_valid = 1'b1;
@(posedge clk);
#1;
@@ -199,10 +191,8 @@ module tb_mf_chain_synth;
angle = 6.28318530718 * tone_bin * k / (1.0 * FFT_SIZE);
adc_data_i = $rtoi(8000.0 * $cos(angle));
adc_data_q = $rtoi(8000.0 * $sin(angle));
long_chirp_real = $rtoi(8000.0 * $cos(angle));
long_chirp_imag = $rtoi(8000.0 * $sin(angle));
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = $rtoi(8000.0 * $cos(angle));
ref_chirp_imag = $rtoi(8000.0 * $sin(angle));
adc_valid = 1'b1;
@(posedge clk);
#1;
@@ -219,16 +209,14 @@ module tb_mf_chain_synth;
if (k == 0) begin
adc_data_i = 16'sh4000; // 0.5 in Q15
adc_data_q = 16'sh0000;
long_chirp_real = 16'sh4000;
long_chirp_imag = 16'sh0000;
ref_chirp_real = 16'sh4000;
ref_chirp_imag = 16'sh0000;
end else begin
adc_data_i = 16'sh0000;
adc_data_q = 16'sh0000;
long_chirp_real = 16'sh0000;
long_chirp_imag = 16'sh0000;
ref_chirp_real = 16'sh0000;
ref_chirp_imag = 16'sh0000;
end
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
adc_valid = 1'b1;
@(posedge clk);
#1;
@@ -309,10 +297,8 @@ module tb_mf_chain_synth;
for (i = 0; i < FFT_SIZE; i = i + 1) begin
adc_data_i = 16'd0;
adc_data_q = 16'd0;
long_chirp_real = 16'd0;
long_chirp_imag = 16'd0;
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = 16'd0;
ref_chirp_imag = 16'd0;
adc_valid = 1'b1;
@(posedge clk); #1;
end
@@ -379,10 +365,8 @@ module tb_mf_chain_synth;
for (i = 0; i < 512; i = i + 1) begin
adc_data_i = 16'sh1000;
adc_data_q = 16'sh0000;
long_chirp_real = 16'sh1000;
long_chirp_imag = 16'sh0000;
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = 16'sh1000;
ref_chirp_imag = 16'sh0000;
adc_valid = 1'b1;
@(posedge clk); #1;
end
@@ -439,10 +423,8 @@ module tb_mf_chain_synth;
for (i = 0; i < FFT_SIZE; i = i + 1) begin
adc_data_i = $rtoi(8000.0 * $cos(6.28318530718 * 5 * i / 1024.0));
adc_data_q = $rtoi(8000.0 * $sin(6.28318530718 * 5 * i / 1024.0));
long_chirp_real = $rtoi(8000.0 * $cos(6.28318530718 * 10 * i / 1024.0));
long_chirp_imag = $rtoi(8000.0 * $sin(6.28318530718 * 10 * i / 1024.0));
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = $rtoi(8000.0 * $cos(6.28318530718 * 10 * i / 1024.0));
ref_chirp_imag = $rtoi(8000.0 * $sin(6.28318530718 * 10 * i / 1024.0));
adc_valid = 1'b1;
@(posedge clk); #1;
end
@@ -469,10 +451,8 @@ module tb_mf_chain_synth;
for (i = 0; i < FFT_SIZE; i = i + 1) begin
adc_data_i = 16'sh7FFF;
adc_data_q = 16'sh7FFF;
long_chirp_real = 16'sh7FFF;
long_chirp_imag = 16'sh7FFF;
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = 16'sh7FFF;
ref_chirp_imag = 16'sh7FFF;
adc_valid = 1'b1;
@(posedge clk); #1;
end
@@ -495,10 +475,8 @@ module tb_mf_chain_synth;
for (i = 0; i < FFT_SIZE; i = i + 1) begin
adc_data_i = 16'sh1000;
adc_data_q = 16'sh0000;
long_chirp_real = 16'sh1000;
long_chirp_imag = 16'sh0000;
short_chirp_real = 16'd0;
short_chirp_imag = 16'd0;
ref_chirp_real = 16'sh1000;
ref_chirp_imag = 16'sh0000;
adc_valid = 1'b1;
@(posedge clk); #1;
+10 -18
View File
@@ -88,10 +88,8 @@ reg [15:0] adc_data_i;
reg [15:0] adc_data_q;
reg adc_valid;
reg [5:0] chirp_counter;
reg [15:0] long_chirp_real;
reg [15:0] long_chirp_imag;
reg [15:0] short_chirp_real;
reg [15:0] short_chirp_imag;
reg [15:0] ref_chirp_real;
reg [15:0] ref_chirp_imag;
wire signed [15:0] range_profile_i;
wire signed [15:0] range_profile_q;
@@ -108,10 +106,8 @@ matched_filter_processing_chain dut (
.adc_data_q(adc_data_q),
.adc_valid(adc_valid),
.chirp_counter(chirp_counter),
.long_chirp_real(long_chirp_real),
.long_chirp_imag(long_chirp_imag),
.short_chirp_real(short_chirp_real),
.short_chirp_imag(short_chirp_imag),
.ref_chirp_real(ref_chirp_real),
.ref_chirp_imag(ref_chirp_imag),
.range_profile_i(range_profile_i),
.range_profile_q(range_profile_q),
.range_profile_valid(range_profile_valid),
@@ -157,10 +153,8 @@ task apply_reset;
adc_data_q <= 16'd0;
adc_valid <= 1'b0;
chirp_counter <= 6'd0;
long_chirp_real <= 16'd0;
long_chirp_imag <= 16'd0;
short_chirp_real <= 16'd0;
short_chirp_imag <= 16'd0;
ref_chirp_real <= 16'd0;
ref_chirp_imag <= 16'd0;
repeat(4) @(posedge clk);
reset_n <= 1'b1;
@(posedge clk);
@@ -201,18 +195,16 @@ initial begin
@(posedge clk);
adc_data_i <= sig_mem_i[i];
adc_data_q <= sig_mem_q[i];
long_chirp_real <= ref_mem_i[i];
long_chirp_imag <= ref_mem_q[i];
short_chirp_real <= 16'd0;
short_chirp_imag <= 16'd0;
ref_chirp_real <= ref_mem_i[i];
ref_chirp_imag <= ref_mem_q[i];
adc_valid <= 1'b1;
end
@(posedge clk);
adc_valid <= 1'b0;
adc_data_i <= 16'd0;
adc_data_q <= 16'd0;
long_chirp_real <= 16'd0;
long_chirp_imag <= 16'd0;
ref_chirp_real <= 16'd0;
ref_chirp_imag <= 16'd0;
$display("All samples fed. Waiting for processing...");
+10 -16
View File
@@ -56,10 +56,8 @@ reg [5:0] chirp_counter;
reg mc_new_chirp;
reg mc_new_elevation;
reg mc_new_azimuth;
reg [15:0] long_chirp_real;
reg [15:0] long_chirp_imag;
reg [15:0] short_chirp_real;
reg [15:0] short_chirp_imag;
reg [15:0] ref_chirp_real;
reg [15:0] ref_chirp_imag;
reg mem_ready;
wire signed [15:0] pc_i_w;
@@ -84,10 +82,8 @@ matched_filter_multi_segment dut (
.mc_new_chirp(mc_new_chirp),
.mc_new_elevation(mc_new_elevation),
.mc_new_azimuth(mc_new_azimuth),
.long_chirp_real(long_chirp_real),
.long_chirp_imag(long_chirp_imag),
.short_chirp_real(short_chirp_real),
.short_chirp_imag(short_chirp_imag),
.ref_chirp_real(ref_chirp_real),
.ref_chirp_imag(ref_chirp_imag),
.segment_request(segment_request),
.sample_addr_out(sample_addr_out),
.mem_request(mem_request),
@@ -123,11 +119,11 @@ end
always @(posedge clk) begin
if (mem_request) begin
if (use_long_chirp) begin
long_chirp_real <= ref_mem_i[{segment_request, sample_addr_out}];
long_chirp_imag <= ref_mem_q[{segment_request, sample_addr_out}];
ref_chirp_real <= ref_mem_i[{segment_request, sample_addr_out}];
ref_chirp_imag <= ref_mem_q[{segment_request, sample_addr_out}];
end else begin
short_chirp_real <= ref_mem_i[sample_addr_out];
short_chirp_imag <= ref_mem_q[sample_addr_out];
ref_chirp_real <= ref_mem_i[sample_addr_out];
ref_chirp_imag <= ref_mem_q[sample_addr_out];
end
mem_ready <= 1'b1;
end else begin
@@ -176,10 +172,8 @@ task apply_reset;
mc_new_chirp <= 1'b0;
mc_new_elevation <= 1'b0;
mc_new_azimuth <= 1'b0;
long_chirp_real <= 16'd0;
long_chirp_imag <= 16'd0;
short_chirp_real <= 16'd0;
short_chirp_imag <= 16'd0;
ref_chirp_real <= 16'd0;
ref_chirp_imag <= 16'd0;
mem_ready <= 1'b0;
repeat(10) @(posedge clk);
reset_n <= 1'b1;
@@ -7,43 +7,21 @@
// -> matched_filter_multi_segment -> range_bin_decimator
// -> doppler_processor_optimized -> doppler_output
//
// ============================================================================
// TWO MODES (compile-time define):
//
// 1. GOLDEN_GENERATE mode (-DGOLDEN_GENERATE):
// Dumps all Doppler output samples to golden reference files.
// Run once on known-good RTL:
// iverilog -g2001 -DSIMULATION -DGOLDEN_GENERATE -o tb_golden_gen.vvp \
// <src files> tb/tb_radar_receiver_final.v
// mkdir -p tb/golden
// vvp tb_golden_gen.vvp
//
// 2. Default mode (no GOLDEN_GENERATE):
// Loads golden files, compares each Doppler output against reference,
// and runs physics-based bounds checks.
// iverilog -g2001 -DSIMULATION -o tb_radar_receiver_final.vvp \
// <src files> tb/tb_radar_receiver_final.v
// vvp tb_radar_receiver_final.vvp
//
// PREREQUISITES:
// - The directory tb/golden/ must exist before running either mode.
// Create it with: mkdir -p tb/golden
//
// TAP POINTS:
// Tap 1 (DDC output) - bounds checking only (CDC jitter -> non-deterministic)
// Signals: dut.ddc_out_i [17:0], dut.ddc_out_q [17:0], dut.ddc_valid_i
// Tap 2 (Doppler output) - golden compared (deterministic after MF buffering)
// Tap 2 (Doppler output) - structural + bounds checks (deterministic after MF)
// Signals: doppler_output[31:0], doppler_valid, doppler_bin[4:0],
// range_bin_out[5:0]
//
// Golden file: tb/golden/golden_doppler.mem
// 2048 entries of 32-bit hex, indexed by range_bin*32 + doppler_bin
//
// Strategy:
// - Uses behavioral stub for ad9484_interface_400m (no Xilinx primitives)
// - Overrides radar_mode_controller timing params for fast simulation
// - Feeds 120 MHz tone at ADC input (IF frequency -> DDC passband)
// - Verifies structural correctness + golden comparison + bounds checks
// - Verifies structural correctness (S1-S10) + physics bounds checks (B1-B5)
// - Bit-accurate golden comparison is done by the MF co-sim tests
// (tb_mf_cosim.v + compare_mf.py) and full-chain co-sim tests
// (tb_doppler_realdata.v, tb_fullchain_realdata.v), not here.
//
// Convention: check task, VCD dump, CSV output, pass/fail summary
// ============================================================================
@@ -96,31 +74,15 @@ end
reg [5:0] chirp_counter;
reg mc_new_chirp_prev;
// Frame-start pulse: mirrors the real transmitter's new_chirp_frame signal.
// In the real system this fires on IDLELONG_CHIRP transitions in the chirp
// controller. Here we derive it from the mode controller's chirp_count
// wrapping back to 0 (which wraps correctly at cfg_chirps_per_elev).
reg tx_frame_start;
reg [5:0] rmc_chirp_prev;
always @(posedge clk_100m or negedge reset_n) begin
if (!reset_n) begin
chirp_counter <= 6'd0;
mc_new_chirp_prev <= 1'b0;
tx_frame_start <= 1'b0;
rmc_chirp_prev <= 6'd0;
end else begin
mc_new_chirp_prev <= dut.mc_new_chirp;
if (dut.mc_new_chirp != mc_new_chirp_prev) begin
chirp_counter <= chirp_counter + 1;
end
// Detect when the internal mode controller's chirp_count wraps to 0
tx_frame_start <= 1'b0;
if (dut.rmc_chirp_count == 6'd0 && rmc_chirp_prev != 6'd0) begin
tx_frame_start <= 1'b1;
end
rmc_chirp_prev <= dut.rmc_chirp_count;
end
end
@@ -144,7 +106,6 @@ radar_receiver_final dut (
.adc_pwdn(),
.chirp_counter(chirp_counter),
.tx_frame_start(tx_frame_start),
.doppler_output(doppler_output),
.doppler_valid(doppler_valid),
@@ -211,46 +172,6 @@ task check;
end
endtask
// ============================================================================
// GOLDEN MEMORY DECLARATIONS AND LOAD/STORE LOGIC
// ============================================================================
localparam GOLDEN_ENTRIES = 2048; // 64 range bins * 32 Doppler bins
localparam GOLDEN_TOLERANCE = 2; // +/- 2 LSB tolerance for comparison
reg [31:0] golden_doppler [0:2047];
// -- Golden comparison tracking --
integer golden_match_count;
integer golden_mismatch_count;
integer golden_max_err_i;
integer golden_max_err_q;
integer golden_compare_count;
`ifdef GOLDEN_GENERATE
// In generate mode, we just initialize the array to X/0
// and fill it as outputs arrive
integer gi;
initial begin
for (gi = 0; gi < GOLDEN_ENTRIES; gi = gi + 1)
golden_doppler[gi] = 32'd0;
golden_match_count = 0;
golden_mismatch_count = 0;
golden_max_err_i = 0;
golden_max_err_q = 0;
golden_compare_count = 0;
end
`else
// In comparison mode, load the golden reference
initial begin
$readmemh("tb/golden/golden_doppler.mem", golden_doppler);
golden_match_count = 0;
golden_mismatch_count = 0;
golden_max_err_i = 0;
golden_max_err_q = 0;
golden_compare_count = 0;
end
`endif
// ============================================================================
// DDC ENERGY ACCUMULATOR (Bounds Check B1)
// ============================================================================
@@ -274,7 +195,7 @@ always @(posedge clk_100m) begin
end
// ============================================================================
// DOPPLER OUTPUT CAPTURE, GOLDEN COMPARISON, AND DUPLICATE DETECTION
// DOPPLER OUTPUT CAPTURE AND DUPLICATE DETECTION
// ============================================================================
integer doppler_output_count;
integer doppler_frame_count;
@@ -328,13 +249,6 @@ end
// Monitor doppler outputs -- only after reset released
always @(posedge clk_100m) begin
if (reset_n && doppler_valid) begin : doppler_capture_block
// ---- Signed intermediates for golden comparison ----
reg signed [16:0] actual_i, actual_q;
reg signed [16:0] expected_i, expected_q;
reg signed [16:0] err_i_signed, err_q_signed;
integer abs_err_i, abs_err_q;
integer gidx;
reg [31:0] expected_val;
// ---- Magnitude intermediates for B2 ----
reg signed [16:0] mag_i_signed, mag_q_signed;
integer mag_i, mag_q, mag_sum;
@@ -367,9 +281,6 @@ always @(posedge clk_100m) begin
if ((doppler_output_count % 256) == 0)
$display("[INFO] %0d doppler outputs so far (t=%0t)", doppler_output_count, $time);
// ---- Golden index computation ----
gidx = range_bin_out * 32 + doppler_bin;
// ---- Duplicate detection (B5) ----
if (range_bin_out < 64 && doppler_bin < 32) begin
if (index_seen[range_bin_out][doppler_bin]) begin
@@ -393,44 +304,6 @@ always @(posedge clk_100m) begin
if (mag_sum > peak_dbin_mag[range_bin_out])
peak_dbin_mag[range_bin_out] = mag_sum;
end
`ifdef GOLDEN_GENERATE
// ---- GOLDEN GENERATE: store output ----
if (gidx < GOLDEN_ENTRIES)
golden_doppler[gidx] = doppler_output;
`else
// ---- GOLDEN COMPARE: check against reference ----
if (gidx < GOLDEN_ENTRIES) begin
expected_val = golden_doppler[gidx];
actual_i = $signed(doppler_output[15:0]);
actual_q = $signed(doppler_output[31:16]);
expected_i = $signed(expected_val[15:0]);
expected_q = $signed(expected_val[31:16]);
err_i_signed = actual_i - expected_i;
err_q_signed = actual_q - expected_q;
abs_err_i = (err_i_signed < 0) ? -err_i_signed : err_i_signed;
abs_err_q = (err_q_signed < 0) ? -err_q_signed : err_q_signed;
golden_compare_count = golden_compare_count + 1;
if (abs_err_i > golden_max_err_i) golden_max_err_i = abs_err_i;
if (abs_err_q > golden_max_err_q) golden_max_err_q = abs_err_q;
if (abs_err_i <= GOLDEN_TOLERANCE && abs_err_q <= GOLDEN_TOLERANCE) begin
golden_match_count = golden_match_count + 1;
end else begin
golden_mismatch_count = golden_mismatch_count + 1;
if (golden_mismatch_count <= 20)
$display("[MISMATCH] idx=%0d rbin=%0d dbin=%0d actual=%08h expected=%08h err_i=%0d err_q=%0d",
gidx, range_bin_out, doppler_bin,
doppler_output, expected_val,
abs_err_i, abs_err_q);
end
end
`endif
end
// Track frame completions via doppler_proc -- only after reset
@@ -573,13 +446,6 @@ initial begin
end
end
// ---- DUMP GOLDEN FILE (generate mode only) ----
`ifdef GOLDEN_GENERATE
$writememh("tb/golden/golden_doppler.mem", golden_doppler);
$display("[GOLDEN_GENERATE] Wrote tb/golden/golden_doppler.mem (%0d entries captured)",
doppler_output_count);
`endif
// ================================================================
// RUN CHECKS
// ================================================================
@@ -666,33 +532,7 @@ initial begin
"S10: DDC produced substantial output (>100 valid samples)");
// ================================================================
// GOLDEN COMPARISON REPORT
// ================================================================
`ifdef GOLDEN_GENERATE
$display("");
$display("Golden comparison: SKIPPED (GOLDEN_GENERATE mode)");
$display(" Wrote golden reference with %0d Doppler samples", doppler_output_count);
`else
$display("");
$display("------------------------------------------------------------");
$display("GOLDEN COMPARISON (tolerance=%0d LSB)", GOLDEN_TOLERANCE);
$display("------------------------------------------------------------");
$display("Golden comparison: %0d/%0d match (tolerance=%0d LSB)",
golden_match_count, golden_compare_count, GOLDEN_TOLERANCE);
$display(" Mismatches: %0d (I-ch max_err=%0d, Q-ch max_err=%0d)",
golden_mismatch_count, golden_max_err_i, golden_max_err_q);
// CHECK G1: All golden comparisons match
if (golden_compare_count > 0) begin
check(golden_mismatch_count == 0,
"G1: All Doppler outputs match golden reference within tolerance");
end else begin
check(0, "G1: All Doppler outputs match golden reference (NO COMPARISONS)");
end
`endif
// ================================================================
// BOUNDS CHECKS (active in both modes)
// BOUNDS CHECKS
// ================================================================
$display("");
$display("------------------------------------------------------------");
@@ -765,16 +605,8 @@ initial begin
// ================================================================
$display("");
$display("============================================================");
$display("INTEGRATION TEST -- GOLDEN COMPARISON + BOUNDS");
$display("INTEGRATION TEST -- STRUCTURAL + BOUNDS");
$display("============================================================");
`ifdef GOLDEN_GENERATE
$display("Mode: GOLDEN_GENERATE (reference dump, comparison skipped)");
`else
$display("Golden comparison: %0d/%0d match (tolerance=%0d LSB)",
golden_match_count, golden_compare_count, GOLDEN_TOLERANCE);
$display(" Mismatches: %0d (I-ch max_err=%0d, Q-ch max_err=%0d)",
golden_mismatch_count, golden_max_err_i, golden_max_err_q);
`endif
$display("Bounds checks:");
$display(" B1: DDC RMS energy in range [%0d, %0d]",
(ddc_energy_acc > 0) ? 1 : 0, DDC_MAX_ENERGY);
+5 -5
View File
@@ -108,7 +108,7 @@ class GPSData:
@dataclass
class RadarSettings:
"""Radar system configuration"""
system_frequency: float = 10e9 # Hz
system_frequency: float = 10.5e9 # Hz (PLFM TX LO)
chirp_duration_1: float = 30e-6 # Long chirp duration (s)
chirp_duration_2: float = 0.5e-6 # Short chirp duration (s)
chirps_per_position: int = 32
@@ -116,8 +116,8 @@ class RadarSettings:
freq_max: float = 30e6 # Hz
prf1: float = 1000 # PRF 1 (Hz)
prf2: float = 2000 # PRF 2 (Hz)
max_distance: float = 50000 # Max detection range (m)
coverage_radius: float = 50000 # Map coverage radius (m)
max_distance: float = 1536 # Max detection range (m) -- 64 bins x 24 m
coverage_radius: float = 1536 # Map coverage radius (m)
class TileServer(Enum):
@@ -198,7 +198,7 @@ class RadarMapWidget(QWidget):
pitch=0.0
)
self._targets: list[RadarTarget] = []
self._coverage_radius = 50000 # meters
self._coverage_radius = 1536 # meters (64 bins x 24 m, 3 km mode)
self._tile_server = TileServer.OPENSTREETMAP
self._show_coverage = True
self._show_trails = False
@@ -1088,7 +1088,7 @@ class TargetSimulator(QObject):
new_range = target.range - target.velocity * 0.5 # 0.5 second update
# Check if target is still in range
if new_range < 500 or new_range > 50000:
if new_range < 50 or new_range > 1536:
# Remove this target and add a new one
continue
+5 -5
View File
@@ -81,7 +81,7 @@ class RadarTarget:
@dataclass
class RadarSettings:
system_frequency: float = 10e9
system_frequency: float = 10.5e9
chirp_duration_1: float = 30e-6 # Long chirp duration
chirp_duration_2: float = 0.5e-6 # Short chirp duration
chirps_per_position: int = 32
@@ -89,8 +89,8 @@ class RadarSettings:
freq_max: float = 30e6
prf1: float = 1000
prf2: float = 2000
max_distance: float = 50000
map_size: float = 50000 # Map size in meters
max_distance: float = 1536
map_size: float = 1536 # Map size in meters (64 bins x 24 m)
@dataclass
@@ -1196,8 +1196,8 @@ class RadarGUI:
("Frequency Max (Hz):", "freq_max", 30e6),
("PRF1 (Hz):", "prf1", 1000),
("PRF2 (Hz):", "prf2", 2000),
("Max Distance (m):", "max_distance", 50000),
("Map Size (m):", "map_size", 50000),
("Max Distance (m):", "max_distance", 1536),
("Map Size (m):", "map_size", 1536),
("Google Maps API Key:", "google_maps_api_key", "YOUR_GOOGLE_MAPS_API_KEY"),
]
+5 -5
View File
@@ -77,7 +77,7 @@ class RadarTarget:
@dataclass
class RadarSettings:
system_frequency: float = 10e9
system_frequency: float = 10.5e9
chirp_duration_1: float = 30e-6 # Long chirp duration
chirp_duration_2: float = 0.5e-6 # Short chirp duration
chirps_per_position: int = 32
@@ -85,8 +85,8 @@ class RadarSettings:
freq_max: float = 30e6
prf1: float = 1000
prf2: float = 2000
max_distance: float = 50000
map_size: float = 50000 # Map size in meters
max_distance: float = 1536
map_size: float = 1536 # Map size in meters (64 bins x 24 m)
@dataclass
@@ -1254,8 +1254,8 @@ class RadarGUI:
("Frequency Max (Hz):", "freq_max", 30e6),
("PRF1 (Hz):", "prf1", 1000),
("PRF2 (Hz):", "prf2", 2000),
("Max Distance (m):", "max_distance", 50000),
("Map Size (m):", "map_size", 50000),
("Max Distance (m):", "max_distance", 1536),
("Map Size (m):", "map_size", 1536),
]
self.settings_vars = {}
+5 -5
View File
@@ -64,7 +64,7 @@ class RadarTarget:
@dataclass
class RadarSettings:
system_frequency: float = 10e9
system_frequency: float = 10.5e9
chirp_duration_1: float = 30e-6 # Long chirp duration
chirp_duration_2: float = 0.5e-6 # Short chirp duration
chirps_per_position: int = 32
@@ -72,8 +72,8 @@ class RadarSettings:
freq_max: float = 30e6
prf1: float = 1000
prf2: float = 2000
max_distance: float = 50000
map_size: float = 50000 # Map size in meters
max_distance: float = 1536
map_size: float = 1536 # Map size in meters (64 bins x 24 m)
@dataclass
class GPSData:
@@ -1653,8 +1653,8 @@ class RadarGUI:
('Frequency Max (Hz):', 'freq_max', 30e6),
('PRF1 (Hz):', 'prf1', 1000),
('PRF2 (Hz):', 'prf2', 2000),
('Max Distance (m):', 'max_distance', 50000),
('Map Size (m):', 'map_size', 50000),
('Max Distance (m):', 'max_distance', 1536),
('Map Size (m):', 'map_size', 1536),
('Google Maps API Key:', 'google_maps_api_key', 'YOUR_GOOGLE_MAPS_API_KEY')
]
+13 -11
View File
@@ -98,9 +98,10 @@ class DemoTarget:
__slots__ = ("azimuth", "classification", "id", "range_m", "snr", "velocity")
# Physical range grid: 64 bins x ~4.8 m/bin = ~307 m max
_RANGE_PER_BIN: float = (3e8 / (2 * 500e6)) * 16 # ~4.8 m
_MAX_RANGE: float = _RANGE_PER_BIN * NUM_RANGE_BINS # ~307 m
# Physical range grid: matched-filter receiver, 100 MSPS post-DDC, 16:1 decimation
# range_per_bin = c / (2 * 100e6) * 16 = 24.0 m
_RANGE_PER_BIN: float = (3e8 / (2 * 100e6)) * 16 # 24.0 m
_MAX_RANGE: float = _RANGE_PER_BIN * NUM_RANGE_BINS # 1536 m
def __init__(self, tid: int):
self.id = tid
@@ -187,10 +188,10 @@ class DemoSimulator:
mag = np.zeros((NUM_RANGE_BINS, NUM_DOPPLER_BINS), dtype=np.float64)
det = np.zeros((NUM_RANGE_BINS, NUM_DOPPLER_BINS), dtype=np.uint8)
# Range/Doppler scaling (approximate)
range_per_bin = (3e8 / (2 * 500e6)) * 16 # ~4.8 m/bin
# Range/Doppler scaling -- matched-filter receiver, 100 MSPS, 16:1 decimation
range_per_bin = (3e8 / (2 * 100e6)) * 16 # 24.0 m/bin
max_range = range_per_bin * NUM_RANGE_BINS
vel_per_bin = 1.484 # m/s per Doppler bin (from WaveformConfig)
vel_per_bin = 2.67 # m/s per Doppler bin (lam/(2*32*167us))
for t in targets:
if t.range_m > max_range or t.range_m < 0:
@@ -385,7 +386,9 @@ class RadarDashboard:
UPDATE_INTERVAL_MS = 100 # 10 Hz display refresh
# Radar parameters used for range-axis scaling.
BANDWIDTH = 500e6 # Hz — chirp bandwidth
# Matched-filter receiver: range_per_bin = c / (2 * fs_processing) * decimation
# = 3e8 / (2 * 100e6) * 16 = 24.0 m/bin
BANDWIDTH = 20e6 # Hz — chirp bandwidth (for display/info only)
C = 3e8 # m/s — speed of light
def __init__(self, root: tk.Tk, connection: FT2232HConnection,
@@ -514,10 +517,9 @@ class RadarDashboard:
self._build_log_tab(tab_log)
def _build_display_tab(self, parent):
# Compute physical axis limits
range_res = self.C / (2.0 * self.BANDWIDTH) # ~0.3 m per FFT bin
# After decimation 1024→64, each range bin = 16 FFT bins
range_per_bin = range_res * 16
# Compute physical axis limits -- matched-filter receiver
# Range per bin: c / (2 * fs_processing) * decimation_factor = 24.0 m
range_per_bin = self.C / (2.0 * 100e6) * 16 # 24.0 m
max_range = range_per_bin * NUM_RANGE_BINS
doppler_bin_lo = 0
+2 -2
View File
@@ -45,7 +45,7 @@ class RadarSettings:
range_bins: int = 1024
doppler_bins: int = 32
prf: float = 1000
max_range: float = 5000
max_range: float = 1536
max_velocity: float = 100
cfar_threshold: float = 13.0
@@ -577,7 +577,7 @@ class RadarDemoGUI:
('Range Bins:', 'range_bins', 1024, 256, 2048),
('Doppler Bins:', 'doppler_bins', 32, 8, 128),
('PRF (Hz):', 'prf', 1000, 100, 10000),
('Max Range (m):', 'max_range', 5000, 100, 50000),
('Max Range (m):', 'max_range', 1536, 100, 25000),
('Max Velocity (m/s):', 'max_vel', 100, 10, 500),
('CFAR Threshold (dB):', 'cfar', 13.0, 5.0, 30.0)
]
-338
View File
@@ -1,338 +0,0 @@
# ruff: noqa: T201
#!/usr/bin/env python3
"""
One-off AGC saturation analysis for ADI CN0566 raw IQ captures.
Bit-accurate simulation of rx_gain_control.v AGC inner loop applied
to real captured IQ data. Three scenarios per dataset:
Row 1 AGC OFF: Fixed gain_shift=0 (pass-through). Shows raw clipping.
Row 2 AGC ON: Auto-adjusts from gain_shift=0. Clipping clears.
Row 3 AGC delayed: OFF for first half, ON at midpoint.
Shows the transition: clipping AGC activates clears.
Key RTL details modelled exactly:
- gain_shift[3]=direction (0=amplify/left, 1=attenuate/right), [2:0]=amount
- Internal agc_gain is signed -7..+7
- Peak is measured PRE-gain (raw input |sample|, upper 8 of 15 bits)
- Saturation is measured POST-gain (overflow from shift)
- Attack: gain -= agc_attack when any sample clips (immediate)
- Decay: gain += agc_decay when peak < target AND holdoff expired
- Hold: when peak >= target AND no saturation, hold gain, reset holdoff
Usage:
python adi_agc_analysis.py
python adi_agc_analysis.py --data /path/to/file.npy --label "my capture"
"""
import argparse
import sys
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from v7.agc_sim import (
encoding_to_signed,
apply_gain_shift,
quantize_iq,
AGCConfig,
AGCState,
process_agc_frame,
)
# ---------------------------------------------------------------------------
# FPGA AGC parameters (rx_gain_control.v reset defaults)
# ---------------------------------------------------------------------------
AGC_TARGET = 200 # host_agc_target (8-bit, default 200)
ADC_RAIL = 4095 # 12-bit ADC max absolute value
# ---------------------------------------------------------------------------
# Per-frame AGC simulation using v7.agc_sim (bit-accurate to RTL)
# ---------------------------------------------------------------------------
def simulate_agc(frames: np.ndarray, agc_enabled: bool = True,
enable_at_frame: int = 0,
initial_gain_enc: int = 0x00) -> dict:
"""Simulate FPGA inner-loop AGC across all frames.
Parameters
----------
frames : (N, chirps, samples) complex raw ADC captures (12-bit range)
agc_enabled : if False, gain stays fixed
enable_at_frame : frame index where AGC activates
initial_gain_enc : gain_shift[3:0] encoding when AGC enables (default 0x00 = pass-through)
"""
n_frames = frames.shape[0]
# Output arrays
out_gain_enc = np.zeros(n_frames, dtype=int)
out_gain_signed = np.zeros(n_frames, dtype=int)
out_peak_mag = np.zeros(n_frames, dtype=int)
out_sat_count = np.zeros(n_frames, dtype=int)
out_sat_rate = np.zeros(n_frames, dtype=float)
out_rms_post = np.zeros(n_frames, dtype=float)
# AGC state — managed by process_agc_frame()
state = AGCState(
gain=encoding_to_signed(initial_gain_enc),
holdoff_counter=0,
was_enabled=False,
)
for i in range(n_frames):
frame_i, frame_q = quantize_iq(frames[i])
agc_active = agc_enabled and (i >= enable_at_frame)
# Build per-frame config (enable toggles at enable_at_frame)
config = AGCConfig(enabled=agc_active)
result = process_agc_frame(frame_i, frame_q, config, state)
# RMS of shifted signal
rms = float(np.sqrt(np.mean(
result.shifted_i.astype(np.float64)**2
+ result.shifted_q.astype(np.float64)**2)))
total_samples = frame_i.size + frame_q.size
sat_rate = result.overflow_raw / total_samples if total_samples > 0 else 0.0
# Record outputs
out_gain_enc[i] = result.gain_enc
out_gain_signed[i] = result.gain_signed
out_peak_mag[i] = result.peak_mag_8bit
out_sat_count[i] = result.saturation_count
out_sat_rate[i] = sat_rate
out_rms_post[i] = rms
return {
"gain_enc": out_gain_enc,
"gain_signed": out_gain_signed,
"peak_mag": out_peak_mag,
"sat_count": out_sat_count,
"sat_rate": out_sat_rate,
"rms_post": out_rms_post,
}
# ---------------------------------------------------------------------------
# Range-Doppler processing for heatmap display
# ---------------------------------------------------------------------------
def process_frame_rd(frame: np.ndarray, gain_enc: int,
n_range: int = 64,
n_doppler: int = 32) -> np.ndarray:
"""Range-Doppler magnitude for one frame with gain applied."""
frame_i, frame_q = quantize_iq(frame)
si, sq, _ = apply_gain_shift(frame_i, frame_q, gain_enc)
iq = si.astype(np.float64) + 1j * sq.astype(np.float64)
n_chirps, _ = iq.shape
range_fft = np.fft.fft(iq, axis=1)[:, :n_range]
doppler_fft = np.fft.fftshift(np.fft.fft(range_fft, axis=0), axes=0)
center = n_chirps // 2
half_d = n_doppler // 2
doppler_fft = doppler_fft[center - half_d:center + half_d, :]
rd_mag = np.abs(doppler_fft.real) + np.abs(doppler_fft.imag)
return rd_mag.T # (n_range, n_doppler)
# ---------------------------------------------------------------------------
# Plotting
# ---------------------------------------------------------------------------
def plot_scenario(axes, data: np.ndarray, agc: dict, title: str,
enable_frame: int = 0):
"""Plot one AGC scenario across 5 axes."""
n = data.shape[0]
xs = np.arange(n)
# Range-Doppler heatmap
if enable_frame > 0 and enable_frame < n:
f_before = max(0, enable_frame - 1)
f_after = min(n - 1, n - 2)
rd_before = process_frame_rd(data[f_before], int(agc["gain_enc"][f_before]))
rd_after = process_frame_rd(data[f_after], int(agc["gain_enc"][f_after]))
combined = np.hstack([rd_before, rd_after])
im = axes[0].imshow(
20 * np.log10(combined + 1), aspect="auto", origin="lower",
cmap="inferno", interpolation="nearest")
axes[0].axvline(x=rd_before.shape[1] - 0.5, color="cyan",
linewidth=2, linestyle="--")
axes[0].set_title(f"{title}\nL: f{f_before} (pre) | R: f{f_after} (post)")
else:
worst = int(np.argmax(agc["sat_count"]))
best = int(np.argmin(agc["sat_count"]))
f_show = worst if agc["sat_count"][worst] > 0 else best
rd = process_frame_rd(data[f_show], int(agc["gain_enc"][f_show]))
im = axes[0].imshow(
20 * np.log10(rd + 1), aspect="auto", origin="lower",
cmap="inferno", interpolation="nearest")
axes[0].set_title(f"{title}\nFrame {f_show}")
axes[0].set_xlabel("Doppler bin")
axes[0].set_ylabel("Range bin")
plt.colorbar(im, ax=axes[0], label="dB", shrink=0.8)
# Signed gain history (the real AGC state)
axes[1].plot(xs, agc["gain_signed"], color="#00ff88", linewidth=1.5)
axes[1].axhline(y=0, color="gray", linestyle=":", alpha=0.5,
label="Pass-through")
if enable_frame > 0:
axes[1].axvline(x=enable_frame, color="yellow", linewidth=2,
linestyle="--", label="AGC ON")
axes[1].set_ylim(-8, 8)
axes[1].set_ylabel("Gain (signed)")
axes[1].set_title("AGC Internal Gain (-7=max atten, +7=max amp)")
axes[1].legend(fontsize=7, loc="upper right")
axes[1].grid(True, alpha=0.3)
# Peak magnitude (PRE-gain, 8-bit)
axes[2].plot(xs, agc["peak_mag"], color="#ffaa00", linewidth=1.0)
axes[2].axhline(y=AGC_TARGET, color="cyan", linestyle="--",
alpha=0.7, label=f"Target ({AGC_TARGET})")
axes[2].axhspan(240, 255, color="red", alpha=0.15, label="Clip zone")
if enable_frame > 0:
axes[2].axvline(x=enable_frame, color="yellow", linewidth=2,
linestyle="--", alpha=0.8)
axes[2].set_ylim(0, 260)
axes[2].set_ylabel("Peak (8-bit)")
axes[2].set_title("Peak Magnitude (pre-gain, raw input)")
axes[2].legend(fontsize=7, loc="upper right")
axes[2].grid(True, alpha=0.3)
# Saturation count (POST-gain overflow)
axes[3].fill_between(xs, agc["sat_count"], color="red", alpha=0.4)
axes[3].plot(xs, agc["sat_count"], color="red", linewidth=0.8)
if enable_frame > 0:
axes[3].axvline(x=enable_frame, color="yellow", linewidth=2,
linestyle="--", alpha=0.8)
axes[3].set_ylabel("Overflow Count")
total = int(agc["sat_count"].sum())
axes[3].set_title(f"Post-Gain Overflow (total={total})")
axes[3].grid(True, alpha=0.3)
# RMS signal level (post-gain)
axes[4].plot(xs, agc["rms_post"], color="#44aaff", linewidth=1.0)
if enable_frame > 0:
axes[4].axvline(x=enable_frame, color="yellow", linewidth=2,
linestyle="--", alpha=0.8)
axes[4].set_ylabel("RMS")
axes[4].set_xlabel("Frame")
axes[4].set_title("Post-Gain RMS Level")
axes[4].grid(True, alpha=0.3)
def analyze_dataset(data: np.ndarray, label: str):
"""Run 3-scenario analysis for one dataset."""
n_frames = data.shape[0]
mid = n_frames // 2
print(f"\n{'='*60}")
print(f" {label} — shape {data.shape}")
print(f"{'='*60}")
# Raw ADC stats
raw_sat = np.sum((np.abs(data.real) >= ADC_RAIL) |
(np.abs(data.imag) >= ADC_RAIL))
print(f" Raw ADC saturation: {raw_sat} samples "
f"({100*raw_sat/(2*data.size):.2f}%)")
# Scenario 1: AGC OFF — pass-through (gain_shift=0x00)
print(" [1/3] AGC OFF (gain=0, pass-through) ...")
agc_off = simulate_agc(data, agc_enabled=False, initial_gain_enc=0x00)
print(f" Post-gain overflow: {agc_off['sat_count'].sum()} "
f"(should be 0 — no amplification)")
# Scenario 2: AGC ON from frame 0
print(" [2/3] AGC ON (from start) ...")
agc_on = simulate_agc(data, agc_enabled=True, enable_at_frame=0,
initial_gain_enc=0x00)
print(f" Final gain: {agc_on['gain_signed'][-1]} "
f"(enc=0x{agc_on['gain_enc'][-1]:X})")
print(f" Post-gain overflow: {agc_on['sat_count'].sum()}")
# Scenario 3: AGC delayed
print(f" [3/3] AGC delayed (ON at frame {mid}) ...")
agc_delayed = simulate_agc(data, agc_enabled=True,
enable_at_frame=mid,
initial_gain_enc=0x00)
pre_sat = int(agc_delayed["sat_count"][:mid].sum())
post_sat = int(agc_delayed["sat_count"][mid:].sum())
print(f" Pre-AGC overflow: {pre_sat} "
f"Post-AGC overflow: {post_sat}")
# Plot
fig, axes = plt.subplots(3, 5, figsize=(28, 14))
fig.suptitle(f"AERIS-10 AGC Analysis — {label}\n"
f"({n_frames} frames, {data.shape[1]} chirps, "
f"{data.shape[2]} samples/chirp, "
f"raw ADC sat={100*raw_sat/(2*data.size):.2f}%)",
fontsize=13, fontweight="bold", y=0.99)
plot_scenario(axes[0], data, agc_off, "AGC OFF (pass-through)")
plot_scenario(axes[1], data, agc_on, "AGC ON (from start)")
plot_scenario(axes[2], data, agc_delayed,
f"AGC delayed (ON at frame {mid})", enable_frame=mid)
for ax, lbl in zip(axes[:, 0],
["AGC OFF", "AGC ON", "AGC DELAYED"],
strict=True):
ax.annotate(lbl, xy=(-0.35, 0.5), xycoords="axes fraction",
fontsize=13, fontweight="bold", color="white",
ha="center", va="center", rotation=90)
plt.tight_layout(rect=[0.03, 0, 1, 0.95])
return fig
def main():
parser = argparse.ArgumentParser(
description="AGC analysis for ADI raw IQ captures "
"(bit-accurate rx_gain_control.v simulation)")
parser.add_argument("--amp", type=str,
default=str(Path.home() / "Downloads/adi_radar_data"
"/amp_radar"
"/phaser_amp_4MSPS_500M_300u_256_m3dB.npy"),
help="Path to amplified radar .npy")
parser.add_argument("--noamp", type=str,
default=str(Path.home() / "Downloads/adi_radar_data"
"/no_amp_radar"
"/phaser_NOamp_4MSPS_500M_300u_256.npy"),
help="Path to non-amplified radar .npy")
parser.add_argument("--data", type=str, default=None,
help="Single dataset mode")
parser.add_argument("--label", type=str, default="Custom Data")
args = parser.parse_args()
plt.style.use("dark_background")
if args.data:
data = np.load(args.data)
analyze_dataset(data, args.label)
plt.show()
return
figs = []
for path, label in [(args.amp, "With Amplifier (-3 dB)"),
(args.noamp, "No Amplifier")]:
if not Path(path).exists():
print(f"WARNING: {path} not found, skipping")
continue
data = np.load(path)
fig = analyze_dataset(data, label)
figs.append(fig)
if not figs:
print("No data found. Use --amp/--noamp or --data.")
sys.exit(1)
plt.show()
if __name__ == "__main__":
main()
+34 -23
View File
@@ -58,16 +58,16 @@ class TestRadarSettings(unittest.TestCase):
def test_has_physical_conversion_fields(self):
s = _models().RadarSettings()
self.assertIsInstance(s.range_resolution, float)
self.assertIsInstance(s.range_bin_spacing, float)
self.assertIsInstance(s.velocity_resolution, float)
self.assertGreater(s.range_resolution, 0)
self.assertGreater(s.range_bin_spacing, 0)
self.assertGreater(s.velocity_resolution, 0)
def test_defaults(self):
s = _models().RadarSettings()
self.assertEqual(s.system_frequency, 10e9)
self.assertEqual(s.coverage_radius, 50000)
self.assertEqual(s.max_distance, 50000)
self.assertEqual(s.system_frequency, 10.5e9)
self.assertEqual(s.coverage_radius, 1536)
self.assertEqual(s.max_distance, 1536)
class TestGPSData(unittest.TestCase):
@@ -425,32 +425,42 @@ class TestWaveformConfig(unittest.TestCase):
def test_defaults(self):
from v7.models import WaveformConfig
wc = WaveformConfig()
self.assertEqual(wc.sample_rate_hz, 4e6)
self.assertEqual(wc.bandwidth_hz, 500e6)
self.assertEqual(wc.chirp_duration_s, 300e-6)
self.assertEqual(wc.center_freq_hz, 10.525e9)
self.assertEqual(wc.sample_rate_hz, 100e6)
self.assertEqual(wc.bandwidth_hz, 20e6)
self.assertEqual(wc.chirp_duration_s, 30e-6)
self.assertEqual(wc.pri_s, 167e-6)
self.assertEqual(wc.center_freq_hz, 10.5e9)
self.assertEqual(wc.n_range_bins, 64)
self.assertEqual(wc.n_doppler_bins, 32)
self.assertEqual(wc.fft_size, 1024)
self.assertEqual(wc.decimation_factor, 16)
def test_range_resolution(self):
"""range_resolution_m should be ~5.62 m/bin with ADI defaults."""
"""bin_spacing_m should be ~24.0 m/bin with PLFM defaults."""
from v7.models import WaveformConfig
wc = WaveformConfig()
self.assertAlmostEqual(wc.range_resolution_m, 5.621, places=1)
self.assertAlmostEqual(wc.bin_spacing_m, 23.98, places=1)
def test_range_resolution_physical(self):
"""range_resolution_m = c/(2*BW), ~7.5 m at 20 MHz BW."""
from v7.models import WaveformConfig
wc = WaveformConfig()
self.assertAlmostEqual(wc.range_resolution_m, 7.49, places=1)
# 30 MHz BW → 5.0 m resolution
wc30 = WaveformConfig(bandwidth_hz=30e6)
self.assertAlmostEqual(wc30.range_resolution_m, 4.996, places=1)
def test_velocity_resolution(self):
"""velocity_resolution_mps should be ~1.484 m/s/bin."""
"""velocity_resolution_mps should be ~2.67 m/s/bin."""
from v7.models import WaveformConfig
wc = WaveformConfig()
self.assertAlmostEqual(wc.velocity_resolution_mps, 1.484, places=2)
self.assertAlmostEqual(wc.velocity_resolution_mps, 2.67, places=1)
def test_max_range(self):
"""max_range_m = range_resolution * n_range_bins."""
"""max_range_m = bin_spacing * n_range_bins."""
from v7.models import WaveformConfig
wc = WaveformConfig()
self.assertAlmostEqual(wc.max_range_m, wc.range_resolution_m * 64, places=1)
self.assertAlmostEqual(wc.max_range_m, wc.bin_spacing_m * 64, places=1)
def test_max_velocity(self):
"""max_velocity_mps = velocity_resolution * n_doppler_bins / 2."""
@@ -466,8 +476,9 @@ class TestWaveformConfig(unittest.TestCase):
"""Non-default parameters correctly change derived values."""
from v7.models import WaveformConfig
wc1 = WaveformConfig()
wc2 = WaveformConfig(bandwidth_hz=1e9) # double BW → halve range res
self.assertAlmostEqual(wc2.range_resolution_m, wc1.range_resolution_m / 2, places=2)
# Matched-filter: bin_spacing = c/(2*fs)*dec — proportional to 1/fs
wc2 = WaveformConfig(sample_rate_hz=200e6) # double fs → halve bin spacing
self.assertAlmostEqual(wc2.bin_spacing_m, wc1.bin_spacing_m / 2, places=2)
def test_zero_center_freq_velocity(self):
"""Zero center freq should cause ZeroDivisionError in velocity calc."""
@@ -925,18 +936,18 @@ class TestExtractTargetsFromFrame(unittest.TestCase):
"""Detection at range bin 10 → range = 10 * range_resolution."""
from v7.processing import extract_targets_from_frame
frame = self._make_frame(det_cells=[(10, 16)]) # dbin=16 = center → vel=0
targets = extract_targets_from_frame(frame, range_resolution=5.621)
targets = extract_targets_from_frame(frame, bin_spacing=23.98)
self.assertEqual(len(targets), 1)
self.assertAlmostEqual(targets[0].range, 10 * 5.621, places=2)
self.assertAlmostEqual(targets[0].range, 10 * 23.98, places=1)
self.assertAlmostEqual(targets[0].velocity, 0.0, places=2)
def test_velocity_sign(self):
"""Doppler bin < center → negative velocity, > center → positive."""
from v7.processing import extract_targets_from_frame
frame = self._make_frame(det_cells=[(5, 10), (5, 20)])
targets = extract_targets_from_frame(frame, velocity_resolution=1.484)
# dbin=10: vel = (10-16)*1.484 = -8.904 (approaching)
# dbin=20: vel = (20-16)*1.484 = +5.936 (receding)
targets = extract_targets_from_frame(frame, velocity_resolution=2.67)
# dbin=10: vel = (10-16)*2.67 = -16.02 (approaching)
# dbin=20: vel = (20-16)*2.67 = +10.68 (receding)
self.assertLess(targets[0].velocity, 0)
self.assertGreater(targets[1].velocity, 0)
@@ -954,7 +965,7 @@ class TestExtractTargetsFromFrame(unittest.TestCase):
pitch=0.0, heading=90.0)
frame = self._make_frame(det_cells=[(10, 16)])
targets = extract_targets_from_frame(
frame, range_resolution=100.0, gps=gps)
frame, bin_spacing=100.0, gps=gps)
# Should be roughly east of radar position
self.assertAlmostEqual(targets[0].latitude, 41.9, places=2)
self.assertGreater(targets[0].longitude, 12.5)
+1 -1
View File
@@ -98,7 +98,7 @@ class RadarMapWidget(QWidget):
)
self._targets: list[RadarTarget] = []
self._pending_targets: list[RadarTarget] | None = None
self._coverage_radius = 50_000 # metres
self._coverage_radius = 1_536 # metres (64 bins x 24 m, 3 km mode)
self._tile_server = TileServer.OPENSTREETMAP
self._show_coverage = True
self._show_trails = False
+39 -25
View File
@@ -105,15 +105,15 @@ class RadarSettings:
tab and Opcode enum in radar_protocol.py. This dataclass holds only
host-side display/map settings and physical-unit conversion factors.
range_resolution and velocity_resolution should be calibrated to
range_bin_spacing and velocity_resolution should be calibrated to
the actual waveform parameters.
"""
system_frequency: float = 10e9 # Hz (carrier, used for velocity calc)
range_resolution: float = 781.25 # Meters per range bin (default: 50km/64)
velocity_resolution: float = 1.0 # m/s per Doppler bin (calibrate to waveform)
max_distance: float = 50000 # Max detection range (m)
map_size: float = 50000 # Map display size (m)
coverage_radius: float = 50000 # Map coverage radius (m)
system_frequency: float = 10.5e9 # Hz (PLFM TX LO, verified from ADF4382 config)
range_bin_spacing: float = 24.0 # Meters per decimated range bin (c/(2*100MSPS)*16)
velocity_resolution: float = 2.67 # m/s per Doppler bin (lam/(2*32*167us))
max_distance: float = 1536 # Max detection range (m) -- 64 bins x 24 m (3 km mode)
map_size: float = 1536 # Map display size (m)
coverage_radius: float = 1536 # Map coverage radius (m)
@dataclass
@@ -196,47 +196,61 @@ class TileServer(Enum):
class WaveformConfig:
"""Physical waveform parameters for converting bins to SI units.
Encapsulates the radar waveform so that range/velocity resolution
Encapsulates the PLFM radar waveform so that range/velocity resolution
can be derived automatically instead of hardcoded in RadarSettings.
Defaults match the ADI CN0566 Phaser capture parameters used in
the golden_reference cosim (4 MSPS, 500 MHz BW, 300 us chirp).
Defaults match the PLFM hardware: 100 MSPS post-DDC processing rate,
20 MHz chirp bandwidth, 30 us long chirp, 167 us PRI, 10.5 GHz carrier.
The receiver uses matched-filter pulse compression (NOT deramped FMCW),
so range-per-bin = c / (2 * fs_processing) * decimation_factor.
"""
sample_rate_hz: float = 4e6 # ADC sample rate
bandwidth_hz: float = 500e6 # Chirp bandwidth
chirp_duration_s: float = 300e-6 # Chirp ramp time
center_freq_hz: float = 10.525e9 # Carrier frequency
n_range_bins: int = 64 # After decimation
sample_rate_hz: float = 100e6 # Post-DDC processing rate (400 MSPS / 4)
bandwidth_hz: float = 20e6 # Chirp bandwidth (Phase 1 target: 30 MHz)
chirp_duration_s: float = 30e-6 # Long chirp ramp (informational only)
pri_s: float = 167e-6 # Pulse repetition interval (chirp + listen)
center_freq_hz: float = 10.5e9 # TX LO carrier (verified: ADF4382 config)
n_range_bins: int = 64 # After decimation (3 km mode)
n_doppler_bins: int = 32 # After Doppler FFT
fft_size: int = 1024 # Pre-decimation FFT length
decimation_factor: int = 16 # 1024 → 64
@property
def range_resolution_m(self) -> float:
"""Meters per decimated range bin (FMCW deramped baseband).
def bin_spacing_m(self) -> float:
"""Meters per decimated range bin (matched-filter receiver).
For deramped FMCW: bin spacing = c * Fs * T / (2 * N_FFT * BW).
For matched-filter pulse compression: bin spacing = c / (2 * fs).
After decimation the bin spacing grows by *decimation_factor*.
This is independent of chirp bandwidth (BW affects physical
resolution, not bin spacing).
"""
c = 299_792_458.0
raw_bin = (
c * self.sample_rate_hz * self.chirp_duration_s
/ (2.0 * self.fft_size * self.bandwidth_hz)
)
raw_bin = c / (2.0 * self.sample_rate_hz)
return raw_bin * self.decimation_factor
@property
def range_resolution_m(self) -> float:
"""Physical range resolution in meters, set by chirp bandwidth.
range_resolution = c / (2 * BW).
At 20 MHz BW 7.5 m; at 30 MHz BW 5.0 m.
This is distinct from bin_spacing_m (which depends on sample rate
and decimation factor, not bandwidth).
"""
c = 299_792_458.0
return c / (2.0 * self.bandwidth_hz)
@property
def velocity_resolution_mps(self) -> float:
"""m/s per Doppler bin. lambda / (2 * n_doppler * chirp_duration)."""
"""m/s per Doppler bin. lambda / (2 * n_doppler * PRI)."""
c = 299_792_458.0
wavelength = c / self.center_freq_hz
return wavelength / (2.0 * self.n_doppler_bins * self.chirp_duration_s)
return wavelength / (2.0 * self.n_doppler_bins * self.pri_s)
@property
def max_range_m(self) -> float:
"""Maximum unambiguous range in meters."""
return self.range_resolution_m * self.n_range_bins
return self.bin_spacing_m * self.n_range_bins
@property
def max_velocity_mps(self) -> float:
+4 -4
View File
@@ -490,7 +490,7 @@ def polar_to_geographic(
def extract_targets_from_frame(
frame,
range_resolution: float = 1.0,
bin_spacing: float = 1.0,
velocity_resolution: float = 1.0,
gps: GPSData | None = None,
) -> list[RadarTarget]:
@@ -503,8 +503,8 @@ def extract_targets_from_frame(
----------
frame : RadarFrame
Frame with populated ``detections``, ``magnitude``, ``range_doppler_i/q``.
range_resolution : float
Meters per range bin.
bin_spacing : float
Meters per range bin (bin spacing, NOT bandwidth-limited resolution).
velocity_resolution : float
m/s per Doppler bin.
gps : GPSData | None
@@ -525,7 +525,7 @@ def extract_targets_from_frame(
mag = float(frame.magnitude[rbin, dbin])
snr = 10.0 * math.log10(max(mag, 1.0)) if mag > 0 else 0.0
range_m = float(rbin) * range_resolution
range_m = float(rbin) * bin_spacing
velocity_ms = float(dbin - doppler_center) * velocity_resolution
lat, lon, azimuth, elevation = 0.0, 0.0, 0.0, 0.0
+4 -4
View File
@@ -169,7 +169,7 @@ class RadarDataWorker(QThread):
The FPGA already does: FFT, MTI, CFAR, DC notch.
Host-side DSP adds: clustering, tracking, geo-coordinate mapping.
Bin-to-physical conversion uses RadarSettings.range_resolution
Bin-to-physical conversion uses RadarSettings.range_bin_spacing
and velocity_resolution (should be calibrated to actual waveform).
"""
targets: list[RadarTarget] = []
@@ -180,7 +180,7 @@ class RadarDataWorker(QThread):
# Extract detections from FPGA CFAR flags
det_indices = np.argwhere(frame.detections > 0)
r_res = self._settings.range_resolution
r_res = self._settings.range_bin_spacing
v_res = self._settings.velocity_resolution
for idx in det_indices:
@@ -368,7 +368,7 @@ class TargetSimulator(QObject):
for t in self._targets:
new_range = t.range - t.velocity * 0.5
if new_range < 500 or new_range > 50000:
if new_range < 50 or new_range > 1536:
continue # target exits coverage — drop it
new_vel = max(-150, min(150, t.velocity + random.uniform(-2, 2)))
@@ -559,7 +559,7 @@ class ReplayWorker(QThread):
# Target extraction
targets = self._extract_targets(
frame,
range_resolution=self._waveform.range_resolution_m,
bin_spacing=self._waveform.bin_spacing_m,
velocity_resolution=self._waveform.velocity_resolution_mps,
gps=self._gps,
)
@@ -793,3 +793,51 @@ def parse_stm32_gpio_init(filepath: Path | None = None) -> list[GpioPin]:
))
return pins
# ===================================================================
# FPGA radar_params.vh parser
# ===================================================================
def parse_radar_params_vh() -> dict[str, int]:
"""
Parse `define values from radar_params.vh.
Returns dict like {"RP_FFT_SIZE": 1024, "RP_DECIMATION_FACTOR": 16, ...}.
Only parses defines with simple integer or Verilog literal values.
Skips bit-width prefixed literals (e.g. 2'b00) — returns the numeric value.
"""
path = FPGA_DIR / "radar_params.vh"
text = path.read_text()
params: dict[str, int] = {}
for m in re.finditer(
r'`define\s+(RP_\w+)\s+(\S+)', text
):
name = m.group(1)
val_str = m.group(2).rstrip()
# Skip non-numeric defines (like RADAR_PARAMS_VH guard)
if name == "RADAR_PARAMS_VH":
continue
# Handle Verilog bit-width literals: 2'b00, 8'h30, etc.
verilog_lit = re.match(r"\d+'([bhd])(\w+)", val_str)
if verilog_lit:
base_char = verilog_lit.group(1)
digits = verilog_lit.group(2)
base = {"b": 2, "h": 16, "d": 10}[base_char]
params[name] = int(digits, base)
continue
# Handle parenthesized expressions like (`RP_X * `RP_Y)
if "(" in val_str or "`" in val_str:
continue # Skip computed defines
# Plain integer
try:
params[name] = int(val_str)
except ValueError:
continue
return params
@@ -27,10 +27,12 @@ layers agree (because both could be wrong).
from __future__ import annotations
import os
import re
import struct
import subprocess
import tempfile
from pathlib import Path
from typing import ClassVar
import pytest
@@ -202,6 +204,58 @@ class TestTier1OpcodeContract:
f"but ground truth says '{expected_reg}'"
)
def test_opcode_count_exact_match(self):
"""
Total opcode count must match ground truth exactly.
This is a CANARY test: if an LLM agent or developer adds/removes
an opcode in one layer without updating ground truth, this fails
immediately. Update GROUND_TRUTH_OPCODES when intentionally
changing the register map.
"""
expected_count = len(GROUND_TRUTH_OPCODES) # 25
py_count = len(cp.parse_python_opcodes())
v_count = len(cp.parse_verilog_opcodes())
assert py_count == expected_count, (
f"Python has {py_count} opcodes but ground truth has {expected_count}. "
f"If intentional, update GROUND_TRUTH_OPCODES in this test file."
)
assert v_count == expected_count, (
f"Verilog has {v_count} opcodes but ground truth has {expected_count}. "
f"If intentional, update GROUND_TRUTH_OPCODES in this test file."
)
def test_no_extra_verilog_opcodes(self):
"""
Verilog must not have opcodes absent from ground truth.
Catches the case where someone adds a new case entry in
radar_system_top.v but forgets to update the contract.
"""
v_opcodes = cp.parse_verilog_opcodes()
extra = set(v_opcodes.keys()) - set(GROUND_TRUTH_OPCODES.keys())
assert not extra, (
f"Verilog has opcodes not in ground truth: "
f"{[f'0x{x:02X} ({v_opcodes[x].register})' for x in extra]}. "
f"Add them to GROUND_TRUTH_OPCODES if intentional."
)
def test_no_extra_python_opcodes(self):
"""
Python must not have opcodes absent from ground truth.
Catches phantom opcodes (like the 0x06 incident) added by
LLM agents that assume without verifying.
"""
py_opcodes = cp.parse_python_opcodes()
extra = set(py_opcodes.keys()) - set(GROUND_TRUTH_OPCODES.keys())
assert not extra, (
f"Python has opcodes not in ground truth: "
f"{[f'0x{x:02X} ({py_opcodes[x].name})' for x in extra]}. "
f"Remove phantom opcodes or add to GROUND_TRUTH_OPCODES."
)
class TestTier1BitWidths:
"""Verify register widths and opcode bit slices match ground truth."""
@@ -300,6 +354,122 @@ class TestTier1StatusFieldPositions:
)
class TestTier1ArchitecturalParams:
"""
Verify radar_params.vh (FPGA single source of truth) matches Python
WaveformConfig defaults and frozen architectural constants.
These tests catch:
- LLM agents changing FFT size, bin counts, or sample rates in one
layer without updating the other
- Accidental parameter drift between FPGA and GUI
- Unauthorized changes to critical architectural constants
When intentionally changing a parameter (e.g. FFT 10242048),
update BOTH radar_params.vh AND WaveformConfig, then update the
FROZEN_PARAMS dict below.
"""
# Frozen architectural constants — update deliberately when changing arch
FROZEN_PARAMS: ClassVar[dict[str, int]] = {
"RP_FFT_SIZE": 1024,
"RP_DECIMATION_FACTOR": 16,
"RP_BINS_PER_SEGMENT": 64,
"RP_OUTPUT_RANGE_BINS_3KM": 64,
"RP_DOPPLER_FFT_SIZE": 16,
"RP_NUM_DOPPLER_BINS": 32,
"RP_CHIRPS_PER_FRAME": 32,
"RP_CHIRPS_PER_SUBFRAME": 16,
"RP_DATA_WIDTH": 16,
"RP_PROCESSING_RATE_MHZ": 100,
"RP_RANGE_PER_BIN_DM": 240, # 24.0 m in decimeters
}
def test_radar_params_vh_parseable(self):
"""radar_params.vh must exist and parse without error."""
params = cp.parse_radar_params_vh()
assert len(params) > 10, (
f"Only parsed {len(params)} defines from radar_params.vh — "
f"expected > 10. Parser may be broken."
)
def test_frozen_constants_unchanged(self):
"""
Critical architectural constants must match frozen values.
If this test fails, someone changed a fundamental parameter.
Verify the change is intentional, update FROZEN_PARAMS, AND
update all downstream consumers (GUI, testbenches, docs).
"""
params = cp.parse_radar_params_vh()
for name, expected in self.FROZEN_PARAMS.items():
assert name in params, (
f"{name} missing from radar_params.vh! "
f"Was it renamed or removed?"
)
assert params[name] == expected, (
f"ARCHITECTURAL CHANGE DETECTED: {name} = {params[name]}, "
f"expected {expected}. If intentional, update FROZEN_PARAMS "
f"in this test AND all downstream consumers."
)
def test_fpga_python_fft_size_match(self):
"""FPGA FFT size must match Python WaveformConfig.fft_size."""
params = cp.parse_radar_params_vh()
sys.path.insert(0, str(cp.GUI_DIR))
from v7.models import WaveformConfig
wc = WaveformConfig()
assert params["RP_FFT_SIZE"] == wc.fft_size, (
f"FFT size mismatch: radar_params.vh={params['RP_FFT_SIZE']}, "
f"WaveformConfig={wc.fft_size}"
)
def test_fpga_python_decimation_match(self):
"""FPGA decimation factor must match Python WaveformConfig."""
params = cp.parse_radar_params_vh()
sys.path.insert(0, str(cp.GUI_DIR))
from v7.models import WaveformConfig
wc = WaveformConfig()
assert params["RP_DECIMATION_FACTOR"] == wc.decimation_factor, (
f"Decimation mismatch: radar_params.vh={params['RP_DECIMATION_FACTOR']}, "
f"WaveformConfig={wc.decimation_factor}"
)
def test_fpga_python_range_bins_match(self):
"""FPGA 3km output bins must match Python WaveformConfig.n_range_bins."""
params = cp.parse_radar_params_vh()
sys.path.insert(0, str(cp.GUI_DIR))
from v7.models import WaveformConfig
wc = WaveformConfig()
assert params["RP_OUTPUT_RANGE_BINS_3KM"] == wc.n_range_bins, (
f"Range bins mismatch: radar_params.vh={params['RP_OUTPUT_RANGE_BINS_3KM']}, "
f"WaveformConfig={wc.n_range_bins}"
)
def test_fpga_python_doppler_bins_match(self):
"""FPGA Doppler bins must match Python WaveformConfig.n_doppler_bins."""
params = cp.parse_radar_params_vh()
sys.path.insert(0, str(cp.GUI_DIR))
from v7.models import WaveformConfig
wc = WaveformConfig()
assert params["RP_NUM_DOPPLER_BINS"] == wc.n_doppler_bins, (
f"Doppler bins mismatch: radar_params.vh={params['RP_NUM_DOPPLER_BINS']}, "
f"WaveformConfig={wc.n_doppler_bins}"
)
def test_fpga_python_sample_rate_match(self):
"""FPGA processing rate must match Python WaveformConfig.sample_rate_hz."""
params = cp.parse_radar_params_vh()
sys.path.insert(0, str(cp.GUI_DIR))
from v7.models import WaveformConfig
wc = WaveformConfig()
fpga_rate_hz = params["RP_PROCESSING_RATE_MHZ"] * 1e6
assert fpga_rate_hz == wc.sample_rate_hz, (
f"Sample rate mismatch: radar_params.vh={fpga_rate_hz/1e6} MHz, "
f"WaveformConfig={wc.sample_rate_hz/1e6} MHz"
)
class TestTier1PacketConstants:
"""Verify packet header/footer/size constants match across layers."""
@@ -724,8 +894,8 @@ class TestTier3CStub:
"freq_max": 30.0e6,
"prf1": 1000.0,
"prf2": 2000.0,
"max_distance": 50000.0,
"map_size": 50000.0,
"max_distance": 1536.0,
"map_size": 1536.0,
}
pkt = self._build_settings_packet(values)
result = self._run_stub(stub_binary, pkt)
@@ -784,11 +954,11 @@ class TestTier3CStub:
def test_bad_markers_rejected(self, stub_binary):
"""Packet with wrong start/end markers must be rejected."""
values = {
"system_frequency": 10.0e9, "chirp_duration_1": 30.0e-6,
"system_frequency": 10.5e9, "chirp_duration_1": 30.0e-6,
"chirp_duration_2": 0.5e-6, "chirps_per_position": 32,
"freq_min": 10.0e6, "freq_max": 30.0e6,
"prf1": 1000.0, "prf2": 2000.0,
"max_distance": 50000.0, "map_size": 50000.0,
"max_distance": 1536.0, "map_size": 1536.0,
}
pkt = self._build_settings_packet(values)
@@ -826,3 +996,107 @@ class TestTier3CStub:
assert result.get("parse_ok") == "true", (
f"Boundary values rejected: {result}"
)
# ===================================================================
# TIER 4: Stale Value Detection (LLM Agent Guardrails)
# ===================================================================
class TestTier4BannedPatterns:
"""
Scan source files for known-wrong values that have been corrected.
These patterns are stale ADI Phaser defaults, wrong sample rates,
and incorrect range calculations that were cleaned up in commit
d259e5c. If an LLM agent reintroduces them, this test catches it.
IMPORTANT: Allowlist entries exist for legitimate uses (e.g. comments
explaining what was wrong, test files checking for these values).
"""
# (regex_pattern, description, file_extensions_to_scan)
BANNED_PATTERNS: ClassVar[list[tuple[str, str, tuple[str, ...]]]] = [
# Wrong carrier frequency (ADI Phaser default, not PLFM)
(r'10[._]?525\s*e\s*9|10\.525\s*GHz|10525000000',
"Stale ADI Phaser carrier freq — PLFM uses 10.5 GHz",
("*.py", "*.v", "*.vh", "*.cpp", "*.h")),
# Wrong post-DDC sample rate (ADI Phaser uses 4 MSPS)
(r'(?<!\d)4e6(?!\d)|4_?000_?000\.0?\s*#.*(?:sample|samp|rate|fs)',
"Stale ADI 4 MSPS rate — PLFM post-DDC is 100 MSPS",
("*.py",)),
# Wrong range per bin values from old calculations
(r'(?<!\d)4\.8\s*(?:m/bin|m per|meters?\s*per)',
"Stale bin spacing 4.8 m — PLFM is 24.0 m/bin",
("*.py", "*.cpp")),
(r'(?<!\d)5\.6\s*(?:m/bin|m per|meters?\s*per)',
"Stale bin spacing 5.6 m — PLFM is 24.0 m/bin",
("*.py", "*.cpp")),
# Wrong range resolution from deramped FMCW formula
(r'781\.25',
"Stale ADI range value 781.25 — not applicable to PLFM",
("*.py",)),
]
# Files that are allowed to contain banned patterns
# (this test file, historical docs, comparison scripts)
# ADI co-sim files legitimately reference ADI Phaser hardware params
# because they process ADI test stimulus data (10.525 GHz, 4 MSPS).
ALLOWLIST: ClassVar[set[str]] = {
"test_cross_layer_contract.py", # This file — contains the patterns!
"CLAUDE.md", # Context doc may reference old values
"golden_reference.py", # Processes ADI Phaser test data
"tb_fullchain_mti_cfar_realdata.v", # $display of ADI test stimulus info
"tb_doppler_realdata.v", # $display of ADI test stimulus info
"tb_range_fft_realdata.v", # $display of ADI test stimulus info
"tb_fullchain_realdata.v", # $display of ADI test stimulus info
}
def _scan_files(self, pattern_re, extensions):
"""Scan firmware source files for a regex pattern."""
hits = []
firmware_dir = cp.REPO_ROOT / "9_Firmware"
for ext in extensions:
for fpath in firmware_dir.rglob(ext.replace("*", "**/*") if "**" in ext else ext):
# Skip allowlisted files
if fpath.name in self.ALLOWLIST:
continue
# Skip __pycache__, .git, etc.
parts = set(fpath.parts)
if parts & {"__pycache__", ".git", ".venv", "venv", ".ruff_cache"}:
continue
try:
text = fpath.read_text(encoding="utf-8", errors="ignore")
except OSError:
continue
for i, line in enumerate(text.splitlines(), 1):
if pattern_re.search(line):
hits.append(f"{fpath.relative_to(cp.REPO_ROOT)}:{i}: {line.strip()[:120]}")
return hits
def test_no_banned_stale_values(self):
"""
No source file should contain known-wrong stale values.
If this fails, an LLM agent likely reintroduced a corrected value.
Check the flagged lines and fix them. If a line is a legitimate
use (e.g. a comment explaining history), add the file to ALLOWLIST.
"""
all_hits = []
for pattern_str, description, extensions in self.BANNED_PATTERNS:
pattern_re = re.compile(pattern_str, re.IGNORECASE)
hits = self._scan_files(pattern_re, extensions)
all_hits.extend(f"[{description}] {hit}" for hit in hits)
assert not all_hits, (
f"Found {len(all_hits)} stale/banned value(s) in source files:\n"
+ "\n".join(f" {h}" for h in all_hits[:20])
+ ("\n ... and more" if len(all_hits) > 20 else "")
)