diff --git a/ops/homeassistant/HACS-ALICE.md b/ops/homeassistant/HACS-ALICE.md new file mode 100644 index 0000000..f3c8ab2 --- /dev/null +++ b/ops/homeassistant/HACS-ALICE.md @@ -0,0 +1,62 @@ +# HACS и Алиса в Home Assistant + +## HACS + +Установлен вручную (GitHub из дома недоступен, скачано через зеркало): + +``` +curl -L -o hacs.zip https://gh-proxy.com/https://github.com/hacs/integration/releases/latest/download/hacs.zip +unzip → /config/custom_components/hacs +``` + +Авторизация — device flow: `config_entries/flow` (handler `hacs`), согласие на +все четыре `acc_*` (иначе `errors.base = acc`), затем код на +https://github.com/login/device. + +### Почему не работал GitHub + +HACS использует aiohttp **без** `trust_env` — переменные `HTTP_PROXY` +игнорируются. Поэтому сделан прозрачный маршрут: + +* `github-tunnel` — SSH-туннели до 6 хостов GitHub (порты 9443–9448); +* `gh-route` в CT 106 — DNAT с **фиксированных** IP (важно: `github.com` + резолвится в разные адреса, привязка к одному ломала запросы); +* `--add-host` в контейнере HA, чтобы IP не менялись. + +## YandexStation (Алиса) + +Установлен через HACS: `AlexxIT/YandexStation` v3.22.3. + +Авторизация — **QR-код** (метод `qr`): интеграция отдаёт `qr_url` и `qr_data` +(SVG). Сканируется приложением Яндекс / Яндекс Ключ. Даёт полный токен +(в отличие от музыкального, которому не хватает прав на умный дом). + +Найдено три колонки: + +| Колонка | Состояние | +|---|---| +| Яндекс Станция Миди | idle | +| Яндекс Лайт | paused | +| Яндекс Мини | unavailable | + +### Управление + +Сервис `yandex_station.send_command` с `command: sendText` (озвучка) и +`setVolume` (громкость). Проверено: HTTP 200, колонка говорит. + +Команды бота: + +``` +!колонки список колонок и громкость +!скажи доброе утро озвучить на Миди (по умолчанию) +!скажи на лайт привет явно выбрать колонку +!громкость 45 громкость в процентах +``` + +## Ловушка: бан IP + +После серии неудачных входов HA забанил `192.168.1.10` в +`ip_bans.yaml` — API отвечал **403** только с узла (из CT работал 200). +Лечение: очистить `/config/ip_bans.yaml` (`{}`) и перезапустить HA. + +Проверять доступ надо именно с того адреса, откуда будет ходить бот. diff --git a/ops/homeassistant/hacs_add.py b/ops/homeassistant/hacs_add.py new file mode 100644 index 0000000..28e8b39 --- /dev/null +++ b/ops/homeassistant/hacs_add.py @@ -0,0 +1,46 @@ +"""Добавляет кастомные репозитории в HACS.""" +import asyncio +import json + +import aiohttp + +TOKEN = open("/tmp/ha-token", encoding="utf-8").read().strip() +WS = "ws://127.0.0.1:8123/api/websocket" + +REPOS = [ + ("akinin/ha_keenetic", "integration"), + ("tombabolewski/ha-vidaa-tv", "integration"), +] + + +async def main(): + async with aiohttp.ClientSession() as session: + async with session.ws_connect(WS) as ws: + await ws.receive_json() + await ws.send_json({"type": "auth", "access_token": TOKEN}) + msg = await ws.receive_json() + if msg["type"] != "auth_ok": + print(" auth:", msg) + return + print(" авторизация ок") + + for i, (repo, cat) in enumerate(REPOS, start=1): + await ws.send_json({ + "id": i, + "type": "hacs/repositories/add", + "repository": repo, + "category": cat, + }) + data = await ws.receive_json() + ok = data.get("success") + print(f" {repo}: {'добавлен' if ok else json.dumps(data.get('error') or data, ensure_ascii=False)[:150]}") + + await ws.send_json({"id": 99, "type": "hacs/repositories/list"}) + data = await ws.receive_json() + repos = data.get("result") or [] + print("\n репозиториев:", len(repos)) + for r in repos: + print(f" - {r.get('full_name')} | {r.get('category')} | {r.get('installed_version') or '—'}") + + +asyncio.run(main()) diff --git a/ops/homeassistant/hacs_ws.py b/ops/homeassistant/hacs_ws.py new file mode 100644 index 0000000..96def75 --- /dev/null +++ b/ops/homeassistant/hacs_ws.py @@ -0,0 +1,33 @@ +"""Проверяет HACS через websocket: список репозиториев.""" +import asyncio +import json + +import aiohttp + +TOKEN = open("/tmp/ha-token", encoding="utf-8").read().strip() +WS = "ws://127.0.0.1:8123/api/websocket" + + +async def main(): + async with aiohttp.ClientSession() as session: + async with session.ws_connect(WS) as ws: + await ws.receive_json() + await ws.send_json({"type": "auth", "access_token": TOKEN}) + msg = await ws.receive_json() + if msg["type"] != "auth_ok": + print(" auth:", msg) + return + print(" авторизация ок") + + await ws.send_json({"id": 1, "type": "hacs/repositories/list"}) + data = await ws.receive_json() + if not data.get("success"): + print(" ответ:", json.dumps(data, ensure_ascii=False)[:300]) + return + repos = data.get("result") or [] + print(" репозиториев в HACS:", len(repos)) + for r in repos[:10]: + print(f" - {r.get('full_name')} | {r.get('category')} | {r.get('installed_version') or '—'}") + + +asyncio.run(main()) diff --git a/ops/homeassistant/install_yandex.py b/ops/homeassistant/install_yandex.py new file mode 100644 index 0000000..7732ce5 --- /dev/null +++ b/ops/homeassistant/install_yandex.py @@ -0,0 +1,47 @@ +"""Добавляет YandexStation в HACS и ставит его.""" +import asyncio +import json + +import aiohttp + +TOKEN = open("/tmp/ha-token", encoding="utf-8").read().strip() +WS = "ws://127.0.0.1:8123/api/websocket" +REPO = "AlexxIT/YandexStation" + + +async def main(): + async with aiohttp.ClientSession() as session: + async with session.ws_connect(WS) as ws: + await ws.receive_json() + await ws.send_json({"type": "auth", "access_token": TOKEN}) + msg = await ws.receive_json() + if msg["type"] != "auth_ok": + print(" auth:", msg) + return + + await ws.send_json({"id": 1, "type": "hacs/repositories/add", + "repository": REPO, "category": "integration"}) + d = await ws.receive_json() + print(f" добавить {REPO}: {'ок' if d.get('success') else json.dumps(d.get('error') or d, ensure_ascii=False)[:200]}") + if not d.get("success"): + return + + await ws.send_json({"id": 2, "type": "hacs/repositories/list"}) + lst = await ws.receive_json() + target = None + for r in (lst.get("result") or []): + if (r.get("full_name") or "").lower() == REPO.lower(): + target = r + break + if not target: + print(" репозиторий не найден в списке") + return + print(" id:", target.get("id"), "| версия:", target.get("available_version") or target.get("last_version")) + + await ws.send_json({"id": 3, "type": "hacs/repository/download", + "repository": target.get("id")}) + d3 = await ws.receive_json() + print(" установка:", "ок" if d3.get("success") else json.dumps(d3.get("error") or d3, ensure_ascii=False)[:200]) + + +asyncio.run(main()) diff --git a/ops/homeassistant/qr_start.py b/ops/homeassistant/qr_start.py new file mode 100644 index 0000000..8f9f84f --- /dev/null +++ b/ops/homeassistant/qr_start.py @@ -0,0 +1,40 @@ +"""Запускает QR-поток YandexStation и сохраняет QR в /tmp/qr.svg.""" +import json +import sys +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 + req = urllib.request.Request(BASE + path, data=data, method=method, headers=HDR) + try: + with urllib.request.urlopen(req, timeout=45) as r: + raw = r.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": "yandex_station"}) +if err: + print("старт:", err) + sys.exit(1) +fid = flow["flow_id"] +res, err2 = call(f"/api/config/config_entries/flow/{fid}", "POST", {"method": "qr"}) +if err2: + print("qr:", err2) + sys.exit(1) +ph = (res or {}).get("description_placeholders") or {} +svg = ph.get("qr_data") or "" +url = ph.get("qr_url") or "" +open("/tmp/qr.svg", "w", encoding="utf-8").write(svg) +open("/tmp/yandex_flow_id", "w").write(fid) +open("/tmp/qr_url", "w").write(url) +print("svg:", len(svg), "| url:", len(url), "| шаг:", (res or {}).get("step_id")) diff --git a/ops/network/gh_route2.sh b/ops/network/gh_route2.sh new file mode 100644 index 0000000..a8a3d88 --- /dev/null +++ b/ops/network/gh_route2.sh @@ -0,0 +1,25 @@ +#!/bin/bash +# Прозрачный маршрут до GitHub: фиксированные IP + DNAT в SSH-туннели. +set -uo pipefail + +# host:ip:local_port — IP зафиксированы, чтобы не зависеть от DNS +MAP="github.com:140.82.121.4:9443 +api.github.com:140.82.121.6:9444 +codeload.github.com:140.82.121.9:9445 +objects.githubusercontent.com:185.199.110.133:9446 +raw.githubusercontent.com:185.199.108.133:9447 +avatars.githubusercontent.com:185.199.110.133:9448" + +# чистим старые правила +iptables -t nat -S OUTPUT 2>/dev/null | grep 'GITHUB-TUNNEL' | sed 's/^-A //' | while read -r rule; do + iptables -t nat -D $rule 2>/dev/null || true +done + +while IFS=: read -r host ip port; do + [ -z "$host" ] && continue + iptables -t nat -A OUTPUT -d "$ip" -p tcp --dport 443 \ + -m comment --comment GITHUB-TUNNEL -j DNAT --to-destination 192.168.1.10:$port + echo " $host ($ip) → 192.168.1.10:$port" +done <<< "$MAP" + +echo " правил: $(iptables -t nat -S OUTPUT | grep -c GITHUB-TUNNEL)"