PlatSim_Genova/_doc/ANALISI_TARGET3_VS_CORRENTE.md
2026-02-04 10:04:05 +01:00

35 KiB
Raw Blame History

Analisi Differenze: Target3 vs Codice Corrente

Data Analisi: 3 Febbraio 2026
Autore: GitHub Copilot (AI Agent)


1. EXECUTIVE SUMMARY

La configurazione presente nella cartella target3 implementa una versione semplificata e focalizzata del test GRIFO che si concentra principalmente sul rilevamento target dal radar tramite messaggi B9 (Target Report). A differenza del nostro codice corrente che è un framework completo di test PBIT con power cycling, drill-down B8 e statistiche approfondite, target3 è orientato alla validazione operativa del radar in modalità target detection.

Differenze Principali:

  1. Focus primario: Target detection (B9) invece di PBIT completo
  2. Architettura: Test loop semplificato senza power cycling automatico
  3. ICD: Verifica di subset ridotto di campi LRU (solo 6 invece di 12)
  4. Mancanza funzionalità: Nessun supporto per B8 drill-down, statistiche CSV, GUI
  5. Target generation: Implementazione attiva di stimolazione target via bus 1553

2. STRUTTURA E ARCHITETTURA

2.1 Target3 - Caratteristiche

target3/GrifoAutomaticTestEnv/
├── TestEnvironment/
│   ├── env/                    # Moduli supporto (identici)
│   ├── scripts/
│   │   ├── GRIFO_M_PBIT.py    # Script principale (450 righe)
│   │   ├── GRIFO_test_debug.py
│   │   └── ... (varianti e log)
│   └── json/
│       └── GRIFO_M_PBIT.json  # Metadata test base
└── Documents/
    └── ICD7033158 Rev. D.pdf

Dimensione script principale: ~450 righe (vs 1919 righe corrente)

2.2 Codice Corrente - Caratteristiche

GrifoAutomaticTestEnv/
├── TestEnvironment/
│   ├── env/                     # Moduli supporto completi
│   ├── scripts/
│   │   ├── GRIFO_M_PBIT.py     # Script principale (1919 righe)
│   │   ├── GRIFO_M_PBIT_mock.py # Simulazione completa
│   │   ├── GRIFO_M_PBIT_gui.py  # GUI wrapper
│   │   └── power_on/off helpers
│   └── json/
│       └── GRIFO_M_PBIT.json   # Template report esteso
├── python_simulate_wrapper.py
├── run_simulate.bat
└── Documentation estesa (5+ file MD)

Dimensione script principale: ~1919 righe con supporto completo


3. ANALISI FUNZIONALE TARGET3

3.1 Funzione Principale: tgt_gen(interface)

Scopo: Generare messaggi 1553 per simulare dati di navigazione e inertiali, quindi monitorare il messaggio B9 (Target Report) per rilevare la presenza del target nel radar.

Implementazione (target3):

def tgt_gen(interface):
    logging.info('tgt_gen()')
    time.sleep(5)
    period=10 #ms
    tt=0
    
    if only_bc:  # Broadcasting mode
        setValue(theGrifo1553, 0, "A2_MsgRdrOperationCommand",
                "rdr_mode_command_RdrModeCommandWord_stby", commitChanges=True)
    
    # Phase 1: Send initial A5 messages (INU High Speed)
    for i in range(10):
        time.sleep(0.020)
        if only_bc:
            setValue(theGrifo1553, tt, "A5_MsgInuHighSpeed",
                "timetag_RelativeTimetag_raw", commitChanges=True)
        tt+=150
    
    # Phase 2: Main loop - stimulate A4 (Nav Data) and monitor B9 (Target Report)
    p_tt=0
    hit=0
    for i in range(1000):
        time.sleep(0.010)
        
        if only_bc:
            setValue(theGrifo1553, tt, "A4_MsgNavDataAndCursor",
                    "timetag_RelativeTimetag_raw", commitChanges=True)
        tt+=150
        if tt>0x70ff:
            tt=10
            
        # Monitor B9 message
        cnt = interface.getSingleMessageReceivedSz("B9")                              
        t_num=interface.getMessageFieldValue("B9", "b9_t_num")
        t_rng=interface.getMessageFieldValue("B9", "b9_t1_rng")
        t_tt=interface.getMessageFieldValue("B9", "b9_w12")
        
        if (p_tt==0):
            p_tt=t_tt
            continue
            
        if (i % 10)==0:
            dcnt=cnt-pcnt
            pcnt=cnt
            logging.info(f'TgtMsg: {cnt}  {dcnt}')
            
        # Check if target detected
        if (t_num>0) or (p_tt!=t_tt):
            logging.info(f'Tgt: {t_num} @ {t_rng} tt={t_tt}')
            tgt_expected=2536
            ret_proc_sts, err=check(theGrifo1553,
                (tgt_expected-1000, tgt_expected+200), "B9", "b9_t1_rng")
            if (ret_proc_sts is True):
                logging.info(f'TgtMsg hit {hit}')
                hit=hit+1
                if (hit>10):  # Exit after 10 successful detections
                    logging.info(f'TgtMsg hit {hit}')
                    return
        p_tt=t_tt
        if interruptRequest is True:
            break

Parametri chiave:

  • tgt_expected: 2536 (range atteso del target - in unità ICD)
  • Tolleranza: ±1000 a ±200 unità (range: 1536-2736)
  • Successo: 10 rilevamenti consecutivi
  • Timeout implicito: ~10 secondi (1000 iterazioni × 10ms)

3.2 Funzione Wrapper: tgt_gen_alone(interface)

Scopo: Eseguire ripetutamente tgt_gen() in modalità standalone con logging 1553.

def tgt_gen_alone(interface):
    interface.logStart(3, os.path.dirname(sys.argv[0]))
    for n in range(10*1000):  # 10K iterations
        logging.info(f'tgt_gen_alone(): {n}')
        tgt_gen(interface)
        if interruptRequest is True:
            break
    interface.logStop()        
    return True

Caratteristiche:

  • Logging 1553 attivo (livello 3)
  • Loop infinito (10K iterazioni)
  • Supporto Ctrl-C per interruzione

4. FLOW DI TEST TARGET3

4.1 Sequenza di Test Principale

def test_proc():
    # 1. Setup iniziale
    logger_setup('GRIFO_M_PBIT.log')
    report = testReport(sys.argv[0])
    interface = theGrifo1553.getInterface()
    terminal = leo_grifo_terminal.GrifoSerialTerminal()
    terminal.connect()
    
    # 2. Configurazione iniziale radar
    setValue(theGrifo1553, 127, "A1_MsgRdrSettingsAndParameters",
            "settings_RDROperationalSettings_rdr_symbology_intensity", commitChanges=True)
    setValue(theGrifo1553, 1, "A2_MsgRdrOperationCommand",
            "rdr_mode_command_RdrModeCommandWord_silence")
    setValue(theGrifo1553, 1, "A2_MsgRdrOperationCommand",
            "param1_RdrFunAndParam1_azimuth_scan_width_selection")      
    setValue(theGrifo1553, 2, "A2_MsgRdrOperationCommand",
            "param1_RdrFunAndParam1_range_scale_selection")      
    setValue(theGrifo1553, 1, "A2_MsgRdrOperationCommand",
            "param1_RdrFunAndParam1_number_of_bars_selection")      
    setValue(theGrifo1553, 1, "A2_MsgRdrOperationCommand",
            "rdr_mode_command_RdrModeCommandWord_stby", commitChanges=True)
    
    # 3. Configurazione dati navigazione (A4)
    setValue(theGrifo1553, 1060, "A4_MsgNavDataAndCursor",
            "z_acceleration_Acceleration_raw")      
    setValue(theGrifo1553, 2500, "A4_MsgNavDataAndCursor",
            "corrected_baro_altitude_BaroAltitude_raw")      
    setValue(theGrifo1553, 2500, "A4_MsgNavDataAndCursor",
            "radio_altitude_RadioAltitude_raw", commitChanges=True)
    
    # 4. Configurazione INU (A5)
    setValue(theGrifo1553, 0xAA54, "A5_MsgInuHighSpeed",
            "mode_word", commitChanges=True)
    
    # 5. Loop ripetizioni
    for repetition in range(NUMBER_OF_REPETITIONS):
        report.open_session(f'Repetition {1 + repetition} of {NUMBER_OF_REPETITIONS}')
        
        if only_bc:
            setValue(theGrifo1553, 1, "A2_MsgRdrOperationCommand",
                    "rdr_mode_command_RdrModeCommandWord_silence")
            setValue(theGrifo1553, 1, "A2_MsgRdrOperationCommand",
                    "rdr_mode_command_RdrModeCommandWord_stby", commitChanges=True)
            setValue(theGrifo1553, 127, "A1_MsgRdrSettingsAndParameters",
                    "settings_RDROperationalSettings_rdr_symbology_intensity", commitChanges=True)
        
        # 5a. Esegui target generation test
        tgt_gen_alone(interface)
        
        # 5b. Power cycling test (opzionale)
        for onoff_rep in range(1):
            report.add_comment("Switch off target and wait 3 seconds.")
            power_grifo_off(4, 1)
            if interruptRequest is True:
                break
            report.add_comment("Switch on target.")
            power_grifo_on(0.100)
        
        # 5c. Wait for BIT completion
        remaining_time = PBIT_SEC_TIME
        max_counter_1553_msg = 20
        
        setValue(theGrifo1553, 100, "A1_MsgRdrSettingsAndParameters",
                "settings_RDROperationalSettings_rdr_symbology_intensity", commitChanges=True)
        
        while remaining_time > 0:
            start = time.perf_counter()
            ret_rep_is_avail = False 
            msg_cnt = 0  
            mil1553_error_flag = max_counter_1553_msg
            
            for i in range(100):  
                cnt = interface.getSingleMessageReceivedSz("B6_MsgRdrSettingsAndParametersTellback")
                value = interface.getMessageFieldValue("B6_MsgRdrSettingsAndParametersTellback",
                    "radar_health_status_and_bit_report_valid_RdrHealthStatusAndBitReport_bit_report_available")
                ret_rep_is_avail = value == "true"
                if ret_rep_is_avail is True:    
                    break
                time.sleep(0.05) 
                
                # 1553 comm loss detection
                if cnt > msg_cnt: 
                    mil1553_error_flag = max_counter_1553_msg  
                else:
                    mil1553_error_flag -=1
                msg_cnt = cnt 
                    
                if mil1553_error_flag == 0:
                    logging.critical("1553 communication lost") 
                    return False
            
            # 5d. Check LRU status (B6)
            if ret_rep_is_avail is True:
                time.sleep(0.02)                
                report.add_comment("bit report avail occurred..")
                logging.info("Check health status...")
                
                no_fail=True
                for lru in lru_fields:  # Only 6 LRU fields
                    ret_proc_sts, err = check(theGrifo1553,"false",
                                "B6_MsgRdrSettingsAndParametersTellback", lru)
                    if ret_proc_sts is False: 
                        no_fail=False
                
                # 5e. Force B8 drill-down (unconditional)
                no_fail=False  # Force check to verify SW requirements
                if no_fail is False:
                    logging.info("Check BIT Report...")                        
                    for f in bit_fields:  # Subset di campi B8
                        ret_error_field, err = check(theGrifo1553,"false","B8_MsgBitReport",f)
                        test_return = (test_return and ret_error_field)
            
            time_passed = time.perf_counter() - start              
            remaining_time -= time_passed
            if ret_rep_is_avail is True:
                remaining_time = 0
            logging.info(f'{remaining_time:.1f}s remaining ...')
        
        report.close_session()
        
        if interruptRequest is True:
            report.add_comment("Test interrupted by user (Ctrl-C)")
            break
        
        # 5f. Return to STBY
        setValue(theGrifo1553, 0, "A2_MsgRdrOperationCommand",
            "rdr_mode_command_RdrModeCommandWord_stby", commitChanges=True)
    
    # 6. Cleanup
    report.add_comment("Repetitions terminated.")
    power_grifo_off()        
    if terminal is not None:
        terminal.disconnect()
    report.generate_pdf()
    
    return test_return

5. CONFRONTO: TARGET3 VS CORRENTE

5.1 Messaggi 1553 Utilizzati

Messaggio Target3 Corrente Scopo
A1 ✓ Intensity ✓ Completo Settings & Parameters
A2 ✓ Basic ✓ Completo Operation Command
A4 ✓ Nav Data ✓ Completo Navigation Data & Cursor
A5 ✓ Timetag ✓ Completo INU High Speed
B6 ✓ 6 LRU ✓ 12 LRU Settings Tellback & Status
B8 ✓ Subset ✓ Completo BIT Report (185 fields)
B9 ✓ FOCUS ✗ ASSENTE Target Report

DIFFERENZA CRITICA: Target3 usa B9 per rilevamento target, assente nel nostro codice ICD.

5.2 Campi B6 (LRU Status)

Target3 - Solo 6 campi:

lru_fields = (
    "radar_health_status_and_bit_report_valid_RdrHealthStatusAndBitReport_processor_status",
    "radar_health_status_and_bit_report_valid_RdrHealthStatusAndBitReport_trasmitter_status",
    "radar_health_status_and_bit_report_valid_RdrHealthStatusAndBitReport_receiver_status",
    "radar_health_status_and_bit_report_valid_RdrHealthStatusAndBitReport_rx_front_end_status",
    "radar_health_status_and_bit_report_valid_RdrHealthStatusAndBitReport_servoloop_status",
    "radar_health_status_and_bit_report_valid_RdrHealthStatusAndBitReport_array_status"        
)

Corrente - 12 campi completi (include anche pedestal, radar_fail_status, ecc.)

⚠️ Note: Target3 esclude:

  • radar_fail_status (campo aggregato)
  • pedestal_status (commentato - HW non disponibile)

5.3 Campi B8 (BIT Report)

Target3 - Subset ridotto:

  • Degradation: Tutti commentati (non verificati)
  • SRU Failures: ~40 campi (vs 43 corrente)
  • Test Results: ~115 campi (vs 118 corrente)

Esclusioni principali:

# Target3 - Commentati/esclusi:
# "degradation_conditions_w1_..." (tutti i 12 campi degradation)
# "failure_location_pedestal_FailureLocationPedestal_sru1_gimbal"
# "integrated_system_test_results_..._pedestal_status"
# "servoloop_test_results_..._test_sl15_pedestal_centre_scan_location"

Corrente - Set completo con gestione KNOWN_FAILURES per HW non disponibile.

5.4 Gestione Power Cycling

Feature Target3 Corrente
Auto power off before test
Auto power on before test
Power off between reps ✓ Manual ✓ Auto
Wait times configurabili
Timing aligned with target2

Target3: Power cycling manuale richiesto dall'operatore con prompts.
Corrente: Power cycling automatico con timing configurabili (wait_before, wait_after).

5.5 Statistiche e Report

Feature Target3 Corrente
PDF Report ✓ Basic ✓ Completo
CSV Export
JSON Statistics
Per-run timing
B6/B8 counters
Serial statistics
Failure drill-down
Known failures tracking
Target detection stats ✓ Placeholder

Corrente ha sistema statistiche avanzato con export CSV/JSON e tracking granulare.

5.6 Modalità Simulazione

Feature Target3 Corrente
Mock mode
--simulate flag
Mock objects
Replay scenarios
GUI wrapper

Corrente supporta modalità simulazione completa senza HW (GRIFO_M_PBIT_mock.py).


6. MESSAGGI B9 - ANALISI DETTAGLIATA

6.1 Struttura Messaggio B9 (Target Report)

Campi utilizzati in target3:

# B9 message fields (da codice target3)
cnt = interface.getSingleMessageReceivedSz("B9")  # Message counter
t_num = interface.getMessageFieldValue("B9", "b9_t_num")  # Number of targets
t_rng = interface.getMessageFieldValue("B9", "b9_t1_rng")  # Target 1 range
t_tt = interface.getMessageFieldValue("B9", "b9_w12")  # Word 12 (timetag?)

Campi ICD B9 (presunti da utilizzo):

  • b9_t_num: Number of detected targets (0-N)
  • b9_t1_rng: Target 1 range (unità da ICD - presumibilmente meters o yards)
  • b9_w12: Word 12 - Timetag o altro campo temporale

Range atteso: 2536 ± (1000 to 200) unità ICD

6.2 Correlazione con Messaggi A4/A5

Target3 stimola:

  • A4 (MsgNavDataAndCursor): Dati navigazione (altitudine, accelerazione)
  • A5 (MsgInuHighSpeed): Dati inerziali ad alta frequenza (timetag)

Ipotesi: Il radar utilizza A4/A5 per:

  1. Stabilizzazione antenna (A4: accelerazioni)
  2. Riferimento temporale (A5: timetag)
  3. Generazione tracce target sintetiche interne per test

Il nostro codice corrente:

  • Ha stub tgt_gen() ma non stimola attivamente A4/A5
  • Manca supporto ICD per B9 (messaggio non definito)

7. COSA MANCA AL NOSTRO CODICE

7.1 ICD - Definizione Messaggio B9

AGGIORNAMENTO (2026-02-03): Il messaggio B9 È GIÀ PRESENTE nel nostro ICD XML!

Verifica completata:

  1. ✓ B9 definito in icd_1553_bus_controller.xml (Message Id="19", 512 bit, RX, periodic 20ms)
  2. ✓ Tutti i campi chiave presenti:
    • b9_t_num (offset 176) - numero target rilevati
    • b9_t1_rng (offset 224) - range target 1
    • b9_w12 (offset 192) - word 12 (timetag)
    • b9_t1_az (offset 304) - azimuth target 1
    • b9_t2_rng (offset 384) - range target 2
    • b9_t2_az (offset 464) - azimuth target 2
  3. ✓ B9 già mappato nel simulator (Map Id="19")
  4. ✓ Mock completo già implementato in GRIFO_M_PBIT_mock.py

Conclusione: Non serve modificare l'ICD o i bindings SWIG. B9 è accessibile e pronto all'uso.

7.2 Funzione tgt_gen() Operativa

Corrente: Stub placeholder (righe 619-667) con:

  • Logging basic
  • Timeout configurabile
  • Check B9 fields (ma B9 non disponibile)
  • Return True/False per detection

Mancante rispetto target3:

# 1. Stimolazione attiva A4/A5 con timetag
setValue(theGrifo1553, tt, "A4_MsgNavDataAndCursor",
        "timetag_RelativeTimetag_raw", commitChanges=True)
setValue(theGrifo1553, tt, "A5_MsgInuHighSpeed",
        "timetag_RelativeTimetag_raw", commitChanges=True)

# 2. Loop incremento timetag con wrap
tt += 150
if tt > 0x70ff:
    tt = 10

# 3. Monitoring continuo B9 con contatori
cnt = interface.getSingleMessageReceivedSz("B9")
dcnt = cnt - pcnt  # Delta count

# 4. Detection basata su t_num>0 oppure cambiamento timetag
if (t_num>0) or (p_tt!=t_tt):
    # Target found!

Azioni richieste:

  1. ✗ Implementare stimolazione attiva A4/A5 in tgt_gen()
  2. ✗ Aggiungere logica incremento timetag con wrap
  3. ✗ Implementare monitoring B9 con delta counting
  4. ✗ Aggiungere check range atteso (configurabile)

7.3 Configurazione Radar Pre-Test

Target3 configura esplicitamente:

# Range scale, scan width, bars
setValue(theGrifo1553, 1, "A2_MsgRdrOperationCommand",
        "param1_RdrFunAndParam1_azimuth_scan_width_selection")      
setValue(theGrifo1553, 2, "A2_MsgRdrOperationCommand",
        "param1_RdrFunAndParam1_range_scale_selection")      
setValue(theGrifo1553, 1, "A2_MsgRdrOperationCommand",
        "param1_RdrFunAndParam1_number_of_bars_selection")

# Nav data values
setValue(theGrifo1553, 1060, "A4_MsgNavDataAndCursor",
        "z_acceleration_Acceleration_raw")
setValue(theGrifo1553, 2500, "A4_MsgNavDataAndCursor",
        "corrected_baro_altitude_BaroAltitude_raw")
setValue(theGrifo1553, 2500, "A4_MsgNavDataAndCursor",
        "radio_altitude_RadioAltitude_raw", commitChanges=True)

# INU mode
setValue(theGrifo1553, 0xAA54, "A5_MsgInuHighSpeed",
        "mode_word", commitChanges=True)

Corrente: Ha set_radar_operational() ma non configura questi valori specifici.

Azioni richieste:

  1. ✗ Aggiungere configurazione scan width/range/bars in set_radar_operational()
  2. ✗ Aggiungere settaggio valori nav data (altitude, accel)
  3. ✗ Aggiungere settaggio INU mode word

7.4 Gestione STBY/SILENCE per Target Test

Target3 workflow:

# 1. Set SILENCE
setValue(..., "rdr_mode_command_RdrModeCommandWord_silence")

# 2. Set STBY
setValue(..., "rdr_mode_command_RdrModeCommandWord_stby", commitChanges=True)

# 3. Run target generation
tgt_gen_alone(interface)

# 4. Return to STBY only (unset both)
setValue(..., 0, "rdr_mode_command_RdrModeCommandWord_stby", commitChanges=True)

Corrente: Ha helper verify_tellback_stby() ma non sequence specifica per target test.

Azioni richieste:

  1. ✗ Creare helper prepare_radar_for_target_test() che sequenza SILENCE→STBY
  2. ✗ Validare timing delays dopo ogni set
  3. ✗ Aggiungere cleanup function per unset STBY dopo test

7.5 Integrazione in Test Flow

Target3: tgt_gen_alone() chiamato prima del power cycling e BIT check.

Corrente: Ha placeholder per target test ma non integrato in main loop.

Azioni richieste:

  1. ✗ Decidere posizione target test nel flow (pre-PBIT? post-PBIT? separato?)
  2. ✗ Aggiungere flag ENABLE_TARGET_TEST (default: False fino a B9 disponibile)
  3. ✗ Integrare tgt_gen() in loop ripetizioni con statistiche
  4. ✗ Aggiungere colonna "Target Detected" in CSV export

8. ROADMAP IMPLEMENTAZIONE

8.1 Phase 1: ICD e Infrastruttura ( COMPLETATO)

SCOPERTA: B9 è già presente e completamente funzionante!

  1. ICD XML contiene B9 - Verificato in icd_1553_bus_controller.xml
  2. SWIG bindings includono B9 - interpreter.py già supporta B9
  3. Mock implementato - GRIFO_M_PBIT_mock.py simula B9 completamente
  4. Mappatura 1553 - B9 mappato correttamente (Map Id="19")

Phase 1 completata automaticamente - Non serve nessuna azione!

Tempo stimato: 2-3 giorni (dipende da disponibilità ICD e toolchain SWIG) Tempo reale: 0 giorni (già presente)

8.2 Phase 2: Implementazione tgt_gen() Base

  1. Aggiornare tgt_gen() in GRIFO_M_PBIT.py

    • Rimuovere placeholder corrente (righe 619-667)
    • Port logica da target3 con miglioramenti:
      def tgt_gen(interface, timeout_sec=None, expected_range=2536, range_tolerance=(1000, 200)):
          """
          Target generation and detection test.
      
          Stimulates radar with A4/A5 nav data and monitors B9 for target detection.
      
          Args:
              interface: Grifo1553 interface object
              timeout_sec: Max seconds to wait (default: TARGET_DETECTION_TIMEOUT_SEC)
              expected_range: Expected target range in ICD units (default: 2536)
              range_tolerance: (lower_tol, upper_tol) tuple (default: (1000, 200))
      
          Returns:
              dict: {'detected': bool, 'hits': int, 'range': float, 'iterations': int}
          """
          # Implementation here
      
  2. Implementare stimolazione A4/A5

    • Settaggio timetag incrementale con wrap a 0x70ff
    • Commit messages a ~10ms rate
    • Logging delta counts ogni 10 iterazioni
  3. Implementare monitoring B9

    • Lettura continua getSingleMessageReceivedSz("B9")
    • Parsing b9_t_num, b9_t1_rng, b9_w12
    • Detection logic: t_num>0 OR timetag_changed
    • Range validation con tolerance configurabile
  4. Aggiungere return structured result

    return {
        'detected': bool,
        'hits': int,           # Successful range validations
        'range': float,        # Last detected range
        'iterations': int,     # Total loop iterations
        'time_to_detect': float,  # Seconds until first detection
        'message_count': int   # B9 messages received
    }
    

Tempo stimato: 1-2 giorni

8.3 Phase 3: Configurazione Radar Pre-Test

  1. Estendere set_radar_operational()

    • Aggiungere parametri:
      def set_radar_operational(interface, range_nm=40.0, intensity=127,
                                master_mode='RWS', gm_submode=0,
                                # NEW:
                                azimuth_scan_width=1,
                                range_scale_selection=2,
                                number_of_bars=1,
                                altitude_ft=8202,  # 2500m * 3.28
                                z_accel_g=1.08,    # 1060 raw units
                                inu_mode_word=0xAA54):
      
  2. Implementare sequence SILENCE→STBY

    def prepare_radar_for_target_test(interface):
        """Set radar in SILENCE+STBY mode before target generation test."""
        setValue(interface, 1, "A2_MsgRdrOperationCommand",
                "rdr_mode_command_RdrModeCommandWord_silence", commitChanges=True)
        time.sleep(TELLBACK_POST_SET_DELAY_SEC)
    
        setValue(interface, 1, "A2_MsgRdrOperationCommand",
                "rdr_mode_command_RdrModeCommandWord_stby", commitChanges=True)
        time.sleep(TELLBACK_POST_SET_DELAY_SEC)
    
        # Verify tellbacks
        return verify_tellback_stby(interface, timeout_sec=5.0)
    
  3. Implementare cleanup

    def cleanup_radar_after_target_test(interface):
        """Unset STBY after target test."""
        setValue(interface, 0, "A2_MsgRdrOperationCommand",
                "rdr_mode_command_RdrModeCommandWord_stby", commitChanges=True)
        time.sleep(STBY_POST_UNSET_DELAY_SEC)
    

Tempo stimato: 1 giorno

8.4 Phase 4: Integrazione in Test Loop

  1. Aggiungere flag configurazione

    # Top of GRIFO_M_PBIT.py
    ENABLE_TARGET_TEST = False  # Set True when B9 available
    TARGET_TEST_POSITION = 'pre-pbit'  # 'pre-pbit' | 'post-pbit' | 'standalone'
    
  2. Integrare in run_single_pbit_cycle()

    def run_single_pbit_cycle(...):
        # ... existing power on ...
    
        if ENABLE_TARGET_TEST and TARGET_TEST_POSITION == 'pre-pbit':
            logging.info("=== TARGET DETECTION TEST ===")
            report.open_session("Target Detection Pre-PBIT")
    
            # Prepare radar
            prepare_ok = prepare_radar_for_target_test(theGrifo1553.getInterface())
            if not prepare_ok:
                report.add_comment("WARN: Could not prepare radar for target test")
    
            # Run target test
            tgt_result = tgt_gen(theGrifo1553.getInterface())
    
            # Record result
            repetition_stats['target_detected'] = tgt_result.get('detected', False)
            repetition_stats['target_hits'] = tgt_result.get('hits', 0)
            repetition_stats['target_range'] = tgt_result.get('range', None)
    
            if tgt_result['detected']:
                report.add_comment(f"Target DETECTED after {tgt_result['time_to_detect']:.1f}s "
                                 f"@ range {tgt_result['range']}")
            else:
                report.add_comment("Target NOT detected (timeout)")
    
            # Cleanup
            cleanup_radar_after_target_test(theGrifo1553.getInterface())
            report.close_session()
    
        # ... existing PBIT flow ...
    
  3. Aggiornare CSV export

    • Aggiungere colonne: Target Detected, Target Hits, Target Range
  4. Aggiornare statistiche aggregate

    # In calculate_statistics()
    target_tests = [r.get('target_detected', None) for r in stats['repetitions']]
    target_detected_count = sum(1 for t in target_tests if t is True)
    target_pass_rate = (target_detected_count / len(target_tests) * 100) if target_tests else 0.0
    
    stats['aggregate']['target_detected_count'] = target_detected_count
    stats['aggregate']['target_not_detected_count'] = len(target_tests) - target_detected_count
    stats['aggregate']['target_pass_rate'] = target_pass_rate
    

Tempo stimato: 2 giorni

8.5 Phase 5: Testing e Validazione

  1. Test simulazione (mock)

    • Aggiornare GRIFO_M_PBIT_mock.py con mock B9 responses
    • Testare tgt_gen() in modalità --simulate
    • Validare statistiche e report
  2. Test HW (se disponibile)

    • Eseguire su setup reale con radar
    • Validare range detection
    • Tune timeout e tolerance parameters
  3. Documentazione

    • Aggiornare IMPLEMENTATION_SUMMARY.md
    • Aggiungere sezione "Target Detection" in GRIFO_Test_Environment_Analysis.md
    • Creare TARGET_DETECTION_GUIDE.md con:
      • ICD B9 reference
      • Configuration parameters
      • Troubleshooting

Tempo stimato: 2-3 giorni


9. CONFIGURAZIONI DA COPIARE DA TARGET3

9.1 Valori Hardcoded da Preservare

# From target3 - VALORI CRITICI PER TARGET DETECTION

# A2 - Radar Operation
AZIMUTH_SCAN_WIDTH_SELECTION = 1  # param1
RANGE_SCALE_SELECTION = 2         # param1 (range scale 40nm?)
NUMBER_OF_BARS_SELECTION = 1      # param1

# A4 - Navigation Data
Z_ACCELERATION_RAW = 1060         # ~1.08g
CORRECTED_BARO_ALTITUDE_RAW = 2500  # ~8202 ft (2500m)
RADIO_ALTITUDE_RAW = 2500         # Matching baro

# A5 - INU High Speed
INU_MODE_WORD = 0xAA54            # Mode/status word

# B9 - Target Detection
TARGET_EXPECTED_RANGE = 2536      # ICD units (meters? yards?)
TARGET_RANGE_TOLERANCE_LOW = 1000  # -1000 units
TARGET_RANGE_TOLERANCE_HIGH = 200  # +200 units
TARGET_HITS_THRESHOLD = 10        # Successful detections before exit

# Timing
TIMETAG_INCREMENT = 150           # Increment per iteration
TIMETAG_WRAP = 0x70ff            # Wrap point
TIMETAG_RESET = 10               # Reset value after wrap
TARGET_GEN_PERIOD_MS = 10        # Loop period (ms)
TARGET_GEN_MAX_ITERATIONS = 1000  # ~10s timeout

9.2 Sequence Diagram - Target Detection

Operator              Test Script         Radar (via 1553)      Result
   |                       |                     |                 |
   |-- Start Test -------->|                     |                 |
   |                       |-- A2: SILENCE ----->|                 |
   |                       |-- A2: STBY -------->|                 |
   |                       |      (wait 2s)      |                 |
   |                       |                     |                 |
   |                       |-- A4: Nav Data ---->|                 |
   |                       |-- A5: INU Mode ---->|                 |
   |                       |      (wait 5s)      |                 |
   |                       |                     |                 |
   |                       |====== LOOP (1000 iterations) ======   |
   |                       |-- A4: Timetag ----->|                 |
   |                       |      (tt+=150)      |                 |
   |                       |<--- B9: Target -----|                 |
   |                       |-- Check t_num ----->|                 |
   |                       |-- Check t_rng ----->|                 |
   |                       |                     |                 |
   |                       | [if t_num>0]        |                 |
   |                       |-- Validate range -->|-- ✓ HIT ------->|
   |                       | [if 10 hits]        |                 |
   |                       |====== EXIT LOOP =================     |
   |                       |                     |                 |
   |                       |-- A2: Unset STBY -->|                 |
   |                       |                     |                 |
   |                       |====== Continue to PBIT ==============  |

10. RACCOMANDAZIONI

10.1 Priorità Alta - Bloccanti

  1. Ottenere ICD Rev. D

    • Richiesta formale a team documentazione
    • Verificare se già disponibile in PlatformSimulator/ o archivi
  2. Validare esistenza B9 in simulator

    • Test manuale con uPlatSim per vedere se B9 è già supportato
    • Potrebbe essere già nel simulator ma non esposto in Python bindings
  3. Decision: Dove integrare target test

    • Opzione A: Pre-PBIT (come target3) - validazione radar operativo prima di BIT
    • Opzione B: Post-PBIT - validazione funzionale dopo BIT passed
    • Opzione C: Standalone - test separato eseguibile indipendentemente

10.2 Priorità Media - Miglioramenti

  1. Configurazioni flessibili

    • Spostare valori hardcoded in instrument_settings.json
    • Permettere override via CLI arguments
  2. Mock simulation

    • Estendere GRIFO_M_PBIT_mock.py con B9 synthetic responses
    • Testare target detection senza HW
  3. Diagnostics

    • Aggiungere logging dettagliato timetag progression
    • Plot range detections over time (matplotlib export)

10.3 Priorità Bassa - Nice to Have

  1. Multi-target support

    • Target3 check solo b9_t1_rng (target 1)
    • Estendere per N targets se B9 supporta
  2. Range sweep test

    • Variare A4 altitude/accel per testare range variations
  3. Integration con GUI

    • Live plot target detections in GRIFO_M_PBIT_gui.py

11. RISCHI E MITIGAZIONI

Rischio Impatto Probabilità Mitigazione
B9 non disponibile in ICD corrente 🔴 Alto Media Ottenere ICD Rev. D; verificare simulator
SWIG rebuild richiede toolchain non disponibile 🔴 Alto Bassa Usare binaries pre-compilati da target3
Range units non documentati 🟡 Medio Media Reverse-engineer da test HW; validare con team radar
Target detection timeout su HW reale 🟡 Medio Alta Parametri configurabili; increase timeout
Stimolazione A4/A5 interfere con PBIT 🟡 Medio Bassa Separare target test con cleanup; testare sequenze

12. CONCLUSIONI

12.1 Gap Summary

Il codice target3 è una variante specializzata focalizzata su:

  1. Validazione operativa radar (target detection)
  2. Test manuale con operatore (power cycling, visual checks)
  3. Subset ridotto di verifiche (6 LRU, subset B8)

Il nostro codice corrente è un framework completo ma manca:

  1. Supporto ICD per B9 (messaggio target report)
  2. Stimolazione attiva A4/A5 per target generation
  3. Workflow target detection integrato nel flow

12.2 Next Steps

IMMEDIATO:

  1. Analizzare target3/Documents/ICD7033158 Rev. D.pdf per definizione B9
  2. Verificare se B9 è già nel simulator (test manuale)
  3. Decidere architecture target test (pre/post/standalone PBIT)

SHORT-TERM (1-2 settimane): 4. Implementare Phase 1-2 della roadmap (ICD + tgt_gen base) 5. Testing in modalità simulazione 6. Documentazione

MEDIUM-TERM (3-4 settimane): 7. Integrazione completa nel test loop 8. Validazione su HW 9. Statistiche e report estesi


APPENDICE A: FILE DA ANALIZZARE

Da target3:

  1. target3/.../Documents/ICD7033158 Rev. D.pdf - PRIORITÀ 1
  2. target3/.../scripts/GRIFO_M_PBIT.py (righe 1-450)
  3. target3/.../env/leo_grifo_1553.py (identico al nostro)

Da corrente:

  1. TestEnvironment/scripts/GRIFO_M_PBIT.py (righe 619-667 - stub tgt_gen)
  2. TestEnvironment/env/leo_grifo_1553.py (no B9 support)
  3. PlatformSimulator/bin/interpreter.py (bindings SWIG)

APPENDICE B: CONTATTI E RISORSE

Domande da porre al team:

  1. È disponibile ICD7033158 Rev. D con definizione B9?
  2. Il simulator uPlatSim già supporta B9 message?
  3. Quali sono le unità di misura per b9_t1_rng? (meters? yards? feet?)
  4. Esiste documentazione per target generation test procedure?
  5. I valori hardcoded (2536 range, 0xAA54 INU mode) sono specifici per setup Genova?

Risorse:

  • ICD: ICD7033158 Rev. D.pdf (in target3/Documents)
  • Simulator: PlatformSimulator/bin/uPlatSim.exe
  • SWIG source: (verificare se disponibile per rebuild)

Fine Documento


Autore: GitHub Copilot AI Agent
Data: 2026-02-03
Versione: 1.0
Repository: GrifoAutomaticTestEnv