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
2 changes: 2 additions & 0 deletions apps/motion-detect/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@

平台 WebSocket `/ws/ai/results/v2` 的来源 ID 仍为 `motion-detect`,迁移后的身份为经过 AppMgr 验证的应用身份。应用发送 `status` envelope,`summary` 包含 `motion`、`score`、`changed_ratio`、`changed_pixels`、`daemon_running`;状态变化即发,并独立保持 10 秒平台心跳(不改变 HA 的 `heartbeat_sec`)。正常退出时发送 `motion:false`、`daemon_running:false`;异常退出由平台应用生命周期处理离线状态。

同一来源还发布带归一化 `geometry[]` 标签的 `frame` envelope,供浏览器绘制左上角叠加。标签在运动状态切换时立即更新,并定期刷新最新的检测值。

平台 envelope 与 HA 消息独立,不改变 HA MQTT 字段。原来按 `source.kind=system` 过滤的客户端应调整为按来源 ID 订阅。

## 配置
Expand Down
4 changes: 4 additions & 0 deletions apps/motion-detect/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@

配置由应用中心管理,持久化到 `/userdata/local/appdata/motion-detect/config.json`。`sample_fps` 修改后重启,其余 UI 参数热更新。`manifest.json` 的配置分组与 `config_schema.json` 保持一致,由测试检查。

## 浏览器预览叠加

启动移动检测后,在实时预览中开启浏览器叠加,选择主码流和「移动检测」来源。画面左上角显示预热或检测状态。预热完成后,同一行显示运动得分、变化比例和分析画面中变化的像素数。叠加沿用平台浏览器图元的主码流及画面旋转限制。

## 保持兼容的 HA/MQTT 协议

`ha_mqtt.py` 沿用原服务的专用上报适配器和 Kit `MqttSink`。使用应用自己的 `mqtt_host`、`mqtt_port`、`mqtt_user`、`mqtt_pass`;`mqtt_host` 为空时关闭 HA 上报。`owns_mqtt=True` 禁止 Kit 再按全局/CLI 设置创建第二个 MQTT 发布器。
Expand Down
71 changes: 49 additions & 22 deletions apps/motion-detect/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,20 @@
import math

from kit.app import App, run_app
from kit.geometry import point

from config_schema import derive_tables, load_schema
from ha_mqtt import HaMqttBridge
from motion_core import MotionCore, retention_seconds


_EMPTY_METRICS = {"score": 0.0, "changed_ratio": 0.0, "changed_pixels": 0}
# The browser expires geometry after 1.5 s. Refresh independently of analysis,
# which can be configured as low as 0.2 fps.
_OVERLAY_REFRESH_SEC = 0.75
_MIN_FRAME_FPS = 2.0


class MotionDetectApp(App):
id = "motion-detect"
name = "Motion Detection"
Expand All @@ -31,21 +39,22 @@ def setup(self, config):
self._last_sample_pts = -math.inf
self._last_notify = 0.0
self._last_hub_notify = -math.inf
self._last_result = {"score": 0.0, "changed_ratio": 0.0,
"changed_pixels": 0}
self._last_overlay_pts = -math.inf
self._last_result = None

def prepare_runtime(self):
from recamera_ext import FrameConfig, FrameSource

divisor = max(1, round(30.0 / float(self.sample_fps)))
divisor = max(1, round(30.0 / max(_MIN_FRAME_FPS, float(self.sample_fps))))
self._source = FrameSource(FrameConfig(fps_divisor=divisor),
timeout_ms=5000)
self._mqtt = HaMqttBridge(self.config)
self._publish_hub(False, self._last_result, 0.0)
self._publish_hub(False, _EMPTY_METRICS, 0.0)

def on_params_changed(self, changed):
if "analysis_width" in changed:
self._core = MotionCore(analysis_width=int(self.analysis_width))
self._last_result = None
if changed & {"mqtt_host", "mqtt_port", "mqtt_user", "mqtt_pass"}:
if self._mqtt is not None:
self._mqtt.close()
Expand All @@ -58,22 +67,41 @@ def run(self):
break
now = float(frame.pts_us) / 1e6
interval = 1.0 / float(self.sample_fps)
if now - self._last_sample_pts < interval * 0.9:
continue
self._last_sample_pts = now
# downscale() makes a small owned array before the SDK borrow expires.
self._core.push(now, self._core.downscale(frame.array))
self._core.trim(now, retention_seconds(
interval * 1000, self.baseline_gap_ms,
self.baseline_frames, self.current_frames))
result = self._core.evaluate(
now, baseline_gap_ms=self.baseline_gap_ms,
baseline_frames=self.baseline_frames,
current_frames=self.current_frames,
sq_diff_threshold=self.sq_diff_threshold,
min_changed_ratio=self.min_changed_ratio)
if result is not None:
self._step(result, now)
was_active = self._active
was_warming = self._last_result is None
if now - self._last_sample_pts >= interval * 0.9:
self._last_sample_pts = now
# downscale() makes an owned array before the SDK borrow expires.
self._core.push(now, self._core.downscale(frame.array))
self._core.trim(now, retention_seconds(
interval * 1000, self.baseline_gap_ms,
self.baseline_frames, self.current_frames))
result = self._core.evaluate(
now, baseline_gap_ms=self.baseline_gap_ms,
baseline_frames=self.baseline_frames,
current_frames=self.current_frames,
sq_diff_threshold=self.sq_diff_threshold,
min_changed_ratio=self.min_changed_ratio)
if result is not None:
self._step(result, now)
if (was_active != self._active
or (was_warming and self._last_result is not None)
or now - self._last_overlay_pts >= _OVERLAY_REFRESH_SEC):
self._publish_overlay(frame, now)

def _publish_overlay(self, frame, now):
result = self._last_result
if result is None:
label = "Motion: warming up"
else:
state = "detected" if self._active else "clear"
label = (f"Motion: {state} | Score {result['score']:.4f} | "
f"Change {result['changed_ratio']:.2%} ({result['changed_pixels']:,} px)")
color = "#ffda73" if result is not None and self._active else "#ffffff"
self.emit(ts=now, geometry=[point(0.02, 0.09, id="motion-status",
label=label, color=color, opacity=0)],
extra={"frame": {"width": frame.width, "height": frame.height}})
self._last_overlay_pts = now

def _step(self, result, now):
self._last_result = result
Expand Down Expand Up @@ -117,8 +145,7 @@ def finish(self):
try:
if self._rt is not None and getattr(self, "_source", None) is not None:
self.emit_status({"motion": False, "daemon_running": False,
"score": 0.0, "changed_ratio": 0.0,
"changed_pixels": 0})
**_EMPTY_METRICS})
finally:
try:
source, self._source = getattr(self, "_source", None), None
Expand Down
29 changes: 27 additions & 2 deletions apps/motion-detect/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"manifest_version": 2,
"release": {
"sequence": 1,
"sequence": 2,
"channel": "stable"
},
"compatibility": {
Expand Down Expand Up @@ -88,7 +88,7 @@
},
"id": "motion-detect",
"name": "Motion Detection",
"version": "1.0.0",
"version": "1.1.0",
"image": "/appcenter/apps/motion-detect.png",
"icon": {
"path": "icon.png",
Expand All @@ -101,6 +101,31 @@
"capabilities": [],
"models": [],
"postproc": "motion",
"render": {
"schema_version": 1,
"geometry": {
"types": ["point"],
"max_items": 1,
"max_points": 1
}
},
"output": {
"contract_version": 2,
"sink": "ws",
"schema": "geometry[]{type,points,id,label,style}",
"default_channel": ["ws"],
"default_mode": "raw",
"fields": [
{
"name": "geometry",
"from": "geometry[]",
"type": "geometry[]",
"coord": "normalized_points",
"description": "Motion status label for the browser preview"
}
],
"default_mapping": []
},
"tags": [
"motion",
"cpu",
Expand Down
57 changes: 53 additions & 4 deletions apps/motion-detect/tests/test_managed_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,12 @@ def test_hot_reload_rebuilds_only_changed_resources(monkeypatch):
def test_managed_loop_uses_raw_frames_and_closes_all_resources(monkeypatch):
import recamera_ext
import kit.app as kit_app
from market.appmgr.result_hub import ResultHub

calls, packets, messages = [], [], []
calls, packets, messages, overlays = [], [], [], []
frames = [SimpleNamespace(
pts_us=1_000_000 + index * 200_000,
width=32, height=32,
array=np.full((32, 32), 255 if 6 <= index < 12 else 0, dtype=np.uint8),
) for index in range(20)]
class Source:
Expand All @@ -163,7 +165,7 @@ class Bridge:
def __init__(self, config):
calls.append("mqtt opened")
def emit(self, events, pts):
messages.append(events)
messages.append((events, pts))
def close(self):
calls.append("mqtt closed")
monkeypatch.setattr(recamera_ext, "FrameSource", Source)
Expand All @@ -172,7 +174,8 @@ def close(self):
lambda **kw: pytest.fail("opened an RGB frame adapter"))
app = MotionDetectApp()
monkeypatch.setattr(app, "_load_model", lambda *a: pytest.fail("loaded an NPU model"))
sink = SimpleNamespace(emit_typed=lambda payload, pts: packets.append(payload))
sink = SimpleNamespace(emit_typed=lambda payload, pts: packets.append(payload),
emit=lambda payload, pts: overlays.append((payload, pts)))
try:
app.start(app_dir=str(ROOT), manifest=MANIFEST, sink=sink, verbose=False,
config={"baseline_frames": 1, "current_frames": 1,
Expand All @@ -185,4 +188,50 @@ def close(self):
assert any(packet["summary"]["motion"] for packet in packets)
assert packets[-1]["summary"]["daemon_running"] is False
# Both the upward and downward luminance transitions are motion.
assert [events[-1]["motion"] for events in messages] == [True, False, True, False]
assert [events[-1]["motion"] for events, _ in messages] == [True, False, True, False]

hub = ResultHub()
identity = {"app_id": app.id, "instance_id": "test", "generation": 1}
assert hub.refresh_app_manifest(identity, MANIFEST, stream_contract={
"id": "main", "kind": "frame.sock", "path": "/live/0",
})
states = {pts: hub.publish_app({**payload, "pts": pts, "seq": seq}, identity)[0]
for seq, (payload, pts) in enumerate(overlays, 1)}
motion = states[2.2]
assert motion["type"] == "frame"
assert (motion["stream"]["id"], motion["stream"]["width"],
motion["stream"]["height"]) == ("main", 32, 32)
assert motion["geometry"][0] == {
"id": "motion-status", "type": "point", "points": [[0.02, 0.09]],
"space": "normalized_points", "style": {"color": "#ffda73", "opacity": 0.0},
"label": "Motion: detected | Score 1.0000 | Change 100.00% (1,024 px)",
}
assert states[1]["geometry"][0]["label"] == "Motion: warming up"
for events, pts in messages:
state = "detected" if events[-1]["motion"] else "clear"
assert states[pts]["geometry"][0]["label"].startswith(f"Motion: {state}")


def test_overlay_refreshes_between_slow_detection_samples(monkeypatch):
import recamera_ext

frames = [SimpleNamespace(pts_us=index * 500_000, width=32, height=32)
for index in range(8)]
frames[0].array = np.zeros((32, 32), dtype=np.uint8)
opened, overlay_times = [], []

def open_source(config, **kwargs):
opened.append(config.fps_divisor)
return frames

monkeypatch.setattr(recamera_ext, "FrameSource", open_source)
monkeypatch.setattr(APP_MODULE, "HaMqttBridge", lambda config: None)
app = MotionDetectApp()
app.setup({"sample_fps": 0.2})
app.emit_status = lambda *args, **kwargs: None
app.emit = lambda *, ts, **kwargs: overlay_times.append(ts)
app.prepare_runtime()
app.run()

assert opened == [15]
assert overlay_times == [0.0, 1.0, 2.0, 3.0]
8 changes: 4 additions & 4 deletions market/appmgr/tests/test_default_apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def test_first_preinstall_is_a_normal_installed_stopped_application(layout, monk
listing = server.do_v1_apps()["apps"]
motion = [item for item in listing if item["id"] == "motion-detect"]
assert len(motion) == 1
assert motion[0]["version"] == "1.0.0"
assert motion[0]["version"] == "1.1.0"
assert motion[0]["status"] == "stopped"
assert motion[0].get("system") is not True
settings = server.do_get_config("motion-detect")
Expand Down Expand Up @@ -210,8 +210,8 @@ def test_store_signed_upgrade_preserves_config_and_ignores_older_firmware(layout
shutil.copytree(REPO / "apps/motion-detect", source)
manifest_path = source / "manifest.json"
manifest = json.loads(manifest_path.read_text())
manifest["version"] = "1.1.0"
manifest["release"]["sequence"] = 2
manifest["version"] = "1.2.0"
manifest["release"]["sequence"] = 3
manifest_path.write_text(json.dumps(manifest))
package = build(str(source), str(root / "uploads"))
private, public = root / "private.pem", root / "public.pem"
Expand All @@ -228,6 +228,6 @@ def test_store_signed_upgrade_preserves_config_and_ignores_older_firmware(layout
assert result["signature"]["verified"] is True
_seed()
current = json.loads(Path(paths.app_dir("motion-detect"), "manifest.json").read_text())
assert current["version"] == "1.1.0"
assert current["version"] == "1.2.0"
assert config.load_user_config("motion-detect")["sq_diff_threshold"] == 700
assert state.get_app("motion-detect")["desired_state"] == "stopped"
Loading