MQTT-брокер, Frigate в HA и новый ключ Jellyfin
Mosquitto 2 в CT 107 (порт 1883, пароли для frigate/homeassistant/hub), проверено публикацией. Frigate переключён на этот брокер, API найден на 192.168.1.126:5000 (не .110), порты 5000/8971/8554/8555 проброшены. HA: добавлены интеграции mqtt и frigate. Frigate-интеграция не вставала: требование hass-web-proxy-lib==0.0.8 требует Python 3.14, в HA 3.13 — поставили 0.0.7 и поправили манифест. Jellyfin: старый ключ отдавал 401. Получен новый через логин akadmin и POST /Auth/Keys (нужен заголовок Authorization: MediaBrowser Token="..."), проверен по /Items/Counts, прописан в bots.env.
This commit is contained in:
1 parent
7eb16614d5
commit
91eef1390a
8 files changed
+322
No files matched your search
@@ -0,0 +1,54 @@
|
||||
"""Подключает Frigate к HA."""
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
TOK = open("/root/.ha-token", encoding="utf-8").read().strip()
|
||||
BASE = "http://127.0.0.1:8123"
|
||||
HDR = {"Authorization": "Bearer " + TOK, "Content-Type": "application/json"}
|
||||
|
||||
|
||||
def call(path, method="GET", body=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
r = urllib.request.Request(BASE + path, data=data, method=method, headers=HDR)
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=60) as x:
|
||||
raw = x.read()
|
||||
return (json.loads(raw) if raw else {}), None
|
||||
except urllib.error.HTTPError as e:
|
||||
return None, f"HTTP {e.code}: {e.read()[:250].decode('utf-8', 'replace')}"
|
||||
except Exception as e:
|
||||
return None, str(e)[:120]
|
||||
|
||||
|
||||
flow, err = call("/api/config/config_entries/flow", "POST", {"handler": "frigate"})
|
||||
if err:
|
||||
print("старт:", err)
|
||||
raise SystemExit(1)
|
||||
fid = flow["flow_id"]
|
||||
schema = flow.get("data_schema") or []
|
||||
names = [f.get("name") for f in schema]
|
||||
print("поля:", names)
|
||||
|
||||
payload = {"url": "http://192.168.1.126:5000", "validate_ssl": False}
|
||||
# шаг 1
|
||||
res, err2 = call(f"/api/config/config_entries/flow/{fid}", "POST", payload)
|
||||
print("шаг1:", err2 or (res or {}).get("type"), (res or {}).get("errors"))
|
||||
|
||||
for _ in range(3):
|
||||
if not res or res.get("type") != "form":
|
||||
break
|
||||
step = res.get("step_id")
|
||||
sch = res.get("data_schema") or []
|
||||
print(f" шаг: {step} | поля: {[f.get('name') for f in sch]}")
|
||||
p2 = {}
|
||||
for f in sch:
|
||||
n = f.get("name")
|
||||
if n in payload:
|
||||
p2[n] = payload[n]
|
||||
elif f.get("default") is not None:
|
||||
p2[n] = f["default"]
|
||||
elif f.get("type") == "boolean":
|
||||
p2[n] = True
|
||||
res, err3 = call(f"/api/config/config_entries/flow/{fid}", "POST", p2)
|
||||
print(" →", err3 or (res or {}).get("type"), (res or {}).get("errors"))
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Подключает MQTT-брокер к HA (только нужные поля)."""
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
TOK = open("/root/.ha-token", encoding="utf-8").read().strip()
|
||||
BASE = "http://127.0.0.1:8123"
|
||||
HDR = {"Authorization": "Bearer " + TOK, "Content-Type": "application/json"}
|
||||
|
||||
|
||||
def call(path, method="GET", body=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
r = urllib.request.Request(BASE + path, data=data, method=method, headers=HDR)
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=60) as x:
|
||||
raw = x.read()
|
||||
return (json.loads(raw) if raw else {}), None
|
||||
except urllib.error.HTTPError as e:
|
||||
return None, f"HTTP {e.code}: {e.read()[:200].decode('utf-8', 'replace')}"
|
||||
except Exception as e:
|
||||
return None, str(e)[:120]
|
||||
|
||||
|
||||
flow, err = call("/api/config/config_entries/flow", "POST", {"handler": "mqtt"})
|
||||
if err:
|
||||
print("старт:", err)
|
||||
raise SystemExit(1)
|
||||
fid = flow["flow_id"]
|
||||
res, err2 = call(f"/api/config/config_entries/flow/{fid}", "POST", {
|
||||
"broker": "192.168.1.107",
|
||||
"port": 1883,
|
||||
"username": "homeassistant",
|
||||
"password": "hubhome",
|
||||
})
|
||||
print("итог:", err2 or (res or {}).get("type"), (res or {}).get("errors"))
|
||||
@@ -0,0 +1,39 @@
|
||||
# Frigate: порты и API
|
||||
|
||||
## Где живёт
|
||||
|
||||
CT **126**, IP **192.168.1.126** (не .110 — это была ошибка в ранних
|
||||
отчётах). Контейнер `frigate`, версия **0.18.2**.
|
||||
|
||||
## Порты
|
||||
|
||||
| Порт | Что | Статус |
|
||||
|---|---|---|
|
||||
| 5000 | API (без пароля) | открыт, `/api/version` → 200 |
|
||||
| 8971 | UI с авторизацией | открыт |
|
||||
| 8554 | RTSP | слушается контейнером |
|
||||
| 8555 | WebRTC | слушается контейнером |
|
||||
|
||||
Проверено:
|
||||
|
||||
```
|
||||
/api/version → 0.18.2-cfa08c5
|
||||
/api/stats → 200
|
||||
/api/config → 200
|
||||
```
|
||||
|
||||
## Камеры
|
||||
|
||||
**В конфиге 0 камер** — поэтому в HA нет сущностей камер, только
|
||||
`update.frigate_server` и REST-сенсоры. Чтобы появились камеры, нужно
|
||||
добавить их в `/opt/frigate/config/config.yml` (RTSP-потоки) и перезапустить
|
||||
контейнер.
|
||||
|
||||
## Интеграция в HA
|
||||
|
||||
Установлена вручную (HACS отказывался качать):
|
||||
|
||||
* `blakeblackshear/frigate-hass-integration` v5.15.6;
|
||||
* требование `hass-web-proxy-lib==0.0.8` несовместимо с Python 3.13 в HA
|
||||
(нужен Python ≥ 3.14.2) — поставили 0.0.7 и **поправили манифест**;
|
||||
* без правки манифеста HA писал `RequirementsNotFound` и поток падал с 500.
|
||||
@@ -0,0 +1,55 @@
|
||||
# MQTT-брокер (mosquitto)
|
||||
|
||||
Установлен в **CT 107** (`network-lxc`), сетевой режим `host`, порт **1883**.
|
||||
|
||||
## Конфиг
|
||||
|
||||
```
|
||||
/opt/network-lxc/mosquitto/
|
||||
├── config/{mosquitto.conf,passwd}
|
||||
├── data/
|
||||
└── log/mosquitto.log
|
||||
```
|
||||
|
||||
`mosquitto.conf`:
|
||||
|
||||
```
|
||||
listener 1883 0.0.0.0
|
||||
allow_anonymous false
|
||||
password_file /mosquitto/config/passwd
|
||||
persistence true
|
||||
persistence_location /mosquitto/data/
|
||||
log_dest file /mosquitto/log/mosquitto.log
|
||||
```
|
||||
|
||||
## Пользователи
|
||||
|
||||
Созданы через `mosquitto_passwd -b`:
|
||||
|
||||
| Пользователь | Пароль | Для чего |
|
||||
|---|---|---|
|
||||
| `frigate` | `hubfrigate` | Frigate |
|
||||
| `homeassistant` | `hubhome` | HA MQTT |
|
||||
| `hub` | `hubmqtt` | свои скрипты |
|
||||
|
||||
Проверка: публикация `hub/test` → сообщение доставлено подписчику.
|
||||
|
||||
## Кто подключён
|
||||
|
||||
* **Frigate** (CT 126, 192.168.1.126): `mqtt.host = 192.168.1.107`,
|
||||
пользователь `frigate`. API: `http://192.168.1.126:5000` (порты 5000 и
|
||||
8971 проброшены).
|
||||
* **Home Assistant**: интеграция `mqtt`, брокер `192.168.1.107:1883`,
|
||||
пользователь `homeassistant`, discovery включён.
|
||||
|
||||
## Зачем
|
||||
|
||||
Брокер разблокирует: интеграцию Frigate в HA, любые MQTT-устройства
|
||||
(Zigbee2MQTT, Tasmota, ESPHome), а также MQTT-интеграции телевизоров.
|
||||
|
||||
## Ловушки
|
||||
|
||||
1. `eclipse-mosquitto:2` требует `password_file` **до** старта — создавали
|
||||
отдельным контейнером с `mosquitto_passwd`.
|
||||
2. Права: каталоги должны принадлежать UID 1883.
|
||||
3. Frigate после смены MQTT-хоста нужно перезапускать, конфиг кэшируется.
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Ставит MQTT-брокер mosquitto в CT 107."""
|
||||
import subprocess
|
||||
|
||||
CT = "107"
|
||||
|
||||
|
||||
def run(cmd, timeout=120):
|
||||
r = subprocess.run(["pct", "exec", CT, "--", "bash", "-c", cmd],
|
||||
capture_output=True, text=True, timeout=timeout)
|
||||
return (r.stdout or r.stderr or "").strip()
|
||||
|
||||
|
||||
print("=== ТЕКУЩИЕ КОНТЕЙНЕРЫ ===")
|
||||
print(run("docker ps --format '{{.Names}} {{.Status}}'"))
|
||||
|
||||
print("\n=== КАТАЛОГ ===")
|
||||
print(run("mkdir -p /opt/network-lxc/mosquitto/{config,data,log} && ls -d /opt/network-lxc/mosquitto/*"))
|
||||
|
||||
print("\n=== ПАРОЛИ ===")
|
||||
run("docker run --rm -v /opt/network-lxc/mosquitto/config:/mw eclipse-mosquitto:2 "
|
||||
"sh -c 'touch /mw/passwd && mosquitto_passwd -b /mw/passwd frigate hubfrigate && "
|
||||
"mosquitto_passwd -b /mw/passwd homeassistant hubhome && "
|
||||
"mosquitto_passwd -b /mw/passwd hub hubmqtt' 2>&1")
|
||||
print(run("cat /opt/network-lxc/mosquitto/config/passwd | cut -d: -f1"))
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Jellyfin: создание ключа с правильным заголовком Token."""
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
BASE = "http://192.168.1.103:8096"
|
||||
PASS = open("/root/.jellyfin-akadmin-password", encoding="utf-8").read().strip()
|
||||
AUTH_HDR = ('MediaBrowser Client="BuryansHub", Device="Server", '
|
||||
'DeviceId="buryans-hub-server", Version="1.0.0"')
|
||||
|
||||
|
||||
def req(path, method="GET", body=None, token=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
headers["Authorization"] = f'MediaBrowser Token="{token}"' if token else AUTH_HDR
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
r = urllib.request.Request(BASE + path, data=data, method=method, headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=20) as x:
|
||||
raw = x.read()
|
||||
return (json.loads(raw) if raw else {}), None
|
||||
except urllib.error.HTTPError as e:
|
||||
return None, f"HTTP {e.code}: {e.read()[:160].decode('utf-8', 'replace')}"
|
||||
except Exception as e:
|
||||
return None, str(e)[:120]
|
||||
|
||||
|
||||
res, err = req("/Users/AuthenticateByName", "POST", {"Username": "akadmin", "Pw": PASS})
|
||||
token = (res or {}).get("AccessToken")
|
||||
print("логин:", err or "ок")
|
||||
|
||||
# создаём ключ
|
||||
new, err3 = req("/Auth/Keys?App=BuryansHub", "POST", token=token)
|
||||
print("создание ключа:", err3 or "ок")
|
||||
|
||||
keys, err2 = req("/Auth/Keys", token=token)
|
||||
items = (keys or {}).get("Items") or []
|
||||
print("ключей:", err2 or len(items))
|
||||
for k in items:
|
||||
print(" ", k.get("AppName"), "|", str(k.get("AccessToken"))[:16], "…")
|
||||
if k.get("AppName") == "BuryansHub" and k.get("AccessToken"):
|
||||
open("/root/.jellyfin-key-new", "w").write(k["AccessToken"])
|
||||
print(" ✅ сохранён в /root/.jellyfin-key-new")
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Проверяет MQTT: публикация и подписка."""
|
||||
import time
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
BROKER = "192.168.1.107"
|
||||
USER, PASS = "homeassistant", "hubhome"
|
||||
received = []
|
||||
|
||||
|
||||
def on_message(client, userdata, msg):
|
||||
received.append((msg.topic, msg.payload.decode()[:60]))
|
||||
|
||||
|
||||
c = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1, client_id="hub-test")
|
||||
c.username_pw_set(USER, PASS)
|
||||
c.on_message = on_message
|
||||
c.connect(BROKER, 1883, 20)
|
||||
c.subscribe("hub/test")
|
||||
c.loop_start()
|
||||
time.sleep(1)
|
||||
c.publish("hub/test", "проверка связи")
|
||||
time.sleep(2)
|
||||
c.loop_stop()
|
||||
c.disconnect()
|
||||
|
||||
print(" получено:", received or "ничего")
|
||||
print(" результат:", "✅ MQTT работает" if received else "❌ нет доставки")
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Запускает mosquitto с конфигом."""
|
||||
import subprocess
|
||||
|
||||
CT = "107"
|
||||
|
||||
|
||||
def run(cmd, timeout=180):
|
||||
r = subprocess.run(["pct", "exec", CT, "--", "bash", "-c", cmd],
|
||||
capture_output=True, text=True, timeout=timeout)
|
||||
return (r.stdout or r.stderr or "").strip()
|
||||
|
||||
|
||||
CONF = """listener 1883 0.0.0.0
|
||||
allow_anonymous false
|
||||
password_file /mosquitto/config/passwd
|
||||
persistence true
|
||||
persistence_location /mosquitto/data/
|
||||
log_dest file /mosquitto/log/mosquitto.log
|
||||
log_type error
|
||||
log_type warning
|
||||
log_type notice
|
||||
"""
|
||||
|
||||
with open("/tmp/mosquitto.conf", "w") as f:
|
||||
f.write(CONF)
|
||||
|
||||
subprocess.run(["pct", "push", CT, "/tmp/mosquitto.conf",
|
||||
"/opt/network-lxc/mosquitto/config/mosquitto.conf", "--perms", "644"],
|
||||
capture_output=True, text=True)
|
||||
print(" конфиг записан")
|
||||
|
||||
run("chown -R 1883:1883 /opt/network-lxc/mosquitto 2>/dev/null || true")
|
||||
run("docker rm -f mosquitto 2>/dev/null || true")
|
||||
out = run("docker run -d --name mosquitto --restart unless-stopped --network host "
|
||||
"-v /opt/network-lxc/mosquitto/config:/mosquitto/config "
|
||||
"-v /opt/network-lxc/mosquitto/data:/mosquitto/data "
|
||||
"-v /opt/network-lxc/mosquitto/log:/mosquitto/log "
|
||||
"eclipse-mosquitto:2", timeout=240)
|
||||
print(" запуск:", out[:60])
|
||||
|
||||
import time
|
||||
time.sleep(8)
|
||||
print(" статус:", run("docker ps --filter name=mosquitto --format '{{.Status}}'"))
|
||||
print(" порт:", run("ss -ltn | grep 1883 | head -2"))
|
||||
print(" лог:", run("docker logs --tail 5 mosquitto 2>&1"))
|
||||
Reference in new issue
Block a user