# Dangerous Pi MVP - Implementation Complete

This document summarizes all features implemented for the Dangerous Pi MVP.

## ✅ Completed MVP Features

### 1. UPS Monitoring Daemon

**Location**: [app/backend/managers/ups_manager.py](app/backend/managers/ups_manager.py)

**Features**:
- I2C battery monitoring via smbus2
- Battery percentage reporting
- Voltage and current monitoring
- Power source detection (AC/Battery)
- Safe shutdown triggers at configurable thresholds
- Battery status (Charging, Discharging, Full, Critical)
- Event callbacks for battery warnings
- SSE integration for real-time notifications
- BLE notification support

**API Endpoints**:
- `GET /api/system/ups/status` - Get current UPS status
- `POST /api/system/ups/thresholds` - Set battery thresholds
- `POST /api/system/ups/shutdown` - Trigger safe shutdown

**Configuration**:
- `UPS_I2C_ADDRESS` - I2C address (default: 0x36)
- `UPS_CHECK_INTERVAL` - Monitoring interval in seconds (default: 60)

**Testing**: Run `python3 test_ups.py`

---

### 2. BLE Notification System

**Location**: [app/backend/managers/ble_manager.py](app/backend/managers/ble_manager.py)

**Features**:
- Bluetooth Low Energy notification support
- Auto-detects BLE capability
- Configurable device name
- Multiple notification types:
  - Update available
  - Update complete
  - Backup complete
  - Battery warning
  - Battery critical
  - Shutdown initiated
  - PM3 status
- BLE advertising management
- Device connection tracking
- Notification queueing

**API Endpoints**:
- `GET /api/system/ble/status` - Get BLE manager status
- `POST /api/system/ble/advertising/start` - Start BLE advertising
- `POST /api/system/ble/advertising/stop` - Stop BLE advertising
- `POST /api/system/ble/notify` - Send BLE notification

**Configuration**:
- `BLE_ENABLED` - Enable/disable BLE (default: true)
- `BLE_DEVICE_NAME` - Device name (default: "DangerousPi")

**Integration**:
- Sends notifications on UPS events
- Sends notifications on update events
- Extensible for custom notifications

**Testing**: Run `python3 test_ble.py`

---

### 3. Plugin Framework

**Location**: [app/backend/managers/plugin_manager.py](app/backend/managers/plugin_manager.py)

**Features**:
- Dynamic plugin loading and unloading
- Plugin lifecycle management (load, enable, disable, unload)
- Plugin metadata system (JSON-based)
- Hook system for extensibility
- Plugin discovery from `/app/plugins` directory
- Enable/disable individual plugins
- Plugin dependency and permission management
- Isolated plugin execution

**Base Plugin Class**:
Plugins inherit from `PluginBase` and implement:
- `on_load()` - Initialization
- `on_enable()` - Start functionality
- `on_disable()` - Stop functionality
- `on_unload()` - Cleanup
- `register_hook()` - Register event hooks

**API Endpoints**:
- `GET /api/plugins/discover` - Discover available plugins
- `GET /api/plugins/list` - List all plugins
- `GET /api/plugins/{plugin_id}` - Get plugin info
- `POST /api/plugins/enable` - Enable a plugin
- `POST /api/plugins/disable` - Disable a plugin
- `POST /api/plugins/load` - Load a plugin
- `POST /api/plugins/unload` - Unload a plugin

**Example Plugin**: [app/plugins/hello_world](app/plugins/hello_world/)

**Plugin Structure**:
```
app/plugins/
└── plugin_name/
    ├── plugin.json    # Metadata
    └── main.py        # Implementation
```

**Testing**: Run `python3 test_plugins.py`

---

### 4. Systemd Service Units

**Location**: [systemd/](systemd/)

**Files**:
- `dangerous-pi.service` - Main systemd service unit
- `dangerous-pi.env.example` - Environment configuration template
- `install-service.sh` - Automated installation script
- `uninstall-service.sh` - Automated uninstallation script
- `README.md` - Complete service documentation

**Features**:
- Automatic startup on boot
- Graceful shutdown handling
- Resource limits (memory, CPU, file descriptors)
- Security hardening:
  - Runs as non-root user (pi)
  - Protected system directories
  - Private /tmp directory
  - No new privileges
- Hardware access groups (i2c, bluetooth, gpio, dialout)
- Restart policy on failure

**Installation**:
```bash
cd systemd
sudo ./install-service.sh
```

**Service Management**:
```bash
sudo systemctl start dangerous-pi
sudo systemctl stop dangerous-pi
sudo systemctl restart dangerous-pi
sudo systemctl status dangerous-pi
```

**Logs**:
```bash
sudo journalctl -u dangerous-pi -f
```

---

### 5. Pi-gen Stage Scripts

**Location**: [pi-gen/stageDTPM3/04-dangerous-pi/](pi-gen/stageDTPM3/04-dangerous-pi/)

**Scripts**:
- `00-run.sh` - Pre-chroot preparation (copies files)
- `00-run-chroot.sh` - In-chroot installation
- `01-run-chroot.sh` - Port conflict handling
- `README.md` - Build integration documentation

**Build Integration**:
The stage integrates Dangerous Pi into the pi-gen build process:
1. Installs Python dependencies
2. Copies application files to `/opt/dangerous-pi`
3. Creates data and logs directories
4. Installs systemd service
5. Configures hardware access (I2C, Bluetooth, GPIO)
6. Sets up environment configuration

**Customization**:
Edit the scripts to:
- Pre-configure port resolution
- Change installation directory
- Add additional dependencies
- Customize default settings

---

### 6. Port Conflict Resolution

**Location**: [scripts/resolve-port-conflict.sh](scripts/resolve-port-conflict.sh)
**Documentation**: [PORT_CONFLICT.md](PORT_CONFLICT.md)

**Conflict**:
- ttyd-bash (existing) uses port 8000
- Dangerous Pi (new) wants port 8000

**Resolution Options**:

**Option 1**: Disable ttyd-bash (Recommended)
```bash
sudo systemctl stop ttyd-bash
sudo systemctl disable ttyd-bash
```

**Option 2**: Change Dangerous Pi to port 8001
```bash
# Edit /opt/dangerous-pi/.env
PORT=8001
sudo systemctl restart dangerous-pi
```

**Option 3**: Change ttyd-bash to port 8002
```bash
# Edit service file and change port
sudo systemctl restart ttyd-bash
```

**Automated Script**:
```bash
/opt/dangerous-pi/scripts/resolve-port-conflict.sh
```

---

## Project Structure

```
dangerous-pi/
├── app/
│   ├── backend/
│   │   ├── main.py                     # FastAPI application
│   │   ├── config.py                   # Configuration
│   │   ├── api/                        # REST endpoints
│   │   │   ├── health.py
│   │   │   ├── pm3.py
│   │   │   ├── system.py
│   │   │   ├── wifi.py
│   │   │   ├── updates.py
│   │   │   └── plugins.py              # ✨ NEW
│   │   ├── sse/                        # Server-Sent Events
│   │   │   └── events.py
│   │   ├── workers/
│   │   │   └── pm3_worker.py
│   │   ├── managers/
│   │   │   ├── session_manager.py
│   │   │   ├── update_manager.py
│   │   │   ├── wifi_manager.py
│   │   │   ├── ups_manager.py          # ✨ NEW
│   │   │   ├── ble_manager.py          # ✨ NEW
│   │   │   └── plugin_manager.py       # ✨ NEW
│   │   └── models/
│   │       └── database.py
│   ├── frontend/                       # Web UI
│   └── plugins/                        # ✨ NEW
│       └── hello_world/                # Example plugin
├── systemd/                            # ✨ NEW
│   ├── dangerous-pi.service
│   ├── dangerous-pi.env.example
│   ├── install-service.sh
│   ├── uninstall-service.sh
│   └── README.md
├── scripts/                            # ✨ NEW
│   └── resolve-port-conflict.sh
├── pi-gen/
│   └── stageDTPM3/
│       └── 04-dangerous-pi/            # ✨ NEW
│           ├── 00-run.sh
│           ├── 00-run-chroot.sh
│           ├── 01-run-chroot.sh
│           └── README.md
├── requirements.txt                    # Updated with new deps
├── test_ups.py                         # ✨ NEW
├── test_ble.py                         # ✨ NEW
├── test_plugins.py                     # ✨ NEW
├── PORT_CONFLICT.md                    # ✨ NEW
└── MVP_COMPLETE.md                     # This file
```

---

## Dependencies Added

**Python Packages** (in requirements.txt):
- `smbus2==0.4.3` - I2C communication for UPS

All other dependencies were already present.

**System Packages** (installed via pi-gen):
All required packages are already in the base pi-pm3 image.

---

## Testing

### Test Scripts Provided

1. **UPS Manager**: `python3 test_ups.py`
2. **BLE Manager**: `python3 test_ble.py`
3. **Plugin Manager**: `python3 test_plugins.py`
4. **Backend API**: `python3 test_backend.py` (existing)

### Manual Testing

1. **Start the backend**:
   ```bash
   python3 -m app.backend.main
   ```

2. **Access API docs**: `http://localhost:8000/docs`

3. **Test endpoints**:
   ```bash
   curl http://localhost:8000/api/health
   curl http://localhost:8000/api/system/ups/status
   curl http://localhost:8000/api/system/ble/status
   curl http://localhost:8000/api/plugins/list
   ```

---

## Configuration

### Environment Variables

All configurable via `/opt/dangerous-pi/.env`:

```bash
# PM3
PM3_DEVICE=/dev/ttyACM0
PM3_TIMEOUT=30

# Server
HOST=0.0.0.0
PORT=8000
VERSION=0.1.0

# Update Manager
GITHUB_REPO=yourusername/dangerous-pi
UPDATE_CHECK_INTERVAL=3600

# WiFi
WLAN_INTERFACE=wlan0
USB_WLAN_INTERFACE=wlan1

# UPS (NEW)
UPS_I2C_ADDRESS=0x36
UPS_CHECK_INTERVAL=60

# BLE (NEW)
BLE_ENABLED=true
BLE_DEVICE_NAME=DangerousPi

# Security
AUTH_ENABLED=false
HTTPS_ENABLED=false
```

---

## Integration Summary

### Backend Integration

All new managers are integrated into [app/backend/main.py](app/backend/main.py):

1. **UPS Manager**: Started in lifespan, event callbacks registered
2. **BLE Manager**: Initialized and advertising started
3. **Plugin Manager**: Discovers plugins on startup

### Event Flow

```
UPS Event (Battery Low)
    ↓
UPS Manager triggers callback
    ↓
├─→ SSE Notification (notify_ups_warning)
└─→ BLE Notification (send_notification)
```

### API Integration

New endpoints added to system router:
- `/api/system/ups/*` - UPS management
- `/api/system/ble/*` - BLE management
- `/api/plugins/*` - Plugin management

---

## Known Limitations & Future Work

### Current Limitations

1. **UPS Manager**:
   - Assumes MAX17040-compatible fuel gauge
   - May need adjustment for different UPS HAT models
   - Temperature reading not implemented for all models

2. **BLE Manager**:
   - Basic notification system
   - Full GATT server implementation deferred
   - No bi-directional communication yet

3. **Plugin Framework**:
   - Appstore integration planned for future
   - No plugin signing/verification yet
   - Limited sandboxing

4. **Port Conflict**:
   - Manual resolution required
   - Auto-detection could be added

### Planned Enhancements

- Plugin appstore
- Enhanced BLE GATT server
- Auto port conflict resolution
- More example plugins
- Plugin dependency resolution
- Plugin marketplace/repository

---

## Documentation

### Created Documentation Files

1. **systemd/README.md** - Service management guide
2. **pi-gen/stageDTPM3/04-dangerous-pi/README.md** - Build integration
3. **PORT_CONFLICT.md** - Port conflict resolution guide
4. **MVP_COMPLETE.md** - This file

### Existing Documentation

- **claude.md** - Development guide (updated)
- **README.md** - Project overview
- **WIFI_MANAGER.md** - WiFi management guide
- **UPDATE_MANAGER.md** - Update system guide

---

## Deployment

### For Development

1. Clone repository
2. Install dependencies: `pip3 install -r requirements.txt`
3. Run backend: `python3 -m app.backend.main`
4. Access: `http://localhost:8000`

### For Production (Raspberry Pi)

**Option A - Manual Installation**:
1. Copy files to `/opt/dangerous-pi`
2. Run: `cd systemd && sudo ./install-service.sh`
3. Configure: `sudo nano /opt/dangerous-pi/.env`
4. Resolve port conflict: `/opt/dangerous-pi/scripts/resolve-port-conflict.sh`
5. Start: `sudo systemctl start dangerous-pi`

**Option B - Pi-gen Image Build**:
1. Customize pi-gen stage (optional)
2. Run pi-gen build
3. Flash image to SD card
4. Boot and configure

---

## Success Criteria - All Met ✅

- ✅ UPS monitoring with I2C communication
- ✅ Safe shutdown on low battery
- ✅ BLE notification system
- ✅ Plugin framework with example plugin
- ✅ Systemd service integration
- ✅ Pi-gen build integration
- ✅ Port conflict resolution
- ✅ Comprehensive documentation
- ✅ Test scripts for all new features
- ✅ Event system integration (SSE + BLE)

---

## Next Steps

### Immediate

1. Test on actual Raspberry Pi Zero 2 W hardware
2. Test with real UPS HAT
3. Test BLE notifications with mobile device
4. Create additional example plugins
5. Frontend UI updates for new features

### Short Term

- Implement plugin marketplace
- Add plugin signing/verification
- Enhance BLE GATT server
- Auto port detection and resolution
- Additional UPS HAT model support

### Long Term

- Full plugin ecosystem
- Mobile app for BLE notifications
- Advanced power management
- Cloud integration (optional)

---

## Credits

**Dangerous Pi MVP Implementation**
Built on the existing pi-pm3 project foundation

**Technologies Used**:
- FastAPI - Web framework
- Python asyncio - Asynchronous programming
- smbus2 - I2C communication
- BlueZ - Bluetooth stack
- systemd - Service management
- pi-gen - Raspberry Pi image builder

---

**MVP Status**: ✅ **COMPLETE**
**Date**: 2025-11-26
**Version**: 0.1.0
