chore: docs and scripts organized. clutter cleared.

This commit is contained in:
serversdwn
2026-01-16 19:06:38 +00:00
parent 2a3589ca5c
commit 182920809d
14 changed files with 102 additions and 0 deletions

View File

@@ -0,0 +1,195 @@
# Feature Summary: Device Settings Verification
## What Was Added
A new API endpoint that retrieves all current device settings in a single request, allowing users to quickly verify the NL43/NL53 configuration before starting measurements.
## New Endpoint
**`GET /api/nl43/{unit_id}/settings`**
Returns comprehensive device configuration including:
- Measurement state and weighting settings
- Timing and interval configuration
- Battery level and device clock
- Sleep mode and FTP status
## Files Modified
### 1. [app/routers.py](app/routers.py)
**Lines:** 728-761
Added new route handler `get_all_settings()` that:
- Validates device configuration exists
- Checks TCP communication is enabled
- Calls `NL43Client.get_all_settings()`
- Returns formatted JSON response with all settings
- Handles connection errors, timeouts, and exceptions
### 2. [README.md](README.md)
**Updated sections:**
- Line 134: Added new endpoint to Measurement Settings table
- Lines 259-283: Added usage example showing how to verify device settings
## Files Created
### 1. [test_settings_endpoint.py](test_settings_endpoint.py)
Test/demonstration script showing:
- How to use the `get_all_settings()` method
- Example API endpoint usage with curl
- Expected response format
### 2. [SETTINGS_ENDPOINT.md](SETTINGS_ENDPOINT.md)
Comprehensive documentation including:
- Detailed endpoint description
- Complete list of settings retrieved
- Usage examples in bash, Python, and JavaScript
- Performance considerations
- Best practices and troubleshooting
### 3. [FEATURE_SUMMARY.md](FEATURE_SUMMARY.md)
This file - summary of changes for reference
## Existing Functionality Used
The implementation leverages the existing `get_all_settings()` method in [app/services.py](app/services.py#L538) which was already implemented but not exposed via the API. This method queries multiple device settings and handles errors gracefully.
## How It Works
1. **User makes GET request** to `/api/nl43/{unit_id}/settings`
2. **Router validates** device configuration exists and TCP is enabled
3. **NL43Client queries device** for each setting sequentially (with 1-second delays)
4. **Individual errors** are caught and returned as error strings
5. **Response returned** with all settings in JSON format
## Usage Example
```bash
# Quick verification before measurement
curl http://localhost:8100/api/nl43/NL43-001/settings
# Response:
{
"status": "ok",
"unit_id": "NL43-001",
"settings": {
"measurement_state": "Stop",
"frequency_weighting": "A",
"time_weighting": "F",
"measurement_time": "00:01:00",
"leq_interval": "1s",
"lp_interval": "125ms",
"index_number": "0",
"battery_level": "100%",
"clock": "2025/12/24,20:45:30",
"sleep_mode": "Off",
"ftp_status": "On"
}
}
```
## Benefits
1. **Single request** - Get all settings at once instead of multiple API calls
2. **Pre-flight checks** - Verify configuration before starting measurements
3. **Documentation** - Easy to save configuration snapshots for audit trails
4. **Troubleshooting** - Quickly identify misconfigured settings
5. **Multi-device** - Compare settings across multiple devices
## Performance Notes
- **Query time:** ~10-15 seconds (due to required 1-second delays between commands)
- **Rate limiting:** Automatically enforced by NL43Client
- **Error handling:** Partial failures don't prevent other settings from being retrieved
- **Caching recommended:** Settings don't change frequently, cache for 5-10 minutes
## Testing
To test the new endpoint:
1. **Start the server:**
```bash
uvicorn app.main:app --reload --port 8100
```
2. **Configure a device** (if not already configured):
```bash
curl -X PUT http://localhost:8100/api/nl43/test-meter/config \
-H "Content-Type: application/json" \
-d '{"host": "192.168.1.100", "tcp_port": 80, "tcp_enabled": true}'
```
3. **Query settings:**
```bash
curl http://localhost:8100/api/nl43/test-meter/settings
```
4. **Check Swagger UI:**
- Navigate to http://localhost:8100/docs
- Find "GET /api/nl43/{unit_id}/settings" endpoint
- Click "Try it out" and test interactively
## Integration Tips
### Frontend Integration
```javascript
// React/Vue/Angular example
async function verifyDeviceBeforeMeasurement(unitId) {
const response = await fetch(`/api/nl43/${unitId}/settings`);
const { settings } = await response.json();
// Verify critical settings
if (settings.frequency_weighting !== 'A') {
alert('Warning: Frequency weighting not set to A');
}
// Check battery
const batteryPercent = parseInt(settings.battery_level);
if (batteryPercent < 20) {
alert('Low battery! Please charge device.');
}
return settings;
}
```
### Python Automation
```python
def ensure_correct_config(unit_id: str, required_config: dict):
"""Verify device matches required configuration."""
settings = get_device_settings(unit_id)
mismatches = []
for key, expected in required_config.items():
actual = settings.get(key)
if actual != expected:
mismatches.append(f"{key}: expected {expected}, got {actual}")
if mismatches:
raise ValueError(f"Configuration mismatch: {', '.join(mismatches)}")
return True
```
## Future Enhancements
Potential improvements for future versions:
1. **Filtered queries** - Query parameter to select specific settings
2. **Diff mode** - Compare current settings to expected values
3. **Batch queries** - Get settings from multiple devices in one request
4. **Settings profiles** - Save/load common configuration profiles
5. **Change detection** - Track when settings were last modified
## Support
For questions or issues with this feature:
- See [SETTINGS_ENDPOINT.md](SETTINGS_ENDPOINT.md) for detailed documentation
- Check [README.md](README.md) for general API usage
- Review [COMMUNICATION_GUIDE.md](COMMUNICATION_GUIDE.md) for protocol details
## Version Info
- **Added:** December 24, 2025
- **API Version:** Compatible with existing v1 API
- **Breaking Changes:** None - purely additive feature

26
docs/features/README.md Normal file
View File

@@ -0,0 +1,26 @@
# SLMM Feature Documentation
This directory contains detailed documentation for specific SLMM features and enhancements.
## Feature Documents
### FEATURE_SUMMARY.md
Overview of all major features in SLMM.
### SETTINGS_ENDPOINT.md
Documentation of the device settings endpoint and verification system.
### TIMEZONE_CONFIGURATION.md
Timezone handling and configuration for SLMM timestamps.
### SLEEP_MODE_AUTO_DISABLE.md
Automatic sleep mode wake-up system for background polling.
### UI_UPDATE.md
UI/UX improvements and interface updates.
## Related Documentation
- [../README.md](../../README.md) - Main SLMM documentation
- [../CHANGELOG.md](../../CHANGELOG.md) - Version history
- [../API.md](../../API.md) - Complete API reference

View File

@@ -0,0 +1,258 @@
# Device Settings Verification Endpoint
## Overview
The new `GET /api/nl43/{unit_id}/settings` endpoint provides a comprehensive view of all current device settings. This allows you to quickly verify the configuration of your NL43/NL53 sound level meter before starting measurements, ensuring the device is configured correctly for your testing requirements.
## Endpoint Details
**URL:** `GET /api/nl43/{unit_id}/settings`
**Description:** Retrieves all queryable settings from the device in a single request.
**Response Time:** Approximately 10-15 seconds (due to required 1-second delay between device commands)
## Settings Retrieved
The endpoint queries the following categories of settings:
### Measurement Configuration
- **measurement_state**: Current state (Measure, Stop, Pause)
- **frequency_weighting**: Frequency weighting (A, C, or Z)
- **time_weighting**: Time weighting (F=Fast, S=Slow, I=Impulse)
### Timing and Intervals
- **measurement_time**: Total measurement duration setting
- **leq_interval**: Leq calculation interval
- **lp_interval**: Lp sampling interval
- **index_number**: Current index/file number for storage
### Device Information
- **battery_level**: Current battery percentage
- **clock**: Device clock time (format: YYYY/MM/DD,HH:MM:SS)
### Operational Status
- **sleep_mode**: Sleep mode status (On/Off)
- **ftp_status**: FTP server status (On/Off)
## Usage Examples
### Basic Request
```bash
curl http://localhost:8100/api/nl43/NL43-001/settings
```
### Response Format
```json
{
"status": "ok",
"unit_id": "NL43-001",
"settings": {
"measurement_state": "Stop",
"frequency_weighting": "A",
"time_weighting": "F",
"measurement_time": "00:01:00",
"leq_interval": "1s",
"lp_interval": "125ms",
"index_number": "0",
"battery_level": "100%",
"clock": "2025/12/24,20:45:30",
"sleep_mode": "Off",
"ftp_status": "On"
}
}
```
### Error Handling
Individual settings that fail to query will show an error message instead of a value:
```json
{
"status": "ok",
"unit_id": "NL43-001",
"settings": {
"measurement_state": "Stop",
"frequency_weighting": "A",
"time_weighting": "Error: Status error - device is in wrong state for this command",
...
}
}
```
This partial error handling ensures you get as much information as possible even if some settings fail to query.
## Common Use Cases
### Pre-Measurement Verification
Before starting a measurement session, verify all critical settings:
```bash
# Get all settings
SETTINGS=$(curl -s http://localhost:8100/api/nl43/meter-001/settings)
# Extract specific values (using jq)
FREQ_WEIGHT=$(echo $SETTINGS | jq -r '.settings.frequency_weighting')
TIME_WEIGHT=$(echo $SETTINGS | jq -r '.settings.time_weighting')
echo "Frequency: $FREQ_WEIGHT, Time: $TIME_WEIGHT"
```
### Configuration Audit
Document device configuration for quality assurance:
```bash
# Save settings snapshot
curl http://localhost:8100/api/nl43/meter-001/settings > config_snapshot_$(date +%Y%m%d_%H%M%S).json
```
### Multi-Device Comparison
Compare settings across multiple devices:
```bash
# Compare two devices
curl http://localhost:8100/api/nl43/meter-001/settings > device1.json
curl http://localhost:8100/api/nl43/meter-002/settings > device2.json
diff device1.json device2.json
```
## Integration Examples
### Python
```python
import requests
def verify_device_settings(unit_id: str) -> dict:
"""Retrieve and verify device settings."""
response = requests.get(f"http://localhost:8100/api/nl43/{unit_id}/settings")
response.raise_for_status()
data = response.json()
settings = data["settings"]
# Verify critical settings
assert settings["frequency_weighting"] == "A", "Wrong frequency weighting!"
assert settings["time_weighting"] == "F", "Wrong time weighting!"
return settings
# Usage
settings = verify_device_settings("NL43-001")
print(f"Battery: {settings['battery_level']}")
print(f"Clock: {settings['clock']}")
```
### JavaScript/TypeScript
```typescript
interface DeviceSettings {
measurement_state: string;
frequency_weighting: string;
time_weighting: string;
measurement_time: string;
leq_interval: string;
lp_interval: string;
index_number: string;
battery_level: string;
clock: string;
sleep_mode: string;
ftp_status: string;
}
async function getDeviceSettings(unitId: string): Promise<DeviceSettings> {
const response = await fetch(`http://localhost:8100/api/nl43/${unitId}/settings`);
const data = await response.json();
if (data.status !== "ok") {
throw new Error("Failed to retrieve settings");
}
return data.settings;
}
// Usage
const settings = await getDeviceSettings("NL43-001");
console.log(`Frequency weighting: ${settings.frequency_weighting}`);
console.log(`Battery level: ${settings.battery_level}`);
```
## Performance Considerations
### Query Duration
The endpoint queries multiple settings sequentially with required 1-second delays between commands. Total query time depends on:
- Number of settings queried (~10-12 settings)
- Network latency
- Device response time
**Expected duration:** 10-15 seconds
### Caching Strategy
For applications that need frequent access to settings:
1. **Cache results** - Settings don't change frequently unless you modify them
2. **Refresh periodically** - Query every 5-10 minutes or on-demand
3. **Track changes** - Re-query after sending configuration commands
### Rate Limiting
The endpoint respects device rate limiting (1-second delay between commands). Concurrent requests to the same device will be serialized automatically.
## Best Practices
1. **Pre-flight check**: Always verify settings before starting critical measurements
2. **Document configuration**: Save settings snapshots for audit trails
3. **Monitor battery**: Check battery level to avoid measurement interruption
4. **Sync clocks**: Verify device clock is accurate for timestamped data
5. **Error handling**: Check for "Error:" prefixes in individual setting values
## Related Endpoints
- `GET /api/nl43/{unit_id}/frequency-weighting` - Get single frequency weighting setting
- `PUT /api/nl43/{unit_id}/frequency-weighting` - Set frequency weighting
- `GET /api/nl43/{unit_id}/time-weighting` - Get single time weighting setting
- `PUT /api/nl43/{unit_id}/time-weighting` - Set time weighting
- `GET /api/nl43/{unit_id}/battery` - Get battery level only
- `GET /api/nl43/{unit_id}/clock` - Get device clock only
## Troubleshooting
### Slow Response
**Problem:** Endpoint takes longer than expected
**Solutions:**
- Normal behavior due to rate limiting (1 second between commands)
- Check network connectivity
- Verify device is not in sleep mode
### Partial Errors
**Problem:** Some settings show "Error:" messages
**Solutions:**
- Device may be in wrong state for certain queries
- Check if measurement is running (some settings require stopped state)
- Verify firmware version supports all queried commands
### Connection Timeout
**Problem:** 504 Gateway Timeout error
**Solutions:**
- Verify device IP address and port in configuration
- Check if device is powered on and connected
- Ensure TCP communication is enabled in device config
## See Also
- [README.md](README.md) - Main documentation
- [API.md](API.md) - Complete API reference
- [COMMUNICATION_GUIDE.md](COMMUNICATION_GUIDE.md) - NL43 protocol details

View File

@@ -0,0 +1,154 @@
# Sleep Mode Auto-Disable Feature
## Problem Statement
NL-43/NL-53 sound level meters have a sleep/eco mode feature that conserves battery power. However, when these devices enter sleep mode, **they turn off TCP communications**, which completely breaks remote monitoring and control capabilities. This makes it impossible to:
- Query device status remotely
- Start/stop measurements
- Stream real-time data
- Download files via FTP
- Perform any remote management tasks
This is particularly problematic in deployed scenarios where physical access to devices is limited or impossible.
## Solution
SLMM now automatically disables sleep mode in two key scenarios:
### 1. Device Configuration
When a device configuration is created or updated with TCP enabled, SLMM automatically:
- Checks the current sleep mode status on the device
- Disables sleep mode if it's enabled
- Logs the operation for visibility
**Endpoint:** `PUT /api/nl43/{unit_id}/config`
### 2. Measurement Start
Before starting any measurement, SLMM:
- Proactively disables sleep mode
- Ensures TCP remains active throughout the measurement session
- Allows remote monitoring to work reliably
**Endpoint:** `POST /api/nl43/{unit_id}/start`
## Implementation Details
### Helper Function
A new async helper function was added to [app/routers.py](app/routers.py:21-38):
```python
async def ensure_sleep_mode_disabled(client: NL43Client, unit_id: str):
"""
Helper function to ensure sleep mode is disabled on the device.
Sleep/eco mode turns off TCP communications, preventing remote monitoring.
This should be called when configuring a device or starting measurements.
"""
try:
current_status = await client.get_sleep_status()
logger.info(f"Current sleep mode status for {unit_id}: {current_status}")
# If sleep mode is on, disable it
if "On" in current_status or "on" in current_status:
logger.info(f"Sleep mode is enabled on {unit_id}, disabling it to maintain TCP connectivity")
await client.wake()
logger.info(f"Successfully disabled sleep mode on {unit_id}")
else:
logger.info(f"Sleep mode already disabled on {unit_id}")
except Exception as e:
logger.warning(f"Could not verify/disable sleep mode on {unit_id}: {e}")
# Don't raise - we want configuration to succeed even if sleep mode check fails
```
### Non-Blocking Design
The sleep mode check is **non-blocking**:
- If the device is unreachable, the operation logs a warning but continues
- Configuration updates succeed even if sleep mode can't be verified
- Measurement starts proceed even if sleep mode check fails
- This prevents device communication issues from blocking critical operations
### Logging
All sleep mode operations are logged with appropriate levels:
- **INFO**: Successful operations and status checks
- **WARNING**: Failed operations (device unreachable, timeout, etc.)
Example logs:
```
2026-01-14 18:37:12,889 - app.routers - INFO - TCP enabled for test-nl43-001, ensuring sleep mode is disabled
2026-01-14 18:37:12,889 - app.services - INFO - Sending command to 192.168.1.100:2255: Sleep Mode?
2026-01-14 18:37:17,890 - app.routers - WARNING - Could not verify/disable sleep mode on test-nl43-001: Failed to connect to device at 192.168.1.100:2255
```
## Testing
A comprehensive test script is available: [test_sleep_mode_auto_disable.py](test_sleep_mode_auto_disable.py)
Run it with:
```bash
python3 test_sleep_mode_auto_disable.py
```
The test verifies:
1. Config updates trigger sleep mode check
2. Config retrieval works correctly
3. Start measurement triggers sleep mode check
4. Operations succeed even without a physical device (non-blocking)
## API Documentation Updates
The following documentation files were updated to reflect this feature:
### [docs/API.md](docs/API.md)
- Updated config endpoint documentation with sleep mode auto-disable note
- Added warning to start measurement endpoint
- Enhanced power management section with detailed warnings about sleep mode behavior
Key additions:
- Configuration section now explains that sleep mode is automatically disabled when TCP is enabled
- Measurement control section notes that sleep mode is disabled before starting measurements
- Power management section includes comprehensive warnings about sleep mode affecting TCP connectivity
## Usage Notes
### For Operators
- You no longer need to manually disable sleep mode before starting remote monitoring
- Sleep mode will be automatically disabled when you configure a device or start measurements
- Check logs to verify sleep mode operations if experiencing connectivity issues
### For Developers
- The `ensure_sleep_mode_disabled()` helper can be called from any endpoint that requires reliable TCP connectivity
- Always use it before long-running operations that depend on continuous device communication
- The function is designed to fail gracefully - don't worry about exception handling
### Battery Conservation
If battery conservation is a concern:
- Consider using Timer Auto mode with scheduled measurements
- Sleep mode can be manually re-enabled between measurements using `POST /{unit_id}/sleep`
- Be aware that TCP connectivity will be lost until the device wakes or is physically accessed
## Deployment
The feature is automatically included when building the SLMM container:
```bash
cd /home/serversdown/tmi/terra-view
docker compose build slmm
docker compose up -d slmm
```
No configuration changes are required - the feature is active by default.
## Future Enhancements
Potential improvements for future versions:
- Add a user preference to optionally skip sleep mode disable
- Implement smart sleep mode scheduling (enable between measurements, disable during)
- Add sleep mode status to device health checks
- Create alerts when sleep mode is detected as enabled
## References
- NL-43 Command Reference: [docs/nl43_Command_ref.md](docs/nl43_Command_ref.md)
- Communication Guide: [docs/COMMUNICATION_GUIDE.md](docs/COMMUNICATION_GUIDE.md) (page 65, Sleep Mode)
- API Documentation: [docs/API.md](docs/API.md)
- SLMM Services: [app/services.py](app/services.py:395-417) (sleep mode commands)

View File

@@ -0,0 +1,164 @@
# Timezone Configuration for SLMM
## Overview
The SLMM system now supports configurable timezone settings. All timestamps are stored internally in UTC for consistency, but the system can interpret FTP timestamps and display times in your local timezone.
## Configuration
### Environment Variables
Set the following environment variables to configure your timezone:
#### `TIMEZONE_OFFSET` (required)
The number of hours offset from UTC. Use negative numbers for zones west of UTC, positive for east.
**Examples:**
- `-5` = EST (Eastern Standard Time, UTC-5)
- `-4` = EDT (Eastern Daylight Time, UTC-4)
- `0` = UTC (Coordinated Universal Time)
- `+1` = CET (Central European Time, UTC+1)
- `-8` = PST (Pacific Standard Time, UTC-8)
**Default:** `-5` (EST)
#### `TIMEZONE_NAME` (optional)
A friendly name for your timezone, used in log messages.
**Examples:**
- `EST`
- `EDT`
- `UTC`
- `PST`
**Default:** Auto-generated from offset (e.g., "UTC-5")
### Setup Instructions
#### Option 1: Using .env file (Recommended)
1. Copy the example file:
```bash
cd /home/serversdown/slmm
cp .env.example .env
```
2. Edit `.env` and set your timezone:
```bash
TIMEZONE_OFFSET=-5
TIMEZONE_NAME=EST
```
3. Make sure your application loads the .env file (you may need to install `python-dotenv`):
```bash
pip install python-dotenv
```
4. Update `app/main.py` to load the .env file (add at the top):
```python
from dotenv import load_dotenv
load_dotenv()
```
#### Option 2: System Environment Variables
Set the environment variables in your shell or service configuration:
```bash
export TIMEZONE_OFFSET=-5
export TIMEZONE_NAME=EST
```
Or add to your systemd service file if running as a service.
#### Option 3: Docker/Docker Compose
If using Docker, add to your `docker-compose.yml`:
```yaml
services:
slmm:
environment:
- TIMEZONE_OFFSET=-5
- TIMEZONE_NAME=EST
```
Or pass via command line:
```bash
docker run -e TIMEZONE_OFFSET=-5 -e TIMEZONE_NAME=EST ...
```
## How It Works
### Data Flow
1. **FTP Timestamps**: When the system reads file timestamps via FTP from the NL43 device, they are assumed to be in your configured timezone
2. **Conversion**: Timestamps are immediately converted to UTC for internal storage
3. **Database**: All timestamps in the database are stored in UTC
4. **API Responses**: Timestamps are sent to the frontend as UTC ISO strings
5. **Frontend Display**: The browser automatically converts UTC timestamps to the user's local timezone for display
### Example
If you're in EST (UTC-5) and the FTP shows a file timestamp of "Jan 11 21:57":
1. System interprets: `Jan 11 21:57 EST`
2. Converts to UTC: `Jan 12 02:57 UTC` (adds 5 hours)
3. Stores in database: `2026-01-12T02:57:00`
4. Sends to frontend: `2026-01-12T02:57:00` (with 'Z' added = UTC)
5. Browser displays: `Jan 11, 9:57 PM EST` (converts back to user's local time)
### Timer Calculation
The measurement timer calculates elapsed time correctly because:
- `measurement_start_time` is stored in UTC
- FTP folder timestamps are converted to UTC
- Frontend calculates `Date.now() - startTime` using UTC milliseconds
- All timezone offsets cancel out, giving accurate elapsed time
## Troubleshooting
### Timer shows wrong elapsed time
1. **Check your timezone setting**: Make sure `TIMEZONE_OFFSET` matches your actual timezone
```bash
# Check current setting in logs when SLMM starts:
grep "Using timezone" data/slmm.log
```
2. **Verify FTP timestamps**: FTP timestamps from the device should be in your local timezone
- If the device is configured for a different timezone, adjust `TIMEZONE_OFFSET` accordingly
3. **Restart the service**: Changes to environment variables require restarting the SLMM service
### Logs show unexpected timezone
Check the startup logs:
```bash
tail -f data/slmm.log | grep timezone
```
You should see:
```
Using timezone: EST (UTC-5)
```
If not, the environment variable may not be loaded correctly.
## Daylight Saving Time (DST)
**Important:** This configuration uses a fixed offset. If you need to account for Daylight Saving Time:
- **During DST (summer)**: Set `TIMEZONE_OFFSET=-4` (EDT)
- **During standard time (winter)**: Set `TIMEZONE_OFFSET=-5` (EST)
- You'll need to manually update the setting when DST changes (typically March and November)
**Future Enhancement:** Automatic DST handling could be implemented using Python's `zoneinfo` module with named timezones (e.g., "America/New_York").
## Default Behavior
If no environment variables are set:
- **TIMEZONE_OFFSET**: Defaults to `-5` (EST)
- **TIMEZONE_NAME**: Defaults to `UTC-5`
This means the system will work correctly for EST deployments out of the box.

171
docs/features/UI_UPDATE.md Normal file
View File

@@ -0,0 +1,171 @@
# Standalone UI Update: Get ALL Settings Button
## What Was Added
A new **"Get ALL Settings"** button has been added to the standalone web UI at [templates/index.html](templates/index.html).
## Location
The button is located in the **Measurement Settings** fieldset, at the top before the individual frequency and time weighting controls.
## Visual Layout
```
┌─────────────────────────────────────────────────────┐
│ Measurement Settings │
├─────────────────────────────────────────────────────┤
│ │
│ [Get ALL Settings] ← NEW BUTTON (bold styling) │
│ │
│ Frequency Weighting: │
│ [Get] [Set A] [Set C] [Set Z] │
│ │
│ Time Weighting: │
│ [Get] [Set Fast] [Set Slow] [Set Impulse] │
│ │
└─────────────────────────────────────────────────────┘
```
## Functionality
When clicked, the button:
1. **Shows loading message**: "Retrieving all device settings (this may take 10-15 seconds)..."
2. **Calls API**: `GET /api/nl43/{unit_id}/settings`
3. **Displays results in two places**:
- **Status area** (top): Shows formatted JSON with all settings
- **Log area** (bottom): Shows each setting on a separate line
## Example Output
### Status Area Display
```json
{
"measurement_state": "Stop",
"frequency_weighting": "A",
"time_weighting": "F",
"measurement_time": "00:01:00",
"leq_interval": "1s",
"lp_interval": "125ms",
"index_number": "0",
"battery_level": "100%",
"clock": "2025/12/24,20:45:30",
"sleep_mode": "Off",
"ftp_status": "On"
}
```
### Log Area Display
```
Retrieving all device settings (this may take 10-15 seconds)...
=== ALL DEVICE SETTINGS ===
measurement_state: Stop
frequency_weighting: A
time_weighting: F
measurement_time: 00:01:00
leq_interval: 1s
lp_interval: 125ms
index_number: 0
battery_level: 100%
clock: 2025/12/24,20:45:30
sleep_mode: Off
ftp_status: On
===========================
```
## Code Changes
### HTML Changes (Line 60)
```html
<button onclick="getAllSettings()" style="margin-bottom: 12px; font-weight: bold;">
Get ALL Settings
</button>
```
### JavaScript Changes (Lines 284-305)
```javascript
async function getAllSettings() {
const unitId = document.getElementById('unitId').value;
log('Retrieving all device settings (this may take 10-15 seconds)...');
const res = await fetch(`/api/nl43/${unitId}/settings`);
const data = await res.json();
if (!res.ok) {
log(`Get All Settings failed: ${res.status} - ${data.detail || JSON.stringify(data)}`);
return;
}
// Display in status area
statusEl.textContent = JSON.stringify(data.settings, null, 2);
// Log summary
log('=== ALL DEVICE SETTINGS ===');
Object.entries(data.settings).forEach(([key, value]) => {
log(`${key}: ${value}`);
});
log('===========================');
}
```
## Usage Flow
1. **Configure device** using the "Unit Config" section
2. **Click "Get ALL Settings"** to retrieve current configuration
3. **Review settings** in the Status and Log areas
4. **Verify** critical settings match requirements before starting measurements
## Benefits
**Quick verification** - One click to see all device settings
**Pre-measurement check** - Ensure device is configured correctly
**Debugging** - Identify misconfigured settings easily
**Documentation** - Copy settings from status area for records
**Comparison** - Compare settings across multiple devices
## Error Handling
If the request fails:
- Error message is displayed in the log
- Status code and details are shown
- Previous status display is preserved
Example error output:
```
Retrieving all device settings (this may take 10-15 seconds)...
Get All Settings failed: 502 - Failed to communicate with device
```
## Testing the Feature
1. **Start the SLMM server**:
```bash
cd /home/serversdown/slmm
uvicorn app.main:app --reload --port 8100
```
2. **Open the standalone UI**:
```
http://localhost:8100
```
3. **Configure a device**:
- Enter Unit ID (e.g., "nl43-1")
- Enter Host IP (e.g., "192.168.1.100")
- Enter Port (e.g., "80")
- Click "Save Config"
4. **Test the new button**:
- Click "Get ALL Settings"
- Wait 10-15 seconds for results
- Review settings in Status and Log areas
## Related Files
- [templates/index.html](templates/index.html) - Standalone UI (updated)
- [app/routers.py](app/routers.py#L728-L761) - Settings endpoint
- [app/services.py](app/services.py#L538-L606) - Client implementation
- [README.md](README.md) - Main documentation
- [SETTINGS_ENDPOINT.md](SETTINGS_ENDPOINT.md) - API documentation