Skip to content

BetterCorp/Smart-AI-Access-Control

Repository files navigation

Smart AI Access Control

Headless Raspberry Pi 5 + AI HAT+ access-control appliance for low-FPS RTSP analytics, relay control, and webhook automation.

This first implementation is a working scaffold:

  • FastAPI + server-rendered HTML/HTMX web shell.
  • SQLite persistence for admin sessions, cameras, AI monitors, relays, rules, events, and settings.
  • Dependency-light core domain services for rules, relays, storage, webhooks, and RTSP URL building.
  • Plugin-ready AI monitor shape with templates over the built-in object detector classes.
  • Worker loop with mockable inference, a Raspberry Pi Hailo object-detection path, snapshot event creation, relay arbitration, and webhook dispatch.
  • Raspberry Pi deployment notes and verification scripts.
  • Focused tests for the safety-critical logic.

Rule Model

The system separates camera input, AI interpretation, rules, and outputs:

  • Cameras define RTSP connection details.
  • AI Monitors run a model or analytic against one camera and publish typed metrics.
  • AI Monitors can optionally apply a visual zone after detection so rules only see objects inside the configured boundary.
  • Rules evaluate conditions against one monitor's metrics.
  • Outputs perform relay changes, webhooks, snapshots, debounce, cooldown, and fail behavior.

Examples:

  • Object Detector uses the built-in YOLOv8s object detector and publishes <class>.count as a number and <class>.present as a boolean.
  • Monitor templates expose the detector classes already available from that model, such as person, car, or dog.
  • A mantrap rule can evaluate person.count >= 2.
  • A presence rule can evaluate person.present is true.
  • Webhooks include observation metadata with the selected class, confidence threshold, active zone geometry, and matched detection boxes/confidences.

Local Development

python -m pip install -e .[dev]
npm ci
npm run build
python -m pytest
python -m uvicorn backend.app.main:app --reload --host 127.0.0.1 --port 8000

Open http://127.0.0.1:8000.

On first launch, create the single admin password at /bootstrap.

Runtime Environment

Useful environment variables:

SMARTAI_DATA_DIR=.smartai
SMARTAI_DB=.smartai/smartai.db
SMARTAI_SNAPSHOT_ROOT=.smartai/snapshots
SMARTAI_MOCK_INFERENCE=1
SMARTAI_ENABLE_RELAY_HARDWARE=0

Use mock inference during development. On the Pi, the relay hardware is only driven when SMARTAI_ENABLE_RELAY_HARDWARE=1.

When mock inference is enabled, AI monitor values are simulated and do not come from live camera frames. The Monitors page states the active inference mode and exposes live metric updates plus debug-snapshot slots for real providers.

In real inference mode, detector-backed monitors use the official Hailo detection resources and write live debug snapshots from the analyzed frame.

Zone editing is available from a monitor's edit form after that monitor has produced a debug snapshot. Zones are evaluated after full-frame detection so multiple zone monitors can reuse one detector pipeline for the same camera.

Raspberry Pi Target

Use Raspberry Pi OS Lite 64-bit on the Pi 5. Install the Hailo stack with Raspberry Pi packages, verify with hailortcli fw-control identify, then run the app as systemd services using the templates under deploy/.

Pi Setup Process

Recommended base image:

  • Raspberry Pi OS Lite 64-bit.
  • SSH enabled.
  • Wired Ethernet preferred.
  • Raspberry Pi AI HAT+ attached before installing the Hailo packages.

Deployment is split into two scripts:

  • scripts/pi-setup.sh is the small bootstrap entrypoint. It installs the minimum packages, syncs the requested Git branch, then runs the checked-out latest pi-sync.sh with the original arguments and environment preserved.

  • scripts/pi-sync.sh is the full idempotent install/update worker. It will:

  • install required apt packages, including the native Hailo post-process build dependencies,

  • create the smartai service user,

  • create /var/lib/smartai for the SQLite DB and snapshots,

  • clone or update the repo at /opt/smart-ai-access-control,

  • create/update the Python virtual environment,

  • install Node.js/npm and build TypeScript assets from source,

  • install the Debian usbrelay CLI used by the relay driver,

  • install systemd services,

  • install an hourly smartai-cleanup.timer to prune snapshots and app-owned old logs,

  • serve the web API with two Uvicorn worker processes,

  • install HailoRT monitor support but keep session-level monitor mode disabled by default for pipeline stability,

  • install an aggressive Raspberry Pi 5 fan curve in /boot/firmware/config.txt,

  • install the USB relay udev rule,

  • expose the app directly on 0.0.0.0:8000,

  • optionally configure UFW,

  • restart services,

  • verify http://127.0.0.1:8000/healthz.

  • install the official hailo-apps Python package used by the real object-detection provider when Hailo support is enabled.

  • build the app virtualenv with access to system Python packages so apt-installed gi/Hailo bindings remain visible.

  • run Hailo post-install for the detection group so the default HEF, post-process libraries, and environment file exist before the worker starts.

  • reuse already-downloaded Hailo detection resources on later syncs and only rebuild the post-process side when the files are already present.

Fresh install or update from GitHub:

curl -fsSL https://raw.githubusercontent.com/BetterCorp/Smart-AI-Access-Control/main/scripts/pi-setup.sh | sudo bash

The repo is public, so the installer uses HTTPS git checkout by default. If you need to override the repo URL, run:

sudo env SMARTAI_REPO_URL=https://github.com/BetterCorp/Smart-AI-Access-Control.git scripts/pi-setup.sh

or pipe the script while preserving the override:

curl -fsSL https://raw.githubusercontent.com/BetterCorp/Smart-AI-Access-Control/main/scripts/pi-setup.sh \
  | sudo env SMARTAI_REPO_URL=https://github.com/BetterCorp/Smart-AI-Access-Control.git bash

Run again any time to pull and apply the latest code:

sudo /opt/smart-ai-access-control/scripts/pi-setup.sh

Local pi-setup.sh runs are safe because that script only refreshes the checkout and then hands off to the latest versioned pi-sync.sh; it does not keep running stale full-install logic after a pull.

Useful installer overrides:

sudo env \
  SMARTAI_BRANCH=main \
  SMARTAI_MOCK_INFERENCE=1 \
  SMARTAI_ENABLE_RELAY_HARDWARE=0 \
  SMARTAI_ENABLE_HAILO_PACKAGES=1 \
  SMARTAI_ENABLE_HAILO_MONITOR=1 \
  SMARTAI_ENABLE_HAILO_SESSION_MONITOR=0 \
  SMARTAI_HAILO_MONITOR_INTERVAL_MS=5000 \
  SMARTAI_ENABLE_PI_FAN_TUNING=1 \
  SMARTAI_TIMEZONE=Africa/Johannesburg \
  SMARTAI_LOG_RETENTION_DAYS=7 \
  SMARTAI_LOG_MAX_BYTES=52428800 \
  SMARTAI_HAILO_APPS_REF=main \
  SMARTAI_ENABLE_UFW=1 \
  /opt/smart-ai-access-control/scripts/pi-setup.sh

Cleanup runs hourly through smartai-cleanup.timer. It applies the configured snapshot storage limits, including monitor debug snapshots under snapshots/monitor-debug, and removes app-owned *.log / rotated .log.* files under /var/lib/smartai by age and total size.

Fan tuning writes a marked Smart AI Access Control block to /boot/firmware/config.txt and replaces only that block on future runs. Disable it with SMARTAI_ENABLE_PI_FAN_TUNING=0. The default curve starts cooling earlier than Raspberry Pi OS defaults: 40C at 50% PWM, 50C at 75% PWM, 60C at 88% PWM, and 70C at 100% PWM. A reboot is required for boot config changes to take effect.

Timezone setup is opt-in. If SMARTAI_TIMEZONE is set when running setup, the script validates /usr/share/zoneinfo/<timezone>, configures the OS timezone, and passes the same value to the API, worker, and cleanup services. If it is not set, setup leaves the OS timezone and service timezone environment unchanged.

Hailo monitor telemetry is available only when both SMARTAI_ENABLE_HAILO_MONITOR=1 and SMARTAI_ENABLE_HAILO_SESSION_MONITOR=1 are set. Session-level HailoRT monitor mode is disabled by default because it can keep the Hailo device busy during pipeline startup on the Raspberry Pi AI HAT+. The dashboard still shows PCIe/device/driver checks with monitor mode disabled. Enable session monitor mode only while troubleshooting utilization/FPS, then disable it again if camera startup becomes unreliable.

After setup:

systemctl status smartai-api smartai-worker
curl http://127.0.0.1:8000/healthz

Open from another machine on the LAN:

http://<pi-ip>:8000/bootstrap

Use /bootstrap once to create the single admin password.

Production switchovers after hardware validation:

sudo env SMARTAI_MOCK_INFERENCE=0 SMARTAI_ENABLE_RELAY_HARDWARE=1 /opt/smart-ai-access-control/scripts/pi-setup.sh

After switching to real inference, the Cameras page shows the last stream/provider error for each camera. A working person monitor should move from stream_error to online, publish live metrics on the Monitors page, and begin producing debug snapshots.

The setup script verifies the worker virtualenv can import gi, hailo, and hailo_apps before it restarts services. If that verification fails, setup stops with the missing binding instead of leaving the worker in a hidden half-configured state.

For an existing install created before Hailo support was wired in, rerunning setup repairs an isolated virtualenv by rebuilding it with system packages enabled.

Health separates relay software enablement from relay visibility:

  • Relay control enabled reflects SMARTAI_ENABLE_RELAY_HARDWARE.
  • Relay channels visible is how many channels the worker can see through the usbrelay command.

For the default single-board setup, the relay driver maps the placeholder board id board-1 to the one detected usbrelay board id automatically. Multi-board installs need explicit relay mapping rather than relying on that convenience path.

Frontend build output under backend/app/static/dist/ is generated during local setup and Pi deployment; it is not committed to the repository.

License

AGPL-3.0-only OR Commercial.

Commercial licensing is available only under a separate written agreement with the copyright holder.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors