# Getting Started with Dangerous Pi

Complete guide to running the Dangerous Pi stack (backend + frontend).

## Quick Start (Development)

### 1. Start Backend

```bash
# Install Python dependencies
pip install -r requirements.txt

# Run backend
python -m app.backend.main
```

Backend will be available at **http://localhost:8000**

API Documentation: http://localhost:8000/docs

### 2. Start Frontend

```bash
# Navigate to frontend
cd app/frontend

# Install dependencies
npm install

# Run development server
npm run dev
```

Frontend will be available at **http://localhost:3000**

### 3. Open Browser

Navigate to http://localhost:3000 and you should see the Dangerous Pi dashboard!

---

## Architecture Overview

```
┌─────────────────────────────────────────────────────────┐
│                    Browser (User)                        │
│              http://localhost:3000                       │
└────────────────────┬────────────────────────────────────┘
                     │
                     ├─── SSE (/sse/events)
                     │    Real-time notifications
                     │
                     ├─── REST API (/api/*)
                     │    Command execution, status
                     │
┌────────────────────▼────────────────────────────────────┐
│              Frontend (Remix.js)                         │
│                   Port 3000                              │
│                                                          │
│  • Dashboard     • Commands                              │
│  • Settings      • Logs                                  │
│  • Cyberpunk Theme                                       │
└────────────────────┬────────────────────────────────────┘
                     │
                     │ Proxies to backend
                     │
┌────────────────────▼────────────────────────────────────┐
│              Backend (FastAPI)                           │
│                  Port 8000                               │
│                                                          │
│  • PM3 Worker    • Session Manager                       │
│  • SSE Events    • Database (SQLite)                     │
└────────────────────┬────────────────────────────────────┘
                     │
                     │ pm3 Python module
                     │
┌────────────────────▼────────────────────────────────────┐
│             Proxmark3 Hardware                           │
│              /dev/ttyACM0                                │
└─────────────────────────────────────────────────────────┘
```

---

## Features

### ✅ Implemented

**Backend:**
- FastAPI with async support
- SQLite database for sessions and history
- PM3 worker with built-in `pm3` module integration
- Mock PM3 worker for development without hardware
- Session management (single-user with takeover)
- SSE for real-time notifications
- Health check and system info endpoints

**Frontend:**
- Responsive Remix.js application
- Cyberpunk theme (dark default, light mode available)
- Dashboard with system status
- Command interface with history
- Settings page
- Command logs
- Real-time SSE integration
- Mobile-first responsive design

### 🚧 Planned

- Wi-Fi manager (AP/Client/Dual modes)
- Update manager (GitHub releases)
- UPS monitoring
- BLE notifications
- Backup/restore system
- Authentication
- HTTPS support

---

## Testing the Stack

### 1. Backend Health Check

```bash
curl http://localhost:8000/api/health
```

Expected response:
```json
{
  "status": "healthy",
  "version": "0.1.0"
}
```

### 2. PM3 Status

```bash
curl http://localhost:8000/api/pm3/status
```

Expected response (with mock):
```json
{
  "connected": true,
  "device": "/dev/ttyACM0",
  "version": null,
  "session_active": false
}
```

### 3. Execute Command

```bash
# Create session
curl -X POST http://localhost:8000/api/system/session/create \
  -H "Content-Type: application/json" \
  -d '{"force_takeover": false}'

# Execute command (replace SESSION_ID)
curl -X POST http://localhost:8000/api/pm3/command \
  -H "Content-Type: application/json" \
  -d '{
    "command": "hw version",
    "session_id": "SESSION_ID"
  }'
```

### 4. SSE Events

```bash
# Connect to SSE stream
curl -N http://localhost:8000/sse/events
```

You should see:
```
event: connected
data: {"message":"Connected to Dangerous Pi event stream"}
```

---

## Using the Web Interface

### Dashboard
- View system status (CPU, memory, disk)
- Check PM3 connection
- Quick action buttons
- Real-time event notifications

### Commands Page
1. Click "Commands" in navigation
2. Enter a PM3 command (e.g., `hw status`)
3. Click "Execute" or press Enter
4. View output in terminal-style display
5. Use ↑/↓ arrow keys to navigate history

**Quick Commands:**
- `hw status` - Hardware status
- `hw version` - Firmware version
- `hf search` - Search for HF tags
- `lf search` - Search for LF tags
- `hw tune` - Tune antenna

### Settings Page
- View current configuration
- Change Wi-Fi mode (planned)
- Enable/disable features
- Restart backend or shutdown system

### Logs Page
- View command history
- See success/failure status
- Export logs (planned)

---

## Development Tips

### Hot Reload

Both backend and frontend support hot reload:

- **Backend**: Uvicorn watches for file changes
- **Frontend**: Vite HMR (Hot Module Replacement)

Edit code and see changes immediately!

### Mock PM3 vs Real PM3

The backend automatically uses `MockPM3Worker` when the `pm3` module is not available.

**Mock responses:**
```python
"hw version" → "Proxmark3 RFID instrument\n  client: RRG/Iceman/master/v4.14831"
"hw status"  → "Device: PM3 GENERIC\nBootrom: master/v4.14831"
"hw tune"    → "Measuring antenna characteristics..."
```

**To use real PM3:**
1. Install Proxmark3 client with Python support
2. Connect PM3 hardware
3. Set `PM3_DEVICE` environment variable
4. Restart backend

### Theme Toggle

Click the theme button (◐ / ○ / ◑) in the header to cycle:
- **Dark** → **Auto** → **Light** → **Dark**

Default is Dark (cyberpunk aesthetic for Dangerous Things).

---

## Project Structure

```
dangerous-pi/
├── app/
│   ├── backend/              # FastAPI backend
│   │   ├── api/              # REST endpoints
│   │   ├── sse/              # SSE events
│   │   ├── workers/          # PM3 worker
│   │   ├── managers/         # Session, updates, etc.
│   │   ├── models/           # Database models
│   │   └── main.py           # Entry point
│   └── frontend/             # Remix.js frontend
│       ├── app/
│       │   ├── routes/       # Page routes
│       │   ├── root.tsx      # Layout
│       │   └── styles.css    # Cyberpunk theme
│       └── package.json
├── data/                     # SQLite database
├── requirements.txt          # Python dependencies
├── test_backend.py           # Backend tests
└── claude.md                 # AI development guide
```

---

## Troubleshooting

### Backend won't start

**Error: Port 8000 already in use**

The existing pi-pm3 uses ttyd on port 8000. Either:
- Change PORT to 8001 in config
- Stop ttyd: `sudo systemctl stop ttyd-bash`

**Error: pm3 module not found**

Expected during development. The mock worker will be used automatically.

### Frontend won't start

**Error: Cannot connect to backend**

Make sure backend is running on http://localhost:8000

**Error: npm install fails**

Try:
```bash
rm -rf node_modules package-lock.json
npm install
```

### SSE not working

Check browser console for errors. SSE requires:
- Backend running
- Modern browser (no IE11)
- No aggressive ad blockers

---

## Next Steps

1. **Try the interface**: Execute some commands
2. **Explore the code**: See how SSE, workers, and sessions work
3. **Add features**: Wi-Fi manager, updates, backups
4. **Test on Pi**: Transfer code to actual hardware
5. **Customize theme**: Edit `app/frontend/app/styles.css`

---

## Resources

- **Backend**: [README_DEV.md](README_DEV.md)
- **Frontend**: [app/frontend/README.md](app/frontend/README.md)
- **UI Guidelines**: [UI_GUIDELINES.md](UI_GUIDELINES.md)
- **AI Guide**: [claude.md](claude.md)

---

## Support

For issues or questions:
- Check [claude.md](claude.md) for detailed architecture
- Review API docs at http://localhost:8000/docs
- Test with curl before debugging frontend

Built with ❤️ for [Dangerous Things](https://dangerousthings.com)
