# UART Loader Host (Standalone Executable)

## Overview
This tool provides a standalone executable for flashing binaries to Atmosic devices via UART.
It supports Windows platforms and comes as a ready-to-use executable file with no additional dependencies required.

## Hardware Requirements
- P25 (UART1_TX) must be connected.
- P27 (UART1_RX) must be connected.
- Ensure the COM port is properly enumerated in the system before powering up the ATM (some environments may not allow hot-plugging or re-enumeration without PWD).

## Setup Instructions

1. **Extract the package**
   Extract the ZIP file to your desired location.
   The extracted folder contains:
   - `UartLoaderHost.exe` - Main executable
   - `binfile/` - Directory containing uart_loader.bin and other binary files
   - Other supporting files and libraries

2. **No additional installation required**
   The executable is self-contained and includes all necessary dependencies.
   No Python installation or additional setup is needed.

3. **Open Command Prompt**
   Use `cmd.exe` to navigate into the extracted folder:
   ```
   cd path\to\extracted\folder
   ```

## Usage

### Command Structure
```
UartLoaderHost.exe {prog_bin,prog_atm,atm_show,atm_export,atm_append_flash_bin,atm_append_rram_bin,diagno_tput,diagno_latency} [options]
```

### Commands

#### Programming files

**prog_bin** - Program binary file via fast-load
- Uploads a single binary file to the device at a specified address

**prog_atm** - Program .atm file via fast-load
- Uploads multiple binary files from an .atm package file

#### ATM file operations

**atm_show** - Show ATM file content
- Show content of ATM file, including all commands and their details

**atm_export** - Export ATM file content to multiple files
- Export all binary files from an .atm package file to individual files

**atm_append_flash_bin** - Append binary file to ATM file as flash command
- Append a binary file to an existing .atm file as a flash command

**atm_append_rram_bin** - Append binary file to ATM file as RRAM command
- Append a binary file to an existing .atm file as a RRAM command

#### Diagnostics

**diagno_tput** - Diagnose throughput
- Diagnose the throughput of the device

**diagno_latency** - Diagnose latency
- Diagnose the latency of the device

### Required Arguments

#### Programming files

**For all commands:**
- `--serial SERIAL`
  Serial port for communication (e.g., `COM33`)
- `--baudrate BAUDRATE`
  Baudrate for serial communication when programming (default: 1000000)
- `--skip-check-sha256`
  Disable SHA256 verification for programmed firmware
- `--ram-image RAM_IMAGE`
  Path to RAM image file to upload via xmodem (default: `binfile/uart_loader.bin`)

**For prog_bin:**
- `--bin-path BIN_PATH`
  Path to binary file to program via fast-load
- `--target-address TARGET_ADDRESS`
  Target storage address for programming (e.g., `0x78000`, `491520`)
- `--erase-size ERASE_SIZE`
  Size to erase before programming (default: 0).
  Accepts decimal or hex (e.g., `65536`, `0x10000`).

**For prog_atm:**
- `--atm-path ATM_PATH`
  Path to .atm file to program via fast-load
  
#### ATM file operations

**For atm_show:**
- `--atm-path ATM_PATH`
  Path to .atm file to show

**For atm_export:**
- `--atm-path ATM_PATH`
  Path to .atm file to export
- `--export-dir EXPORT_DIR`
  Export directory for extracted files

**For atm_append_flash_bin:**
- `--atm-path ATM_PATH`
  Path to .atm file to append to
- `--output-atm-path OUTPUT_ATM_PATH`
  Path to output .atm file
- `--bin-path BIN_PATH`
  Path to binary file to append
- `--address ADDRESS`
  Address of binary file to append
- `--erasing-region-size ERASING_REGION_SIZE`
  Region size for erasing before programming (default: 0).
  Accepts decimal or hex (e.g., `65536`, `0x10000`).
  Must be aligned to 0x1000.
- `--extra-info EXTRA_INFO`
  Extra info for appended command (optional)

**For atm_append_rram_bin:**
- `--input-atm-path INPUT_ATM_PATH`
  Path to input .atm file
- `--output-atm-path OUTPUT_ATM_PATH`
  Path to output .atm file
- `--bin-path BIN_PATH`
  Path to binary file to append
- `--address ADDRESS`
  Address of binary file to append
- `--extra-info EXTRA_INFO`
  Extra info for appended command (optional)

#### Diagnostics

**For diagno_tput:**
- `--serial SERIAL`
  Serial port for communication (e.g., `COM33`)
- `--data-len DATA_LEN`
  Data length for diagno throughput

**For diagno_latency:**
- `--serial SERIAL`
  Serial port for communication (e.g., `COM33`)

### Optional Arguments

**Basic Options:**
- `-h, --help`
  Show help message and exit
- `--version`
  Show version information and exit
- `--log-debug, -v`
  Enable debug logging

### Examples

#### Basic Usage
```cmd
# Show version information
UartLoaderHost.exe --version

# Show basic help
UartLoaderHost.exe --help

```

#### Programming Binary Files
```cmd
# Basic binary programming
UartLoaderHost.exe prog_bin --serial COM33 --bin-path firmware.bin --target-address 0x10000

# With higher baudrate for faster programming
UartLoaderHost.exe prog_bin --serial COM33 --bin-path firmware.bin --target-address 0x10000 --baudrate 2000000

# Skip SHA256 verification (faster but less safe)
UartLoaderHost.exe prog_bin --serial COM33 --bin-path firmware.bin --target-address 0x10000 --skip-check-sha256

# With debug logging for troubleshooting
UartLoaderHost.exe prog_bin --serial COM33 --bin-path firmware.bin --target-address 0x10000 --log-debug

# Using custom RAM image
UartLoaderHost.exe prog_bin --serial COM33 --bin-path firmware.bin --target-address 0x10000 --ram-image custom_loader.bin

# Erase 64KB from target address before programming (hex)
UartLoaderHost.exe prog_bin --serial COM33 --bin-path firmware.bin --target-address 0x10000 --erase-size 0x10000

# Erase 64KB from target address before programming (decimal)
UartLoaderHost.exe prog_bin --serial COM33 --bin-path firmware.bin --target-address 0x10000 --erase-size 65536
```

#### Programming ATM Files
```cmd
# Basic ATM file programming
UartLoaderHost.exe prog_atm --serial COM33 --atm-path firmware.atm

# With higher baudrate
UartLoaderHost.exe prog_atm --serial COM33 --atm-path firmware.atm --baudrate 2000000

# Skip SHA256 verification
UartLoaderHost.exe prog_atm --serial COM33 --atm-path firmware.atm --skip-check-sha256

# With debug logging
UartLoaderHost.exe prog_atm --serial COM33 --atm-path firmware.atm --log-debug
```

## Logging and Debug Information

The UART Loader Host automatically generates detailed log files to help with debugging and troubleshooting.

### Log File Locations

All log files are stored in the `logs/` directory with the following structure:

logs/
├── tool/ # Main application logs
│ └── YYYYMMDD_HHMMSS_/
│ └── tool_detail.log # Detailed debug information
└── csv_report/ # Performance and timing reports
  ├── program_full_spend_time.csv
  ├── program_one_bin.csv
  └── xmodem_spend_time.csv

### Debug Log Files

**Main debug logs:** `logs/tool/YYYYMMDD_HHMMSS_<command>/tool_detail.log`

**File naming convention:**
- `YYYYMMDD_HHMMSS`: Timestamp when the command was executed
- `<command>`: The command that was run (e.g., prog_bin, prog_atm)
- `tool_detail.log`: Contains detailed debug information including error traces

**Examples:**
logs/tool/20241209_143022_prog_bin/tool_detail.log
logs/tool/20241209_143155_prog_atm/tool_detail.log
logs/tool/20241209_144301_atm_show/tool_detail.log

### Log Content Format

Debug logs contain detailed information including:
- Timestamps for all operations
- HCI command/response details
- Serial communication data
- Error stack traces
- Performance timing information

**Example log entries:**
2024-12-09 14:30:22,123 - INFO - uart_loader_host_main.py:155 - Creating task: prog_bin
2024-12-09 14:30:22,124 - DEBUG - hci_gateway.py:89 - Sent HCI command: 04 0E 03 01 FF 00
2024-12-09 14:30:22,125 - DEBUG - serial_io_entry.py:67 - Received response: 04 0E 04 01 FF 00 00
2024-12-09 14:30:22,126 - ERROR - uart_loader_agent.py:145 - [Error 107001] Boot event timeout

### Viewing Log Files

**How to find your log file:**
1. Open Windows File Explorer
2. Navigate to the `uart_loader_host` folder
3. Open the `logs` folder, then the `tool` folder
4. Find the folder with the **most recent date and time** (folders are named like `20241209_143022_prog_bin`)
5. Double-click to open that folder
6. Double-click `tool_detail.log` to open it in Notepad

**Visual guide:**
uart_loader_host/
└── logs/
    └── tool/
        ├── 20241208_091234_prog_bin/ ← Older
        ├── 20241208_142156_prog_atm/ ← Older
        └── 20241209_143022_prog_bin/ ← Most recent (your error log)
            └── tool_detail.log ← Open this file

**Tip:** The folder names show the date and time when you ran the command, so the **bottom folder** (or the one with the latest date/time) contains your most recent error information.

#### Log Levels
The tool uses different log levels:

- DEBUG: Detailed technical information (only in log files)
- INFO: General operation information (console + log files)
- WARNING: Important notices (console + log files)
- ERROR: Error conditions (console + log files)

#### Log File Management
- Log files are created automatically for each command execution
- Old log files are not automatically deleted
- You can safely delete old log directories to free up space
- Each command execution creates a new timestamped directory

#### Tips for Using Logs
- After an error occurs, check the latest log file for detailed error information
- When reporting issues, include relevant log file excerpts
- For serial communication debugging, look for SR (Serial Read) and SW (Serial Write) entries

## Error Codes

The UART Loader Host uses a structured error code system to help diagnose issues during operation.

### Error Code Format

Error codes follow the format **VMMIII**:
- **V**: Version (1 digit) - Error code schema version (currently 1)
- **MM**: Major (2 digits) - Major error category (01-99)
- **III**: Minor (3 digits) - Specific error within category (001-999)

**Examples:**
- `101001`: Version=1, Major=01, Minor=001
- `102003`: Version=1, Major=02, Minor=003
- `107004`: Version=1, Major=07, Minor=004

## Error Codes

The UART Loader Host uses a structured error code system to help diagnose issues during operation.

For complete error code reference, see **[ERROR_CODE.md](ERROR_CODE.md)**.

### Quick Reference

**Error Code Format:** VMMIII
- **V**: Version (1 digit) - Currently 1
- **MM**: Major (2 digits) - Error category (01-11)  
- **III**: Minor (3 digits) - Specific error (001-999)

**Exit Codes:**
- **0**: Success
- **999999**: Maximum expected error code
- **1000000**: Unexpected/unknown error
- **1000001**: Keyboard interrupt (Ctrl+C)

**Common Error Categories:**
- **101xxx**: HCI Status Errors (device-reported errors)
- **102xxx**: Serial I/O Errors (communication problems)
- **107xxx**: Programming Agent Errors (programming failures)
- **111xxx**: Xmodem Operation Errors (upload problems)

**For detailed troubleshooting and complete error code list, see [ERROR_CODE.md](ERROR_CODE.md).**


### Getting Detailed Error Information
When an error occurs, the UART Loader Host provides multiple sources of information to help diagnose the issue:

#### 1. Console Error Messages
The tool displays immediate error information in the console:
```
[Error 107001] Boot event timeout: Device did not respond within 30 seconds
```

#### 2. Check the Detail Log Files (Recommended)
The most comprehensive error information is stored in the detail log files.
**Log file location:**
```
logs/tool/YYYYMMDD_HHMMSS_<command>/tool_detail.log
```
**How to find your log file:**
1. Open Windows File Explorer
2. Navigate to the `uart_loader_host` folder
3. Open the `logs` folder, then the `tool` folder
4. Find the folder with the **most recent date and time** (folders are named like `20241209_143022_prog_bin`)
5. Double-click to open that folder
6. Double-click `tool_detail.log` to open it in Notepad

**Visual guide:**
uart_loader_host/
└── logs/
    └── tool/
        ├── 20241208_091234_prog_bin/ ← Older
        ├── 20241208_142156_prog_atm/ ← Older
        └── 20241209_143022_prog_bin/ ← Most recent (your error log)
            └── tool_detail.log ← Open this file

**Tip:** The folder names show the date and time when you ran the command, so the **bottom folder** (or the one with the latest date/time) contains your most recent error information.

## Troubleshooting

### Getting Help

```cmd
# Show basic help
UartLoaderHost.exe --help

# Get help for specific command
UartLoaderHost.exe prog_bin --help
UartLoaderHost.exe prog_atm --help
```

### Getting Support
If you encounter issues not covered here, please provide:
- The exact command you ran
- The complete error message
- Your device model and COM port information

## File Structure

The release package contains:
```
UartLoaderHost_YYYYMMDD_HHMMSS_VX.XX.XX.X/
├── UartLoaderHost.exe          # Main executable
├── binfile/                    # Binary files directory
│   └── uart_loader.bin          # Default RAM image for xmodem
├── python312.dll              # Python runtime
├── *.pyd                       # Python extension modules
├── *.dll                       # System libraries
└── [other supporting files]
```

## Version Information

This tool is built with Nuitka and includes version information embedded in the executable.
Use `UartLoaderHost.exe --version` to see the current version and build information.

The version format includes:
- Version number (e.g., 25.09.01.0)
- Git commit SHA (first 8 characters)
- Build timestamp
