# Device-Specific MQTT Command Implementation

## Overview
Implemented device-aware MQTT command generation system that automatically adapts based on the terminal device model (MF919, SR600, Kozen, etc.).

## Architecture Design

### 1. **MQTT Command Builder Module** (`mqtt_command_builder.ex`)
Centralized module handling all device-specific payload generation with the following functions:

#### Main Functions:
- **`build_command/2`** - Router function that dispatches to device-specific builders
- **`build_mf919_command/1`** - Generates TMS command payload for MF919 devices
- **`build_sr600_command/1`** - Generates file_download payload for SR600 devices
- **`build_kozen_command/1`** - Kozen-specific builder (extends SR600)

#### Helper Functions:
- **`generate_request_id/0`** - Creates unique request IDs (format: `req-{timestamp}-{random}`)
- **`get_file_categories/1`** - Returns device-specific file categories
- **`get_command_types/1`** - Returns available command types per device
- **`get_url_hint/2`** - Provides URL hints for each device/category combo
- **`validate_device_params/2`** - Validates parameters based on device model

### 2. **Command Payload Structures**

#### MF919 (TMS Command Format):
```json
{
  "type": "tms_command",
  "command": "UPDATE_PARAMS|UPDATE_L3_CONFIG|LOAD_KEYS",
  "requestId": "req-{timestamp}-{random}",
  "downloadUrl": "http://demo.ctrmv.com/ota/mf919/{params.zip|l3config.zip|keys.json}"
}
```

**Supported Commands:**
- `UPDATE_PARAMS` - Update terminal parameters from params.zip
- `UPDATE_L3_CONFIG` - Update L3 configuration from l3config.zip
- `LOAD_KEYS` - Load encryption keys from keys.json

#### SR600 (File Download Format):
```json
{
  "command": "file_download",
  "local_path_to_save": "exdata|config|firmware|apps",
  "url_path_from_download": "https://example.com/file.bin",
  "file_size": "optional",
  "file_category": "firmware|application|config|logo_image|keys|parameters|emv",
  "file_name": "firmware.bin",
  "merchant_config": "true|false",
  "retry_count": "3",
  "request_id": "req-{timestamp}-{random}"
}
```

### 3. **Event Handler Updates** (`index.ex`)

The `handle_event("send_file_download", ...)` handler now:

1. **Validates** parameters against device-specific requirements
2. **Generates** unique request ID
3. **Routes** through `MQTTCommandBuilder.build_command/2`
4. **Publishes** via MQTT with proper topic structure
5. **Returns** appropriate success/error messages

#### Handler Flow:
```
send_file_download event
    ↓
Get terminal & extract model
    ↓
Validate device-specific params
    ↓
Generate request ID
    ↓
Build command (router dispatches to builder)
    ↓
Publish via MQTT
    ↓
Return success/error
```

### 4. **UI Adaptations** (`index.html.heex`)

#### Dynamic Form Rendering:
- **Device Badge**: Shows current device model
- **Conditional Sections**: Different forms for MF919 vs SR600/others

#### MF919-Specific UI:
- Command Type selector (UPDATE_PARAMS, UPDATE_L3_CONFIG, LOAD_KEYS)
- Simplified URL input
- Helper text with available URLs

#### SR600+ UI:
- Traditional file download form
- **Enhanced File Categories** including:
  - 🖼️ Logo Image
  - 🔧 Firmware
  - 📱 Application
  - ⚙️ Configuration
  - **🔑 Keys** (NEW)
  - **📦 Parameters** (NEW)
  - **💳 EMV** (NEW)
- File path selection
- Merchant config checkbox

## Implementation Details

### Device Model Routing
```elixir
def build_command(device_model, download_params) when is_binary(device_model) do
  case String.downcase(device_model) do
    "mf919" -> build_mf919_command(download_params)
    "sr600" -> build_sr600_command(download_params)
    "kozen" -> build_kozen_command(download_params)
    _ -> build_sr600_command(download_params)  # Default fallback
  end
end
```

### Parameter Validation
Each device model has specific required parameters:

**MF919 Requirements:**
- `command_type` (UPDATE_PARAMS, UPDATE_L3_CONFIG, LOAD_KEYS)
- `url_path_from_download` (full file URL)

**SR600 Requirements:**
- `local_path_to_save` (exdata, config, firmware, apps)
- `url_path_from_download` (file URL)
- `file_name` (local filename)

## File Changes Summary

### Created Files:
1. **`lib/da_product_app/terminal_management/mqtt_command_builder.ex`** (178 lines)
   - New module with device-specific builders
   - Helper functions for categories, types, validation

### Modified Files:
1. **`lib/da_product_app_web/live/terminal_live/index.ex`**
   - Updated `handle_event("send_file_download", ...)`
   - Added `send_mqtt_command/4` helper
   - Added device model awareness and parameter validation

2. **`lib/da_product_app_web/live/terminal_live/index.html.heex`**
   - Converted file_download tab to conditional rendering
   - MF919-specific form with command type selector
   - SR600+ form with enhanced file categories
   - Device model badge display

## Benefits

1. **Scalability**: Easy to add new device models - just add a new builder function
2. **Maintainability**: Device-specific logic isolated in dedicated module
3. **Flexibility**: File categories and command types configurable per device
4. **User Experience**: Form adapts automatically to selected device
5. **Type Safety**: Validation ensures correct parameters for each device
6. **Logging**: Comprehensive logging for debugging device commands

## Testing Recommendations

### Test Cases:

1. **MF919 Commands**:
   - UPDATE_PARAMS with params.zip URL
   - UPDATE_L3_CONFIG with l3config.zip URL
   - LOAD_KEYS with keys.json URL

2. **SR600 Commands**:
   - File download to exdata path
   - File download to firmware path
   - All file category types

3. **Error Handling**:
   - Missing required parameters
   - Invalid device model (should default to SR600)
   - MQTT publish failures

4. **UI Validation**:
   - Form switches correctly when device changes
   - MF919 form shows correct command types
   - SR600 form shows enhanced categories
   - Device badge displays correctly

## Future Enhancements

1. Add Kozen-specific command builders
2. Support for device groups (command batching)
3. Command scheduling/retry logic
4. Response tracking via request_id
5. Device firmware version awareness
6. Progressive form validation
