diff --git a/CHANGELOG.md b/CHANGELOG.md index 9331957..f046e30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Import a floorplan card already in Home Assistant** (toolbar → **Import card**): scans every + Lovelace dashboard over the WebSocket (or takes pasted card / view / dashboard YAML) for + `custom:floorplan-card` and `picture-elements` cards and imports one as a new project or a new + floor. The SVG / image / stylesheet / split-out config is fetched from `/local` or + `/api/image/serve` (or decoded from inline data URIs, or taken from files the user adds). The + browser measures each rule-bound element: markers land at their rendered centre with entities and + actions; `area.` (Ramses Extras convention) and `room_*` shapes become rooms with their HA + area / name; the remaining drawing becomes the background with converted elements stripped. + Studio's own exports round-trip icons, colours, labels and state rules. +- Room inspector keeps an imported HA area visible even when it isn't in the entity list. +- **RAMSES RF / Ramses Extras import** (toolbar → **RAMSES**): adds evohome / RAMSES-II + devices as markers. Reads live from Ramses Extras' + `ramses_extras/floorplan_helper/get_topology` WebSocket command, falling back to the HA + device/entity registries filtered to `ramses_cc` when Extras isn't installed. Offline it accepts a + pasted/loaded topology, a `floorplan_seed_studio` response or studio project (merged into the + current project, rooms included, scaled to the canvas), or any text with device ids + (`known_list`, schema, packet log). Devices land in the room mapped to their HA area (room + `areaId` or name), otherwise in a staging row on the floor matching the area's HA floor; class + icons, group colours, optional extra entities and state rules (offline, battery low, window + open, heat demand). Idempotent and one undo step. Works in both token and dashboard-card mode. - **Inline SVG delivery for ha-floorplan (no file copy)**: the export can now embed the whole floorplan SVG straight into the card as a `data:` URI (`config.image: { location: data:image/svg+xml…, cache: true }`), so there are diff --git a/README.md b/README.md index 2827a0c..b355f8b 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,14 @@ no HACS? The standalone build below still works. pulls the entity + area registries and subscribes to live states; "Test connection" button with clear CORS / mixed-content guidance. Token stays in your browser and is only ever sent to your own HA. +- **Import existing cards** — scan your dashboards (or paste YAML) for ha-floorplan and + picture-elements cards and bring them back as an editable floor: bound SVG elements → markers at + their real positions, `area.*` / `room_*` shapes → rooms, the rest of the drawing → background. + Round-trips Studio's own exports and Ramses Extras' generated floorplans. +- **RAMSES RF / Ramses Extras import** — pull evohome zones, TRVs, thermostats, ventilation units, + CO₂ sensors and remotes straight from HA (Ramses Extras' floorplan helper, or plain `ramses_cc`), + or paste a topology / `floorplan_seed_studio` result / `known_list`. Devices auto-place into the + room mapped to their HA area, with class icons and ready-made state rules. - **Persistence** — named projects in IndexedDB with autosave; JSON export/import for portable backups; undo/redo history. - **Export** — ha-floorplan (SVG + `custom:floorplan-card` YAML + stylesheet), Picture diff --git a/USER_GUIDE.md b/USER_GUIDE.md index f38c54f..4d1d1e0 100644 --- a/USER_GUIDE.md +++ b/USER_GUIDE.md @@ -81,6 +81,67 @@ HA instance. Click **Disconnect** to wipe it and return to demo mode. - Toggle **Preview** in the top bar to see your rules driven by live states (or the demo set). Toggle back to **Edit** to keep working. +### Import a floorplan card already in Home Assistant + +**Import card** (toolbar) brings an existing dashboard floorplan back into the editor — a card you +exported from Floorplan Studio earlier, one generated by Ramses Extras' floorplan helper, or a +hand-made ha-floorplan / picture-elements card. + +1. **Scan dashboards** (needs the Home Assistant link) reads every dashboard and lists each + `custom:floorplan-card` and `picture-elements` card, including ones inside stacks, sections and + conditional cards. Or paste YAML — a single card, a view or the whole raw dashboard config. +2. Pick a card, choose **New project** or **New floor in this project**, and import. +3. Files the card references are fetched from Home Assistant: `/local/…` (public) and uploaded + images under `/api/image/serve/…` (sent with your token). Inline `data:` images need no + download. If a download is blocked (CORS from a standalone app, or no HA link), use + **Add files…** — files are matched to the card's references by file name. A split-out + ha-floorplan `config: /local/…yaml` and its `stylesheet` are loaded the same way. + +What you get: + +- **ha-floorplan**: every element a rule binds (`element:` or the entity id) becomes a marker at + its rendered centre, with its entities and tap / hold / double-tap actions. Studio exports also + get their icon, colour, label and state rules back; Ramses Extras markers keep their icon, colour + and device name. Sizeable closed shapes become rooms; `area.` elements become rooms carrying + that **HA area** (so the RAMSES import drops devices straight into them) and `room_*` elements + (Studio exports) keep their names. Everything else in the drawing becomes the floor background, + with the converted elements removed so nothing is drawn twice (toggleable). Rules whose element + isn't in the SVG can be parked in a row along the bottom. +- **picture-elements**: the image becomes the background (canvas = image size) and each positioned + entity element a marker (`state-label` → live label, conditional elements → marker visibility). + +### Import RAMSES RF / Ramses Extras devices + +For evohome / RAMSES-II systems run through [Ramses RF](https://github.com/ramses-rf/ramses_cc) +(`ramses_cc`) and, optionally, [Ramses Extras](https://github.com/wimpie70/ramses_extras): + +1. Draw a room for every space and set its **HA area** in the Inspector (or give the room the same + name as the HA area). This is how devices find their room. +2. Click **RAMSES** in the toolbar. +3. **Read RAMSES devices** (needs the Home Assistant link — token or dashboard-card mode): + - with **Ramses Extras** installed it calls `ramses_extras/floorplan_helper/get_topology`, which + already resolves zones, parent links, display names and each device's primary entity; + - without Extras it rebuilds the same list from the HA device/entity/area/floor registries, + filtered to `ramses_cc`. +4. Or **paste / load** offline data: + - a saved `get_topology` result (raw or wrapped in the WebSocket `result`), + - the response of the Extras service `ramses_extras.floorplan_seed_studio` (or any studio project + JSON) — its markers and missing rooms are **merged** into the current project, scaled to this + canvas, + - a ramses_cc `known_list`, a ramses_rf schema or even a packet log — every device id + (`04:123456`, zones `01:123456_02`) is matched to your HA entities. +5. Review the table: tick devices (gateway is off by default), choose labels, extra entities + (temperature, heat demand, CO₂…), ready-made **state rules** (offline grey, battery-low blink, + window-open icon, heat-demand gradient) and marker size. Each row shows where the device goes: + *room*, *staging row* (bottom edge of the floor matching the area's HA floor, else the active + floor) or *already on plan*. +6. **Add markers**. The whole import is one undo step, and running it again only adds devices that + aren't on the plan yet. + +Icons follow the device class: zone `home-thermometer`, TRV `radiator`, controller `thermostat`, +FAN `fan`, remote `remote`, CO₂ `molecule-co2`, relay `pipe-valve`, gateway `router-wireless`… +Heating devices are orange, ventilation blue. + ### Saving - Everything **autosaves** to your browser. Use **Projects** to create/open/delete projects, **Export current as JSON** for a backup, or **Import JSON…** to restore one. diff --git a/src/App.tsx b/src/App.tsx index 987d483..0d15543 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -11,10 +11,12 @@ import { HelpModal } from './ui/HelpModal'; import { ConnectModal } from './ha/ConnectModal'; import { ProjectsModal } from './persist/ProjectsModal'; import { ExportModal } from './export/ExportModal'; +import { RamsesImportModal } from './ramses/RamsesImportModal'; +import { HaImportModal } from './haimport/HaImportModal'; import { useAutosave } from './persist/useAutosave'; import { subscribeHass, hassToSource, getHass, HassLike } from './ha/hassBridge'; -type ModalId = null | 'help' | 'connect' | 'projects' | 'export'; +type ModalId = null | 'help' | 'connect' | 'projects' | 'export' | 'ramses' | 'haimport'; export default function App() { const [modal, setModal] = useState(null); @@ -97,6 +99,8 @@ export default function App() { onOpenExport={() => setModal('export')} onOpenProjects={() => setModal('projects')} onOpenConnect={() => setModal('connect')} + onOpenRamses={() => setModal('ramses')} + onOpenHaImport={() => setModal('haimport')} onOpenHelp={() => setModal('help')} />
@@ -121,6 +125,8 @@ export default function App() { {modal === 'connect' && setModal(null)} />} {modal === 'projects' && setModal(null)} />} {modal === 'export' && setModal(null)} />} + {modal === 'ramses' && setModal(null)} />} + {modal === 'haimport' && setModal(null)} />}
); } diff --git a/src/ha/client.ts b/src/ha/client.ts index a952adc..ff146aa 100644 --- a/src/ha/client.ts +++ b/src/ha/client.ts @@ -85,6 +85,12 @@ export class HaClient { }); } + /** Raw WebSocket command (registries, integration-specific commands like Ramses Extras). */ + async sendWS(msg: Record): Promise { + if (!this.conn) throw new Error('Not connected'); + return this.conn.sendMessagePromise(msg as { type: string }); + } + /** Call a service on the connected instance (used by preview tap actions). */ async callService(domain: string, service: string, data: Record): Promise { if (!this.conn) throw new Error('Not connected'); diff --git a/src/ha/hassBridge.ts b/src/ha/hassBridge.ts index 829e6dd..315372b 100644 --- a/src/ha/hassBridge.ts +++ b/src/ha/hassBridge.ts @@ -26,6 +26,11 @@ export interface HassLike { // degrade gracefully to state attributes when they're missing. entities?: Record; areas?: Record; + /** Lovelace's WebSocket helper — used for registry / integration commands. */ + callWS?: (msg: Record) => Promise; + /** auth of the logged-in user (dashboard-card mode): base URL + token for /api fetches */ + auth?: { data?: { hassUrl?: string; access_token?: string } }; + connection?: { sendMessagePromise: (msg: Record) => Promise }; callService?: ( domain: string, service: string, diff --git a/src/haimport/HaImportModal.tsx b/src/haimport/HaImportModal.tsx new file mode 100644 index 0000000..782d71c --- /dev/null +++ b/src/haimport/HaImportModal.tsx @@ -0,0 +1,288 @@ +import { useMemo, useRef, useState } from 'react'; +import yaml from 'js-yaml'; +import { useStore } from '../state/store'; +import { Modal } from '../ui/Modal'; +import { createProject } from '../model/defaults'; +import { saveProject } from '../persist/db'; +import { liveWsCaller } from '../ramses/fetch'; +import { cardsFromText, cardSummary, FoundCard, parseFloorplanCard, parsePictureElements, shortRef } from './cards'; +import { basename, isSvgRef, liveAssetContext, loadText } from './assets'; +import { scanDashboards } from './scan'; +import { ImportResult, importFloorplanSvg, importPictureElements } from './svgImport'; + +type Msg = { kind: 'ok' | 'err' | 'info'; text: string } | null; +type Target = 'new-project' | 'new-floor'; + +export function HaImportModal({ onClose }: { onClose: () => void }) { + useStore((s) => s.conn); + const call = liveWsCaller(); + const [busy, setBusy] = useState(null); + const [msg, setMsg] = useState(null); + const [cards, setCards] = useState([]); + const [picked, setPicked] = useState(null); + const [text, setText] = useState(''); + const [files, setFiles] = useState>(new Map()); + const [target, setTarget] = useState('new-project'); + const [stripBound, setStripBound] = useState(true); + const [stageUnresolved, setStageUnresolved] = useState(true); + const [result, setResult] = useState(null); + const fileRef = useRef(null); + + const card = cards.find((c) => c.key === picked) ?? null; + const defaultName = useMemo(() => { + const last = card?.where.split(' › ').pop(); + return !last || last === 'Pasted YAML' ? 'Imported floorplan' : last; + }, [card]); + const [floorName, setFloorName] = useState(''); + + function setFound(list: FoundCard[], from: string) { + setCards(list); + setPicked(list[0]?.key ?? null); + setFloorName(''); + setResult(null); + setMsg( + list.length + ? { kind: 'info', text: `${list.length} floorplan card${list.length === 1 ? '' : 's'} found in ${from}.` } + : { kind: 'err', text: `No custom:floorplan-card or picture-elements card found in ${from}.` }, + ); + } + + async function scan() { + if (!call) return; + setBusy('Reading dashboards…'); + setMsg(null); + try { + const { cards: found, errors } = await scanDashboards(call); + setFound(found, 'your dashboards'); + if (errors.length && !found.length) setMsg({ kind: 'err', text: errors.join(' · ') }); + } catch (e) { + setMsg({ kind: 'err', text: (e as Error).message }); + } finally { + setBusy(null); + } + } + + function parsePasted() { + try { + setFound(cardsFromText(text), 'the pasted YAML'); + } catch (e) { + setMsg({ kind: 'err', text: (e as Error).message }); + } + } + + async function addFiles(list: FileList | null) { + if (!list?.length) return; + const next = new Map(files); + let yamlText: string | null = null; + for (const f of Array.from(list)) { + next.set(f.name.toLowerCase(), f); + if (/\.(ya?ml)$/i.test(f.name)) yamlText = await f.text(); + } + setFiles(next); + if (yamlText && !text.trim()) { + setText(yamlText); + try { + setFound(cardsFromText(yamlText), f0(list)); + } catch { + /* a split-out ha-floorplan config; picked up via config: path */ + } + } + } + + async function runImport() { + if (!card) return; + setBusy('Importing…'); + setMsg(null); + setResult(null); + const st = useStore.getState(); + const assets = liveAssetContext(files); + const name = floorName.trim() || defaultName; + const ctx = { floorName: name, stripBound, stageUnresolved, entities: st.entities, states: st.states, assets }; + try { + let res: ImportResult; + if (card.kind === 'floorplan') { + let spec = parseFloorplanCard(card.card); + if (spec.configRef) spec = parseFloorplanCard({ config: yaml.load(await loadText(spec.configRef, assets)) }); + let image = spec.image; + // Only one SVG loaded by hand and the card points somewhere else? Use it. + if (image && !files.has(basename(image))) { + const svgs = [...files.values()].filter((f) => /\.svg$/i.test(f.name)); + if (svgs.length === 1 && !assets.base && !image.startsWith('data:')) image = svgs[0].name; + } + if (!image) throw new Error('The card has no config.image.'); + if (!isSvgRef(image) && !files.has(basename(image))) + throw new Error(`ha-floorplan image ${shortRef(image)} isn't an SVG — nothing to bind rules to.`); + res = await importFloorplanSvg(await loadText(image, assets), spec, ctx); + } else { + res = await importPictureElements(parsePictureElements(card.card), ctx); + } + + if (target === 'new-project') { + const p = createProject(name); + p.floors = [res.floor]; + p.activeFloorId = res.floor.id; + await saveProject(p).catch(() => {}); + st.loadProject(p); + } else { + st.commit((p) => { + p.floors.push(res.floor); + p.activeFloorId = res.floor.id; + }); + } + st.setTool('select'); + st.select(null); + setResult(res); + setMsg({ + kind: 'ok', + text: + `Imported "${name}": ${res.markers} markers, ${res.rooms} rooms, background ` + + (res.background === 'svg' ? 'from the original drawing' : res.background === 'image' ? 'image' : 'none') + + (res.staged.length ? ` · ${res.staged.length} element(s) not found in the SVG, parked along the bottom` : '') + + (target === 'new-project' ? ' · opened as a new project' : ' · added as a new floor (Ctrl+Z undoes)') + + '.', + }); + } catch (e) { + setMsg({ kind: 'err', text: (e as Error).message || String(e) }); + } finally { + setBusy(null); + } + } + + return ( + +

+ Bring an existing ha-floorplan card (SVG + rules — e.g. one generated by Ramses Extras or + exported from Floorplan Studio) or a picture-elements card back into the editor. Bound SVG + elements become markers, area.* / room_* shapes become rooms, and the rest of the + drawing stays as the background. +

+ +
+
+
From your dashboards
+ +
+ {call + ? 'Finds every floorplan / picture-elements card; images are downloaded from /local/….' + : 'Connect to Home Assistant first (top-right HA button) — or paste the card YAML.'} +
+
+
+
Paste card YAML
+