# Real-Time Temperature Logger with Matplotlib

A comprehensive Python script for logging TMP117 temperature data in real-time with live matplotlib visualizations.

> **New!** There's also a professional GUI wrapper: `temp-logger-gui`
>
> For an easier, user-friendly experience with point-and-click interface, embedded plots, and comprehensive logging features, see [GUI_README.md](GUI_README.md)

## Features

- **Live Graphical Display**: Real-time matplotlib plots updated as data arrives
- **Dual Sensor Support**: Displays temperature and temperature difference for synchronized pair measurements (2 optimized plots)
- **Single Sensor Mode**: Simple temperature tracking for single sensor configurations
- **CSV Logging**: Automatic logging to timestamped CSV files (includes all data including timing skew and correlation metrics)
- **Flexible Configuration**: Adjustable update intervals and output filenames
- **Text Scaling**: Global 1.4x text scaling by default for improved readability
- **Color-Coded Terminal Output**: Pretty-printed console status with ANSI colors
- **Adaptive Layout**: Different plot layouts for single vs. dual sensor modes
- **Window Title**: Clean window title display
- **Robust Data Validation**: Range checking, corruption detection, and auto-recovery

## Usage

### Basic Usage (Dual Sensor with Live Plot)

```bash
temp-logger
```

Auto-detects the serial port and displays live graphs.

### Single Sensor Mode

If you have one TMP117 sensor connected:

```bash
temp-logger
```

The script auto-detects the sensor count and adjusts accordingly.

### Specify Serial Port

```bash
temp-logger --port /dev/cu.usbmodem2101
```

Or on Linux:

```bash
temp-logger --port /dev/ttyACM0
```

Or on Windows:

```bash
temp-logger --port COM3
```

### Data Logging Only (No Plot)

To just log data without displaying live plots:

```bash
temp-logger --no-plot
```

### Custom Output File

Specify the CSV output filename:

```bash
temp-logger --output my_experiment.csv
```

### Combined Options

```bash
temp-logger --port /dev/cu.usbmodem2101 --output thermal_test.csv
```

## Output

### CSV File Format

#### Dual Sensor Mode

```txt
Elapsed_Time_s,Timestamp,T1_C,T2_C,Skew_ms,Delta_T_C
0.150,2026-01-01T12:34:56.789123,22.1234,22.1256,0.845,0.0022
0.210,2026-01-01T12:34:56.849123,22.1235,22.1257,0.821,0.0022
0.270,2026-01-01T12:34:56.909123,22.1236,22.1258,0.832,0.0022
```

#### Single Sensor Mode _

```txt
Elapsed_Time_s,Timestamp,T1_C
0.150,2026-01-01T12:34:56.789123,22.1234
0.210,2026-01-01T12:34:56.849123,22.1235
0.270,2026-01-01T12:34:56.909123,22.1236
```

### Live Graphs (Dual Sensor)

The real-time display shows 2 stacked plots for optimal readability:

1. **Temperature vs Time (Top)**: Both T1 and T2 over time
   - Blue line: T1 (Sensor 1)
   - Red line: T2 (Sensor 2)

2. **Temperature Difference (ΔT) (Bottom)**: T2 - T1
   - Orange line shows the difference
   - Dashed reference line at ΔT = 0°C
   - Useful for detecting sensor drift

**Note:** Additional data (timing skew and correlation metrics) is still collected and available in the CSV file for post-processing analysis.

### Live Graph (Single Sensor)

Simple single plot showing temperature over time.

### Console Output

Real-time status printed every 10 samples:

**Dual Sensor:**

```txt
[   15.45s] | 🌡️  T1  22.12°C | 🌡️  T2  22.13°C | skew:   0.85ms | ΔT:  +0.01°C
[   16.45s] | 🌡️  T1  22.13°C | 🌡️  T2  22.14°C | skew:   0.92ms | ΔT:  +0.01°C
```

**Single Sensor:**

```txt
[   15.45s] | 🌡️  T1  22.12°C
[   16.45s] | 🌡️  T1  22.13°C
```

## Typical Workflow

### Data Collection

1. Start the logger:

```bash
temp-logger
```

1. Watch the live graphs update in real-time

2. Stop with Ctrl+C when done

3. Data is automatically saved to `tmp117_log_<timestamp>.csv`

### Analysis

The CSV file can be analyzed with:

```python
import pandas as pd
import matplotlib.pyplot as plt

# Load data
df = pd.read_csv('tmp117_log_20260101_123456.csv')

# Plot temperature difference over time
plt.plot(df['Elapsed_Time_s'], df['Delta_T_C'])
plt.xlabel('Time (s)')
plt.ylabel('Temperature Difference (°C)')
plt.show()
```

## Keyboard Controls

- **Ctrl+C**: Stop data collection and close gracefully
- **Window Close Button**: Also closes the application (saves data first)

## Requirements

- `matplotlib`: For plotting
- `pyserial`: For serial communication
- `temp_logger/tools/myserial/scpi_serial`: Bundled in this package

Install matplotlib if needed:

```bash
pip install matplotlib
```

## Troubleshooting

### "No ports found" error

- Check that the device is connected: `ls /dev/tty*` (macOS/Linux) or check Device Manager (Windows)
- Verify the USB cable is properly connected
- Try specifying the port manually: `temp-logger --port /dev/cu.usbmodem2101`

### Plot doesn't update

- Ensure matplotlib is properly installed: `pip install --upgrade matplotlib`
- Try increasing the update interval: `--interval 1.0`

### Slow performance

- Increase the update interval to reduce plot refresh rate
- Use `--no-plot` to disable plotting and just log data

### Empty CSV file

- This is normal if Ctrl+C is pressed immediately after startup
- The first data point is logged once the device responds

## Performance Notes

- **Memory**: Keeps last 300 points in memory (configurable via `MAX_POINTS`)
- **CPU**: Live plotting consumes ~5-10% CPU depending on update interval
- **Disk**: CSV grows ~100 bytes per sample (~50KB for 10 minutes of dual-sensor data)

## Examples

### Thermal Response Measurement

Monitor how temperature changes affect both sensors:

```bash
temp-logger --output thermal_response.csv
```

Watch the ΔT subplot to see the temperature difference over time.

### Long-Term Stability Test

Log data for an extended period:

```bash
temp-logger --no-plot --output stability_test.csv
```

Run this overnight or over several hours to check sensor stability.

### Synchronization Quality Check

Monitor the timing skew subplot to verify dual-sensor synchronization:

```bash
temp-logger
```

The skew should remain consistently low (typically < 2ms).
