Metadata-Version: 2.4
Name: neopi
Version: 0.1.0
Summary: NeoPixel animation scenes and a friendly Raspberry Pi web controller
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: fastapi<1,>=0.110
Requires-Dist: pydantic<3,>=2
Requires-Dist: uvicorn[standard]<1,>=0.29
Provides-Extra: hardware
Requires-Dist: Adafruit-Blinka>=8; extra == "hardware"
Requires-Dist: adafruit-circuitpython-neopixel>=6; extra == "hardware"
Requires-Dist: rpi-ws281x>=5; extra == "hardware"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: httpx>=0.27; extra == "dev"

# NeoPi: NeoPixel Animations and Web Controls

NeoPi runs customizable seasonal animations on Raspberry Pi NeoPixel lightstrips and provides a responsive local web dashboard. It also includes a simulator fallback for development without LED hardware.

## Quick Start

On a Raspberry Pi with Python 3.9 or newer:

```bash
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -e ".[hardware]"
neopi setup
sudo .venv/bin/neopi serve
```

The setup command asks only for the pixel count, strip color order, and GPIO data pin. Then open `http://<your-pi-hostname>:8000` on a device connected to the same network. The dashboard includes a sampled live preview of the animation being sent to the strip.

For development on a computer without LEDs:

```bash
python -m pip install -e ".[dev]"
neopi setup
neopi serve --reload
```

The simulator is selected automatically off the Pi. To choose it explicitly, set `NEOPI_DRIVER=simulator`.

After changing branches or pulling packaging changes, refresh the editable install:

```bash
python -m pip install -e ".[dev]"
```

The supported installed entry point is `neopi serve`. To run a small animation loop without the web dashboard, use `python example_serverless.py` from a source checkout.

> **Hardware safety:** Long strips need a separate, correctly sized 5 V supply. Connect the Pi and supply grounds together; do not power a long strip from the Pi's 5 V pin. A level shifter, 300–500 ohm data resistor, and 500–1000 µF capacitor at the strip input are strongly recommended. Begin with power disconnected and verify DIN, 5 V, and ground before starting the server.

---

## Repository and Package Architecture

NeoPi uses a `src` layout so tests and development commands exercise the same importable package that is installed from a wheel:

```text
neopi/
├── pyproject.toml
├── README.md
├── example_serverless.py    # Small animation loop without the web server
├── src/neopi/
│   ├── app.py                # FastAPI application and controller
│   ├── cli.py                # neopi command
│   ├── config.py             # Hardware initialization and simulator
│   ├── hue.py                # Philips Hue synchronization
│   ├── presets.py            # Preset catalog
│   ├── animations/           # One module per animation
│   └── static/               # Dashboard assets bundled in the wheel
└── tests/
```

---

## Installation & Requirements

To run this server and correctly interface with the physical lightstrip on your Raspberry Pi, you need the following Python libraries installed:

1. **Web Server & API Libraries:**
   * `fastapi` (for the REST/WebSocket API)
   * `uvicorn[standard]` (the ASGI server to run FastAPI)
   * `pydantic` (for data validation)

2. **Hardware Control Libraries:**
   * `adafruit-circuitpython-neopixel` (provides the `neopixel` module to control the LEDs)
   * `Adafruit-Blinka` (provides the `board` module to map the physical Raspberry Pi GPIO pins)
   * `rpi-ws281x` (the underlying hardware driver required for WS2812B/NeoPixels on the Pi)

The recommended editable install records and installs these dependencies for you:

```bash
python -m pip install -e ".[hardware]"
```

For a regular local installation or a distributable wheel:

```bash
python -m pip install ".[hardware]"
python -m pip wheel . --no-deps --wheel-dir dist
```

The resulting `neopi-*.whl` contains the Python server, built-in animations, and dashboard assets. Once the project is published to a package index, the intended installation command is `python -m pip install "neopi[hardware]"`.

To build and publish both the source distribution and wheel from Windows, use the release script. Configure a PyPI token when Twine prompts for credentials:

```bat
publish.cmd
```

Configuration and controller state are stored in `~/.config/neopi/`. Set `NEOPI_DATA_DIR` to choose another directory, or override individual files with `NEOPI_CONFIG_FILE`, `NEOPI_SETTINGS_FILE`, and `NEOPI_HUE_SETTINGS_FILE`. Re-run `neopi setup` whenever the strip is replaced or moved to another supported GPIO pin. Controlling NeoPixels on Raspberry Pi commonly requires root privileges, so the production command may need `sudo .venv/bin/neopi serve`.

Existing checkout-local `lightstrip_config.json`, `settings.json`, and `hue_settings.json` files are not moved automatically. Copy their contents into `~/.config/neopi/config.json`, `~/.config/neopi/settings.json`, and `~/.config/neopi/hue.json`, respectively, or point the corresponding environment variables at the existing files.

---

## Setting Up as a System Service (Raspberry Pi/Linux)

To ensure NeoPi starts automatically when the Raspberry Pi boots and restarts after a failure, configure it as a systemd service.

### 1. Create a Service File
On your Raspberry Pi, create a new file for your service in the `/etc/systemd/system/` directory:
```bash
sudo nano /etc/systemd/system/neopi.service
```

### 2. Add the Configuration
Replace `yourusername` and the virtual-environment path with the values from your installation.

```ini
[Unit]
Description=NeoPi lightstrip server
After=network.target

[Service]
# The user you are running the script as (e.g., 'pi' or your custom username)
User=yourusername

Environment=NEOPI_DATA_DIR=/home/yourusername/.config/neopi
ExecStart=/home/yourusername/neopi/.venv/bin/neopi serve

# Restart the service automatically if it crashes
Restart=always
# Wait 5 seconds before restarting
RestartSec=5

# Forward outputs to the system journal
StandardOutput=inherit
StandardError=inherit

[Install]
# Starts the service on boot
WantedBy=multi-user.target
```
*(Press `Ctrl+O` then `Enter` to save, and `Ctrl+X` to exit nano).*

### 3. Enable and Start the Service
Reload the systemd daemon to recognize the new file, enable it to start on boot, and start it immediately:

```bash
# Reload systemd to recognize your new service file
sudo systemctl daemon-reload

# Enable the service to run automatically on boot
sudo systemctl enable neopi.service

# Start the service right now
sudo systemctl start neopi.service
```

### 4. Check the Status and Logs
To verify that your server is running successfully:
```bash
sudo systemctl status neopi.service
```

To view the live application logs:
```bash
sudo journalctl -u neopi.service -f
```

### 5. If You Need to Stop or Restart the Service
```bash
# To stop the service
sudo systemctl stop neopi.service
# To restart the service after installing changes
sudo systemctl restart neopi.service
```

---

## Control Center Web Dashboard Features

The NeoPi Control Center is a responsive single-page application for mobile and desktop browsers:

1. **Decoupled Animation Preview and Customization**: Clicking on any card in the library selects it, showing its specific configurable sliders in the "Configure & Play" settings panel without immediately playing it. The user can adjust parameters first, then click "Play Now" or "+ Queue" to execute.
2. **Interactive Live Parameter Tuning**: If the selected card is the currently active manual animation, dragging sliders or choosing colors immediately pushes live REST updates to the Raspberry Pi, showing immediate hardware feedback.
3. **Dynamic Hover Tooltips**: Every parameter (e.g., frame wait times, segment counts, speeds, spacing) has custom tooltips. Hovering over a slider or input group expands a micro-description explaining exactly how it affects the visual pattern.
4. **Customizable Auto-Cycle Queue**: Users can choose to run the lightstrip autonomously using a customized sequence list. Queued patterns can be added, deleted, or reordered instantly. Settings are persisted in the NeoPi data directory so that they survive a system restart.
5. **Global Fade Transitions and Cycling Times**: Users can set how long each auto-cycle animation runs (Active Animation Duration) and how long they fade into one another (Transition Fade Time) using global sliders.
6. **Restore Defaults Action**: A dedicated action button that instantly restores uvicorn state, cycle modes, parameters, active duration settings, and the default holiday queue back to factory defaults.
7. **Full RGBW Color & White Channel Control**: Complete 4-channel LED control is supported. The frontend dynamically renders a companion White intensity slider (0-255) next to the color wheel picker for any pattern with an RGBW color parameter. Color values are serialized and transmitted in an extended 8-character hex format (#RRGGBBWW), allowing granular tuning of white channel intensity alongside RGB colors.

---

## Guiding Principles for Writing Animations

To maintain consistency, safety, and visual quality, every animation must adhere to these guidelines:

### 1. Standard Parameters and Signature
Every animation function must accept at least these two arguments to ensure compatibility with the automated cycle loop and the web control server:
*   `wait` (float): The speed controller. It is the time in seconds to sleep between rendering frames.
*   `duration` (int or float): The total time in seconds the animation should run before returning.

Example signature:
```python
def my_new_animation(wait=0.05, duration=10, speed_multiplier=1.0, color=(255, 0, 0, 0)):
    # ... implementation ...
```

### 2. Documentation Guidelines
We use the Google Python Style Guide for docstrings. Every animation module must specify:
1. A summary line describing the visual effect.
2. A detailed description of the physical look.
3. An Args section detailing every parameter.

Example:
```python
def starry_sky(wait=0.1, duration=15, star_count=10):
    """Simulates glowing stars fading in and out on a dark blue background.

    Args:
        wait (float): Time to sleep between frames (seconds).
        duration (int): Total run time of the animation (seconds).
        star_count (int): Maximum number of concurrent stars to render.
    """
```

### 3. Parametrization and Avoiding Magic Numbers
*   Never use hardcoded magic numbers for speeds, counts, densities, or colors in the rendering loop.
*   Expose these variables as default argument parameters on the function signature.
*   This enables the FastAPI web server to dynamically inspect the function signature using reflection (inspect module) and automatically render customization sliders on the web control panel.

### 4. RGBW Color Parameter Formatting
Color parameters can be defined as 3-channel RGB tuples `(R, G, B)` or 4-channel RGBW tuples `(R, G, B, W)`. The backend parses these into hex values for web interface compatibility:
*   Standard 6-character hex (`#RRGGBB`): Default for standard RGB strips.
*   Extended 8-character hex (`#RRGGBBWW`): Utilized for RGBW strips to package both the color and the white channel intensity. The server automatically translates `#RRGGBBWW` strings back into `(R, G, B, W)` tuples for the animation functions, allowing native hardware integration.

---

## Anti-Flickering Guidelines (CRITICAL)

To prevent data line interference, voltage drops, and visual flickering on long strips (e.g., our 289-pixel strip), **don't update all pixels in a single frame**.

### Rules for Implementation:
1.  **Interlacing (Stepped Ranges)**: Stagger updates between frames using a stepped range based on the frame parity.
    ```python
    # Correct way to loop through pixels
    for i in range(frame % 2, NUM_PIXELS, 2):
        pixels[i] = (r, g, b, w)
    ```
2.  **Conditional Drawing**: If calculating a single moving object (e.g., a train engine or comet head), only write to it if it matches the current frame's parity.
    ```python
    if pixel_index % 2 == frame % 2:
        pixels[pixel_index] = color
    ```
3.  **No pixels.fill() inside rendering loops**: Avoid filling the entire strip in every frame. Clear old pixels in two staggered passes or clear pixels individually using the interlaced frame parity.

---

## Step-by-Step: Adding a New Animation

Adding a new custom animation is clean and straightforward:

### Step 1: Create the Animation File
Create a new file in `src/neopi/animations/`, e.g., `my_custom_pattern.py`.
Import necessary items from `neopi.config` and `neopi.utils`:

```python
import time
from neopi.config import pixels, NUM_PIXELS
from neopi.utils import fade_transition

@fade_transition()  # Optional: Adds standard fade-out/fade-in between animations
def my_custom_pattern(wait=0.05, duration=10, main_color=(255, 0, 128, 0)):
    """A beautiful neon-pink wave sweeping down the strip.

    Args:
        wait (float): Time to sleep between frames.
        duration (int): Total run time in seconds.
        main_color (tuple): The RGBW color of the sweeping wave.
    """
    start_time = time.time()
    frame = 0
    
    while time.time() - start_time < duration:
        # Use anti-flicker interlaced rendering
        for i in range(frame % 2, NUM_PIXELS, 2):
            # ... rendering logic ...
            pixels[i] = main_color
            
        pixels.show()
        time.sleep(wait)
        frame += 1
```

### Step 2: Register the Animation
Open `src/neopi/animations/__init__.py`:
1. Import your new function:
   ```python
   from .my_custom_pattern import my_custom_pattern
   ```
2. Add it to the central `ANIMATIONS` registry dictionary:
   ```python
   ANIMATIONS = {
       ...
       "my_custom_pattern": my_custom_pattern,
   }
   ```

### Step 3: Run / Verify
Run the test suite to verify your function executes correctly without syntax or parameter errors:
```bash
python -m pytest
```

Registering the animation makes it available in the web dashboard. For a minimal serverless installation, import it in `example_serverless.py` and add it to `run_serverless_cycle()`.

---

## Running Without the Web Server

The source checkout includes a minimal loop with Rainbow Cycle, Color Waves, and Counterflow Waves:

```bash
python example_serverless.py
```

It uses the same NeoPi configuration and hardware driver as the installed package, but it does not start FastAPI, save a queue, or synchronize with Philips Hue. Press `Ctrl+C` to stop and blank the strip. Edit the imported functions and calls in `run_serverless_cycle()` to choose a different small set of animations.

---

## Offline Local Development (Mock Mode)

If you are not running the code on a Raspberry Pi (e.g., developing on Windows or macOS), the package will **automatically fall back to Mock mode**:
* It bypasses the physical `board` and `neopixel` hardware libraries.
* It initializes a `MockNeoPixel` class that matches the interface of the Adafruit library.
* This allows you to run, test, and develop the FastAPI Web Server and the responsive dashboard locally on your development machine before deploying.

## Philips Hue room color sync

1. Start the server and open **Hue Room Sync** in the dashboard.
2. Enter the Hue Bridge's LAN IP address (reserve it in your router to keep it stable).
3. Press the physical bridge link button, then click **Pair Bridge** within its pairing window.
4. Load rooms, choose a room or zone, select a palette mode, enable sync, and save. The refresh interval defaults to **10 seconds** and accepts **5–3600 seconds**.
5. Open the **Hue** library filter and play or queue any of the seven room-aware animations. In addition to Waves, Chase, and Twinkle, the library includes Color Wash, Bloom, Mirror Pulse, and Mosaic. Adjust **Wait** and **Motion Speed** in Configure & Play independently of the bridge refresh interval.

All seven Hue animations continuously read a shared palette and blend toward changed colors without restarting their motion or cycle duration. A background worker reads one bridge snapshot per interval, regardless of bulb count. It samples the selected room's individual powered-on, reachable bulbs, including xy colors, hue/saturation, and white color temperature. Global strip brightness remains separately adjustable.

**Inferred scene colors** groups perceptually similar bulb readings and exposes up to five representative colors. A nearly uniform room produces one color, while multicolor scenes retain their major color families and isolated contrasting accents. Representatives are actual bulb readings rather than averaged colors. **Direct bulb colors** preserves the original behavior and exposes every exact unique bulb color in the room's bridge order.

If the bridge is unavailable, the room is removed, or all its bulbs are off/unreachable, the last usable palette remains active and status explains the condition. Before the first successful sync, the Hue animations use a violet/green/orange fallback. Disabling sync clears the cached palette. Other animation categories continue using their own colors. For uninterrupted manual playback, disable the existing **Auto-Return to Cycle** option.

This integration uses the bridge's local **v1 REST API**, following the [official Hue pairing workflow](https://developers.meethue.com/develop/get-started-2/). Bulbs must belong to a Hue Bridge; direct Bluetooth or Zigbee bulb pairing is not implemented. It samples current bulb states rather than extracting every color from a named Hue scene, and does not change Hue bulb state. A dynamic Hue scene is sampled at your chosen interval. Colors are an RGB approximation and can differ between Hue bulbs and your strip.

Pairing credentials and Hue settings stay server-side in the NeoPi data directory, separate from ordinary animation settings. The local v1 transport uses HTTP, so use it on your trusted LAN. Bridge addresses are restricted to LAN IP literals; redirects and system HTTP proxies are disabled. **Restore Defaults** also clears local Hue settings; it does not revoke the previously created application user on the bridge.

Regression checks: `python -m pytest`. Hue tests mock bridge responses; physical bridge/LED validation is still needed on the Pi.
