[HOME] Прототип 3D-карты в HA: three.js, кликабельный светильник, обратная связь; найдено: Яндекс-устройства read-only
lint / hygiene (push) Successful in 20s

This commit is contained in:
root committed 2026-10-31 00:42:36 +03:00
1 parent 839a67ea7e
commit 7f70c37917
2 files changed
+239

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
# 3D-карта в Home Assistant — прототип (31.10.2026)
## Что сделано
| Компонент | Где |
|---|---|
| `three.min.js` (r160) | `/config/www/house3d/three.min.js` (в HA) |
| Карта `house3d-card.js` | `/config/www/house3d/house3d-card.js` |
| Ресурс Lovelace | `/local/house3d/house3d-card.js` (тип `js`) |
| Дашборд | **Дом 3D**, url_path `house-3d`, страница `/house-3d/home` |
## Что умеет прототип
* настоящая 3D-сцена (three.js) внутри HA: комната, стены, окно, мебель, светильник;
* вращение мышью/пальцем, зум колесом;
* клик по светильнику → вызов `hass.callService(domain, service, {entity_id})`;
* цвет и яркость светильника меняются по `hass.states` (обратная связь из HA);
* карта параметризована: `entity`, `domain`, `service`, `title`.
## Важная находка: устройства Яндекса в HA — только для чтения
`light.svet_v_tambure...` имеет `supported_features = 0`, команды `light.turn_off`
не меняют состояние; `switch.uvlazhnitel...` — то же. То есть текущие
Яндекс-устройства **не управляются из HA**, только отображаются.
Следствие: для дашборда с реальной обратной связью нужны управляемые
устройства — Zigbee-реле/розетки из плана закупки (или отдельная задача
по интеграции Яндекс-устройств на запись).
Для демонстрации цикла выбрана безопасная управляемая сущность
`switch.qbittorrent_alternative_speed` (проверено: переключение работает).
## Следующие шаги
1. Исправить геометрию дома в Blender и экспортировать **GLB (low-poly)**.
2. Карта: загрузка GLB, комнаты как отдельные меши, подсветка при наведении.
3. Привязки комнат и сущностей (`areas`/`entities`), панель комнаты с устройствами.
4. Живые эффекты: цвет комнаты по температуре/влажности, день/ночь.
5. Решить вопрос управляемости Яндекс-устройств (или ждать Zigbee-реле).
+200
View File
@@ -0,0 +1,200 @@
/* house3d-card — прототип 3D-карты для Home Assistant.
* Одна комната, кликабельный светильник, обновление цвета из состояния HA.
* Конфиг:
* type: custom:house3d-card
* entity: light.svet_v_tambure_svet_v_tambure
* title: Спальня (прототип)
*/
class House3dCard extends HTMLElement {
setConfig(config) {
this._config = Object.assign({ entity: "", title: "3D", domain: "light", service: "toggle" }, config || {});
this._root = this.attachShadow({ mode: "open" });
this._root.innerHTML = `
<style>
:host { display:block; }
.wrap { position:relative; width:100%; height:420px; border-radius:18px; overflow:hidden;
background: radial-gradient(circle at 50% 30%, #16202b 0%, #0b0f14 70%);
box-shadow: inset 0 0 60px rgba(0,0,0,.6); cursor:grab; }
.hud { position:absolute; left:16px; top:14px; font:600 15px/1.3 'Segoe UI',sans-serif;
color:#dfe8f2; letter-spacing:.02em; text-shadow:0 1px 8px rgba(0,0,0,.8); pointer-events:none; }
.state { position:absolute; right:16px; top:14px; font:500 13px/1.2 'Segoe UI',sans-serif;
color:#9fb0c3; pointer-events:none; }
.hint { position:absolute; left:16px; bottom:12px; font:400 12px/1.2 'Segoe UI',sans-serif;
color:#71839a; pointer-events:none; }
.err { position:absolute; inset:0; display:flex; align-items:center; justify-content:center;
color:#ff9b9b; font:500 14px 'Segoe UI',sans-serif; }
</style>
<div class="wrap"><div class="hud"></div><div class="state"></div>
<div class="hint">клик по светильнику — вкл/выкл · тянуть — поворот · колесо — зум</div></div>`;
this._wrap = this._root.querySelector(".wrap");
this._hud = this._root.querySelector(".hud");
this._stateEl = this._root.querySelector(".state");
this._hud.textContent = this._config.title;
}
set hass(hass) {
this._hass = hass;
if (!this._ready) this._boot();
this._syncState();
}
_boot() {
if (this._booted) return;
this._booted = true;
const src = "/local/house3d/three.min.js";
const start = () => this._build();
if (window.THREE) return start();
const s = document.createElement("script");
s.src = src;
s.onload = start;
s.onerror = () => { this._wrap.innerHTML = '<div class="err">three.js не загрузился</div>'; };
document.head.appendChild(s);
}
_build() {
if (!window.THREE) return;
const T = window.THREE;
const W = this._wrap.clientWidth || 800;
const H = this._wrap.clientHeight || 420;
this._scene = new T.Scene();
this._scene.fog = new T.Fog(0x0b0f14, 12, 30);
this._cam = new T.PerspectiveCamera(42, W / H, 0.1, 100);
this._cam.position.set(4.2, 3.4, 5.2);
this._cam.lookAt(0, 0.9, 0);
this._renderer = new T.WebGLRenderer({ antialias: true, alpha: true });
this._renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
this._renderer.setSize(W, H);
this._wrap.appendChild(this._renderer.domElement);
// свет
this._scene.add(new T.HemisphereLight(0x6f8bb0, 0x141a22, 0.55));
this._point = new T.PointLight(0xffd7a0, 0, 12, 2);
this._point.position.set(0, 2.4, 0);
this._scene.add(this._point);
// комната
const g = new T.Group();
this._group = g;
this._scene.add(g);
const floorMat = new T.MeshStandardMaterial({ color: 0x2a323c, roughness: 0.85, metalness: 0.1 });
const floor = new T.Mesh(new T.BoxGeometry(6, 0.12, 5), floorMat);
floor.position.set(0, -0.06, 0);
g.add(floor);
const wallMat = new T.MeshStandardMaterial({ color: 0x1c232b, roughness: 0.9 });
const back = new T.Mesh(new T.BoxGeometry(6, 2.6, 0.12), wallMat);
back.position.set(0, 1.3, -2.5);
g.add(back);
const left = new T.Mesh(new T.BoxGeometry(0.12, 2.6, 5), wallMat);
left.position.set(-3, 1.3, 0);
g.add(left);
// «окно»-подсветка
const win = new T.Mesh(new T.PlaneGeometry(2.2, 1.3),
new T.MeshBasicMaterial({ color: 0x2b4a63, transparent: true, opacity: 0.55 }));
win.position.set(0.6, 1.6, -2.43);
g.add(win);
// светильник (бра) — кликабельный
const lampMat = new T.MeshStandardMaterial({
color: 0xffe6bf, emissive: 0xffbe73, emissiveIntensity: 0.1, roughness: 0.4,
});
this._lampMat = lampMat;
const lamp = new T.Mesh(new T.SphereGeometry(0.26, 32, 24), lampMat);
lamp.position.set(-2.4, 1.7, -2.2);
g.add(lamp);
this._lamp = lamp;
const lampBase = new T.Mesh(new T.BoxGeometry(0.1, 0.5, 0.1),
new T.MeshStandardMaterial({ color: 0x0e1216, metalness: 0.6, roughness: 0.5 }));
lampBase.position.set(-2.4, 1.35, -2.2);
g.add(lampBase);
// «мебель» для объёма
const bedMat = new T.MeshStandardMaterial({ color: 0x33424f, roughness: 0.9 });
const bed = new T.Mesh(new T.BoxGeometry(2.2, 0.45, 3.0), bedMat);
bed.position.set(1.4, 0.22, 0.2);
g.add(bed);
const bedHead = new T.Mesh(new T.BoxGeometry(2.2, 0.9, 0.16), bedMat);
bedHead.position.set(1.4, 0.45, -1.28);
g.add(bedHead);
// рамка вокруг сцены (футуристичный контур)
const ring = new T.Mesh(new T.RingGeometry(4.6, 4.66, 64),
new T.MeshBasicMaterial({ color: 0x2f7fa8, transparent: true, opacity: 0.35, side: T.DoubleSide }));
ring.rotation.x = -Math.PI / 2;
ring.position.y = -0.02;
this._scene.add(ring);
// управление
this._rot = { x: 0, y: 0 };
this._dragging = false;
const el = this._renderer.domElement;
el.style.touchAction = "none";
el.addEventListener("pointerdown", (e) => { this._dragging = true; this._px = e.clientX; this._py = e.clientY; });
el.addEventListener("pointerup", (e) => {
this._dragging = false;
const dx = Math.abs(e.clientX - this._px), dy = Math.abs(e.clientY - this._py);
if (dx < 5 && dy < 5) this._click(e);
});
el.addEventListener("pointermove", (e) => {
if (!this._dragging) return;
this._rot.y += (e.clientX - this._px) * 0.006;
this._rot.x = Math.max(-0.5, Math.min(0.5, this._rot.x + (e.clientY - this._py) * 0.004));
this._px = e.clientX; this._py = e.clientY;
});
el.addEventListener("wheel", (e) => {
e.preventDefault();
this._cam.position.multiplyScalar(e.deltaY > 0 ? 1.06 : 0.94);
this._cam.position.clampLength(4, 14);
this._cam.lookAt(0, 0.9, 0);
}, { passive: false });
new ResizeObserver(() => {
const w = this._wrap.clientWidth, h = this._wrap.clientHeight;
if (!w || !h) return;
this._cam.aspect = w / h;
this._cam.updateProjectionMatrix();
this._renderer.setSize(w, h);
}).observe(this._wrap);
const loop = () => {
requestAnimationFrame(loop);
this._group.rotation.y = this._rot.y;
this._group.rotation.x = this._rot.x;
this._renderer.render(this._scene, this._cam);
};
loop();
this._ready = true;
this._syncState();
}
_click(ev) {
if (!this._hass || !this._ready) return;
const r = this._renderer.domElement.getBoundingClientRect();
const p = new window.THREE.Vector2(
((ev.clientX - r.left) / r.width) * 2 - 1,
-((ev.clientY - r.top) / r.height) * 2 + 1,
);
const ray = new window.THREE.Raycaster();
ray.setFromCamera(p, this._cam);
const hit = ray.intersectObject(this._lamp, true).length > 0;
if (hit && this._config.entity) {
this._hass.callService(this._config.domain, this._config.service, { entity_id: this._config.entity });
}
}
_syncState() {
if (!this._ready || !this._hass) return;
const st = this._hass.states[this._config.entity];
const on = st && st.state === "on";
this._lampMat.emissiveIntensity = on ? 1.6 : 0.05;
this._lampMat.color.set(on ? 0xffe6bf : 0x59636e);
this._point.intensity = on ? 9 : 0;
this._stateEl.textContent = st ? (on ? "включено" : "выключено") : "нет сущности";
}
}
customElements.define("house3d-card", House3dCard);