frigate_camera.py: список, проверка YAML, добавление и удаление камеры,
черновик без записи, применение с перезапуском.
Имя камеры транслитерируется (Frigate не принимает кириллицу):
двор → dvor, калитка 2 → kalitka_2.
Проверено: --validate даёт «YAML в порядке, камер: 0», --add двор --dry-run —
«камер: 1» с блоком dvor, конфиг после черновика не изменён.
По пути: пустой блок cameras: {} нельзя просто дополнить отступом —
YAML ломался, поэтому он заменяется словарём.
238 lines
7.9 KiB
Python
238 lines
7.9 KiB
Python
"""Добавление камеры в 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())
|