# Sound Level Meters Dashboard

## Overview

The Sound Level Meters dashboard is a new feature in SFM (soon to be rebranded as Terra-view) that provides real-time monitoring and control of Rion NL-43/NL-53 sound level meters through the SLMM backend integration.

## Features

### 1. Dashboard Summary Statistics
- **Total Units**: Count of all SLM devices in the system
- **Deployed Units**: Active devices currently in the field
- **Active Now**: Units that have checked in within the last hour
- **Benched Units**: Devices not currently deployed

### 2. Unit List (Sidebar)
- Searchable list of all deployed SLM units
- Real-time status indicators:
  - 🟢 Green: Active (recently checked in)
  - ⚪ Gray: No check-in data
- Quick unit information:
  - Device model (NL-43, NL-53, etc.)
  - Location/address
  - Network address (IP:port)
- Click any unit to view its live data

### 3. Live View Panel

When a unit is selected, the live view panel displays:

#### Control Buttons
- **Start**: Begin measurement
- **Pause**: Pause current measurement
- **Stop**: Stop measurement
- **Reset**: Reset measurement data
- **Start Live Stream**: Open WebSocket connection for real-time DRD data

#### Real-time Metrics
- **Lp (Current)**: Instantaneous sound level in dB
- **Leq (Average)**: Equivalent continuous sound level
- **Lmax (Peak)**: Maximum sound level recorded
- **Lmin**: Minimum sound level recorded

#### Live Chart
- Real-time line chart showing Lp and Leq over time
- 60-second rolling window (adjustable)
- Chart.js-powered visualization with dark mode support
- No animation for smooth real-time updates

#### Device Information
- Battery level and power source
- Frequency weighting (A, C, Z)
- Time weighting (F, S, I)
- SD card remaining space

## Architecture

### Frontend Components

#### Main Template
**File**: `templates/sound_level_meters.html`

The main dashboard page that includes:
- Page header and navigation integration
- Stats summary section (auto-refreshes every 10s)
- Two-column layout: unit list (left) + live view (right)
- JavaScript functions for unit selection and WebSocket streaming

#### Partial Templates

1. **slm_stats.html** - Summary statistics cards
   - Auto-loads on page load
   - Refreshes every 10 seconds via HTMX

2. **slm_unit_list.html** - Searchable unit list
   - Auto-loads on page load
   - Refreshes every 10 seconds via HTMX
   - Supports search filtering

3. **slm_live_view.html** - Live data panel for selected unit
   - Loaded on-demand when unit is selected
   - Includes Chart.js for visualization
   - WebSocket connection for streaming data

4. **slm_live_view_error.html** - Error state display

### Backend Components

#### Router: `backend/routers/slm_dashboard.py`

**Endpoints:**

```python
GET /api/slm-dashboard/stats
```
Returns HTML partial with summary statistics.

```python
GET /api/slm-dashboard/units?search={term}
```
Returns HTML partial with filtered unit list.

```python
GET /api/slm-dashboard/live-view/{unit_id}
```
Returns HTML partial with live view panel for specific unit.
- Fetches unit details from database
- Queries SLMM API for current measurement state
- Queries SLMM API for live status (DOD data)

```python
POST /api/slm-dashboard/control/{unit_id}/{action}
```
Sends control commands to SLMM backend.
- Valid actions: start, stop, pause, resume, reset
- Proxies to `http://localhost:8100/api/nl43/{unit_id}/{action}`

### Integration with SLMM

The dashboard communicates with the SLMM backend service running on port 8100:

**REST API Calls:**
- `GET /api/nl43/{unit_id}/measurement-state` - Check if measuring
- `GET /api/nl43/{unit_id}/live` - Get current DOD data
- `POST /api/nl43/{unit_id}/start|stop|pause|resume|reset` - Control commands

**WebSocket Streaming:**
- `WS /api/nl43/{unit_id}/live` - Real-time DRD data stream
- Proxied through SFM at `/api/slmm/{unit_id}/live`
- Streams continuous measurement data for live charting

### Database Schema

**Table**: `roster`

SLM-specific fields in the RosterUnit model:

```python
device_type = "slm"  # Distinguishes SLMs from seismographs
slm_host = String                   # Device IP or hostname
slm_tcp_port = Integer               # TCP control port (default 2255)
slm_model = String                   # NL-43, NL-53, etc.
slm_serial_number = String           # Device serial number
slm_frequency_weighting = String     # A, C, or Z weighting
slm_time_weighting = String          # F (Fast), S (Slow), I (Impulse)
slm_measurement_range = String       # e.g., "30-130 dB"
slm_last_check = DateTime            # Last communication timestamp
```

## Navigation

The Sound Level Meters page is accessible from:
- **URL**: `/sound-level-meters`
- **Sidebar**: "Sound Level Meters" menu item (between Fleet Roster and Projects)
- **Icon**: Speaker/sound wave SVG icon

## Real-time Updates

The dashboard uses three mechanisms for real-time updates:

1. **HTMX Polling** (10-second intervals)
   - Summary statistics
   - Unit list
   - Ensures data freshness even without user interaction

2. **On-Demand Loading** (HTMX)
   - Live view panel loads when unit is selected
   - Control button responses

3. **WebSocket Streaming** (continuous)
   - Real-time DRD data for live charting
   - User-initiated via "Start Live Stream" button
   - Automatically closed on page unload or unit change

## Measurement Duration Tracking

**Important**: The NL-43/NL-53 devices do not expose measurement duration via their API. Elapsed time and interval counts are only visible on the device's on-screen display (OSD).

**Solution**: Track measurement start time in your application when calling the `/start` endpoint:

```javascript
// When starting measurement
const startTime = new Date();
localStorage.setItem(`slm_${unitId}_start`, startTime.toISOString());

// Calculate elapsed time
const startTime = new Date(localStorage.getItem(`slm_${unitId}_start`));
const elapsed = (new Date() - startTime) / 1000; // seconds
```

**Future Enhancement**: SLMM backend could store measurement start times in a database table to track duration across sessions.

## Testing

### Add Test Data

Use the included script to add test SLM units:

```bash
python3 add_test_slms.py
```

This creates:
- 3 deployed test units (nl43-001, nl43-002, nl53-001)
- 1 benched unit (nl43-003)

### Running the Dashboard

1. Start SLMM backend (port 8100):
   ```bash
   cd /home/serversdown/slmm
   uvicorn main:app --host 0.0.0.0 --port 8100
   ```

2. Start SFM (port 8000):
   ```bash
   cd /home/serversdown/sfm/seismo-fleet-manager
   uvicorn backend.main:app --host 0.0.0.0 --port 8000 --reload
   ```

3. Access dashboard:
   ```
   http://localhost:8000/sound-level-meters
   ```

### Testing Without Physical Devices

The dashboard will work without physical NL-43 devices connected:
- Unit list will display based on database records
- Live view will show connection errors (gracefully handled)
- Mock data can be added to SLMM for testing

## Future Enhancements

### Near-term
1. **Measurement Duration Tracking**
   - Add database table to track measurement sessions
   - Display elapsed time in live view
   - Store start/stop timestamps

2. **Historical Data View**
   - Chart historical Leq intervals
   - Export measurement data
   - Comparison between units

3. **Alerts & Thresholds**
   - Configurable sound level alerts
   - Email/SMS notifications when thresholds exceeded
   - Visual indicators on dashboard

### Long-term
1. **Map View**
   - Display all SLMs on a map (like seismographs)
   - Click map markers to view live data
   - Color-coded by current sound level

2. **Batch Operations**
   - Start/stop multiple units simultaneously
   - Synchronized measurements
   - Group configurations

3. **Advanced Analytics**
   - Noise compliance reports
   - Statistical summaries
   - Trend analysis

## Integration with Terra-view

When SFM is rebranded to Terra-view:

1. **Multi-Module Dashboard**
   - Sound Level Meters module (this dashboard)
   - Seismograph Fleet Manager module (existing)
   - Future monitoring modules

2. **Project Management**
   - Link SLMs to projects
   - Combined project view with seismographs + SLMs
   - Project-level reporting

3. **Unified Navigation**
   - Top-level module switcher
   - Consistent UI/UX across modules
   - Shared authentication and settings

## Technical Notes

### HTMX Integration
The dashboard extensively uses HTMX for dynamic updates without full page reloads:
- `hx-get`: Fetch and swap content
- `hx-trigger`: Auto-refresh intervals
- `hx-swap`: Content replacement strategy
- `hx-target`: Specify update target

### Dark Mode Support
All components support dark mode:
- Chart.js colors adapt to theme
- Tailwind dark: classes throughout
- Automatic theme detection

### Performance Considerations
- WebSocket connections are per-unit (only one active at a time)
- Chart data limited to 60 points (1 minute) to prevent memory bloat
- Polling intervals balanced for responsiveness vs server load
- Lazy loading of live view panel (only when unit selected)

## Files Modified/Created

### New Files
- `templates/sound_level_meters.html`
- `templates/partials/slm_stats.html`
- `templates/partials/slm_unit_list.html`
- `templates/partials/slm_live_view.html`
- `templates/partials/slm_live_view_error.html`
- `backend/routers/slm_dashboard.py`
- `add_test_slms.py`
- `docs/SOUND_LEVEL_METERS_DASHBOARD.md`

### Modified Files
- `backend/main.py` - Added route and router import
- `templates/base.html` - Added navigation menu item

## Support

For issues or questions:
- Check SLMM API documentation: `/home/serversdown/slmm/docs/API.md`
- Review SFM changelog: `CHANGELOG.md`
- Submit issues to project repository

---

**Version**: 1.0.0
**Created**: January 2026
**Last Updated**: January 5, 2026
