# SLM Configuration Interface

This document describes the SLM configuration interface added to the Sound Level Meters dashboard.

## Overview

Sound Level Meters can now be configured directly from the dashboard without needing to navigate to the unit detail page. A configuration button appears on each SLM unit card on hover, opening a modal with all configurable parameters.

## Features

### 1. Quick Access Configuration Button

- **Location**: Appears on each SLM unit card in the unit list
- **Behavior**: Shows on hover (desktop) or always visible (mobile)
- **Icon**: Gear/settings icon in top-right corner of unit card

### 2. Configuration Modal

The configuration modal provides a comprehensive interface for all SLM parameters:

#### Device Information
- **Model**: Dropdown selection (NL-43, NL-53)
- **Serial Number**: Text input for device serial number

#### Measurement Parameters
- **Frequency Weighting**: A, C, or Z (Linear)
- **Time Weighting**: Fast (125ms), Slow (1s), or Impulse
- **Measurement Range**: 30-130 dB, 40-140 dB, or 50-140 dB

#### Network Configuration
- **Assigned Modem**: Dropdown list of available modems
  - Shows modem ID and IP address
  - Option for "No modem (direct connection)"
- **Direct IP Address**: Only shown when no modem assigned
- **TCP Port**: Only shown when no modem assigned (default: 502)

### 3. Actions

The modal provides three action buttons:

- **Test Connection**: Tests network connectivity to the SLM
  - Uses current form values (not saved values)
  - Shows toast notification with results
  - Green: Connection successful
  - Yellow: Connection failed or device offline
  - Red: Test error

- **Cancel**: Closes modal without saving changes

- **Save Configuration**: Saves all changes to database
  - Shows success/error toast
  - Refreshes unit list on success
  - Auto-closes modal after 2 seconds

## Implementation

### Frontend Components

#### Unit List Partial
**File**: [templates/partials/slm_unit_list.html](../templates/partials/slm_unit_list.html)

```html
<!-- Configure button (appears on hover) -->
<button onclick="event.stopPropagation(); openConfigModal('{{ unit.id }}');"
        class="absolute top-2 right-2 opacity-0 group-hover:opacity-100...">
    <svg>...</svg>
</button>
```

#### Configuration Modal
**File**: [templates/sound_level_meters.html](../templates/sound_level_meters.html#L73)

```html
<!-- Configuration Modal -->
<div id="config-modal" class="hidden fixed inset-0 bg-black bg-opacity-50...">
    <div id="config-modal-content">
        <!-- Content loaded via HTMX -->
    </div>
</div>
```

#### Configuration Form
**File**: [templates/partials/slm_config_form.html](../templates/partials/slm_config_form.html)

Form fields mapped to database columns:
- `slm_model` → `unit.slm_model`
- `slm_serial_number` → `unit.slm_serial_number`
- `slm_frequency_weighting` → `unit.slm_frequency_weighting`
- `slm_time_weighting` → `unit.slm_time_weighting`
- `slm_measurement_range` → `unit.slm_measurement_range`
- `deployed_with_modem_id` → `unit.deployed_with_modem_id`
- `slm_host` → `unit.slm_host` (legacy, only if no modem)
- `slm_tcp_port` → `unit.slm_tcp_port` (legacy, only if no modem)

### Backend Endpoints

#### GET /api/slm-dashboard/config/{unit_id}
**File**: [backend/routers/slm_dashboard.py:184](../backend/routers/slm_dashboard.py#L184)

Returns configuration form HTML partial with current unit values pre-populated.

**Response**: HTML partial (slm_config_form.html)

#### POST /api/slm-dashboard/config/{unit_id}
**File**: [backend/routers/slm_dashboard.py:203](../backend/routers/slm_dashboard.py#L203)

Saves configuration changes to database.

**Request**: Form data with configuration parameters

**Response**: JSON
```json
{
  "status": "success",
  "unit_id": "nl43-001"
}
```

**Behavior**:
- Updates all SLM-specific fields from form data
- If modem is assigned: clears legacy `slm_host` and `slm_tcp_port`
- If no modem: uses direct IP fields from form

### JavaScript Functions

#### openConfigModal(unitId)
**File**: [templates/sound_level_meters.html:127](../templates/sound_level_meters.html#L127)

Opens configuration modal and loads form via HTMX.

```javascript
function openConfigModal(unitId) {
    const modal = document.getElementById('config-modal');
    modal.classList.remove('hidden');

    htmx.ajax('GET', `/api/slm-dashboard/config/${unitId}`, {
        target: '#config-modal-content',
        swap: 'innerHTML'
    });
}
```

#### closeConfigModal()
**File**: [templates/sound_level_meters.html:136](../templates/sound_level_meters.html#L136)

Closes configuration modal.

#### handleConfigSave(event)
**File**: [templates/partials/slm_config_form.html:109](../templates/partials/slm_config_form.html#L109)

Handles HTMX response after form submission:
- Shows success/error toast
- Refreshes unit list
- Auto-closes modal after 2 seconds

#### testConnection(unitId)
**File**: [templates/partials/slm_config_form.html:129](../templates/partials/slm_config_form.html#L129)

Tests connection to SLM unit:
```javascript
async function testConnection(unitId) {
    const response = await fetch(`/api/slmm/${unitId}/status`);
    const data = await response.json();

    if (response.ok && data.status === 'online') {
        // Show success toast
    } else {
        // Show warning toast
    }
}
```

#### loadModemsForConfig()
**File**: [templates/partials/slm_config_form.html:87](../templates/partials/slm_config_form.html#L87)

Loads available modems from `/api/roster/modems` and populates dropdown.

## User Workflow

### Configuring an SLM

1. Navigate to Sound Level Meters dashboard ([/sound-level-meters](../sound-level-meters))
2. Hover over desired SLM unit card in the list
3. Click the gear icon that appears in top-right corner
4. Configuration modal opens with current values pre-filled
5. Modify desired parameters:
   - Update model/serial if needed
   - Set measurement parameters (frequency/time weighting, range)
   - Choose network configuration:
     - **Option A**: Select a modem from dropdown (recommended)
     - **Option B**: Enter direct IP address and port
6. (Optional) Click "Test Connection" to verify network settings
7. Click "Save Configuration"
8. Modal shows success message and auto-closes
9. Unit list refreshes to show updated information

### Network Configuration Options

**Modem Assignment (Recommended)**:
- Select modem from dropdown
- IP address automatically resolved from modem's `ip_address` field
- Direct IP/port fields hidden
- Enables modem tracking and management

**Direct Connection (Legacy)**:
- Select "No modem (direct connection)"
- Enter IP address and TCP port manually
- Direct IP/port fields become visible
- Useful for temporary setups or non-modem connections

## Database Schema

The configuration interface updates these `roster` table columns:

```sql
-- SLM-specific fields
slm_model VARCHAR               -- Device model (NL-43, NL-53)
slm_serial_number VARCHAR       -- Serial number
slm_frequency_weighting VARCHAR -- A, C, or Z weighting
slm_time_weighting VARCHAR      -- Fast, Slow, or Impulse
slm_measurement_range VARCHAR   -- Measurement range (30-130, 40-140, 50-140)

-- Network configuration
deployed_with_modem_id VARCHAR  -- FK to modem unit (preferred method)
slm_host VARCHAR                -- Legacy direct IP (only if no modem)
slm_tcp_port INTEGER            -- Legacy TCP port (only if no modem)
```

## UI/UX Design

### Modal Behavior
- **Opens**: Via configure button on unit card
- **Closes**:
  - Cancel button
  - X button in header
  - Escape key
  - Clicking outside modal (on backdrop)
- **Auto-close**: After successful save (2 second delay)

### Responsive Design
- **Desktop**: Configuration button appears on hover
- **Mobile**: Configuration button always visible
- **Modal**: Responsive width, scrollable on small screens
- **Form**: Two-column layout on desktop, single column on mobile

### Visual Feedback
- **Loading**: Skeleton loader while form loads
- **Saving**: HTMX handles form submission
- **Success**: Green toast notification
- **Error**: Red toast notification
- **Testing**: Blue toast while testing, then green/yellow/red based on result

### Accessibility
- **Keyboard**: Modal can be closed with Escape key
- **Focus**: Modal traps focus when open
- **Labels**: All form fields have proper labels
- **Colors**: Sufficient contrast in dark/light modes

## Future Enhancements

Potential improvements for future versions:

1. **Bulk Configuration**: Configure multiple SLMs at once
2. **Configuration Templates**: Save and apply configuration presets
3. **Configuration History**: Track configuration changes over time
4. **Remote Configuration**: Push configuration directly to device via SLMM
5. **Validation**: Real-time validation of IP addresses and ports
6. **Advanced Settings**: Additional NL-43/NL-53 specific parameters
7. **Configuration Import/Export**: JSON/CSV configuration files

## Related Documentation

- [SOUND_LEVEL_METERS_DASHBOARD.md](SOUND_LEVEL_METERS_DASHBOARD.md) - Main SLM dashboard
- [MODEM_INTEGRATION.md](MODEM_INTEGRATION.md) - Modem assignment architecture
- [DEVICE_TYPE_SLM_SUPPORT.md](DEVICE_TYPE_SLM_SUPPORT.md) - SLM device type implementation
