chore: import upstream snapshot with attribution
Firmware QEMU Tests (ADR-061) / QEMU Test (edge-tier1) (push) Has been skipped
Firmware QEMU Tests (ADR-061) / QEMU Test (full-adr060) (push) Has been skipped
Firmware QEMU Tests (ADR-061) / QEMU Test (tdm-3node) (push) Has been skipped
Firmware QEMU Tests (ADR-061) / Swarm Test (ADR-062) (push) Has been skipped
npm packages / tools/ruview-mcp (node 22) (push) Failing after 1s
nvsim-server → ghcr.io / build-and-publish (push) Failing after 1s
ruview-swarm CI guard / tests (full+train) (push) Failing after 2s
Bench Regression Guard / bench compile-verify (--no-run) (push) Failing after 0s
Bench Regression Guard / bench fast-run (informational, non-gating) (push) Has been skipped
Firmware CI / Verify version.txt matches release tag (push) Has been skipped
Dashboard a11y + cross-browser / a11y (push) Failing after 0s
nvsim Dashboard → GitHub Pages / build-and-deploy (push) Failing after 2s
Firmware CI / Build firmware (esp32s3 / 4mb) (push) Failing after 15s
Firmware QEMU Tests (ADR-061) / Build Espressif QEMU (push) Failing after 1s
Firmware QEMU Tests (ADR-061) / Fuzz Testing (ADR-061 Layer 6) (push) Failing after 1s
Continuous Deployment / Pre-deployment Checks (push) Has been skipped
Firmware CI / Build firmware (esp32c6 / c6-4mb) (push) Failing after 15s
Firmware CI / Build firmware (esp32s3 / 8mb) (push) Failing after 15s
Firmware QEMU Tests (ADR-061) / QEMU Test (boundary-max) (push) Has been skipped
Firmware QEMU Tests (ADR-061) / QEMU Test (boundary-min) (push) Has been skipped
Firmware QEMU Tests (ADR-061) / QEMU Test (default) (push) Has been skipped
Firmware QEMU Tests (ADR-061) / QEMU Test (edge-tier0) (push) Has been skipped
Firmware QEMU Tests (ADR-061) / NVS Matrix Generation (push) Failing after 1s
Security Scanning / Security Policy Compliance (push) Failing after 0s
Security Scanning / Dependency Vulnerability Scan (push) Failing after 0s
Security Scanning / Static Application Security Testing (push) Failing after 1s
Security Scanning / Infrastructure Security Scan (push) Failing after 1s
Security Scanning / Secret Scanning (push) Failing after 1s
npm packages / harness/ruview (node 22) (push) Failing after 17s
Security Scanning / License Compliance Scan (push) Failing after 1s
Security Scanning / Container Security Scan (push) Failing after 4s
three.js demos → GitHub Pages / build-and-deploy (push) Failing after 1s
Verify Pipeline Determinism / Verify Pipeline Determinism (3.11) (push) Failing after 1s
Fix-Marker Regression Guard / Verify fix markers (push) Failing after 1s
ADR-115 MQTT integration tests / mqtt-integration (push) Failing after 1s
npm packages / harness/ruview (node 20) (push) Failing after 1s
npm packages / tools/ruview-mcp (node 20) (push) Failing after 1s
npm packages / tools/ruview-cli (node 20) (push) Failing after 1s
npm packages / tools/ruview-cli (node 22) (push) Failing after 1s
BFLD MQTT Integration / cargo test --features mqtt (live mosquitto) (push) Failing after 29s
ruview-swarm CI guard / build train_marl bin (push) Failing after 2s
ruview-swarm CI guard / clippy (-D warnings, --no-deps) (push) Failing after 3s
ruview-swarm CI guard / tests (ruflo) (push) Failing after 1s
ruview-swarm CI guard / tests (train) (push) Failing after 2s
ruview-swarm CI guard / tests (default) (push) Failing after 2s
Point Cloud Viewer → GitHub Pages / build-and-deploy (push) Failing after 8s
ruview-swarm CI guard / ITAR / publish guard (push) Failing after 0s
wifi-densepose sensing-server → Docker Hub + ghcr.io / build · push · smoke-test (push) Failing after 1s
Continuous Deployment / Deploy to Production (push) Has been cancelled
Continuous Deployment / Rollback Deployment (push) Has been cancelled
Continuous Deployment / Post-deployment Monitoring (push) Has been cancelled
Continuous Deployment / Notify Deployment Status (push) Has been cancelled
Continuous Deployment / Deploy to Staging (push) Has been cancelled
Security Scanning / Security Report (push) Has been cancelled
Firmware QEMU Tests (ADR-061) / QEMU Test (edge-tier1) (push) Has been skipped
Firmware QEMU Tests (ADR-061) / QEMU Test (full-adr060) (push) Has been skipped
Firmware QEMU Tests (ADR-061) / QEMU Test (tdm-3node) (push) Has been skipped
Firmware QEMU Tests (ADR-061) / Swarm Test (ADR-062) (push) Has been skipped
npm packages / tools/ruview-mcp (node 22) (push) Failing after 1s
nvsim-server → ghcr.io / build-and-publish (push) Failing after 1s
ruview-swarm CI guard / tests (full+train) (push) Failing after 2s
Bench Regression Guard / bench compile-verify (--no-run) (push) Failing after 0s
Bench Regression Guard / bench fast-run (informational, non-gating) (push) Has been skipped
Firmware CI / Verify version.txt matches release tag (push) Has been skipped
Dashboard a11y + cross-browser / a11y (push) Failing after 0s
nvsim Dashboard → GitHub Pages / build-and-deploy (push) Failing after 2s
Firmware CI / Build firmware (esp32s3 / 4mb) (push) Failing after 15s
Firmware QEMU Tests (ADR-061) / Build Espressif QEMU (push) Failing after 1s
Firmware QEMU Tests (ADR-061) / Fuzz Testing (ADR-061 Layer 6) (push) Failing after 1s
Continuous Deployment / Pre-deployment Checks (push) Has been skipped
Firmware CI / Build firmware (esp32c6 / c6-4mb) (push) Failing after 15s
Firmware CI / Build firmware (esp32s3 / 8mb) (push) Failing after 15s
Firmware QEMU Tests (ADR-061) / QEMU Test (boundary-max) (push) Has been skipped
Firmware QEMU Tests (ADR-061) / QEMU Test (boundary-min) (push) Has been skipped
Firmware QEMU Tests (ADR-061) / QEMU Test (default) (push) Has been skipped
Firmware QEMU Tests (ADR-061) / QEMU Test (edge-tier0) (push) Has been skipped
Firmware QEMU Tests (ADR-061) / NVS Matrix Generation (push) Failing after 1s
Security Scanning / Security Policy Compliance (push) Failing after 0s
Security Scanning / Dependency Vulnerability Scan (push) Failing after 0s
Security Scanning / Static Application Security Testing (push) Failing after 1s
Security Scanning / Infrastructure Security Scan (push) Failing after 1s
Security Scanning / Secret Scanning (push) Failing after 1s
npm packages / harness/ruview (node 22) (push) Failing after 17s
Security Scanning / License Compliance Scan (push) Failing after 1s
Security Scanning / Container Security Scan (push) Failing after 4s
three.js demos → GitHub Pages / build-and-deploy (push) Failing after 1s
Verify Pipeline Determinism / Verify Pipeline Determinism (3.11) (push) Failing after 1s
Fix-Marker Regression Guard / Verify fix markers (push) Failing after 1s
ADR-115 MQTT integration tests / mqtt-integration (push) Failing after 1s
npm packages / harness/ruview (node 20) (push) Failing after 1s
npm packages / tools/ruview-mcp (node 20) (push) Failing after 1s
npm packages / tools/ruview-cli (node 20) (push) Failing after 1s
npm packages / tools/ruview-cli (node 22) (push) Failing after 1s
BFLD MQTT Integration / cargo test --features mqtt (live mosquitto) (push) Failing after 29s
ruview-swarm CI guard / build train_marl bin (push) Failing after 2s
ruview-swarm CI guard / clippy (-D warnings, --no-deps) (push) Failing after 3s
ruview-swarm CI guard / tests (ruflo) (push) Failing after 1s
ruview-swarm CI guard / tests (train) (push) Failing after 2s
ruview-swarm CI guard / tests (default) (push) Failing after 2s
Point Cloud Viewer → GitHub Pages / build-and-deploy (push) Failing after 8s
ruview-swarm CI guard / ITAR / publish guard (push) Failing after 0s
wifi-densepose sensing-server → Docker Hub + ghcr.io / build · push · smoke-test (push) Failing after 1s
Continuous Deployment / Deploy to Production (push) Has been cancelled
Continuous Deployment / Rollback Deployment (push) Has been cancelled
Continuous Deployment / Post-deployment Monitoring (push) Has been cancelled
Continuous Deployment / Notify Deployment Status (push) Has been cancelled
Continuous Deployment / Deploy to Staging (push) Has been cancelled
Security Scanning / Security Report (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
"""WiFi-DensePose — passive human sensing from WiFi CSI.
|
||||
|
||||
ADR-117 — v2.0 is a PyO3-bound replacement for the legacy pure-Python
|
||||
``wifi-densepose==1.1.0`` (released 2025-06-07). The compiled core is
|
||||
the same Rust workspace published in `v2/crates/` of the
|
||||
`ruvnet/RuView <https://github.com/ruvnet/RuView>`_ repository.
|
||||
|
||||
Quick start::
|
||||
|
||||
import wifi_densepose
|
||||
print(wifi_densepose.__version__)
|
||||
print(wifi_densepose.__rust_version__)
|
||||
print(wifi_densepose.hello()) # → "ok"
|
||||
|
||||
P1 (this release): scaffold. Core types land in P2; vital signs +
|
||||
signal DSP in P3; WebSocket/MQTT client in P4. See the
|
||||
`ADR-117 modernization plan
|
||||
<https://github.com/ruvnet/RuView/blob/main/docs/adr/ADR-117-pip-wifi-densepose-modernization.md>`_
|
||||
for the full phase ledger.
|
||||
|
||||
Migrating from v1.x: the v1 line was pure-Python and had a different
|
||||
API surface. v2 is a hard break (semver-justified). See the
|
||||
``v1.99.0`` tombstone wheel for the migration URL.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# Public Python version follows the wheel version, NOT the Rust core
|
||||
# version. The Rust core version is surfaced separately as
|
||||
# `__rust_version__` for diagnostics.
|
||||
__version__ = "2.0.0a1"
|
||||
|
||||
# Re-export the compiled module's surface. The leading underscore on
|
||||
# `_native` is intentional — it marks the binding module as internal.
|
||||
# Users always import from `wifi_densepose` directly.
|
||||
from wifi_densepose import _native
|
||||
|
||||
# ─── P2 — Core type re-exports ───────────────────────────────────────
|
||||
# Bound types land in `wifi_densepose._native` and are re-exported here
|
||||
# under their stable public names. Users always `from wifi_densepose
|
||||
# import Keypoint, KeypointType` — never reach into `_native`.
|
||||
Keypoint = _native.Keypoint
|
||||
KeypointType = _native.KeypointType
|
||||
BoundingBox = _native.BoundingBox
|
||||
PersonPose = _native.PersonPose
|
||||
PoseEstimate = _native.PoseEstimate
|
||||
|
||||
# ─── P3 — Vital sign extraction ──────────────────────────────────────
|
||||
VitalStatus = _native.VitalStatus
|
||||
VitalEstimate = _native.VitalEstimate
|
||||
VitalReading = _native.VitalReading
|
||||
BreathingExtractor = _native.BreathingExtractor
|
||||
HeartRateExtractor = _native.HeartRateExtractor
|
||||
|
||||
# ─── P3.5 — BFLD (Beamforming Feedback Loop Data) ─────────────────────
|
||||
BfldKind = _native.BfldKind
|
||||
BfldFrame = _native.BfldFrame
|
||||
BfldReport = _native.BfldReport
|
||||
|
||||
|
||||
__rust_version__: str = _native.__rust_version__
|
||||
"""Version of the bound Rust core. Useful for bug reports."""
|
||||
|
||||
__rust_build_tag__: str = _native.__rust_build_tag__
|
||||
"""Build tag of the Rust core (P5 will swap this for the git SHA)."""
|
||||
|
||||
__build_features__: list[str] = list(_native.__build_features__)
|
||||
"""Feature flags the wheel was compiled with."""
|
||||
|
||||
|
||||
def hello() -> str:
|
||||
"""Smoke test — confirms the compiled module loads and is callable.
|
||||
|
||||
Returns:
|
||||
Always ``"ok"`` if the wheel built and loaded correctly.
|
||||
|
||||
Used by ``python/tests/test_smoke.py`` to assert the PyO3 round-trip
|
||||
works end-to-end on every cibuildwheel target.
|
||||
"""
|
||||
return _native.hello()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"__version__",
|
||||
"__rust_version__",
|
||||
"__rust_build_tag__",
|
||||
"__build_features__",
|
||||
"hello",
|
||||
# P2 — core types
|
||||
"Keypoint",
|
||||
"KeypointType",
|
||||
"BoundingBox",
|
||||
"PersonPose",
|
||||
"PoseEstimate",
|
||||
# P3 — vital sign extraction
|
||||
"VitalStatus",
|
||||
"VitalEstimate",
|
||||
"VitalReading",
|
||||
"BreathingExtractor",
|
||||
"HeartRateExtractor",
|
||||
# P3.5 — BFLD (forward-compat surface for the future Rust crate)
|
||||
"BfldKind",
|
||||
"BfldFrame",
|
||||
"BfldReport",
|
||||
]
|
||||
@@ -0,0 +1,93 @@
|
||||
"""ADR-117 P4 — Pure-Python client layer.
|
||||
|
||||
This sub-package is the **client-facing** half of `wifi-densepose`:
|
||||
end users who only want to *consume* live RuView telemetry (rather than
|
||||
running DSP locally) get a tight, opt-in client extra:
|
||||
|
||||
```
|
||||
pip install "wifi-densepose[client]"
|
||||
```
|
||||
|
||||
The runtime install footprint stays small for users who only need the
|
||||
compiled PyO3 surface: `websockets` and `paho-mqtt` are declared as the
|
||||
`[client]` extra in `pyproject.toml` and are NOT pulled in by the
|
||||
default install.
|
||||
|
||||
## Modules
|
||||
|
||||
- `ws` — `SensingClient`: asyncio WebSocket client for the
|
||||
sensing-server `/ws/sensing` endpoint (ADR-115 §1)
|
||||
- `mqtt` — `RuViewMqttClient`: paho-mqtt v2 wrapper for
|
||||
`ruview/<node>/raw/+` + `homeassistant/+/wifi_densepose_<node>/+/+`
|
||||
topics (ADR-115 §3)
|
||||
- `primitives` — `SemanticPrimitiveListener`: typed view over the
|
||||
10 HA-MIND semantic primitives (ADR-115 §3.12)
|
||||
- `ha` — `HABlueprintHelper`: parses MQTT-discovery payloads, helps
|
||||
users introspect what entities a node is publishing
|
||||
|
||||
No PyO3 here — this module is pure Python so it loads without the
|
||||
compiled extension (useful for users who only want the client surface
|
||||
and not the DSP pipeline).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# Re-export the user-facing types. Import errors are deferred to the
|
||||
# moment the user actually instantiates one of these classes — that way
|
||||
# `from wifi_densepose.client import HABlueprintHelper` still works
|
||||
# even if the user hasn't installed `[client]` extras yet (HABlueprint
|
||||
# is pure stdlib).
|
||||
from wifi_densepose.client.ha import (
|
||||
HaDiscoveryPayload,
|
||||
HaEntity,
|
||||
HABlueprintHelper,
|
||||
)
|
||||
from wifi_densepose.client.primitives import (
|
||||
SemanticPrimitive,
|
||||
SemanticPrimitiveEvent,
|
||||
SemanticPrimitiveListener,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
# ws — re-exported lazily; see module docstring
|
||||
"SensingClient",
|
||||
"SensingMessage",
|
||||
"EdgeVitalsMessage",
|
||||
"PoseDataMessage",
|
||||
"ConnectionEstablishedMessage",
|
||||
# mqtt — re-exported lazily; see module docstring
|
||||
"RuViewMqttClient",
|
||||
# ha — pure stdlib
|
||||
"HaDiscoveryPayload",
|
||||
"HaEntity",
|
||||
"HABlueprintHelper",
|
||||
# primitives — pure stdlib
|
||||
"SemanticPrimitive",
|
||||
"SemanticPrimitiveEvent",
|
||||
"SemanticPrimitiveListener",
|
||||
]
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
"""Lazy re-exports for the modules that pull in optional extras.
|
||||
|
||||
`SensingClient` needs `websockets`; `RuViewMqttClient` needs
|
||||
`paho-mqtt`. Importing those at package init would make
|
||||
`wifi_densepose.client` unusable without the extras installed
|
||||
— defeating the point of an *optional* extra. We defer the import
|
||||
until the attribute is actually looked up.
|
||||
"""
|
||||
if name in {
|
||||
"SensingClient",
|
||||
"SensingMessage",
|
||||
"EdgeVitalsMessage",
|
||||
"PoseDataMessage",
|
||||
"ConnectionEstablishedMessage",
|
||||
}:
|
||||
from wifi_densepose.client import ws as _ws
|
||||
return getattr(_ws, name)
|
||||
if name == "RuViewMqttClient":
|
||||
from wifi_densepose.client.mqtt import RuViewMqttClient as _R
|
||||
return _R
|
||||
raise AttributeError(f"module 'wifi_densepose.client' has no attribute {name!r}")
|
||||
@@ -0,0 +1,194 @@
|
||||
"""ADR-117 P4 — Home Assistant MQTT-discovery payload helpers.
|
||||
|
||||
Parses the `homeassistant/<entity_kind>/wifi_densepose_<node>/<id>/config`
|
||||
discovery payloads described in ADR-115 §3 into typed Python objects so
|
||||
client code can introspect what a node is publishing without
|
||||
hand-parsing JSON.
|
||||
|
||||
This is **read-only**: we do NOT generate discovery payloads from
|
||||
Python (that's the sensing-server's job). The helper exists so a
|
||||
client (HA blueprint author, debugger, dashboard) can ask "what
|
||||
entities does this node expose?" and get a structured answer.
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
from wifi_densepose.client import HaDiscoveryPayload, HABlueprintHelper
|
||||
|
||||
helper = HABlueprintHelper()
|
||||
helper.add_payload(topic, json_bytes)
|
||||
for entity in helper.entities_for_node("aabbccddeeff"):
|
||||
print(entity.entity_kind, entity.object_id, entity.unique_id)
|
||||
```
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Iterable
|
||||
|
||||
|
||||
# ─── Topic schema ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
# Matches discovery topics like:
|
||||
# homeassistant/binary_sensor/wifi_densepose_aabbccddeeff/presence/config
|
||||
# homeassistant/sensor/wifi_densepose_aabbccddeeff/heart_rate/config
|
||||
# homeassistant/event/wifi_densepose_aabbccddeeff/fall/config
|
||||
_DISCOVERY_TOPIC_RE = re.compile(
|
||||
r"^homeassistant/"
|
||||
r"(?P<entity_kind>[A-Za-z_]+)/"
|
||||
r"wifi_densepose_(?P<node_id>[A-Za-z0-9]+)/"
|
||||
r"(?P<object_id>[A-Za-z0-9_\-]+)/"
|
||||
r"config$"
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HaDiscoveryPayload:
|
||||
"""One MQTT discovery payload (config topic + JSON body)."""
|
||||
entity_kind: str # "binary_sensor", "sensor", "event", "switch", ...
|
||||
node_id: str # the node's MAC-ish identifier
|
||||
object_id: str # entity slug (e.g. "presence", "heart_rate")
|
||||
payload: dict[str, Any]
|
||||
|
||||
@property
|
||||
def topic(self) -> str:
|
||||
return (
|
||||
f"homeassistant/{self.entity_kind}/"
|
||||
f"wifi_densepose_{self.node_id}/{self.object_id}/config"
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HaEntity:
|
||||
"""A user-facing view of one HA entity registered by a node."""
|
||||
entity_kind: str
|
||||
node_id: str
|
||||
object_id: str
|
||||
unique_id: str = ""
|
||||
name: str = ""
|
||||
state_topic: str = ""
|
||||
device_class: str = ""
|
||||
unit_of_measurement: str = ""
|
||||
icon: str = ""
|
||||
json_attributes_topic: str = ""
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, p: HaDiscoveryPayload) -> "HaEntity":
|
||||
body = p.payload
|
||||
return cls(
|
||||
entity_kind=p.entity_kind,
|
||||
node_id=p.node_id,
|
||||
object_id=p.object_id,
|
||||
unique_id=str(body.get("unique_id", "")),
|
||||
name=str(body.get("name", "")),
|
||||
state_topic=str(body.get("state_topic", "")),
|
||||
device_class=str(body.get("device_class", "")),
|
||||
unit_of_measurement=str(body.get("unit_of_measurement", "")),
|
||||
icon=str(body.get("icon", "")),
|
||||
json_attributes_topic=str(body.get("json_attributes_topic", "")),
|
||||
)
|
||||
|
||||
|
||||
def parse_discovery_topic(topic: str) -> tuple[str, str, str] | None:
|
||||
"""Parse a discovery config topic into (entity_kind, node_id,
|
||||
object_id). Returns None for non-discovery topics."""
|
||||
m = _DISCOVERY_TOPIC_RE.match(topic)
|
||||
if not m:
|
||||
return None
|
||||
return (m.group("entity_kind"), m.group("node_id"), m.group("object_id"))
|
||||
|
||||
|
||||
def parse_discovery_payload(
|
||||
topic: str, payload: bytes | str | dict[str, Any]
|
||||
) -> HaDiscoveryPayload | None:
|
||||
"""Decode an HA discovery payload. Returns None for non-discovery
|
||||
topics OR malformed JSON; raises only on programmer error."""
|
||||
parsed = parse_discovery_topic(topic)
|
||||
if parsed is None:
|
||||
return None
|
||||
entity_kind, node_id, object_id = parsed
|
||||
body: dict[str, Any]
|
||||
if isinstance(payload, dict):
|
||||
body = payload
|
||||
else:
|
||||
if isinstance(payload, bytes):
|
||||
try:
|
||||
payload = payload.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
return None
|
||||
try:
|
||||
decoded = json.loads(payload)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
if not isinstance(decoded, dict):
|
||||
return None
|
||||
body = decoded
|
||||
return HaDiscoveryPayload(
|
||||
entity_kind=entity_kind,
|
||||
node_id=node_id,
|
||||
object_id=object_id,
|
||||
payload=body,
|
||||
)
|
||||
|
||||
|
||||
# ─── Helper / aggregator ─────────────────────────────────────────────
|
||||
|
||||
|
||||
class HABlueprintHelper:
|
||||
"""Aggregates HA discovery payloads observed on the bus and offers
|
||||
structured queries against them.
|
||||
|
||||
Intended use: subscribe a RuViewMqttClient to
|
||||
`homeassistant/+/wifi_densepose_+/+/config`, feed every message
|
||||
into `add_payload()`, then ask the helper "what entities does
|
||||
node X expose?" or "what binary_sensors are presence-class?".
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
# (node_id, entity_kind, object_id) → HaDiscoveryPayload
|
||||
self._payloads: dict[tuple[str, str, str], HaDiscoveryPayload] = {}
|
||||
|
||||
def add_payload(self, topic: str, payload: bytes | str | dict[str, Any]) -> bool:
|
||||
"""Returns True if the payload was a valid HA discovery
|
||||
message and was stored; False otherwise."""
|
||||
parsed = parse_discovery_payload(topic, payload)
|
||||
if parsed is None:
|
||||
return False
|
||||
self._payloads[(parsed.node_id, parsed.entity_kind, parsed.object_id)] = parsed
|
||||
return True
|
||||
|
||||
def remove(self, node_id: str, entity_kind: str, object_id: str) -> bool:
|
||||
"""Drop a stored payload — useful when handling a discovery
|
||||
retain-flag clear (HA's convention for removing an entity)."""
|
||||
return self._payloads.pop((node_id, entity_kind, object_id), None) is not None
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self._payloads)
|
||||
|
||||
def __contains__(self, item: tuple[str, str, str]) -> bool:
|
||||
return item in self._payloads
|
||||
|
||||
def all_payloads(self) -> list[HaDiscoveryPayload]:
|
||||
return list(self._payloads.values())
|
||||
|
||||
def entities_for_node(self, node_id: str) -> list[HaEntity]:
|
||||
return [
|
||||
HaEntity.from_payload(p)
|
||||
for p in self._payloads.values()
|
||||
if p.node_id == node_id
|
||||
]
|
||||
|
||||
def nodes(self) -> list[str]:
|
||||
return sorted({p.node_id for p in self._payloads.values()})
|
||||
|
||||
def by_device_class(self, device_class: str) -> list[HaEntity]:
|
||||
out: list[HaEntity] = []
|
||||
for p in self._payloads.values():
|
||||
e = HaEntity.from_payload(p)
|
||||
if e.device_class == device_class:
|
||||
out.append(e)
|
||||
return out
|
||||
@@ -0,0 +1,257 @@
|
||||
"""ADR-117 P4 — paho-mqtt v2 wrapper for RuView MQTT topics.
|
||||
|
||||
Subscribes to the topic namespaces defined in ADR-115:
|
||||
|
||||
- `ruview/<node>/raw/edge_vitals` — opt-in firehose of the WS edge_vitals
|
||||
- `ruview/<node>/raw/pose` — opt-in firehose of pose data
|
||||
- `ruview/<node>/raw/sensing_update` — opt-in firehose of every sensing update
|
||||
- `homeassistant/+/wifi_densepose_<node>/+/config` — HA discovery payloads
|
||||
- `homeassistant/+/wifi_densepose_<node>/+/state` — HA state payloads
|
||||
|
||||
The client uses **paho-mqtt v2's `Client(CallbackAPIVersion.VERSION2)`**
|
||||
API explicitly. v1's deprecated callback signatures will not work.
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
from wifi_densepose.client import RuViewMqttClient
|
||||
|
||||
def on_edge_vitals(topic, payload):
|
||||
print(topic, payload["breathing_rate_bpm"])
|
||||
|
||||
client = RuViewMqttClient(broker_host="localhost", broker_port=1883)
|
||||
client.on_message("ruview/+/raw/edge_vitals", on_edge_vitals)
|
||||
client.start()
|
||||
# ... runs in a background thread; call client.stop() to disconnect
|
||||
```
|
||||
|
||||
The constructor never connects; call `.start()` to enter the network
|
||||
loop and `.stop()` to disconnect cleanly. Both are idempotent.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import uuid
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
try:
|
||||
import paho.mqtt.client as mqtt # type: ignore[import-not-found]
|
||||
from paho.mqtt.enums import CallbackAPIVersion # type: ignore[import-not-found]
|
||||
_PAHO_AVAILABLE = True
|
||||
except ImportError: # pragma: no cover
|
||||
_PAHO_AVAILABLE = False
|
||||
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
MessageHandler = Callable[[str, Any], None]
|
||||
"""(topic, decoded_payload) → None. The payload is JSON-decoded if the
|
||||
content is valid JSON, otherwise the raw bytes are passed through."""
|
||||
|
||||
|
||||
class RuViewMqttClient:
|
||||
"""Wrapper around paho-mqtt v2 with per-topic-pattern callbacks.
|
||||
|
||||
Per the rumqttc lesson [[feedback_mqtt_integration_test_patterns]]:
|
||||
- Each instance gets a unique client_id (per-test isolation when
|
||||
tests run in parallel against the same broker).
|
||||
- Subscription wildcards (`+`, `#`) are supported by paho's
|
||||
built-in matcher; we route by exact pattern match against the
|
||||
registered handler.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
broker_host: str = "localhost",
|
||||
broker_port: int = 1883,
|
||||
client_id: Optional[str] = None,
|
||||
username: Optional[str] = None,
|
||||
password: Optional[str] = None,
|
||||
keepalive: int = 60,
|
||||
tls: bool = False,
|
||||
) -> None:
|
||||
if not _PAHO_AVAILABLE:
|
||||
raise ImportError(
|
||||
"RuViewMqttClient requires the `paho-mqtt` package. Install with "
|
||||
"`pip install \"wifi-densepose[client]\"` to enable the client extras."
|
||||
)
|
||||
self.broker_host = broker_host
|
||||
self.broker_port = broker_port
|
||||
self.keepalive = keepalive
|
||||
self._client_id = client_id or f"wifi-densepose-client-{uuid.uuid4().hex[:12]}"
|
||||
self._handlers: dict[str, MessageHandler] = {}
|
||||
self._handlers_lock = threading.Lock()
|
||||
self._client = mqtt.Client(
|
||||
callback_api_version=CallbackAPIVersion.VERSION2,
|
||||
client_id=self._client_id,
|
||||
clean_session=True,
|
||||
)
|
||||
if username is not None:
|
||||
self._client.username_pw_set(username, password)
|
||||
if tls:
|
||||
self._client.tls_set()
|
||||
self._client.on_connect = self._on_connect
|
||||
self._client.on_message = self._on_message
|
||||
self._client.on_disconnect = self._on_disconnect
|
||||
self._started = False
|
||||
self._connected_event = threading.Event()
|
||||
|
||||
@property
|
||||
def client_id(self) -> str:
|
||||
return self._client_id
|
||||
|
||||
@property
|
||||
def connected(self) -> bool:
|
||||
return self._connected_event.is_set()
|
||||
|
||||
# ── handler registration ─────────────────────────────────────────
|
||||
|
||||
def on_message(self, topic_pattern: str, handler: MessageHandler) -> None:
|
||||
"""Register a handler for a topic pattern. Replaces any
|
||||
previous handler for the same pattern."""
|
||||
with self._handlers_lock:
|
||||
self._handlers[topic_pattern] = handler
|
||||
|
||||
def unsubscribe_handler(self, topic_pattern: str) -> None:
|
||||
with self._handlers_lock:
|
||||
self._handlers.pop(topic_pattern, None)
|
||||
if self._started:
|
||||
self._client.unsubscribe(topic_pattern)
|
||||
|
||||
# ── lifecycle ────────────────────────────────────────────────────
|
||||
|
||||
def start(self) -> None:
|
||||
"""Connect to the broker and enter the network loop in a
|
||||
background thread. Idempotent."""
|
||||
if self._started:
|
||||
return
|
||||
self._client.connect(self.broker_host, self.broker_port, self.keepalive)
|
||||
self._client.loop_start()
|
||||
self._started = True
|
||||
|
||||
def wait_connected(self, timeout: float = 5.0) -> bool:
|
||||
"""Block until CONNACK has been received. Returns True on
|
||||
connect, False on timeout. Mirrors the rumqttc SubAck pump
|
||||
pattern but for paho's connect step."""
|
||||
return self._connected_event.wait(timeout=timeout)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Disconnect and stop the network loop. Idempotent."""
|
||||
if not self._started:
|
||||
return
|
||||
try:
|
||||
self._client.disconnect()
|
||||
except Exception as e: # pragma: no cover — best-effort
|
||||
log.debug("ignored mqtt disconnect error: %r", e)
|
||||
try:
|
||||
self._client.loop_stop()
|
||||
except Exception as e: # pragma: no cover
|
||||
log.debug("ignored mqtt loop_stop error: %r", e)
|
||||
self._started = False
|
||||
self._connected_event.clear()
|
||||
|
||||
def publish(
|
||||
self,
|
||||
topic: str,
|
||||
payload: Any,
|
||||
*,
|
||||
qos: int = 0,
|
||||
retain: bool = False,
|
||||
) -> None:
|
||||
"""Publish a payload. Dicts/lists are JSON-encoded; bytes pass
|
||||
through; strings are encoded UTF-8."""
|
||||
if isinstance(payload, (dict, list)):
|
||||
data: Any = json.dumps(payload, default=str)
|
||||
else:
|
||||
data = payload
|
||||
info = self._client.publish(topic, data, qos=qos, retain=retain)
|
||||
# paho v2 returns MQTTMessageInfo; rc != MQTT_ERR_SUCCESS is a
|
||||
# broker-side error we should propagate so callers don't think
|
||||
# the publish succeeded.
|
||||
if info.rc != mqtt.MQTT_ERR_SUCCESS:
|
||||
raise RuntimeError(f"mqtt publish failed: topic={topic} rc={info.rc}")
|
||||
|
||||
# ── paho callbacks (v2 signatures) ───────────────────────────────
|
||||
|
||||
def _on_connect(self, client: Any, _userdata: Any, _flags: Any, reason_code: Any, _properties: Any = None) -> None:
|
||||
# paho v2 passes ReasonCode; success is 0 ("Success" / Granted_QoS_0)
|
||||
rc = int(reason_code) if hasattr(reason_code, "__int__") else reason_code
|
||||
if rc == 0:
|
||||
self._connected_event.set()
|
||||
# Re-subscribe to all known patterns. Important after a
|
||||
# reconnect — paho doesn't auto-resubscribe with
|
||||
# clean_session=True.
|
||||
with self._handlers_lock:
|
||||
patterns = list(self._handlers.keys())
|
||||
for pattern in patterns:
|
||||
client.subscribe(pattern)
|
||||
log.debug("mqtt CONNACK ok; subscribed to %d pattern(s)", len(patterns))
|
||||
else:
|
||||
log.warning("mqtt CONNACK with non-success rc=%r", reason_code)
|
||||
|
||||
def _on_disconnect(self, _client: Any, _userdata: Any, _flags: Any = None, reason_code: Any = None, _properties: Any = None) -> None:
|
||||
self._connected_event.clear()
|
||||
log.debug("mqtt disconnected rc=%r", reason_code)
|
||||
|
||||
def _on_message(self, _client: Any, _userdata: Any, message: Any) -> None:
|
||||
topic = message.topic
|
||||
# Best-effort JSON decode — fall back to raw bytes if it's not JSON.
|
||||
payload: Any
|
||||
try:
|
||||
payload = json.loads(message.payload.decode("utf-8"))
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
payload = message.payload
|
||||
|
||||
with self._handlers_lock:
|
||||
handlers = list(self._handlers.items())
|
||||
|
||||
for pattern, handler in handlers:
|
||||
if _topic_matches(pattern, topic):
|
||||
try:
|
||||
handler(topic, payload)
|
||||
except Exception as e: # never let a user callback crash the loop
|
||||
log.exception("handler for pattern %r raised: %r", pattern, e)
|
||||
|
||||
# ── re-subscribe on demand ──────────────────────────────────────
|
||||
|
||||
def subscribe_registered(self) -> None:
|
||||
"""Explicitly issue SUBSCRIBE for every registered handler.
|
||||
Useful when you registered handlers AFTER calling start().
|
||||
"""
|
||||
if not self._started:
|
||||
return
|
||||
with self._handlers_lock:
|
||||
patterns = list(self._handlers.keys())
|
||||
for pattern in patterns:
|
||||
self._client.subscribe(pattern)
|
||||
|
||||
|
||||
# ─── Topic-pattern matching ──────────────────────────────────────────
|
||||
|
||||
|
||||
def _topic_matches(pattern: str, topic: str) -> bool:
|
||||
"""MQTT topic wildcard matcher.
|
||||
|
||||
- `+` matches exactly one topic level
|
||||
- `#` matches one or more remaining levels (must be the final segment)
|
||||
"""
|
||||
p_parts = pattern.split("/")
|
||||
t_parts = topic.split("/")
|
||||
i = 0
|
||||
while i < len(p_parts):
|
||||
if p_parts[i] == "#":
|
||||
return i == len(p_parts) - 1 and len(t_parts) >= i
|
||||
if i >= len(t_parts):
|
||||
return False
|
||||
if p_parts[i] == "+":
|
||||
i += 1
|
||||
continue
|
||||
if p_parts[i] != t_parts[i]:
|
||||
return False
|
||||
i += 1
|
||||
return len(p_parts) == len(t_parts)
|
||||
@@ -0,0 +1,222 @@
|
||||
"""ADR-117 P4 — Typed listener for HA-MIND semantic primitives.
|
||||
|
||||
ADR-115 §3.12 defines 10 fused inference outputs that the sensing-server
|
||||
publishes under the HA-DISCO MQTT namespace. This module gives clients
|
||||
a typed handle on them so they can write `if event.kind ==
|
||||
SemanticPrimitive.SomeoneSleeping: ...` instead of pattern-matching
|
||||
strings.
|
||||
|
||||
The 10 v1 primitives (ADR-115 §3.12.1):
|
||||
|
||||
| Enum value | Topic suffix | Output kind |
|
||||
|---|---|---|
|
||||
| `SomeoneSleeping` | `someone_sleeping` | binary_sensor |
|
||||
| `PossibleDistress` | `possible_distress` | binary_sensor + event |
|
||||
| `RoomActive` | `room_active` | binary_sensor |
|
||||
| `ElderlyInactivityAnomaly` | `elderly_inactivity` | binary_sensor + event |
|
||||
| `MeetingInProgress` | `meeting_in_progress` | binary_sensor |
|
||||
| `BathroomOccupied` | `bathroom_occupied` | binary_sensor |
|
||||
| `FallRiskElevated` | `fall_risk_elevated` | sensor (0–100) + event |
|
||||
| `BedExit` | `bed_exit` | event |
|
||||
| `NoMovementSafety` | `no_movement_safety` | binary_sensor + event |
|
||||
| `MultiRoomTransition` | `multi_room_transition` | event |
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
|
||||
# ─── Enum ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class SemanticPrimitive(enum.Enum):
|
||||
"""One of the 10 HA-MIND fused inference outputs."""
|
||||
SomeoneSleeping = "someone_sleeping"
|
||||
PossibleDistress = "possible_distress"
|
||||
RoomActive = "room_active"
|
||||
ElderlyInactivityAnomaly = "elderly_inactivity"
|
||||
MeetingInProgress = "meeting_in_progress"
|
||||
BathroomOccupied = "bathroom_occupied"
|
||||
FallRiskElevated = "fall_risk_elevated"
|
||||
BedExit = "bed_exit"
|
||||
NoMovementSafety = "no_movement_safety"
|
||||
MultiRoomTransition = "multi_room_transition"
|
||||
|
||||
@classmethod
|
||||
def from_object_id(cls, object_id: str) -> Optional["SemanticPrimitive"]:
|
||||
for v in cls:
|
||||
if v.value == object_id:
|
||||
return v
|
||||
return None
|
||||
|
||||
|
||||
# ─── Event payload ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SemanticPrimitiveEvent:
|
||||
"""A single fired event for one semantic primitive.
|
||||
|
||||
`state` semantics depend on the primitive kind:
|
||||
- binary_sensor: "ON" / "OFF"
|
||||
- sensor: numeric string (e.g. "73" for fall_risk_elevated 0–100)
|
||||
- event: "fired" or an event-class string like "bed_exit_detected"
|
||||
"""
|
||||
kind: SemanticPrimitive
|
||||
node_id: str
|
||||
state: str
|
||||
confidence: float = 0.0
|
||||
explanation: tuple[str, ...] = ()
|
||||
timestamp: float = 0.0
|
||||
raw: dict[str, Any] = field(default_factory=dict, hash=False, compare=False)
|
||||
|
||||
|
||||
# ─── Listener ────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
Callback = Callable[[SemanticPrimitiveEvent], None]
|
||||
|
||||
|
||||
class SemanticPrimitiveListener:
|
||||
"""Routes raw MQTT state messages to per-primitive callbacks.
|
||||
|
||||
Designed to plug into RuViewMqttClient:
|
||||
|
||||
```python
|
||||
from wifi_densepose.client import (
|
||||
RuViewMqttClient, SemanticPrimitive, SemanticPrimitiveListener
|
||||
)
|
||||
|
||||
listener = SemanticPrimitiveListener()
|
||||
listener.on(SemanticPrimitive.SomeoneSleeping, lambda e: print(e))
|
||||
|
||||
client = RuViewMqttClient()
|
||||
client.on_message(
|
||||
"homeassistant/+/wifi_densepose_+/+/state",
|
||||
listener.handle_mqtt_message,
|
||||
)
|
||||
client.start()
|
||||
```
|
||||
|
||||
The listener itself never touches MQTT — it's a pure router. You
|
||||
feed it `(topic, payload)` pairs and it figures out which primitive
|
||||
the topic refers to and decodes the payload.
|
||||
"""
|
||||
|
||||
# Matches state topics for any of the 10 primitives.
|
||||
# homeassistant/<kind>/wifi_densepose_<node>/<primitive_slug>/state
|
||||
_SLUGS = {p.value for p in SemanticPrimitive}
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._handlers: dict[Optional[SemanticPrimitive], list[Callback]] = {}
|
||||
|
||||
def on(self, primitive: SemanticPrimitive, cb: Callback) -> None:
|
||||
"""Register a callback for a specific primitive."""
|
||||
self._handlers.setdefault(primitive, []).append(cb)
|
||||
|
||||
def on_any(self, cb: Callback) -> None:
|
||||
"""Register a callback that fires for ALL primitives. Useful
|
||||
for logging or dashboards."""
|
||||
self._handlers.setdefault(None, []).append(cb)
|
||||
|
||||
def handle_mqtt_message(self, topic: str, payload: Any) -> Optional[SemanticPrimitiveEvent]:
|
||||
"""Decode one MQTT message into a SemanticPrimitiveEvent and
|
||||
fire the matching callbacks. Returns the event (or None if the
|
||||
topic was not a semantic-primitive state topic)."""
|
||||
parts = topic.split("/")
|
||||
# Shape: homeassistant / <kind> / wifi_densepose_<node> / <slug> / state
|
||||
if len(parts) != 5:
|
||||
return None
|
||||
if parts[0] != "homeassistant" or parts[4] != "state":
|
||||
return None
|
||||
node_prefix = parts[2]
|
||||
if not node_prefix.startswith("wifi_densepose_"):
|
||||
return None
|
||||
slug = parts[3]
|
||||
if slug not in self._SLUGS:
|
||||
return None
|
||||
|
||||
primitive = SemanticPrimitive.from_object_id(slug)
|
||||
if primitive is None: # pragma: no cover — guarded above
|
||||
return None
|
||||
|
||||
node_id = node_prefix[len("wifi_densepose_"):]
|
||||
event = _decode_event(primitive, node_id, payload)
|
||||
|
||||
# Dispatch — primitive-specific first, then "any" handlers.
|
||||
for cb in self._handlers.get(primitive, ()):
|
||||
cb(event)
|
||||
for cb in self._handlers.get(None, ()):
|
||||
cb(event)
|
||||
return event
|
||||
|
||||
|
||||
def _decode_event(
|
||||
primitive: SemanticPrimitive,
|
||||
node_id: str,
|
||||
payload: Any,
|
||||
) -> SemanticPrimitiveEvent:
|
||||
"""Decode a raw state payload into a typed event.
|
||||
|
||||
HA state payloads come in two shapes:
|
||||
1. Plain string ("ON", "OFF", "73") — used by binary_sensor/sensor
|
||||
with no json_attributes_topic.
|
||||
2. JSON object with `state` + `confidence` + `explanation` fields —
|
||||
used by HA-MIND semantic primitives per ADR-115 §3.12.4.
|
||||
|
||||
Both are supported transparently.
|
||||
"""
|
||||
if isinstance(payload, bytes):
|
||||
try:
|
||||
payload = payload.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
return SemanticPrimitiveEvent(
|
||||
kind=primitive, node_id=node_id, state="", raw={}
|
||||
)
|
||||
|
||||
if isinstance(payload, dict):
|
||||
body = payload
|
||||
elif isinstance(payload, str):
|
||||
# Try to JSON-decode; if it's not JSON, treat as a plain state string.
|
||||
try:
|
||||
decoded = json.loads(payload)
|
||||
except json.JSONDecodeError:
|
||||
return SemanticPrimitiveEvent(
|
||||
kind=primitive,
|
||||
node_id=node_id,
|
||||
state=payload,
|
||||
raw={"state": payload},
|
||||
)
|
||||
if isinstance(decoded, dict):
|
||||
body = decoded
|
||||
else:
|
||||
return SemanticPrimitiveEvent(
|
||||
kind=primitive,
|
||||
node_id=node_id,
|
||||
state=str(decoded),
|
||||
raw={"state": decoded},
|
||||
)
|
||||
else:
|
||||
return SemanticPrimitiveEvent(
|
||||
kind=primitive, node_id=node_id, state=str(payload), raw={}
|
||||
)
|
||||
|
||||
expl = body.get("explanation") or body.get("reason") or ()
|
||||
if isinstance(expl, str):
|
||||
expl_tuple: tuple[str, ...] = (expl,)
|
||||
else:
|
||||
expl_tuple = tuple(str(x) for x in expl)
|
||||
|
||||
return SemanticPrimitiveEvent(
|
||||
kind=primitive,
|
||||
node_id=node_id,
|
||||
state=str(body.get("state", "")),
|
||||
confidence=float(body.get("confidence", 0.0)),
|
||||
explanation=expl_tuple,
|
||||
timestamp=float(body.get("timestamp", 0.0)),
|
||||
raw=body,
|
||||
)
|
||||
@@ -0,0 +1,256 @@
|
||||
"""ADR-117 P4 — Asyncio WebSocket client for the sensing-server.
|
||||
|
||||
The Rust sensing-server (`v2/crates/wifi-densepose-sensing-server`)
|
||||
broadcasts three structured message types over `ws://<host>:<port>/ws/sensing`:
|
||||
|
||||
| `type` field | Source line in main.rs | Payload shape |
|
||||
|---|---|---|
|
||||
| `connection_established` | 2596 | `{node_id, version, capabilities}` |
|
||||
| `pose_data` | 2655 | `{node_id, timestamp, persons: [...], confidence}` |
|
||||
| `edge_vitals` | 4548 | `{node_id, presence, fall_detected, motion, breathing_rate_bpm, heartrate_bpm, ...}` |
|
||||
|
||||
`SensingClient` is a pure-Python asyncio wrapper around `websockets>=12`
|
||||
that connects, decodes JSON, and yields typed dataclasses.
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
from wifi_densepose.client import SensingClient, EdgeVitalsMessage
|
||||
|
||||
async def main():
|
||||
async with SensingClient("ws://localhost:8765/ws/sensing") as client:
|
||||
async for msg in client.stream():
|
||||
if isinstance(msg, EdgeVitalsMessage):
|
||||
print(f"BR={msg.breathing_rate_bpm}, HR={msg.heartrate_bpm}")
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, AsyncIterator, Optional
|
||||
|
||||
# Defer import — only fail at construction time, not at module load.
|
||||
try:
|
||||
import websockets # type: ignore[import-not-found]
|
||||
from websockets.exceptions import ConnectionClosed # type: ignore[import-not-found]
|
||||
_WEBSOCKETS_AVAILABLE = True
|
||||
except ImportError: # pragma: no cover
|
||||
_WEBSOCKETS_AVAILABLE = False
|
||||
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ─── Typed messages ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SensingMessage:
|
||||
"""Base class for typed sensing-server messages. The original JSON
|
||||
payload is preserved in ``raw`` for forward-compatibility with
|
||||
fields not yet modelled here."""
|
||||
type: str
|
||||
raw: dict[str, Any] = field(default_factory=dict, hash=False, compare=False)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ConnectionEstablishedMessage(SensingMessage):
|
||||
"""First message after a successful WS handshake. Lets the client
|
||||
discover the node ID and capability flags without making a separate
|
||||
REST call."""
|
||||
node_id: str = ""
|
||||
version: str = ""
|
||||
capabilities: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EdgeVitalsMessage(SensingMessage):
|
||||
"""Vital-sign telemetry fused from the edge-vitals path
|
||||
(ADR-021/ADR-110). Optional fields may be ``None`` when the
|
||||
upstream channel hasn't produced a measurement yet."""
|
||||
node_id: str = ""
|
||||
presence: bool = False
|
||||
fall_detected: bool = False
|
||||
motion: float = 0.0
|
||||
breathing_rate_bpm: Optional[float] = None
|
||||
heartrate_bpm: Optional[float] = None
|
||||
n_persons: int = 0
|
||||
motion_energy: float = 0.0
|
||||
presence_score: float = 0.0
|
||||
rssi: Optional[float] = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PoseDataMessage(SensingMessage):
|
||||
"""17-keypoint pose data broadcast at the sensing-server's frame
|
||||
cadence. Persons are a list of opaque dicts — typed PoseEstimate
|
||||
decoding lives in the P2 bindings; the WS client passes through."""
|
||||
node_id: str = ""
|
||||
timestamp: float = 0.0
|
||||
persons: tuple[dict[str, Any], ...] = ()
|
||||
confidence: float = 0.0
|
||||
|
||||
|
||||
# ─── Decoder ─────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _decode(raw_text: str) -> SensingMessage:
|
||||
"""Decode a single WS frame into a typed message.
|
||||
|
||||
Unknown ``type`` values yield a plain ``SensingMessage`` rather
|
||||
than raising — the sensing-server is on a faster release cadence
|
||||
than this client, and unknown types should not break the stream.
|
||||
"""
|
||||
obj = json.loads(raw_text)
|
||||
if not isinstance(obj, dict):
|
||||
raise ValueError(f"sensing-server emitted non-dict payload: {type(obj).__name__}")
|
||||
mtype = obj.get("type", "")
|
||||
if mtype == "connection_established":
|
||||
return ConnectionEstablishedMessage(
|
||||
type=mtype,
|
||||
raw=obj,
|
||||
node_id=obj.get("node_id", ""),
|
||||
version=obj.get("version", ""),
|
||||
capabilities=tuple(obj.get("capabilities", ())),
|
||||
)
|
||||
if mtype == "edge_vitals":
|
||||
return EdgeVitalsMessage(
|
||||
type=mtype,
|
||||
raw=obj,
|
||||
node_id=obj.get("node_id", ""),
|
||||
presence=bool(obj.get("presence", False)),
|
||||
fall_detected=bool(obj.get("fall_detected", False)),
|
||||
motion=float(obj.get("motion", 0.0)),
|
||||
breathing_rate_bpm=(
|
||||
float(obj["breathing_rate_bpm"])
|
||||
if obj.get("breathing_rate_bpm") is not None else None
|
||||
),
|
||||
heartrate_bpm=(
|
||||
float(obj["heartrate_bpm"])
|
||||
if obj.get("heartrate_bpm") is not None else None
|
||||
),
|
||||
n_persons=int(obj.get("n_persons", 0)),
|
||||
motion_energy=float(obj.get("motion_energy", 0.0)),
|
||||
presence_score=float(obj.get("presence_score", 0.0)),
|
||||
rssi=(float(obj["rssi"]) if obj.get("rssi") is not None else None),
|
||||
)
|
||||
if mtype == "pose_data":
|
||||
persons = obj.get("persons", ())
|
||||
return PoseDataMessage(
|
||||
type=mtype,
|
||||
raw=obj,
|
||||
node_id=obj.get("node_id", ""),
|
||||
timestamp=float(obj.get("timestamp", 0.0)),
|
||||
persons=tuple(persons) if isinstance(persons, list) else (),
|
||||
confidence=float(obj.get("confidence", 0.0)),
|
||||
)
|
||||
return SensingMessage(type=mtype, raw=obj)
|
||||
|
||||
|
||||
# ─── Client ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class SensingClient:
|
||||
"""Asyncio WebSocket client for the RuView sensing-server.
|
||||
|
||||
Usage as async context manager:
|
||||
|
||||
```python
|
||||
async with SensingClient("ws://localhost:8765/ws/sensing") as c:
|
||||
async for msg in c.stream():
|
||||
...
|
||||
```
|
||||
|
||||
The client does NOT auto-reconnect — if you want resilience, wrap
|
||||
the ``async with`` in your own retry loop. Auto-reconnect logic is
|
||||
application-specific (e.g., "retry forever" for a long-running
|
||||
automation vs "fail fast" for a CLI tool that should exit).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
url: str,
|
||||
*,
|
||||
ping_interval: float = 20.0,
|
||||
ping_timeout: float = 20.0,
|
||||
max_size: int = 16 * 1024 * 1024,
|
||||
) -> None:
|
||||
if not _WEBSOCKETS_AVAILABLE:
|
||||
raise ImportError(
|
||||
"SensingClient requires the `websockets` package. Install with "
|
||||
"`pip install \"wifi-densepose[client]\"` to enable the client extras."
|
||||
)
|
||||
self.url = url
|
||||
self._ping_interval = ping_interval
|
||||
self._ping_timeout = ping_timeout
|
||||
self._max_size = max_size
|
||||
self._ws: Any = None # websockets.WebSocketClientProtocol — typed Any to avoid import cost
|
||||
|
||||
async def __aenter__(self) -> "SensingClient":
|
||||
self._ws = await websockets.connect(
|
||||
self.url,
|
||||
ping_interval=self._ping_interval,
|
||||
ping_timeout=self._ping_timeout,
|
||||
max_size=self._max_size,
|
||||
)
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
||||
await self.close()
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Idempotent connection close."""
|
||||
if self._ws is not None:
|
||||
try:
|
||||
await self._ws.close()
|
||||
except Exception as e: # pragma: no cover — best-effort close
|
||||
log.debug("ignored WS close error: %r", e)
|
||||
self._ws = None
|
||||
|
||||
async def stream(self) -> AsyncIterator[SensingMessage]:
|
||||
"""Yield typed messages until the server closes the connection
|
||||
or the context is exited.
|
||||
|
||||
Decode failures on individual frames are logged at WARN and
|
||||
swallowed — a malformed frame should not terminate the stream
|
||||
(the next frame may be fine)."""
|
||||
if self._ws is None:
|
||||
raise RuntimeError("SensingClient not connected. Use `async with` first.")
|
||||
try:
|
||||
async for frame in self._ws:
|
||||
if isinstance(frame, bytes):
|
||||
frame = frame.decode("utf-8", errors="replace")
|
||||
try:
|
||||
yield _decode(frame)
|
||||
except (ValueError, json.JSONDecodeError) as e:
|
||||
log.warning("dropping malformed sensing-server frame: %r", e)
|
||||
except ConnectionClosed:
|
||||
# Graceful EOF — exit the iterator normally.
|
||||
return
|
||||
|
||||
async def send_ping(self) -> None:
|
||||
"""Send an application-level ping. The sensing-server replies
|
||||
with `{"type": "pong"}` (main.rs:2698)."""
|
||||
if self._ws is None:
|
||||
raise RuntimeError("SensingClient not connected. Use `async with` first.")
|
||||
await self._ws.send(json.dumps({"type": "ping"}))
|
||||
|
||||
async def recv_one(self, *, timeout: Optional[float] = None) -> SensingMessage:
|
||||
"""Receive a single decoded message. Convenience for short
|
||||
scripts and tests that don't need an async generator."""
|
||||
if self._ws is None:
|
||||
raise RuntimeError("SensingClient not connected. Use `async with` first.")
|
||||
if timeout is None:
|
||||
frame = await self._ws.recv()
|
||||
else:
|
||||
frame = await asyncio.wait_for(self._ws.recv(), timeout=timeout)
|
||||
if isinstance(frame, bytes):
|
||||
frame = frame.decode("utf-8", errors="replace")
|
||||
return _decode(frame)
|
||||
Reference in New Issue
Block a user