Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ and rejected.
- The rules engine is a pure function too, `evaluate(state, people, now, mode, settings) -> (new_state, events)`. Events are edge-triggered: raised once per incident, never once per frame.
- Alert channels are one module each under `alerts/`: a pure `build_message` plus a notifier taking an injected `httpx.Client`. Raise delivery errors `from None`, since httpx puts the request URL in its exception text.
- A monitoring failure (heartbeat ping) is logged and detection continues.
- A live camera is a `LiveFrameSource` (`vision/live.py`) given a function that opens its stream. Health is frames arriving, never connection state.

### Testing and tuning

Expand Down
7 changes: 7 additions & 0 deletions PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ ordered only when the P0 bench question (Hailo FPS) is the last one open.
- First real footage from the backyard camera (2026-08-25) showed input
resolution is the dominant detection variable: 0% of frames at the default
640 px input, 87% at 1920. Not yet wired into the pipeline.
- SimpliSafe live bench source (2026-10-12): `vision/live.py` keeps any live
stream alive (rejoin on frame silence, newest-frame-only), with the
SimpliSafe adapter in a `simplisafe` extra and `poolguard-simplisafe-watch`
reporting blindness to Kuma after 3 min. Not yet wired to detection.
- **No hardware purchased. Hardware order is deliberately deferred (ADR-010)**
until PD exit criteria are met.

Expand Down Expand Up @@ -90,6 +94,9 @@ Work happens in reviewable PRs against `main`.
`in_water` is a point-in-polygon test; `poolguard-replay --labels`
applies the shot's camera profile. Not yet checked against real
backyard footage
- [x] Live bench source: SimpliSafe via LiveKit behind `LiveFrameSource`,
rejoin + blindness heartbeat. Still open: rejoin against a real
outage, heartbeat against the real Kuma monitor
- [ ] Pool zone survives a camera re-mount: the outline is traced for one
angle and the battery camera moves every time it is charged
([#23](https://github.com/pizzasaurusrex/poolguard/issues/23))
Expand Down
12 changes: 12 additions & 0 deletions docs/decision-log.md

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ vision = [
labels = [
"pyyaml>=6.0",
]
simplisafe = [
"livekit>=1.1",
"simplisafe-python>=2026.9.0",
]

[dependency-groups]
dev = [
Expand All @@ -34,6 +38,8 @@ poolguard = "poolguard.main:main"
poolguard-alert-test = "poolguard.scripts.alert_test:main"
poolguard-benchmark = "poolguard.scripts.benchmark_fps:main"
poolguard-replay = "poolguard.scripts.replay:main"
poolguard-simplisafe-login = "poolguard.scripts.simplisafe_login:main"
poolguard-simplisafe-watch = "poolguard.scripts.simplisafe_watch:main"
poolguard-view-check = "poolguard.scripts.view_check:main"

[build-system]
Expand Down
23 changes: 22 additions & 1 deletion src/poolguard/alerts/heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from enum import StrEnum

import httpx
from pydantic import SecretStr
from pydantic import BaseModel, ConfigDict, SecretStr

HEARTBEAT_TIMEOUT_SECONDS = 5.0

Expand All @@ -22,6 +22,27 @@ class HeartbeatStatus(StrEnum):
DOWN = "down"


class HeartbeatReport(BaseModel):
model_config = ConfigDict(frozen=True)

status: HeartbeatStatus
message: str


def report_for_frame_age(
frame_age_seconds: float, *, blind_after_seconds: float
) -> HeartbeatReport:
"""What to tell the monitor, given how long it has been since the last frame.

A process that is running but receiving no video must not look healthy,
so UP is earned by fresh frames, not by being alive.
"""
if frame_age_seconds >= blind_after_seconds:
minutes = int(frame_age_seconds // 60)
return HeartbeatReport(status=HeartbeatStatus.DOWN, message=f"no video for {minutes} min")
return HeartbeatReport(status=HeartbeatStatus.UP, message="OK")


class HeartbeatError(RuntimeError):
"""The ping did not reach the monitor.

Expand Down
40 changes: 40 additions & 0 deletions src/poolguard/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
nesting them as plain fields would bypass their env machinery entirely.
"""

from pathlib import Path

from pydantic import Field, SecretStr, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict

Expand Down Expand Up @@ -145,10 +147,47 @@ class AlertSettings(BaseSettings):
description="Seconds between pings. Keep it under the monitor's own heartbeat "
"interval so one late ping does not read as an outage",
)
blind_after_seconds: float = Field(
default=180.0,
gt=0,
description="Seconds without a frame before the heartbeat reports DOWN. Shorter gaps "
"are logged, not alerted: the system runs 24/7 and brief outages are expected",
)
mqtt_host: str | None = None
escalation_ack_timeout_seconds: float = Field(default=30.0, gt=0)


class SimpliSafeSettings(BaseSettings):
"""Bench-only live source (ADR-002): never the production camera."""

model_config = SettingsConfigDict(env_prefix="POOLGUARD_SIMPLISAFE_", **_SECTION_CONFIG)

camera_name: str | None = Field(
default=None, description="Camera name as shown in the SimpliSafe app; None disables"
)
token_path: Path = Field(
default=Path.home() / ".config" / "poolguard" / "simplisafe-token.json",
description="Where the rotating refresh token is kept, outside the repo",
)
stale_rejoin_seconds: float = Field(
default=30.0,
gt=0,
description="Seconds without a frame before the stream is left and joined afresh. "
"Must exceed a cold join, which takes 8 to 13 s to a first frame",
)
rejoin_backoff_base_seconds: float = Field(default=2.0, gt=0)
rejoin_backoff_cap_seconds: float = Field(default=60.0, gt=0)

@model_validator(mode="after")
def _backoff_cap_is_not_below_base(self) -> "SimpliSafeSettings":
if self.rejoin_backoff_cap_seconds < self.rejoin_backoff_base_seconds:
raise ValueError(
f"rejoin_backoff_cap_seconds ({self.rejoin_backoff_cap_seconds}) must be "
f">= rejoin_backoff_base_seconds ({self.rejoin_backoff_base_seconds})"
)
return self


class ViewSettings(BaseSettings):
"""Thresholds for deciding whether the camera still sees what the pool zone was traced for."""

Expand Down Expand Up @@ -182,4 +221,5 @@ class Settings(BaseSettings):
tracking: TrackingSettings = Field(default_factory=TrackingSettings)
rules: RulesSettings = Field(default_factory=RulesSettings)
alerts: AlertSettings = Field(default_factory=AlertSettings)
simplisafe: SimpliSafeSettings = Field(default_factory=SimpliSafeSettings)
view: ViewSettings = Field(default_factory=ViewSettings)
65 changes: 65 additions & 0 deletions src/poolguard/scripts/simplisafe_login.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""One-time SimpliSafe sign-in, to obtain the refresh token the live source uses.

Usage:
poolguard-simplisafe-login

1. Open the printed URL in a browser with DevTools open on the Console tab,
and sign in (including the SMS code).
2. The page appears to hang. The console shows a line starting
"Failed to launch 'com.simplisafe.mobile://...". Copy that whole line.
3. Paste it at the prompt here. The code in it is single-use and expires
within about a minute.

The refresh token is written to POOLGUARD_SIMPLISAFE_TOKEN_PATH, readable
only by you. Needed again only if that file is lost or the token is revoked.
"""

import asyncio
from getpass import getpass

from pydantic import SecretStr

from poolguard.config import SimpliSafeSettings
from poolguard.vision.simplisafe_auth import (
RefreshTokenStore,
SimpliSafeAuthError,
extract_authorization_code,
)


async def _exchange(code: str, verifier: str) -> SecretStr:
import aiohttp
from simplipy import API

async with aiohttp.ClientSession() as session:
api = await API.async_from_auth(code, verifier, session=session)
if api.refresh_token is None:
raise SimpliSafeAuthError("SimpliSafe login returned no refresh token")
return SecretStr(api.refresh_token)


def main() -> None:
# Imported here so this module's helpers stay importable without the `simplisafe` extra.
from simplipy.util.auth import (
get_auth0_code_challenge,
get_auth0_code_verifier,
get_auth_url,
)

settings = SimpliSafeSettings()
verifier = get_auth0_code_verifier()
print("Open this URL, sign in, then copy the 'Failed to launch' console line:\n")
print(get_auth_url(get_auth0_code_challenge(verifier)))
# getpass: the code is a credential, so it is not echoed to the terminal.
pasted = getpass("\nPaste the line (input is hidden) and press Enter: ")
try:
code = extract_authorization_code(pasted)
token = asyncio.run(_exchange(code, verifier))
except SimpliSafeAuthError as error:
raise SystemExit(f"login failed: {error}") from None
RefreshTokenStore(settings.token_path).save(token)
print(f"Signed in. Refresh token saved to {settings.token_path}")


if __name__ == "__main__":
main()
134 changes: 134 additions & 0 deletions src/poolguard/scripts/simplisafe_watch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
"""Watch the SimpliSafe camera's live stream and report its health.

Usage:
poolguard-simplisafe-watch

Reads POOLGUARD_SIMPLISAFE_* and POOLGUARD_ALERT_* from the environment or
.env. Runs until interrupted, logging a line a minute with the frame rate.
If POOLGUARD_ALERT_HEARTBEAT_PUSH_URL is set it also pings Uptime Kuma: UP
while frames are fresh, DOWN once the stream has been blind for
POOLGUARD_ALERT_BLIND_AFTER_SECONDS.

No detection runs here yet. This is the bench source on its own, so its
uptime can be measured before the pipeline is wired to it.
"""

import logging
import time
from collections.abc import Callable
from typing import Protocol

import httpx
from pydantic import BaseModel, ConfigDict, Field

from poolguard.alerts.heartbeat import (
HeartbeatError,
HeartbeatPinger,
HeartbeatReport,
HeartbeatStatus,
report_for_frame_age,
)
from poolguard.config import AlertSettings, SimpliSafeSettings
from poolguard.vision.frames import Frame

logger = logging.getLogger(__name__)

POLL_SECONDS = 1.0
REPORT_INTERVAL_SECONDS = 60.0

Ping = Callable[[HeartbeatReport], None]


class WatchableSource(Protocol):
@property
def dropped_frames(self) -> int: ...

def poll(self, timeout_seconds: float) -> Frame | None: ...

def seconds_since_last_frame(self) -> float: ...


class WatchSettings(BaseModel):
model_config = ConfigDict(frozen=True)

blind_after_seconds: float = Field(gt=0)
heartbeat_interval_seconds: float = Field(gt=0)
report_interval_seconds: float = Field(gt=0)


def watch(
source: WatchableSource,
ping: Ping | None,
settings: WatchSettings,
*,
clock: Callable[[], float] = time.monotonic,
should_stop: Callable[[], bool] = lambda: False,
) -> None:
"""Consume frames, logging the rate and reporting health until told to stop."""
last_ping_at = last_report_at = clock()
frames_since_report = 0
while not should_stop():
if source.poll(POLL_SECONDS) is not None:
frames_since_report += 1
now = clock()
if now - last_ping_at >= settings.heartbeat_interval_seconds:
last_ping_at = now
_report_health(source, ping, settings.blind_after_seconds)
if now - last_report_at >= settings.report_interval_seconds:
fps = frames_since_report / (now - last_report_at)
logger.info(
"%.1f fps, last frame %.0f s ago, %d frames dropped unread",
fps,
source.seconds_since_last_frame(),
source.dropped_frames,
)
last_report_at = now
frames_since_report = 0


def _report_health(source: WatchableSource, ping: Ping | None, blind_after_seconds: float) -> None:
report = report_for_frame_age(
source.seconds_since_last_frame(), blind_after_seconds=blind_after_seconds
)
if report.status is HeartbeatStatus.DOWN:
logger.error("stream is blind: %s", report.message)
if ping is None:
return
try:
ping(report)
except HeartbeatError as error:
# A monitoring outage must never stop the watcher.
logger.warning("heartbeat not delivered: %s", error)


def main() -> None:
# Imported here so the loop above stays importable without the `simplisafe` extra.
from poolguard.vision.simplisafe import simplisafe_frame_source

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
# The SDK logs connection URLs and room names at INFO.
logging.getLogger("livekit").setLevel(logging.WARNING)
alerts = AlertSettings()
source = simplisafe_frame_source(SimpliSafeSettings())
settings = WatchSettings(
blind_after_seconds=alerts.blind_after_seconds,
heartbeat_interval_seconds=alerts.heartbeat_interval_seconds,
report_interval_seconds=REPORT_INTERVAL_SECONDS,
)
try:
with httpx.Client() as client:
ping: Ping | None = None
if alerts.heartbeat_push_url is not None:
pinger = HeartbeatPinger(alerts.heartbeat_push_url, client)
ping = lambda report: pinger.ping(report.status, report.message) # noqa: E731
else:
logger.info("no heartbeat URL configured; health is logged only")
watch(source, ping, settings)
except KeyboardInterrupt:
logger.info("stopped")
finally:
source.close()


if __name__ == "__main__":
main()
Loading
Loading