# GUI Real-time Temperature Logger

A professional graphical interface for the real-time temperature data logger with embedded matplotlib plots and comprehensive logging features.

## Features

- **Professional Dark-Themed UI**
  - Dark background with white text display
  - Easy-to-read Courier monospace font
  - Optimized for extended viewing

- **Easy Configuration**
  - Auto-detect serial port with USB port filtering (excludes Bluetooth)
  - Manual port selection available
  - Choose output CSV file location
  - Configurable max data points (11-5001)
  - Configurable AVG level (1, 8, 32, 64) for sensor sampling synchronization
  - Adjustable graph text scaling (0.8-2.0x)

- **Real-Time Visualization**
  - Dual embedded matplotlib subplots
  - Top plot: Both temperatures (T1 blue, T2 red)
  - Bottom plot: Temperature difference (ΔT) in green
  - Dynamic y-axis scaling based on data range
  - Elapsed time x-axis display (m:ss format)

- **Control Interface**
  - Start/Stop buttons for logging control
  - Real-time status display in status bar
  - Data point counter and sensor mode indicator
  - Pre-flight sensor detection and verification
  - Graceful error handling with user feedback

- **Information Panel**
  - Read-only logging output display
  - White text on dark background for clarity
  - Auto-scroll to latest messages
  - Copy to clipboard button (📋)
  - Clear with confirmation button (🗑)
  - Comprehensive logging of all operations

- **Threading Architecture**
  - Data collection runs in background thread
  - GUI remains responsive during logging
  - Independent matplotlib rendering
  - No blocking operations on UI thread

## Usage

## Installation (recommended)

### Create and use the repo `.venv`

Using a virtual environment avoids dependency conflicts and prevents macOS
architecture mismatches (for example installing an `x86_64` wheel on an Apple
Silicon `arm64` Python).

```bash
cd temp-logger
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -U pip
python -m pip install -e .
```

### Basic Launch

```bash
temp-logger-gui
```

### GUI Workflow

1. **Configure Settings**
   - Serial Port: Auto-detect or select manually
   - Output File: Choose where to save CSV data
   - Max Points: Maximum data points to retain in buffer
   - AVG Level: Sensor sampling averaging level
   - Graph Scale: Adjust text size in plots

2. **Start Logging** (▶ START button)
   - Pre-flight checks run automatically
   - Port accessibility verified
   - Sensor type detected (single/dual)
   - Connection established
   - Data collection begins

3. **Monitor Data**
   - Watch live dual plots update in real-time
   - Check information panel for status messages
   - Status bar shows current data point count
   - Sensor mode displayed (Single/Dual Sync)

4. **Stop Logging** (⏹ STOP button)
   - Data collection gracefully stops
   - Final point count logged
   - CSV file automatically saved
   - All widgets re-enabled for next session

## Configuration Options

### Serial Port

- **Auto-detect**: Automatically finds connected CircuitPython/USB device
  - Filters for: `/dev/cu.usbmodem*`, `/dev/cu.usbserial*`, `/dev/ttyUSB*`, `/dev/ttyACM*`, `COM*`
  - Excludes Bluetooth and other non-USB devices
- **Manual**: Select specific port from dropdown

### Output File

- Default: `tmp117_log.csv` in current directory
- Click "..." to browse and choose different location
- File created with CSV headers (Elapsed_Time_s, Timestamp, T1_C, T2_C, Skew_ms, Delta_T_C)

### Max Data Points

- Range: 11 to 5001 points
- Default: 1501
- Determines size of circular buffer
- Older data discarded when buffer fills

### AVG Level (Sensor Synchronization)

- **1 (Fast)**: ~120ms per point, less averaging
- **8 (Default)**: ~200ms per point, balanced
- **32 (Precise)**: ~575ms per point, more averaging
- **64 (Very Precise)**: ~1.065s per point, maximum averaging

### Graph Scale Factor

- Range: 0.8 to 2.0
- Default: 1.4
- Scales all text in plots (labels, tick marks, legend)
- Updates immediately without restart

## Information Panel Features

- **Read-Only Display**: Prevent accidental edits
- **Auto-Scroll**: Always shows latest messages
- **Message Types**:
  - ✓ Success messages (connection, detection)
  - ❌ Error messages (failed checks, connection issues)
  - ⏹ Status updates (stopping, completion)
  - ==== Separator lines (visual organization)

- **Copy Button**: Export all logged messages to clipboard
- **Clear Button**: Clear display with confirmation dialog

## Performance Characteristics

- **Data Collection**: Runs independently in background thread
- **Plot Update**: 200ms interval (configurable)
- **Memory**: Circular buffer holds last 1501 points (configurable)
- **Response Time**: <100ms UI responsiveness
- **Threading**: No UI blocking during data collection

## Data Validation

- **Range Checking**: Temperature values validated to -50 to +150°C
- **Corrupted Data Handling**: Malformed readings detected and skipped
- **Auto-Recovery**: 5-count consecutive error threshold triggers buffer reset
- **Whitespace Handling**: Robust parsing with whitespace stripping

## Known Limitations & Future Refinements

- **Info Panel Display**: Currently displays all text in monochrome white
  - Colored text support explored with tkinterweb/HtmlFrame
  - Rendering issues encountered with HTML widget
  - Future: Re-implement color coding (green success, red errors, orange warnings)

- **Sensor Re-detection**: Removed from monitoring loop
  - Was causing periodic parsing interference
  - Sensor configuration now detected once at startup
  - Configuration assumed stable during logging session

## Window Layout

```txt
┌──────────────────────── Real-time Temperature Logger ───────────────────────────┐
│                                                                                 │
│ Configuration           │                                                       │
│ ─────────────────────   │  ┌──── PLOTS ──────────────────────────────┐          │
│ Serial Port:            │  │  Temperature (°C)                       │          │
│ [Auto-detect ▼] [↻]     │  │   Blue:   T1 (Sensor 1)                 │          │
│                         │  │   Red:    T2 (Sensor 2)                 │          │
│ Output File:            │  │                                         │          │
│ [tmp117_log.csv  ][...] │  │  ┌─────────────────────────────────┐    │          │
│                         │  │  │                                 │    │          │
│ Max Points: [1501]      │  │  │   Plot 1: Both Temperatures     │    │          │
│                         │  │  │                                 │    │          │
│ AVG Level:              │  │  │                                 │    │          │
│ [8 (Default...)]        │  │  └─────────────────────────────────┘    │          │
│                         │  │                                         │          │
│ Graph Scale: [1.4]      │  │  ┌─────────────────────────────────┐    │          │
│                         │  │  │                                 │    │          │
│ Control                 │  │  │   Plot 2: Temperature Diff (ΔT) │    │          │
│ ─────────────────────   │  │  │   (Green line, m:ss on x-axis)  │    │          │
│ ▶ START                 │  │  │                                 │    │          │
│ ⏹ STOP                  │  │  │                                 │    │          │
│                         │  │  └─────────────────────────────────┘    │          │
│ Information             │  │                                         │          │
│ ─────────────────────   │  └─────────────────────────────────────────┘          │
│ ┌─────────────────────┐ │                                                       │
│ │ Temperature Logger  │ │                                                       │
│ │ Ready               │ │                                                       │
│ │ Click START to      │ │                                                       │
│ │ begin...            │ │                                                       │
│ │ ════════════════════│ │                                                       │
│ │                     │ │                                                       │
│ │                     │ │                                                       │
│ │ [📋 Copy][🗑 Clear]  │ │                                                       │
│ └─────────────────────┘ │                                                       │
│                                                                                 │
├─ Status: Ready     | Points: 0 | Sensors: - | Mode: - ──────────────────────────|
└─────────────────────────────────────────────────────────────────────────────────┘
```

## CSV Output Format

The saved CSV file contains detailed logging data in the following format:

```txt
Elapsed_Time_s,Timestamp,T1_C,T2_C,Skew_ms,Delta_T_C
0.15,2026-01-03T12:34:56.789,22.1234,22.1256,0.845,0.0022
0.21,2026-01-03T12:34:56.849,22.1235,22.1257,0.821,0.0022
0.27,2026-01-03T12:34:56.909,22.1236,22.1258,0.832,0.0022
```

Columns:

- `Elapsed_Time_s`: Seconds since logging started
- `Timestamp`: ISO format datetime with microseconds
- `T1_C`: Temperature from sensor 1 (°C)
- `T2_C`: Temperature from sensor 2 (°C) - single sensor mode shows same as T1
- `Skew_ms`: Timing skew between readings (milliseconds)
- `Delta_T_C`: Temperature difference (T1 - T2)

## Color Coding

- **Green**: Ready / Active
- **Blue**: Processing / Connecting
- **Red**: Error / Failed

## Keyboard Shortcuts

- `Ctrl+C` in terminal: Stop application
- `Alt+F4` / `Cmd+Q`: Close application (saves data if logging)

## Troubleshooting

### Port Not Detected

- Verify device is properly connected via USB
- Check device manager for serial port
- Try refreshing port list with ↻ button
- Manual port selection available if auto-detect fails
- Verify device drivers installed

### Sensor Detection Failed

- Check sensor is powered and responding
- Verify correct port selected
- Try different AVG level setting
- Check data cables and connections
- Check USB connection quality

### No Data Displayed

- Ensure logging has started (▶ START button clicked)
- Check status bar for "Logging active"
- Monitor information panel for error messages
- Verify CSV file location has write permissions
- Check disk space available

### Plot Not Showing

- Ensure matplotlib properly installed
- Try restarting the application
- Check system display settings
- Monitor information panel for rendering errors

### Data Not Saving

- Verify write permissions to output directory
- Check disk space available
- Ensure file path is valid
- Check CSV file isn't open in another application

## Advanced Usage

### CSV Output Format (Dual Sensor)

```csv
Elapsed_Time,Timestamp,T1_C,T2_C,Skew_ms,Delta_T_C
0.001,2026-01-02T12:34:56.789,22.3410,22.3521,0.850,0.0111
0.101,2026-01-02T12:34:56.890,22.3412,22.3523,0.900,0.0111
```

### CSV Output Format (Single Sensor)

```csv
Elapsed_Time,Timestamp,T1_C
0.001,2026-01-02T12:34:56.789,22.3410
0.101,2026-01-02T12:34:56.890,22.3412
```

## System Requirements

- Python 3.9+
- tkinter (usually included with Python)
- matplotlib
- pyserial
- numpy

## Error Handling

The GUI gracefully handles:

- Device disconnection
- Invalid configuration
- File I/O errors
- Serial communication failures
- Thread synchronization issues

All errors are displayed in:

1. Status bar (brief message)
2. Data preview window (detailed info)
3. Message boxes (critical errors)

## Tips for Best Performance

1. **Reduce Plot Update Interval** for smoother visualization
2. **Disable Plot** if you only care about data logging
3. **Use Timestamp Naming** to avoid file conflicts
4. **Monitor Point Count** to verify data collection
5. **Check CSV Periodically** to ensure data quality

(c) 2024-26 Prof. Flavio ABREU ARAUJO. All rights reserved.
