# piNail Project Context

## What this project is
- `piNail` is a Raspberry Pi e-nail temperature controller.
- Legacy scripts in project root (`piNail.py`, `logging_piNail.py`, etc.) are the old implementation.
- `piNail2/` is the active modernized implementation with a web UI and systemd service.

## Active runtime (current)
- Host: Raspberry Pi at `192.168.0.159` (WiFi, static IP configured).
- Service: `pinail2.service` (systemd), enabled at boot.
- App directory on Pi: `/home/pi/piNail2`.
- Web UI:
  - LAN: `http://192.168.0.159:5000`
  - Reverse proxy: `https://nail.sethpc.xyz` (via Caddy + auth)

## High-level architecture (`piNail2/`)
- `app.py`: Flask app, API routes, heartbeat, startup/shutdown wiring.
- `pid_controller.py`: PID loop thread, relay drive, safety logic, autotune logic.
- `thermocouple.py`: MAX6675 wrapper + spike filtering.
- `config.py` + `config.json`: config defaults + persistence.
- `templates/index.html`, `static/app.js`, `static/style.css`: dashboard UI.
- `pinail.service`: systemd unit file template.
- `deploy.sh`: deployment helper script.

## Core API endpoints
- `GET /api/status`: full control + telemetry snapshot.
- `GET /api/history`: chart history stream.
- `POST /api/power`: on/off.
- `POST /api/setpoint`: set target temp.
- `POST /api/pid`: set PID values and proportional mode.
- `POST /api/pid/reset`: reset PID internals.
- `GET /api/autotune`: autotune status.
- `POST /api/autotune/start`: start relay-based autotune.
- `POST /api/autotune/stop`: stop autotune.
- `GET /api/heartbeat`: backend heartbeat for reconnect logic.

## PID modes
- `P-on-Error` (`proportional_mode: error`): default, better target tracking.
- `P-on-Measurement` (`proportional_mode: measurement`): can reduce overshoot but may feel sluggish if not tuned.

## Autotune notes
- Autotune uses relay oscillation around setpoint with hysteresis bands.
- UI shows running phase (`heating`/`cooling`) and peak progress.
- If current temp starts above setpoint, autotune may begin in cooling phase.

## Safety behaviors
- Hard max temp cutoff.
- Thermocouple disconnect handling.
- Idle shutoff timer.
- Watchdog status exposed in heartbeat.

## Operations quick commands
- Service status: `ssh pinail "sudo systemctl status pinail2"`
- Restart service: `ssh pinail "sudo systemctl restart pinail2"`
- Logs: `ssh pinail "sudo journalctl -u pinail2 -f"`
- Verify enabled: `ssh pinail "sudo systemctl is-enabled pinail2"`

## Deployment workflow
- Edit files in this repo under `piNail2/`.
- Copy to Pi (`/home/pi/piNail2`) and restart service.
- Validate in browser with hard refresh to avoid stale JS/CSS.

## Legacy code warning
- Root-level legacy scripts are preserved for reference.
- Do not mix old runtime and `pinail2.service` at the same time.
