// Complete climate-card flow against the built UI and an invented Symcon object tree. import assert from "node:assert/strict"; import { createServer } from "node:http"; import { existsSync, mkdirSync, readFileSync } from "node:fs"; import { extname, join, relative, resolve } from "node:path"; import { build } from "esbuild"; import puppeteer from "puppeteer-core"; const root = resolve(import.meta.dirname, ".."); const types = { ".html": "text/html", ".js": "text/javascript", ".json": "application/json", ".png": "image/png" }; const server = createServer((req, res) => { const file = resolve(root, `.${decodeURIComponent(new URL(req.url, "http://localhost").pathname)}`); if (relative(root, file).startsWith("..") || !existsSync(file)) return res.writeHead(404).end(); res.writeHead(200, { "content-type": types[extname(file)] ?? "application/octet-stream" }).end(readFileSync(file)); }); await new Promise((done) => server.listen(0, "127.0.0.1", done)); const executablePath = [process.env.CHROME_PATH, "C:/Program Files/Google/Chrome/Application/chrome.exe", "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"].find((p) => p && existsSync(p)); let browser; try { browser = await puppeteer.launch({ executablePath, headless: true, args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"] }); const page = await browser.newPage(); const errors = []; page.on("pageerror", (e) => errors.push(String(e))); await page.evaluateOnNewDocument(() => localStorage.setItem("nextfloor.cards", "0")); await page.setViewport({ width: 1440, height: 1000 }); await page.goto(`http://127.0.0.1:${server.address().port}/preview/index.html`, { waitUntil: "networkidle0" }); await page.waitForFunction(() => window.nfPanel?.data.building?.floors.length); const adapter = await build({ entryPoints: [join(root, "frontend/src/symcon-bridge.ts")], bundle: true, write: false, format: "iife", globalName: "SymconAdapter", logLevel: "silent" }); await page.addScriptTag({ content: adapter.outputFiles[0].text }); await page.evaluate(async () => { window.humidityValue = 51.6; window.bootstrapCalls = 0; window.nativeCalls = []; window.presenceValue = true; window.rainValue = false; const raw = (id, name, type, value, unit, domain = "sensor") => ({ entity_id: `${domain}.${id}`, name, path: `Haus / DP KNX / OG Allgemein / Heizen Kühlen / RAT Teeküche / Weiterer Unterordner / Messwerte / ${name}`, state: domain === "cover" ? "open" : String(value), attributes: { symcon_id: id, symcon_variable_type: type, symcon_value: value, symcon_numeric_value: typeof value === "number" ? value : undefined, symcon_formatted: `${String(value).replace(".", ",")}${unit ? ` ${unit}` : ""}`, unit_of_measurement: unit } }); const originalFetch = window.fetch; window.fetch = async (url, init) => { if (!String(url).includes("/hook/climate-fixture/")) return originalFetch(url, init); const request = JSON.parse(init.body); if (request.action === "variables/action") { window.nativeCalls.push(request); return new Response("[]"); } window.bootstrapCalls++; const variables = [raw(201, "Raumtemperatur", 2, 21.5, "°C"), raw(202, "Messwert Raumfeuchtigkeit", 2, window.humidityValue, "%", "cover"), raw(203, "CO₂", 1, 780, "ppm"), raw(204, "Raumhelligkeit", 2, 320.5, "lx"), raw(205, "Zusatztemperatur", 2, 21.5, "°C")]; const heating = raw(206, "Fußbodenheizung Wert", 1, 35, "%", "sensor"); Object.assign(heating.attributes, { symcon_has_action: true, symcon_min: 0, symcon_max: 100, symcon_step: 1 }); const reheat = raw(211, "Nachheizregister Wert", 0, true, "", "light"); reheat.attributes.symcon_has_action = true; const status = raw(212, "Raumstatus Alias", 1, 2, "", "climate"); status.attributes.symcon_formatted = "Besprechung"; variables.push(heating, raw(207, "Zuluft Volumenstrom", 2, 120, "m³/h"), raw(208, "Abluft Volumenstrom", 2, 110, "m³/h"), raw(209, "Zuluft Temperatur", 2, 19.6, "°C"), raw(210, "Abluft Temperatur", 2, 22.3, "°C"), reheat, status, raw(213, "Hannes anwesend", 0, window.presenceValue, "", "light"), raw(214, "Regenkontakt", 0, window.rainValue, "", "cover"), raw(215, "Windmessung", 2, 8, "m/s", "climate"), raw(216, "Wolkenmessung", 1, 65, "%")); for (const id of [217, 218]) variables.push({ entity_id: `schedule.${id}`, name: id === 217 ? "Heizzeiten" : "Lüftungszeiten", path: `Haus / Schaltuhren / ${id === 217 ? "Heizzeiten" : "Lüftungszeiten"}`, state: "on", attributes: { symcon_id: id, symcon_schedule: true, next_run: 1794387600, next_action: 2, actions: [{ id: 1, name: "Nacht", color: 255 }, { id: 2, name: "Tag", color: 16711680 }], groups: [{ id: 0, days: 31, points: [{ hour: 6, minute: 30, second: 0, action: 2 }, { hour: 20, minute: 0, second: 0, action: 1 }] }] } }); const objects = [{ object_id: 100, parent_id: 0, name: "Haus", path: "Haus", object_type: 0, position: 0, hidden: true, icon: "" }, ...variables.map((v) => ({ object_id: v.attributes.symcon_id, parent_id: 100, entity_id: v.entity_id, name: v.name, path: v.path, object_type: v.attributes.symcon_schedule ? 4 : 2, position: 0, hidden: false, icon: "" }))]; return new Response(JSON.stringify({ state_revision: window.bootstrapCalls, building_revision: 1, variables, objects, areas: [] })); }; window.__NEXTFLOOR_SYMCON__ = { endpoint: "/hook/climate-fixture", token: "fixture-only" }; const bridge = new window.SymconAdapter.SymconBridge(); await bridge.start(); bridge.stop(); const p = window.nfPanel; const apply = () => { const h = bridge.snapshot(); p.hass = { ...p.hass, language: "de", states: h.states, entities: h.entities, symconObjects: h.symconObjects, symconRefresh: h.symconRefresh, callService: h.callService }; }; apply(); bridge.onChange(apply); await p.updateComplete; [...p.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.includes("Editor")).click(); }); await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("nf-editor")?.shadowRoot); await page.evaluate(async () => { const e = window.nfPanel.shadowRoot.querySelector("nf-editor"); window.climateEditor = e; e._floorId = e._doc.floors[0].id; window.climateRoomId = e._doc.floors[0].rooms[0].id; window.climateFloorId = e._floorId; e.selectItem("room", window.climateRoomId); await e.updateComplete; const section = [...e.shadowRoot.querySelectorAll("details.nf-points")].find((d) => d.querySelector("summary").textContent === "Raumklima"); section.open = true; window.climateSection = section; window.pickNative = async (scope, label, id, name) => { const field = [...scope.querySelectorAll("label.nf-field")].find((el) => el.textContent.trim().startsWith(label)); const picker = field.querySelector("nf-entity-picker"); await picker.updateComplete; const native = picker.shadowRoot.querySelector("nf-symcon-object-picker"); await native.updateComplete; native.shadowRoot.querySelector(".trigger").click(); await native.updateComplete; const input = native.shadowRoot.querySelector(".search"); input.value = name; input.dispatchEvent(new Event("input", { bubbles: true })); await native.updateComplete; const row = native.shadowRoot.querySelector(`#object-${id}`); if (!row?.classList.contains("selectable")) throw new Error(`${name} must be selectable despite its inferred domain`); row.click(); await native.updateComplete; native.shadowRoot.querySelector(".apply").click(); await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete; }; window.pickClimate = (label, id, name) => window.pickNative(window.climateSection, label, id, name); await window.pickClimate("Temperatur", 201, "Raumtemperatur"); await window.pickClimate("Luftfeuchte", 202, "Messwert Raumfeuchtigkeit"); await window.pickClimate("CO₂", 203, "CO₂"); await window.pickClimate("Helligkeit", 204, "Raumhelligkeit"); for (const [label, id, name] of [["Fußbodenheizung", 206, "Fußbodenheizung Wert"], ["Zuluft-VSR", 207, "Zuluft Volumenstrom"], ["Abluft-VSR", 208, "Abluft Volumenstrom"], ["Zulufttemperatur", 209, "Zuluft Temperatur"], ["Ablufttemperatur", 210, "Abluft Temperatur"], ["NHR", 211, "Nachheizregister Wert"], ["Raumstatus", 212, "Raumstatus Alias"], ["Schaltuhr hinzufügen", 217, "Heizzeiten"], ["Schaltuhr hinzufügen", 218, "Lüftungszeiten"]]) await window.pickClimate(label, id, name); if (/Durchsagen|Ruhezeit für Durchsagen/.test(e.shadowRoot.textContent)) throw new Error("Announcement fields remain in the Symcon room form"); const panel = document.createElement("nf-room-panel"); Object.assign(panel, { hass: window.nfPanel.hass, building: e._doc, floor: e._doc.floors[0], room: e._doc.floors[0].rooms[0] }); panel.style = "position:fixed;right:0;top:0;width:390px;height:100vh;z-index:2000;background:#202020"; document.body.append(panel); await panel.updateComplete; if (!panel.shadowRoot.querySelector(".nf-rp-facts").textContent.includes("Besprechung") || panel.shadowRoot.querySelector(".nf-rp-facts").textContent.includes("Komfort")) throw new Error("Native room status did not replace the calculated comfort score"); const hvac = panel.shadowRoot.querySelector("nf-room-hvac"); await hvac.updateComplete; hvac.shadowRoot.querySelectorAll(".schedule").forEach((d) => d.open = true); if (hvac.shadowRoot.querySelectorAll(".schedule").length !== 2 || !hvac.shadowRoot.textContent.includes("06:30") || !hvac.shadowRoot.textContent.includes("Zuluft-VSR")) throw new Error("Linked native HVAC values and schedules are missing in the room menu"); const input = hvac.shadowRoot.querySelector('input[type="number"]'); input.value = "25"; input.dispatchEvent(new Event("change", { bubbles: true })); const clock = hvac.shadowRoot.querySelector('.schedule input[type="checkbox"]'); clock.click(); await hvac.updateComplete; window.nativeRoomPanel = panel; await window.pickClimate("… und noch ein Sensor", 205, "Zusatztemperatur"); window.unlinkTemperature = async () => { const field = [...window.climateSection.querySelectorAll("label.nf-field")].find((el) => el.textContent.trim().startsWith("Temperatur")); const picker = field.querySelector("nf-entity-picker"); await picker.updateComplete; const native = picker.shadowRoot.querySelector("nf-symcon-object-picker"); await native.updateComplete; native.shadowRoot.querySelector(".clear").click(); await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete; }; await window.unlinkTemperature(); if (e._doc.floors[0].rooms[0].climate.temperature !== "sensor.205") throw new Error("Clearing the first averaged sensor removed its remaining link"); if (e._doc.floors[0].rooms[0].climate.humidity !== "cover.202") throw new Error("Unlinking temperature changed another metric"); await window.unlinkTemperature(); if (e._doc.floors[0].rooms[0].climate.temperature !== "none") throw new Error("The last temperature link must stay explicitly unlinked"); await window.pickClimate("Temperatur", 201, "Raumtemperatur"); const label = [...window.climateSection.querySelectorAll("label.nf-check")].find((el) => el.textContent.includes("schwebende Karte")); label.querySelector("input").click(); await e.updateComplete; const second = e._doc.floors[0].rooms[1]; second.climate = { temperature: "sensor.201", humidity: "none", co2: "none", illuminance: "none" }; window.compactRoomId = second.id; e.selectItem("room", second.id); await e.updateComplete; const section2 = [...e.shadowRoot.querySelectorAll("details.nf-points")].find((d) => d.querySelector("summary").textContent === "Raumklima"); section2.open = true; [...section2.querySelectorAll("label.nf-check")].find((el) => el.textContent.includes("schwebende Karte")).querySelector("input").click(); await e.updateComplete; e.selectItem("room", null); await e.updateComplete; if (/Wetterentität|Bluetooth-Ortung|Durchsagen/.test(e.shadowRoot.textContent)) throw new Error("Home Assistant-only weather, Bluetooth or announcement fields remain in Symcon settings"); const weather = e.shadowRoot.querySelector(".nf-symcon-weather"); weather.open = true; for (const [label, id, name] of [[e.t("rain_sensor"), 214, "Regenkontakt"], ["Windgeschwindigkeit", 215, "Windmessung"], ["Bewölkung", 216, "Wolkenmessung"]]) await window.pickNative(e.shadowRoot.querySelector(".nf-symcon-weather"), label, id, name); const presence = e.shadowRoot.querySelector(".nf-symcon-presence"); presence.open = true; await window.pickNative(presence, "Person hinzufügen", 213, "Hannes anwesend"); const currentPresence = e.shadowRoot.querySelector(".nf-symcon-presence"); const personRow = () => [...e.shadowRoot.querySelectorAll(".nf-symcon-presence .nf-form")].find((row) => row.querySelector("nf-entity-picker")?.value === "light.213"); const ownName = personRow().querySelector('input[type="text"]'); ownName.value = "Hannes"; ownName.dispatchEvent(new Event("change", { bubbles: true })); await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete; const roomSelect = personRow().querySelector("select"); roomSelect.value = window.climateRoomId; roomSelect.dispatchEvent(new Event("change", { bubbles: true })); await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete; [...window.nfPanel.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.trim() === "3D").click(); }); await page.waitForFunction(() => window.nativeCalls.length === 2); assert.deepEqual(await page.evaluate(() => window.nativeCalls.map((r) => [r.domain, r.service, r.data])), [["symcon", "set_value", { entity_id: "sensor.206", value: 25 }], ["schedule", "set_active", { entity_id: "schedule.217", active: false }]]); const out = join(root, "preview/screenshots"); mkdirSync(out, { recursive: true }); await page.screenshot({ path: join(out, "symcon-native-room-hvac.png") }); await page.evaluate(() => window.nativeRoomPanel.remove()); await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("nf-view3d")?.viewer); await page.evaluate(() => { window.climateView = window.nfPanel.shadowRoot.querySelector("nf-view3d"); }); assert.equal(await page.evaluate(() => window.nfPanel.data.building.presence.some((p) => p.person === "light.213" && p.name === "Hannes")), true, "an arbitrary native Boolean is a person presence source"); assert.match(await page.evaluate(() => [...window.climateView.shadowRoot.querySelectorAll(".nf-presence-state")].find((el) => el.textContent.includes("Hannes")).textContent), /Hannes.*Anwesend/s); assert.equal(await page.evaluate(() => window.climateView.hass.states["weather.nextfloor_symcon"].attributes.wind_speed), 28.8); assert.equal(await page.evaluate(() => window.climateView.shadowRoot.querySelectorAll(".nf-presence-state").length), 1, "only configured native Boolean sources appear in the presence bar"); await page.evaluate(() => window.climateView.shadowRoot.querySelector(".nf-weather-values").click()); assert.equal(await page.evaluate(() => window.climateView.shadowRoot.querySelector(".nf-weather-dialog").open), true); assert.match(await page.evaluate(() => window.climateView.shadowRoot.querySelector(".nf-weather-dialog").textContent), /Windgeschwindigkeit.*8 m\/s/s); await page.keyboard.press("Escape"); await page.waitForFunction(() => window.climateView.shadowRoot.querySelector(".nf-card-toggle")); assert.equal(await page.evaluate(() => window.climateView.shadowRoot.querySelector(".nf-card-toggle").getAttribute("aria-pressed")), "false"); await page.evaluate(() => window.climateView.shadowRoot.querySelector(".nf-card-toggle").click()); await page.evaluate(async () => { const p = window.nfPanel; p.shadowRoot.querySelector("nf-view3d").syncDevices(true); await window.climateView.updateComplete; if (window.climateView.shadowRoot.querySelector(".live-card-roomclimate")) throw new Error("All-floors overview must not show room climate cards"); const name = p.data.building.floors.find((f) => f.id === window.climateFloorId).name; [...p.shadowRoot.querySelectorAll(".nf-nav button")].find((b) => b.textContent.trim() === name).click(); }); await page.waitForFunction(() => window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate").length === 2); const text = () => page.evaluate(() => window.climateView.shadowRoot.querySelector(`.live-card[data-room="${window.climateRoomId}"]`).textContent); assert.match(await text(), /21,5\s*°C/); assert.match(await text(), /52\s*%/); assert.match(await text(), /780\s*ppm/); assert.match(await text(), /321\s*lx/); assert.equal(await page.evaluate(() => window.climateView.shadowRoot.querySelector(".live-climate-co2 span").textContent), "☁", "CO2 uses a cloud symbol"); assert.equal(await page.evaluate(() => !!window.climateView.shadowRoot.querySelector(".live-card-house")), false, "climate cards do not require an energy meter"); assert.equal(await page.evaluate(() => window.nfPanel.data.building.floors[0].rooms[0].climate.humidity), "cover.202"); assert.equal(await page.evaluate(() => window.climateView.shadowRoot.querySelector(`.live-card[data-room="${window.compactRoomId}"]`).querySelectorAll(".live-row").length), 1, "unlinked humidity and CO2 do not get rows"); assert.equal(await page.evaluate(() => [...window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate")].some((c) => /Wohnzimmer|Küche|Temperatur|Luftfeuchte/.test(c.textContent))), false, "cards show no repeated room name or metric labels"); await page.evaluate(() => { const p = window.nfPanel; [...p.shadowRoot.querySelectorAll(".nf-nav button")].find((b) => b.textContent.trim() === p.t("all_floors")).click(); }); await page.waitForFunction(() => window.climateView.floorId === null && !window.climateView.shadowRoot.querySelector(".live-card-roomclimate")); await page.evaluate(() => { const p = window.nfPanel; const name = p.data.building.floors.find((f) => f.id === window.climateFloorId).name; [...p.shadowRoot.querySelectorAll(".nf-nav button")].find((b) => b.textContent.trim() === name).click(); }); await page.waitForFunction(() => window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate").length === 2); await page.evaluate(() => { window.humidityValue = 62.4; window.presenceValue = false; window.rainValue = true; window.nfPanel.shadowRoot.querySelector(".nf-reload-variables").click(); }); await page.waitForFunction(() => window.climateView.shadowRoot.querySelector(`.live-card[data-room="${window.climateRoomId}"]`).textContent.includes("62 %")); assert.match(await page.evaluate(() => [...window.climateView.shadowRoot.querySelectorAll(".nf-presence-state")].find((el) => el.textContent.includes("Hannes")).textContent), /Abwesend/); assert.equal(await page.evaluate(() => window.climateView.hass.states["weather.nextfloor_symcon"].state), "rainy"); await page.waitForFunction(() => [...window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate")].every((c) => c.style.visibility === "visible")); await page.screenshot({ path: join(out, "symcon-climate-desktop.png") }); await page.setViewport({ width: 390, height: 844 }); await page.evaluate(() => { window.nfPanel.narrow = true; }); await page.waitForFunction(() => [...window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate")].every((c) => { const r = c.getBoundingClientRect(); return r.left >= 0 && r.right <= innerWidth; })); await page.screenshot({ path: join(out, "symcon-climate-mobile.png") }); await page.evaluate(() => { const p = window.nfPanel; p._floorId = window.climateFloorId; p._roomId = window.climateRoomId; }); await page.waitForFunction(() => window.climateView.panelOpen && window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate").length === 1); assert.match(await text(), /62\s*%/); await page.evaluate(() => window.climateView.shadowRoot.querySelector(".nf-card-toggle").click()); await page.waitForFunction(() => !window.climateView.shadowRoot.querySelector(".live-card-roomclimate")); assert.deepEqual(errors, []); console.log("OK: native float humidity picker, saved per-room card setting, temperature/humidity/CO2 values, missing data, live reload, no-energy toggle, desktop/mobile and opened-room cards"); } finally { await browser?.close(); await new Promise((done) => server.close(done)); }