# PiSugar UPS Support - Native I2C Driver

This substage configures native I2C support for PiSugar 2/3 series UPS HATs.

**NO pisugar-server daemon is required** - we communicate directly with the battery management chip via I2C for minimal CPU usage (<1% vs 350%+ for the daemon).

## Enabling PiSugar Support

PiSugar configuration is **disabled by default**. To enable it during build:

```bash
# Remove the SKIP file
rm pi-gen/stageDangerousPi/04-pisugar/SKIP

# Then build the image
./build-image.sh
```

## How It Works

Dangerous Pi includes a native I2C driver that communicates directly with the PiSugar hardware:

- **IP5209** (PiSugar 2 series) at I2C address `0x75`
- **IP5312** (PiSugar 3 series) at I2C address `0x57`
- **SD3078** RTC at I2C address `0x32`

The driver auto-detects the hardware when `UPS_TYPE=auto` (default).

## Features

- Battery voltage, current, and percentage reading
- Charging status detection (AC/battery power source)
- Button tap detection (single, double, long press)
- RTC read/write for scheduled wake-up alarms
- Force shutdown capability
- Low battery warnings and automatic safe shutdown

## Configuring Dangerous Pi for PiSugar

By default, PiSugar is auto-detected. You can explicitly configure it in `/opt/dangerous-pi/.env`:

```bash
# Auto-detect UPS hardware (default, recommended)
UPS_TYPE=auto

# Or explicitly use native I2C driver
UPS_TYPE=pisugar
```

Then restart Dangerous Pi:

```bash
sudo systemctl restart dangerous-pi
```

## Supported Hardware

| Model | Chip | I2C Address | Notes |
|-------|------|-------------|-------|
| PiSugar 2 (4-LEDs) | IP5209 | 0x75 | For Pi Zero |
| PiSugar 2 Pro | IP5209 | 0x75 | For larger Pis |
| PiSugar 3 | IP5312 | 0x57 | For Pi Zero 2W |
| PiSugar 3 Plus | IP5312 | 0x57 | For Pi 4/5 |

## Verifying Installation

Check if PiSugar hardware is detected:

```bash
# List I2C devices
i2cdetect -y 1

# Expected output for PiSugar 2:
#      0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
# 30: -- -- 32 -- -- -- -- -- -- -- -- -- -- -- -- --   <- RTC
# 70: -- -- -- -- -- 75 -- --                           <- Battery
```

Check UPS status via API:

```bash
curl http://localhost:8000/api/system/ups/status
```

## Migrating from pisugar-server

If you previously installed pisugar-server:

```bash
# Stop and disable the daemon
sudo systemctl stop pisugar-server
sudo systemctl disable pisugar-server

# The native driver will automatically take over
sudo systemctl restart dangerous-pi
```

## Additional Resources

- [PiSugar GitHub](https://github.com/PiSugar/PiSugar)
- [PiSugar Wiki](https://github.com/PiSugar/PiSugar/wiki)
- Native driver source: `app/backend/managers/ups_drivers/pisugar_i2c_driver.py`
