/* Покомнатная панель: подложка-план + обводка комнат мышью (сохранение + экспорт). */ const PLAN_W = 916, PLAN_H = 768; /* стартовые контуры (в пикселях подложки), сняты ориентировочно */ const START = { terrasa: [[180,173],[287,173],[287,524],[180,524]], kitchen: [[287,173],[425,173],[425,294],[441,294],[441,348],[441,524],[287,524]], postirochnaia: [[425,114],[510,114],[510,229],[425,229]], sanuzel: [[510,173],[510,229],[425,229],[425,294],[479,294],[558,294],[558,173]], tualet: [[558,229],[609,229],[609,294],[558,294]], garderob: [[558,173],[558,229],[656,229],[656,173]], kladovaia: [[609,229],[656,229],[656,294],[609,294]], koridor: [[441,294],[441,348],[684,348],[684,294]], prihozhaya: [[441,348],[510,348],[510,442],[441,442]], tambur: [[441,442],[510,442],[510,524],[441,524]], kabinet: [[656,173],[656,294],[684,294],[684,348],[787,348],[787,173],[656,173]], danina_komnata: [[510,348],[633,348],[633,524],[510,524]], spalnia: [[633,348],[787,348],[787,524],[633,524]], kryltso: [[441,524],[441,593],[510,593],[510,524]], }; const KEY_DOMAINS = ["light", "switch", "climate", "media_player", "cover", "fan"]; const SENSOR_HINT = /temperature|humidity|co2|illuminance/; const ROOM_TITLES = { "terrasa": "Терраса", "kitchen": "Кухня-гостиная", "postirochnaia": "Тех.пом.", "sanuzel": "СУ", "tualet": "СУ 2", "garderob": "Гардеробная", "kladovaia": "Кладовая", "koridor": "Холл", "prihozhaya": "Прихожая", "tambur": "Тамбур", "kabinet": "Кабинет", "danina_komnata": "Данина комната", "spalnia": "Спальня", "kryltso": "Крыльцо" }; const STORE = "house3d_room_px_v2"; class RoomsCard extends HTMLElement { constructor() { super(); this._areas = []; this._ent2area = {}; this._selected = null; this._loaded = false; this._mode = "plan"; this._draw = false; this._drawRoom = null; this._tmp = []; this._polys = JSON.parse(JSON.stringify(START)); try { const saved = JSON.parse(localStorage.getItem(STORE) || "null"); if (saved && typeof saved === "object") this._polys = saved; } catch (e) { /* ignore */ } this.attachShadow({ mode: "open" }); } connectedCallback() { this._on3d = (ev) => { const room = ev && ev.detail ? ev.detail.room : null; this._selected = room || null; this._mode = "plan"; this._render(); // клик по дому — показываем план этой комнаты window.setTimeout(() => { const w = this.shadowRoot.querySelector(".plan-wrap"); if (w && w.scrollIntoView) w.scrollIntoView({ behavior: "smooth", block: "center" }); }, 60); }; document.addEventListener("house3d-room", this._on3d); } disconnectedCallback() { if (this._on3d) document.removeEventListener("house3d-room", this._on3d); } setConfig(config) { this._config = config || {}; } set hass(hass) { this._hass = hass; if (!this._loaded) { this._loaded = true; this._loadRegistries(); } else if (!this._busy) this._render(); } async _loadRegistries() { try { const [areas, devices, entities] = await Promise.all([ this._hass.callWS({ type: "config/area_registry/list" }), this._hass.callWS({ type: "config/device_registry/list" }), this._hass.callWS({ type: "config/entity_registry/list" }), ]); this._areas = areas; const devArea = {}; for (const d of devices) if (d.area_id) devArea[d.id] = d.area_id; this._ent2area = {}; for (const e of entities) { const a = e.area_id || devArea[e.device_id]; if (a) this._ent2area[e.entity_id] = a; } } catch (err) { this._error = String(err); } this._render(); } _roomList() { const names = { terrasa: "Терраса", kitchen: "Кухня-гостиная", postirochnaia: "Тех.пом.", sanuzel: "Санузел", tualet: "Туалет", garderob: "Гардероб", kladovaia: "Кладовая", koridor: "Холл", prihozhaya: "Прихожая", tambur: "Тамбур", kabinet: "Спальня", danina_komnata: "Кабинет", spalnia: "Данина комната", kryltso: "Крыльцо", }; return Object.keys(START).map((id) => ({ id, name: names[id] || id })); } _entitiesOf(areaId) { if (!areaId) return []; return Object.entries(this._ent2area).filter(([, a]) => a === areaId) .map(([e]) => e).filter((e) => this._hass.states[e]); } _domain(e) { return e.split(".")[0]; } _on(id) { return this._entitiesOf(id).filter((e) => { const st = this._hass.states[e]; return (this._domain(e) === "light" || this._domain(e) === "switch") && st.state === "on"; }).length; } _sensors(id) { const out = []; for (const e of this._entitiesOf(id)) { if (this._domain(e) !== "sensor" || !SENSOR_HINT.test(e)) continue; const st = this._hass.states[e]; out.push(`${(st.attributes.friendly_name || e).split(" ").slice(-1)[0]}: ${st.state}${st.attributes.unit_of_measurement || ""}`); } return out.slice(0, 2); } _toggle(e) { const d = this._domain(e); if (d === "light" || d === "switch") this._hass.callService(d, "toggle", { entity_id: e }); } _wallsSvg() { const seen = {}; const out = []; for (const r of ROOMS) { const poly = this._polys[ROOMS.indexOf(r)] || r.poly; for (let i = 0; i < poly.length; i++) { const a = poly[i]; const b = poly[(i + 1) % poly.length]; const k1 = a[0] + "," + a[1] + "-" + b[0] + "," + b[1]; const k2 = b[0] + "," + b[1] + "-" + a[0] + "," + a[1]; if (seen[k1] || seen[k2]) continue; seen[k1] = true; out.push(``); } } return out.join(""); } _planSvg(areaId) { let shapes = "", labels = "", tmp = ""; for (const r of this._roomList()) { const poly = this._polys[r.id] || []; if (!poly.length) continue; const sel = r.id === areaId; shapes += `${r.name}`; // на подложке уже есть подписи — свои не рисуем, только подсказку } if (this._tmp.length) { tmp = ``; this._tmp.forEach(([x, y]) => { tmp += ``; }); } return `
${shapes}${labels}${tmp}
`; } _bindDraw() { const svg = this.shadowRoot.querySelector("svg.layer"); if (!svg) return; svg.addEventListener("click", (ev) => { if (!this._draw) return; const pt = svg.createSVGPoint(); pt.x = ev.clientX; pt.y = ev.clientY; const loc = pt.matrixTransform(svg.getScreenCTM().inverse()); this._tmp.push([Math.round(loc.x), Math.round(loc.y)]); this._render(); }); } _entityRow(e, dom) { const st = this._hass.states[e]; const nm = st.attributes.friendly_name || e; const on = st.state === "on"; if (dom === "light") { const br = st.attributes.brightness; const pct = br ? Math.round((br / 255) * 100) : 0; return `
${nm} ${on ? "вкл" : "выкл"}
`; } if (dom === "climate") { const cur = st.attributes.current_temperature; const tgt = st.attributes.temperature; return `
${nm} ${cur !== undefined ? cur + "°" : ""} → ${tgt !== undefined ? tgt + "°" : ""} − +
`; } if (dom === "media_player") { const playing = st.state === "playing"; return `
${nm}${st.state} ${playing ? "⏸" : "▶"}
`; } if (dom === "cover") { return `
${nm}${st.state} ↑ ■ ↓
`; } const val = st.state + (st.attributes.unit_of_measurement || ""); const act = dom === "switch" ? `${on ? "вкл" : "выкл"}` : ""; return `
${nm}${val}${act}
`; } _render() { if (!this._hass) return; const areaId = this._selected; const tiles = this._roomList().map((r) => { const ens = this._entitiesOf(r.id); const on = this._on(r.id); const sensors = this._sensors(r.id).join(" · "); return ``; }).join(""); const list = this._roomList(); const jsonStr = this._jsonPx(); const drawBar = this._draw ? `
кликайте по углам комнаты на плане (${this._tmp.length} точек)
если «Скопировать» не сработало — нажмите в поле и Ctrl+A, Ctrl+C, или скачайте файл
` : ""; let detail = ""; if (areaId) { const ens = this._entitiesOf(areaId); const groups = {}; for (const e of ens) (groups[this._domain(e)] ||= []).push(e); const rows = Object.keys(groups).sort((a, b) => { const ia = KEY_DOMAINS.includes(a) ? KEY_DOMAINS.indexOf(a) : 60 + a.charCodeAt(0); const ib = KEY_DOMAINS.includes(b) ? KEY_DOMAINS.indexOf(b) : 60 + b.charCodeAt(0); return ia - ib; }).map((dom) => { const items = groups[dom].map((e) => this._entityRow(e, dom)).join(""); return `
${dom} · ${groups[dom].length}
${items}
`; }).join(""); detail = `
${(list.find((r) => r.id === areaId) || {}).name || areaId}
${rows || "
устройств пока нет
"}
`; } this.shadowRoot.innerHTML = `
${this._mode === "plan" ? this._planSvg(areaId) + drawBar : `
${tiles}
`} ${detail}`; this.shadowRoot.querySelectorAll("[data-mode]").forEach((b) => b.addEventListener("click", () => { this._mode = b.dataset.mode; this._render(); })); const db = this.shadowRoot.querySelector("[data-draw]"); if (db) db.addEventListener("click", () => { this._draw = !this._draw; this._tmp = []; this._drawRoom = this._drawRoom || "terrasa"; this._render(); }); if (this._mode === "plan") { this.shadowRoot.querySelectorAll(".zone").forEach((el) => el.addEventListener("click", (ev) => { if (this._draw) { return; } this._selected = this._selected === el.dataset.a ? null : el.dataset.a; this._render(); })); if (this._draw) this._bindDraw(); } const sel = this.shadowRoot.querySelector(".sel"); if (sel) sel.addEventListener("change", () => { this._drawRoom = sel.value; this._tmp = []; this._render(); }); const finish = this.shadowRoot.querySelector("[data-act=finish]"); if (finish) finish.addEventListener("click", () => { if (this._tmp.length >= 3 && this._drawRoom) { this._polys[this._drawRoom] = this._tmp.slice(); try { localStorage.setItem(STORE, JSON.stringify(this._polys)); } catch (e) { /* ignore */ } } this._tmp = []; this._render(); }); const cancel = this.shadowRoot.querySelector("[data-act=cancel]"); if (cancel) cancel.addEventListener("click", () => { this._tmp = []; this._render(); }); const clear = this.shadowRoot.querySelector("[data-act=clear]"); if (clear) clear.addEventListener("click", () => { delete this._polys[this._drawRoom]; try { localStorage.setItem(STORE, JSON.stringify(this._polys)); } catch (e) { /* ignore */ } this._tmp = []; this._render(); }); const copy = this.shadowRoot.querySelector("[data-act=copy]"); if (copy) copy.addEventListener("click", async () => { const txt = this._jsonPx(); let ok = false; try { if (navigator.clipboard && window.isSecureContext) { await navigator.clipboard.writeText(txt); ok = true; } } catch (e) { ok = false; } if (!ok) { try { const ta = this.shadowRoot.querySelector(".json"); ta.focus(); ta.select(); ok = document.execCommand("copy"); } catch (e) { ok = false; } } copy.textContent = ok ? "Скопировано ✓" : "Выделите поле и Ctrl+C"; }); const dl = this.shadowRoot.querySelector("[data-act=download]"); if (dl) dl.addEventListener("click", () => this._download()); this.shadowRoot.querySelectorAll(".tile").forEach((el) => el.addEventListener("click", () => { this._selected = this._selected === el.dataset.a ? null : el.dataset.a; window.setTimeout(() => { const w = this.shadowRoot.querySelector('.plan-wrap'); if (w && w.scrollIntoView) w.scrollIntoView({ behavior: 'smooth', block: 'center' }); }, 50); document.dispatchEvent(new CustomEvent("house3d-select", { detail: { room: this._selected ? "zone_" + this._selected : null } })); this._render(); })); this.shadowRoot.querySelectorAll(".sw").forEach((s) => s.addEventListener("click", (ev) => { ev.stopPropagation(); this._toggle(s.dataset.e); })); this.shadowRoot.querySelectorAll(".br").forEach((el) => el.addEventListener("change", (ev) => { ev.stopPropagation(); const pct = parseInt(ev.target.value, 10); this._hass.callService("light", "turn_on", { entity_id: ev.target.dataset.e, brightness_pct: pct, }); })); this.shadowRoot.querySelectorAll("[data-clim]").forEach((el) => el.addEventListener("click", (ev) => { ev.stopPropagation(); const eid = el.dataset.clim; const st = this._hass.states[eid]; const cur = st.attributes.temperature || 20; this._hass.callService("climate", "set_temperature", { entity_id: eid, temperature: Math.round((cur + parseFloat(el.dataset.d)) * 2) / 2, }); })); this.shadowRoot.querySelectorAll("[data-media]").forEach((el) => el.addEventListener("click", (ev) => { ev.stopPropagation(); this._hass.callService("media_player", el.dataset.a, { entity_id: el.dataset.media }); })); this.shadowRoot.querySelectorAll("[data-cover]").forEach((el) => el.addEventListener("click", (ev) => { ev.stopPropagation(); this._hass.callService("cover", el.dataset.a, { entity_id: el.dataset.cover }); })); const close = this.shadowRoot.querySelector(".close"); if (close) close.addEventListener("click", () => { this._selected = null; this._render(); }); } _jsonPx() { try { return JSON.stringify(this._polys); } catch (e) { return "{}"; } } _download() { try { const blob = new Blob([this._jsonPx()], { type: "application/json" }); const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = "room-zones.json"; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 2000); } catch (e) { /* ignore */ } } getCardSize() { return 14; } } customElements.define("rooms-card", RoomsCard);