# LIN Automated Test Scripts

Automated test scripts for LIN bus communication and auto-addressing functionality using the Melexis Universal Master (MUM) hardware.

## Purpose

This folder contains Python scripts to automate LIN bus testing without requiring manual tool switching between MUM and babylin. The scripts provide:

- **LIN Auto-Addressing Test**: Automated BSM-SNPD (Bus Shunt Method - Slave Node Position Detection) auto-addressing
- **LED Control Test**: Verify LIN communication by controlling the board LED
- **Power Cycle Utility**: Power cycle the ECU through MUM
- **Dependency Installation**: Automated setup of required Python packages

## Hardware Setup

### Required Hardware

1. **Melexis Universal Master (MUM)**
   - BeagleBone-based LIN master device
   - Default IP: 192.168.7.2
   - LIN interface: lin0
   - Power control: power_out0

2. **ALM Platform MLX81124 Board**
   - Target ECU with LIN auto-addressing support
   - RGB LED for visual feedback

### Hardware Connections

```
┌─────────────────┐                    ┌──────────────────┐
│      MUM        │                    │  ALM Platform    │
│  (192.168.7.2)  │                    │   MLX81124       │
├─────────────────┤                    ├──────────────────┤
│                 │                    │                  │
│   LIN (lin0)    ├────────────────────┤  LIN             │
│                 │                    │                  │
│   Power         ├────────────────────┤  VCC/GND         │
│   (power_out0)  │                    │                  │
│                 │                    │  RGB LED         │
└─────────────────┘                    └──────────────────┘
```

### Connection Details

1. **LIN Bus**: Connect MUM LIN0 to ALM Platform LIN pin
2. **Power**: Connect MUM power_out0 to ALM Platform power (controlled by scripts)
3. **Ground**: Common ground between MUM and ALM Platform

## Files

### Scripts

- **`test_auto_addressing.py`** - Main auto-addressing test
- **`test_led_control.py`** - LED control verification test
- **`power_cycle.py`** - ECU power cycle utility
- **`install_packages.sh`** - Dependency installer

### Configuration

- **`config.py`** - Hardware and protocol configuration
  - MUM connection settings
  - LIN bus parameters
  - BSM-SNPD protocol constants
  - Test defaults

## Dependencies

### Python Packages

The scripts require these Python packages:
- `pylin` - LIN bus communication library
- `pymumclient` - Melexis Universal Master client library

### Installation

Run the installer script to set up dependencies:

```bash
./install_packages.sh
```

Or manually install:

```bash
pip3 install pylin pymumclient
```

## Usage

### 1. Auto-Addressing Test

Tests LIN auto-addressing using BSM-SNPD protocol. Automatically selects a target NAD different from the current NAD.

**Basic usage:**
```bash
python3 test_auto_addressing.py
```

**With options:**
```bash
python3 test_auto_addressing.py --iterations 1 --check-interval 1
```

**Parameters:**
- `--host` - MUM IP address (default: 192.168.7.2)
- `--iterations` - Number of auto-addressing iterations (default: 1)
- `--check-interval` - Check status every N iterations (0 = only at end)

**What it does:**
1. Connects to MUM
2. Reads current NAD from ECU
3. Selects target NAD (automatically different from current)
4. Sends BSM-SNPD sequence:
   - INIT (0x01) - Initialize auto-addressing
   - ASSIGN (0x02) - Assign NAD (16 frames)
   - STORE (0x03) - Store to NVM
   - FINALIZE (0x04) - Exit auto-addressing mode
5. Polls status frames between iterations
6. Verifies NAD change

**Expected output:**
```
Initial NAD: 0x07
Target NAD: 0x01
SUCCESS! NAD changed from 0x07 to 0x01
```

### 2. LED Control Test

Verifies LIN communication by controlling the RGB LED through color fades.

**Basic usage:**
```bash
python3 test_led_control.py
```

**With options:**
```bash
python3 test_led_control.py --nad 0x02 --cycles 3 --duration 3.0
```

**Parameters:**
- `--host` - MUM IP address (default: 192.168.7.2)
- `--nad` - Node address to control (default: 0x01)
- `--cycles` - Number of fade cycles (default: 3)
- `--duration` - Duration per color in seconds (default: 3.0)

**What it does:**
1. Connects to MUM
2. Reads current NAD from ECU
3. Fades LED through Red → Green → Blue
4. Each color fades in and out smoothly

**Expected output:**
```
Current NAD: 0x02
Fading Red...
Fading Green...
Fading Blue...
LED test complete
```

### 3. Power Cycle Utility

Power cycles the ECU through MUM power control.

**Basic usage:**
```bash
python3 power_cycle.py
```

**With options:**
```bash
python3 power_cycle.py --wait 3.0
```

**Parameters:**
- `--host` - MUM IP address (default: 192.168.7.2)
- `--wait` - Wait time after power down/up in seconds (default: 2.0)

**What it does:**
1. Powers down ECU
2. Waits specified duration
3. Powers up ECU
4. Waits for ECU to boot

## Configuration

All hardware-specific settings are centralized in [`config.py`](config.py). Edit this file to match your setup:

### Common Settings to Modify

```python
# MUM Configuration
MUM_HOST = '192.168.7.2'  # Change if MUM has different IP

# LIN Bus Configuration
LIN_BAUDRATE = 19200      # Change if using different baudrate

# Test Parameters
AUTOADDRESSING_DEFAULT_ITERATIONS = 1  # Default test iterations
LED_DEFAULT_NAD = 0x01                 # Default NAD for LED test
```

## Firmware Requirements

The firmware must have auto-addressing enabled with twist detection disabled for single-node MUM testing:

**File:** `02-Software/02-Source-Code/code/src/03-HAL/LAA/cfg/HAL_LAA_cfg.h`

```c
#define HAL_LAA_LINAATWISTDETECTDISABLE (1u)
```

This allows the `LASTSLAVE` flag to be set directly without requiring multi-node hardware setup.

## Troubleshooting

### MUM Connection Issues

**Problem:** Cannot connect to MUM
```
Error: Connection to 192.168.7.2 failed
```

**Solution:**
1. Check MUM is powered and connected via USB
2. Verify IP address with `ip addr show` or `ifconfig`
3. Ping MUM: `ping 192.168.7.2`
4. Check USB connection is recognized: `lsusb`

### No Response from ECU

**Problem:** ECU not responding to LIN frames
```
Error: S2M frame receiving failed with error code: 3 - Rx timeout error
```

**Solution:**
1. Check LIN bus connections
2. Verify ECU is powered (use power_cycle.py)
3. Check baudrate matches (19200)
4. Verify NAD is correct

### NAD Not Changing

**Problem:** Auto-addressing completes but NAD doesn't change

**Solution:**
1. Verify firmware has `HAL_LAA_LINAATWISTDETECTDISABLE = 1`
2. Rebuild and flash firmware
3. Check initial NAD is in valid range (0x01-0x10)
4. Run test with `--check-interval 1` to see intermediate status

### LED Not Changing

**Problem:** LED control test doesn't change LED color

**Solution:**
1. Verify NAD parameter matches ECU NAD
2. Check `ALM_Req_A` frame ID is 0x01 in LDF
3. Run auto-addressing test first to verify communication
4. Check LED connections on hardware

## Integration with Build/Flash Pipeline

These tests integrate with the automated firmware development pipeline:

```bash
# 1. Modify firmware
vim 02-Software/02-Source-Code/code/src/...

# 2. Build
./00-Tools/migrate_mlx_tools_linux/build_linux.sh

# 3. Flash
./00-Tools/migrate_mlx_tools_linux/flash_linux.sh

# 4. Test auto-addressing
python3 00-Tools/automated_lin_test/test_auto_addressing.py

# 5. Verify LED control
python3 00-Tools/automated_lin_test/test_led_control.py
```

## Technical Details

### LIN Frame IDs

- `0x3C` - MasterReq (diagnostic frames)
- `0x11` - ALM_Status (4 bytes, contains NAD in byte 0)
- `0x01` - ALM_Req_A (8 bytes, LED control)

### BSM-SNPD Protocol

Auto-addressing uses diagnostic service 0xB5 with subfunctions:
- `0x01` - INIT: Enable auto-addressing mode
- `0x02` - ASSIGN: Assign NAD to node
- `0x03` - STORE: Save NAD to NVM
- `0x04` - FINALIZE: Exit auto-addressing mode

Frame structure:
```
Byte 0: NAD = 0x7F (broadcast)
Byte 1: PCI = 0x06 (6 data bytes)
Byte 2: SID = 0xB5 (BSM-SNPD service)
Byte 3: Supplier ID LSB = 0xFF
Byte 4: Supplier ID MSB = 0x7F
Byte 5: Subfunction
Byte 6: Parameter 1
Byte 7: Parameter 2
```

### Checksum Requirements

**Critical:** BSM frames must use **LIN 1.x Classic checksum**. The scripts use `ld_put_raw()` to ensure Classic checksum. Using `send_message()` with Enhanced checksum will cause frames to be rejected by firmware.

## License

Part of the ALM Platform MLX81124 project.
