From 7d82c1415f61cd4a02dfd05f8aa55d207944fe5a Mon Sep 17 00:00:00 2001 From: buryan-agent Date: Mon, 19 Oct 2026 20:21:48 +0300 Subject: [PATCH] =?UTF-8?q?=D0=98=D0=BD=D1=81=D1=82=D1=80=D1=83=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D1=82=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F=20=D0=BA=D0=B0=D0=BC=D0=B5=D1=80=20Frigate?= =?UTF-8?q?=20=D1=81=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=BE?= =?UTF-8?q?=D0=B9=20=D0=BA=D0=BE=D0=BD=D1=84=D0=B8=D0=B3=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit frigate_camera.py: список, проверка YAML, добавление и удаление камеры, черновик без записи, применение с перезапуском. Имя камеры транслитерируется (Frigate не принимает кириллицу): двор → dvor, калитка 2 → kalitka_2. Проверено: --validate даёт «YAML в порядке, камер: 0», --add двор --dry-run — «камер: 1» с блоком dvor, конфиг после черновика не изменён. По пути: пустой блок cameras: {} нельзя просто дополнить отступом — YAML ломался, поэтому он заменяется словарём. --- ops/frigate/CAMERAS.md | 48 +++++++ ops/frigate/camera_tool.py | 237 ++++++++++++++++++++++++++++++++ ops/frigate/cameras.example.yml | 33 +++++ 3 files changed, 318 insertions(+) create mode 100644 ops/frigate/CAMERAS.md create mode 100644 ops/frigate/camera_tool.py create mode 100644 ops/frigate/cameras.example.yml diff --git a/ops/frigate/CAMERAS.md b/ops/frigate/CAMERAS.md new file mode 100644 index 0000000..dcc7539 --- /dev/null +++ b/ops/frigate/CAMERAS.md @@ -0,0 +1,48 @@ +# Добавление камер (подготовлено) + +Инструмент: `/opt/hub-core/frigate_camera.py`. +Камеры подключаются отдельным спринтом — здесь всё готово, чтобы это +заняло минуты. + +## Команды + +``` +# что уже есть +python3 /opt/hub-core/frigate_camera.py --list + +# проверить конфиг +python3 /opt/hub-core/frigate_camera.py --validate + +# посмотреть, что изменится (безопасно, файл не трогается) +python3 /opt/hub-core/frigate_camera.py --add двор \ + --url 'rtsp://user:pass@192.168.1.50:554/stream1' --dry-run + +# применить и перезапустить +python3 /opt/hub-core/frigate_camera.py --add двор \ + --url 'rtsp://user:pass@192.168.1.50:554/stream1' --apply + +# удалить камеру +python3 /opt/hub-core/frigate_camera.py --remove dvor +``` + +## Что делает + +* проверяет, что адрес начинается с `rtsp://`; +* переводит имя на латиницу (Frigate не принимает кириллицу): + `двор → dvor`, `калитка 2 → kalitka_2`; +* собирает блок камеры: детекция, запись 7 дней по движению, снимки 14 дней, + объекты person/car/dog/cat; +* **проверяет YAML перед записью** — сломанный конфиг не попадёт в систему; +* с `--apply` перезапускает контейнер и показывает камеры из API. + +## Проверено + +* `--validate` на текущем конфиге: «YAML в порядке, камер: 0»; +* `--add двор --dry-run`: «YAML в порядке, камер: 1», в блоке `dvor`; +* конфиг после черновика не изменился (камер по-прежнему нет); +* транслитерация: двор→dvor, Улица→ulitsa, калитка 2→kalitka_2. + +## Что нужно от владельца + +RTSP-адреса камер (обычно в веб-интерфейсе камеры): +`rtsp://ЛОГИН:ПАРОЛЬ@192.168.1.X:554/Streaming/Channels/101`. diff --git a/ops/frigate/camera_tool.py b/ops/frigate/camera_tool.py new file mode 100644 index 0000000..827ed6f --- /dev/null +++ b/ops/frigate/camera_tool.py @@ -0,0 +1,237 @@ +"""Добавление камеры в Frigate: правка конфига, проверка, перезапуск. + +Использование: + python3 frigate_camera.py --list + python3 frigate_camera.py --add двор --url rtsp://user:pass@192.168.1.50:554/stream1 + python3 frigate_camera.py --add двор --url ... --dry-run + python3 frigate_camera.py --remove двор + python3 frigate_camera.py --validate +""" +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import urllib.request + +CT = 126 +CONFIG = "/opt/frigate/config/config.yml" +API = "http://192.168.1.126:5000" + + +def run(cmd, timeout=90): + p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) + return p.returncode, (p.stdout or "") + (p.stderr or "") + + +def read_config(): + code, out = run(["pct", "exec", str(CT), "--", "cat", CONFIG]) + if code != 0: + raise SystemExit(f"не прочитал конфиг: {out[:200]}") + return out + + +def write_config(text): + path = "/tmp/frigate-config.yml" + open(path, "w", encoding="utf-8").write(text) + run(["pct", "push", str(CT), path, CONFIG, "--perms", "644"]) + + +def existing_cameras(text): + """Возвращает имена камер из блока cameras:.""" + names = [] + inside = False + for line in text.splitlines(): + if re.match(r"^cameras:\s*$", line): + inside = True + continue + if inside: + if line and not line.startswith(" "): + break + m = re.match(r"^ ([a-zA-Z0-9_-]+):\s*$", line) + if m: + names.append(m.group(1)) + return names + + +TRANSLIT = { + "а": "a", "б": "b", "в": "v", "г": "g", "д": "d", "е": "e", "ё": "e", + "ж": "zh", "з": "z", "и": "i", "й": "y", "к": "k", "л": "l", "м": "m", + "н": "n", "о": "o", "п": "p", "р": "r", "с": "s", "т": "t", "у": "u", + "ф": "f", "х": "h", "ц": "ts", "ч": "ch", "ш": "sh", "щ": "sch", + "ъ": "", "ы": "y", "ь": "", "э": "e", "ю": "yu", "я": "ya", +} + + +def safe_name(raw): + """Frigate принимает только латиницу, цифры, дефис и подчёркивание.""" + low = (raw or "").strip().lower() + out = "".join(TRANSLIT.get(ch, ch) for ch in low) + out = re.sub(r"[^a-z0-9_-]", "_", out) + out = re.sub(r"_+", "_", out).strip("_") + return out or "camera" + + +def camera_block(name, url): + cam = safe_name(name) + return f""" {cam}: + ffmpeg: + inputs: + - path: {url} + roles: + - detect + - record + detect: + width: 1280 + height: 720 + fps: 5 + record: + enabled: true + retain: + days: 7 + mode: motion + snapshots: + enabled: true + retain: + default: 14 + objects: + track: + - person + - car + - dog + - cat +""" + + +def validate(text): + """Проверяем YAML и обязательные ключи, не запуская сервис.""" + try: + import yaml # noqa: F401 + except ImportError: + yaml = None + if yaml: + try: + data = yaml.safe_load(text) + except Exception as e: + return False, f"YAML сломан: {str(e)[:150]}" + cams = data.get("cameras") or {} + return True, f"YAML в порядке, камер: {len(cams)}" + # без pyyaml — грубая проверка отступов + if "\t" in text: + return False, "табуляция в YAML недопустима" + return True, "pyyaml нет, проверены только отступы" + + +def api_config(): + try: + with urllib.request.urlopen(f"{API}/api/config", timeout=10) as r: + data = json.loads(r.read()) + return list((data.get("cameras") or {}).keys()), None + except Exception as e: + return None, str(e)[:100] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--list", action="store_true") + ap.add_argument("--add") + ap.add_argument("--url") + ap.add_argument("--remove") + ap.add_argument("--validate", action="store_true") + ap.add_argument("--dry-run", action="store_true") + ap.add_argument("--apply", action="store_true", help="перезапустить Frigate после правки") + args = ap.parse_args() + + text = read_config() + + if args.list: + cams = existing_cameras(text) + api_cams, err = api_config() + print("в конфиге:", ", ".join(cams) if cams else "камер нет") + print("в работающем Frigate:", ", ".join(api_cams) if api_cams else f"нет ({err})") + return 0 + + if args.validate: + ok, msg = validate(text) + print(("✅ " if ok else "❌ ") + msg) + return 0 if ok else 1 + + if args.remove: + name = safe_name(args.remove) + block = re.compile(r"^ " + re.escape(name) + r":\n(?:(?: .*| .*)\n)*", re.M) + new_text, n = block.subn("", text) + if n == 0: + print(f"камера «{args.remove}» не найдена") + return 1 + ok, msg = validate(new_text) + print(("✅ " if ok else "❌ ") + msg) + if not ok: + return 1 + if args.dry_run: + print("— черновик, файл не изменён —") + return 0 + shutil.copy("/dev/null", "/dev/null") + write_config(new_text) + print(f"камера «{args.remove}» удалена из конфига") + if args.apply: + code, out = run(["pct", "exec", str(CT), "--", "docker", "restart", "frigate"]) + print("перезапуск:", "ок" if code == 0 else out[:120]) + return 0 + + if args.add: + if not args.url: + print("нужен --url rtsp://...") + return 2 + if not args.url.startswith("rtsp://"): + print("адрес должен начинаться с rtsp://") + return 2 + name = safe_name(args.add) + if name in existing_cameras(text): + print(f"камера «{name}» уже есть") + return 1 + if "cameras: {}" in text: + new_text = text.replace("cameras: {}", "cameras:\n" + camera_block(name, args.url).rstrip()) + elif re.search(r"^cameras:\s*$", text, re.M): + # добавляем в конец блока cameras + lines = text.split("\n") + out, inserted, in_cams = [], False, False + for line in lines: + if re.match(r"^cameras:\s*$", line): + in_cams = True + out.append(line) + continue + if in_cams and not inserted and (line.strip() == "" or not line.startswith(" ")): + out.append(camera_block(name, args.url).rstrip("\n")) + inserted = True + in_cams = False + out.append(line) + if not inserted: + out.append(camera_block(name, args.url).rstrip("\n")) + new_text = "\n".join(out) + else: + new_text = text.rstrip() + "\ncameras:\n" + camera_block(name, args.url).rstrip() + ok, msg = validate(new_text) + print(("✅ " if ok else "❌ ") + msg) + if not ok: + return 1 + if args.dry_run: + print("— черновик, вот что было бы добавлено —") + print(camera_block(name, args.url)) + return 0 + write_config(new_text) + print(f"камера «{name}» добавлена в конфиг") + if args.apply: + code, out = run(["pct", "exec", str(CT), "--", "docker", "restart", "frigate"]) + print("перезапуск:", "ок" if code == 0 else out[:150]) + cams, err = api_config() + print("камеры в Frigate:", ", ".join(cams) if cams else f"нет ({err})") + return 0 + + ap.print_help() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ops/frigate/cameras.example.yml b/ops/frigate/cameras.example.yml new file mode 100644 index 0000000..a1f8e91 --- /dev/null +++ b/ops/frigate/cameras.example.yml @@ -0,0 +1,33 @@ +# Как добавить камеру в Frigate +# +# 1) Узнать RTSP-адрес камеры (обычно в её веб-интерфейсе): +# rtsp://ЛОГИН:ПАРОЛЬ@192.168.1.X:554/Streaming/Channels/101 +# +# 2) Добавить командой (безопасно, с проверкой конфига): +# python3 /opt/hub-core/frigate_camera.py --add двор \ +# --url 'rtsp://user:pass@192.168.1.50:554/stream1' --apply +# +# 3) Проверить: +# python3 /opt/hub-core/frigate_camera.py --list + +cameras: + двор: + ffmpeg: + inputs: + - path: rtsp://user:pass@192.168.1.50:554/stream1 + roles: [detect, record] + detect: + width: 1280 + height: 720 + fps: 5 + record: + enabled: true + retain: + days: 7 + mode: motion + snapshots: + enabled: true + retain: + default: 14 + objects: + track: [person, car, dog, cat]