# Glass Curtain Wall – Realtime Capture (Flask)

This is a minimal, ready-to-run Flask app that exposes HTTP and WebSocket endpoints for a realtime sensor capture page. It is structured to be easily extended (auth/JWT, CSV writing, OpenAPI, DB) while keeping the core contract stable.

## Endpoints

- `POST /start_capture`: Start capture. Optional body `{ "rate_hz": number }`.
- `POST /stop_capture`: Stop capture.
- `GET /video_feed`: Placeholder (204). Replace with MJPEG or last-frame when integrating a camera.
- `WS /ws`: Streams samples (object or array) with fields `t`, `volt`, `accel_g`, `accel_mps2`.
- `WS /log_ws`: At least one text line per second. If a CSV path is available, includes a `*.csv` fragment.

All HTTP responses are wrapped as:
- Success: `{ "ok": true, "data": ... }`
- Error: `{ "ok": false, "error": { "code", "message", "details" } }`

## Project Layout

- `app.py`: Flask app, routes, CORS, WebSockets, error handling
- `services/sensor_service.py`: Sensor abstraction and capture state (replaceable with real hardware)
- `schemas/capture.py`: Lightweight request parsing; can be upgraded to Marshmallow later
- `templates/index.html`: Your existing frontend page (copied here)
- `requirements.txt`: Minimal dependencies

## Quickstart

1) Create venv and install dependencies

```
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```

2) Frontend page

- The existing `index.html` has been copied to `templates/index.html` and is rendered by `/`.
- If your frontend uses absolute WS URLs, adjust host/port if backend runs elsewhere.

3) Run (dev)

```
python app.py
# Visit http://127.0.0.1:5000/
```

4) Run (prod, with WebSocket)

```
# Install optional dependency first:
# pip install hypercorn==0.17.3
hypercorn app:app --bind 0.0.0.0:5000
```

## Replacing the Sensor

- Implement real sampling in `SensorService.next_sample()`.
- Optionally add a CSV writer in `SensorService` to persist samples to the path stored in `state.csv_path`.
- Use locks as shown to keep state thread-safe.

## Extending

- Validation & OpenAPI: Add Marshmallow schemas under `schemas/` and integrate `flask-smorest`.
- Auth: `Flask-JWT-Extended` for JWT-based auth.
- Video: Implement `/video_feed` using OpenCV to produce MJPEG (`multipart/x-mixed-replace`).
- Config: Add `config.py` and pull secrets from environment for prod.
- Logging: Add a request ID per request and structured logs.

## Notes

- Contracts are designed to be idempotent where reasonable.
- CORS is open for convenience; lock it down per your deployment needs.
- Prefer running with Hypercorn in production for reliable WebSocket support.
