Metadata-Version: 2.5
Name: rpi-camera-ensemble
Version: 0.27.2
Summary: RPi Camera Ensemble: Central orchestration of video acquisition across multiple Raspberry Pi cameras.
Project-URL: Homepage, https://github.com/MurineShiftWork/rpi-camera-ensemble
Project-URL: Documentation, https://MurineShiftWork.github.io/rpi-camera-ensemble/
Project-URL: Issue Tracker, https://github.com/MurineShiftWork/rpi-camera-ensemble/issues
Author-email: "Lars B. Rollik" <lars@rollik.me>
License: BSD-3-Clause-NonCommercial
        
        Copyright (c) 2025-present, Lars B. Rollik.
        All rights reserved.
        
        Redistribution and use in source and binary forms, with or without
        modification, are permitted for NON-COMMERCIAL research, academic, and
        educational purposes only, provided that the following conditions are met:
        
        1. Redistributions of source code must retain the above copyright notice,
           this list of conditions and the following disclaimer.
        
        2. Redistributions in binary form must reproduce the above copyright notice,
           this list of conditions and the following disclaimer in the documentation
           and/or other materials provided with the distribution.
        
        3. Neither the name of the copyright holder nor the names of its contributors
           may be used to endorse or promote products derived from this software
           without specific prior written permission.
        
        4. Any use of this software or its derivatives for COMMERCIAL purposes -
           including sale, paid licensing, or providing paid services built on it -
           requires a separate commercial licence. Contact lars@rollik.me.
        
        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
        AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
        ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
        LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
        CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
        SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
        INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
        CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
        ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
        POSSIBILITY OF SUCH DAMAGE.
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: License :: Free for non-commercial use
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Multimedia :: Video
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.11
Requires-Dist: numpy
Requires-Dist: pydantic>=2.0
Requires-Dist: pyyaml
Requires-Dist: typing-extensions; python_version < '3.11'
Provides-Extra: agent
Requires-Dist: fastapi; extra == 'agent'
Requires-Dist: uvicorn[standard]; extra == 'agent'
Provides-Extra: all
Requires-Dist: aiohttp; extra == 'all'
Requires-Dist: fastapi; extra == 'all'
Requires-Dist: lgpio; extra == 'all'
Requires-Dist: msw-plugin-api>=0.4.0; extra == 'all'
Requires-Dist: picamera2; (platform_machine == 'aarch64') and extra == 'all'
Requires-Dist: uvicorn[standard]; extra == 'all'
Provides-Extra: conductor
Requires-Dist: aiohttp; extra == 'conductor'
Provides-Extra: dev
Requires-Dist: aiohttp; extra == 'dev'
Requires-Dist: commitizen; extra == 'dev'
Requires-Dist: httpx; extra == 'dev'
Requires-Dist: msw-plugin-api>=0.4.0; extra == 'dev'
Requires-Dist: mypy; extra == 'dev'
Requires-Dist: pre-commit; extra == 'dev'
Requires-Dist: pytest-cov; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: types-pyyaml; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs-material; extra == 'docs'
Requires-Dist: mkdocstrings[python]>=1.0.8; extra == 'docs'
Provides-Extra: lgpio
Requires-Dist: lgpio; extra == 'lgpio'
Provides-Extra: msw
Requires-Dist: aiohttp; extra == 'msw'
Requires-Dist: msw-plugin-api>=0.4.0; extra == 'msw'
Provides-Extra: pigpio
Requires-Dist: pigpio; extra == 'pigpio'
Provides-Extra: rpi
Requires-Dist: fastapi; extra == 'rpi'
Requires-Dist: lgpio; extra == 'rpi'
Requires-Dist: picamera2; (platform_machine == 'aarch64') and extra == 'rpi'
Requires-Dist: uvicorn[standard]; extra == 'rpi'
Provides-Extra: rpigpio
Requires-Dist: rpi-gpio; extra == 'rpigpio'
Description-Content-Type: text/markdown

[![PyPI](https://img.shields.io/pypi/v/rpi-camera-ensemble)](https://pypi.org/project/rpi-camera-ensemble/)

# RPi Camera Ensemble

Central orchestration of synchronized video acquisition across multiple Raspberry Pi cameras.

Runs a **Conductor** on the acquisition machine that controls one or more **Agents**: each Agent is a FastAPI server running on an individual Raspberry Pi, managing local camera acquisition and GPIO-based TTL synchronization.

---

## Features

- **Multi-camera orchestration**: start/stop all cameras with a single call; UUID-guarded sessions prevent accidental stops
- **TTL synchronization**: per-frame GPIO pulses (emitter) and edge-detection timestamps (receiver) via `lgpio` (RPi 4 + RPi 5) or legacy `pigpio`
- **PiCamera2 backend**: uses the modern `libcamera` stack; preview and recording states
- **REST API on each agent** under `/api/v1`: `GET /agent/status`, `GET /agent/info` (version, API schema version, instance name, capabilities), `POST /agent/acquisition/init`, `/preview`, `/record`, `/stop`; a failed command answers 409 (wrong state or UUID), 422 (invalid config), 503 (camera or process failure) or 507 (storage) with `{"success": false, "error": ...}`
- **Heartbeat monitoring**: one background health check per agent, started by `setup_agents()`, with configurable interval
- **Disk space check**: pre-acquisition guard based on estimated bitrate and free space
- **CLI**: `rce-agent run/config` entrypoints for systemd or docker-compose deployment

---

## Architecture

```
Conductor (acquisition machine)
    │  HTTP via aiohttp
    ├── AgentClient → Agent (RPi cam01)  →  Acquisition → PiCamera2
    ├── AgentClient → Agent (RPi cam02)  →  Acquisition → PiCamera2
    └── AgentClient → Agent (RPi cam03)  →  Acquisition → PiCamera2
                                                    │
                                              TTL out pin (lgpio)
                                              TTL in  pin (lgpio)
```

---

## Requirements

- Python ≥ 3.11
- **On each Raspberry Pi**: `picamera2` (system package), `lgpio` (`pip install lgpio`), `gpiod` (system package, diagnostic tools)
- **On the acquisition machine (Conductor)**: `aiohttp`

---

## Installation

```bash
# Acquisition machine (Conductor only)
pip install "rpi-camera-ensemble[conductor]"

# On each Raspberry Pi (Agent + TTL sync)
pip install "rpi-camera-ensemble[agent,lgpio]"
```

Install from source:

```bash
git clone https://github.com/MurineShiftWork/rpi-camera-ensemble.git
cd rpi-camera-ensemble
pip install -e ".[agent,lgpio,dev]"
```

---

## Quick start

### Agent (on each Raspberry Pi)

Create a config file (`agent.yaml`):

```yaml
instance_name: cam01
api_host: 0.0.0.0
api_port: 8876
data_dir: /data/recordings
log_dir: /data/logs
```

Start the agent:

```bash
rce-agent run --config agent.yaml
```

Generate a template config:

```bash
rce-agent config --to-template agent.template.yaml
```

### Conductor (on the acquisition machine)

```python
from rpi_camera_ensemble.conductor.conductor import Conductor
from rpi_camera_ensemble.config.acquisition import EnsembleAcquisitionConfig
from rpi_camera_ensemble.config.conductor import ConductorConfig

ensemble_cfg = EnsembleAcquisitionConfig.from_yaml("ensemble.yaml")
conductor_cfg = ConductorConfig(log_dir="/data/logs/conductor")

with Conductor(config=conductor_cfg, ensemble_config=ensemble_cfg) as conductor:
    conductor.setup_agents()
    conductor.initialize_acquisition(
        acquisition_path="recordings/experiment_001",  # under each agent's data_dir
        acquisition_name="experiment_001",
    )
    conductor.start_preview()
    conductor.start_recording()
    # ... recording ...
    conductor.stop_acquisition()
```

Ensemble config (`ensemble.yaml`). `api_url` is the agent's address; the client adds
the `/api/v1` prefix (`http://host:port/api/v1` and the older `http://host:port//api/v1`
also work):

```yaml
schema_version: 1
agents:
  cam01:
    api_url: http://cam01.local:8876
    camera_config: {}
  cam02:
    api_url: http://cam02.local:8876
    camera_config: {}
```

### msw camera backend

`pip install "rpi-camera-ensemble[msw]"` registers `RceBackend` as the `rce` backend
of the `msw.camera` entry point group (contract from `msw-plugin-api`). It drives
one ensemble as one camera group.

- Settings: `config`, the ensemble YAML (required), `data_dir`, where the
  conductor saves each acquisition's ensemble and conductor YAML (optional), and
  `token`, the agent API token (optional, else the ensemble `api_token`, else
  `RCE_API_TOKEN`). Any other key is a configuration error.
- Each unit is one agent, matched by `camera_config.description`; a unit's `hw_id`,
  if given, must be that agent's host. Agents not named by a unit are never
  contacted. Without units, every agent is used, named by its description.
- `preflight` sets up the agents and reads their status: an agent that does not
  answer is `missing` and is left out of the session. An agent that still holds an
  acquisition (`agent_state` not `idle`, e.g. left recording by a killed host
  process) is `failed` with `agent_busy` (`agent_failed` for a dead acquisition
  process), naming that acquisition's name, UUID and start; preflight does not end it.
- `reset` ends whatever acquisition each agent holds (`Conductor.reset`, files saved)
  and reports each camera `ready`, or `failed` if its agent could not reset. msw runs
  it as `msw cameras reset --setup <setup>`.
- `start` and `stop` run the conductor commands with `raise_on_failure=False` and
  report each agent's `AgentResult` as that camera's `UnitResult`. A camera that fails
  one step keeps that failure (with `step` and the agent's `error_code`) while the
  others record. `stop` sends one stop and returns the same results on later calls.
- The videos stay on the Pis: `files` is empty and `extra` names the host and the
  acquisition path and UUID under the agent's data root.

---

## API token

The agent requires a bearer token on every command and on `/agent/logs` and
`/agent/config` when one is configured: `api_token` in `agent.yaml`, or the
`RCE_API_TOKEN` environment variable (for example from a root-only environment file
of the service). `/agent/status` and `/agent/info` stay open. An agent without a
token accepts every request and logs a warning at start.

The conductor sends the token from `api_token` in the ensemble YAML or from
`RCE_API_TOKEN`; it is never written to the saved session YAML. `setup_agents`
leaves out an agent that refuses the token (`error_code` `unauthorized`).

```bash
curl -H "Authorization: Bearer $RCE_API_TOKEN" http://cam01.local:8876/api/v1/agent/config
```

---

## TTL synchronization

The GPIO facts of each Pi (TTL library, GPIO chip, pins, sensor mode) live in its agent
config under `hardware`, rendered by the deploy (defaults in
`deploy/roles/rce_defaults/defaults/main.yaml`, set per rig or host in the inventory). The agent finds the header GPIO chip by label when it starts (`pinctrl-rp1` on a
Pi 5, `pinctrl-bcm2711` / `pinctrl-bcm2835` on earlier models), because its number depends on
the kernel. `camera_config.ttl` in `ensemble.yaml` leaves these fields at `agent` and
overrides one only when it sets it. Pins are BCM GPIO numbers (0 to 27):

```yaml
agents:
  cam01:
    api_url: http://192.0.2.10:8876
    camera_config:
      ttl:
        out_duration_us: 1000
        # optional overrides of the agent's hardware settings:
        # library: lgpio
        # gpiochip: pinctrl-rp1  # a label, or a number for /dev/gpiochipN
        # out_pin: 25            # emits a pulse on each encoded frame; null disables
        # in_pin: 23             # records edges from an external trigger; null disables
```

`lgpio` uses the GPIO character device directly (no libgpiod needed):

```bash
pip install lgpio
```

> **RPi 5 note**: leave `gpiochip` to the agent; RP1 is gpiochip4 on early Pi 5 kernels and
> gpiochip0 on current ones. `gpiodetect` on the Pi lists the chips.

---

## Output structure

Each agent writes files named `{basename}.rce.{instance}.{timestamp}.{type}.{ext}`:

```
/data/recordings/experiment_001/
├── session.rce.cam01.20260101_120000_000000.video.h264
├── session.rce.cam01.20260101_120000_000000.ttl_out.npz
├── session.rce.cam01.20260101_120000_000000.ttl_in.npz
├── session.rce.cam02.20260101_120000_000000.video.h264
├── session.rce.cam02.20260101_120000_000000.ttl_out.npz
└── session.rce.cam02.20260101_120000_000000.ttl_in.npz
```

Load and validate a session from the acquisition machine:

```python
from rpi_camera_ensemble.io import RCESession, validate_session

session = RCESession.from_directory("/data/recordings/experiment_001/")
qc = validate_session(session)
qc.print_report()
```

---

## Deployment

See [`deploy/`](https://github.com/MurineShiftWork/rpi-camera-ensemble/tree/main/deploy) for Ansible playbooks to provision Raspberry Pis (apt packages, Python venv, systemd service).

---

## Development

```bash
uv sync --extra dev
uv run pre-commit install
uv run pytest
```

---

## License

BSD-3-Clause-NonCommercial: free to use, modify and redistribute for non-commercial research,
academic and educational purposes under the BSD 3-clause conditions. Commercial use, including
sale, paid licensing or paid services built on it, needs a separate commercial licence. Copyright
(c) 2025-present Lars B. Rollik. Full terms in [LICENSE](LICENSE).
