first push
This commit is contained in:
commit
2a81b4a502
845 files changed
+356635
No files matched your search
@@ -0,0 +1,101 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, entity, floorWith, hassOf } from "./fixtures.ts";
|
||||
import { carEntities, carState, carWatched } from "./car.ts";
|
||||
|
||||
const vehicle = hassOf(
|
||||
[
|
||||
entity("binary_sensor.car_present", "on"),
|
||||
entity("sensor.car_battery", "64", { device_class: "battery", unit_of_measurement: "%" }),
|
||||
entity("sensor.car_range", "310", { unit_of_measurement: "km" }),
|
||||
entity("sensor.car_charger_power", "7.4", { unit_of_measurement: "kW" }),
|
||||
entity("binary_sensor.car_cable", "on", { device_class: "plug" }),
|
||||
entity("lock.car", "locked"),
|
||||
entity("climate.car", "off"),
|
||||
entity("device_tracker.car", "home"),
|
||||
entity("sensor.other_battery", "10", { device_class: "battery" }),
|
||||
],
|
||||
{
|
||||
"binary_sensor.car_present": { device_id: "tesla" },
|
||||
"sensor.car_battery": { device_id: "tesla" },
|
||||
"sensor.car_range": { device_id: "tesla" },
|
||||
"sensor.car_charger_power": { device_id: "tesla" },
|
||||
"binary_sensor.car_cable": { device_id: "tesla" },
|
||||
"lock.car": { device_id: "tesla" },
|
||||
"climate.car": { device_id: "tesla" },
|
||||
"device_tracker.car": { device_id: "tesla" },
|
||||
"sensor.other_battery": { device_id: "elsewhere" },
|
||||
},
|
||||
);
|
||||
const spot = { entity: "binary_sensor.car_present", car: undefined } as never;
|
||||
|
||||
test("each role is found among the entities of the presence entity's device", () => {
|
||||
assert.deepEqual(carEntities(vehicle, spot), {
|
||||
soc: "sensor.car_battery",
|
||||
range: "sensor.car_range",
|
||||
charging: "sensor.car_charger_power",
|
||||
plugged: "binary_sensor.car_cable",
|
||||
lock: "lock.car",
|
||||
climate: "climate.car",
|
||||
tracker: "device_tracker.car",
|
||||
});
|
||||
});
|
||||
|
||||
test("a chosen entity wins, a device can be chosen, and 'none' means nothing chosen", () => {
|
||||
const e = carEntities(vehicle, { entity: null, car: { device: "sensor.car_range", soc: "sensor.other_battery", lock: "none" } } as never);
|
||||
assert.equal(e.soc, "sensor.other_battery");
|
||||
assert.equal(e.range, "sensor.car_range");
|
||||
assert.equal(e.lock, "lock.car", "'none' falls back to the automatic match");
|
||||
});
|
||||
|
||||
test("without a device nothing is found", () => {
|
||||
const e = carEntities(vehicle, { entity: "binary_sensor.unknown", car: undefined } as never);
|
||||
assert.deepEqual(Object.values(e), [null, null, null, null, null, null, null]);
|
||||
});
|
||||
|
||||
test("the state reads charge, range, charging power in watts, plug, lock and climate", () => {
|
||||
const s = carState(vehicle, spot);
|
||||
assert.equal(s.soc, 64);
|
||||
assert.equal(s.range, 310);
|
||||
assert.equal(s.rangeUnit, "km");
|
||||
assert.equal(s.chargingW, 7400);
|
||||
assert.equal(s.charging, true);
|
||||
assert.equal(s.plugged, true);
|
||||
assert.equal(s.locked, true);
|
||||
assert.equal(s.climateOn, false);
|
||||
assert.equal(s.away, null);
|
||||
});
|
||||
|
||||
test("charging below 50 W is not charging, and a charge level is kept between 0 and 100", () => {
|
||||
const hass = hassOf([entity("sensor.p", "20", { unit_of_measurement: "W" }), entity("sensor.s", "130", { unit_of_measurement: "%" })]);
|
||||
const s = carState(hass, { entity: null, car: { charging: "sensor.p", soc: "sensor.s" } } as never);
|
||||
assert.equal(s.charging, false);
|
||||
assert.equal(s.soc, 100);
|
||||
});
|
||||
|
||||
test("a charging switch without power reading counts by its state", () => {
|
||||
const hass = hassOf([entity("switch.charge", "on")]);
|
||||
const s = carState(hass, { entity: null, car: { charging: "switch.charge" } } as never);
|
||||
assert.equal(s.chargingW, null);
|
||||
assert.equal(s.charging, true);
|
||||
});
|
||||
|
||||
test("away says where the car is: its zone, or an empty text for plain away", () => {
|
||||
const away = (state: string) => carState(hassOf([entity("device_tracker.t", state)]), { entity: null, car: { tracker: "device_tracker.t" } } as never).away;
|
||||
assert.equal(away("home"), null);
|
||||
assert.equal(away("not_home"), "");
|
||||
assert.equal(away("Work"), "Work");
|
||||
assert.equal(away("unavailable"), null);
|
||||
});
|
||||
|
||||
test("watched entities come from parking spots that have car settings", () => {
|
||||
const floor = floorWith([box("r", 0, 0, 4, 3)], {
|
||||
furniture: [
|
||||
{ id: "p", type: "parking", x: 1, z: 1, rotation: 0, w: 2, d: 5, h: 0.02, variant: null, entity: "binary_sensor.car_present", power: null, car: {} },
|
||||
{ id: "q", type: "parking", x: 3, z: 1, rotation: 0, w: 2, d: 5, h: 0.02, variant: null, entity: "binary_sensor.car_present", power: null },
|
||||
],
|
||||
});
|
||||
const watched = carWatched(vehicle, [floor]);
|
||||
assert.ok(watched.includes("sensor.car_battery"));
|
||||
assert.equal(new Set(watched).size, 7, "only the first spot, one entry per role");
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
// The car on a parking spot: its entities (found on the car's Home Assistant device unless chosen) and what it reports.
|
||||
|
||||
import type { Floor, Furniture } from "../model.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { isUnavailable } from "./kinds.ts";
|
||||
|
||||
/** Every role of the car, resolved to an entity id (or null). */
|
||||
export interface CarEntities {
|
||||
soc: string | null;
|
||||
range: string | null;
|
||||
charging: string | null;
|
||||
plugged: string | null;
|
||||
lock: string | null;
|
||||
climate: string | null;
|
||||
tracker: string | null;
|
||||
}
|
||||
|
||||
type Role = keyof CarEntities;
|
||||
|
||||
/** What the name of a car entity (id, friendly name, translation key) looks like for each role. */
|
||||
const ROLE_NAME: Record<Role, RegExp> = {
|
||||
soc: /(^|_)(soc|state_of_charge|battery_level|battery|ladestand|ladezustand|akku)($|_)/,
|
||||
range: /(^|_)(range|reichweite|remaining_range)($|_)/,
|
||||
charging: /(charging|charge_power|ladeleistung|laden|charger_power|lade)/,
|
||||
plugged: /(plug|cable|connected|stecker|kabel|angeschlossen)/,
|
||||
lock: /(lock|verriegel|schloss)/,
|
||||
climate: /(climat|preheat|precondition|hvac|heiz|klima|standheizung)/,
|
||||
tracker: /./,
|
||||
};
|
||||
|
||||
const WATTS = /^k?W$/;
|
||||
|
||||
const chosen = (ref: string | null | undefined): string | null => (ref && ref !== "none" ? ref : null);
|
||||
|
||||
/** The car's entities: those chosen in the editor, the rest from the device of the chosen entity (or of the presence entity). */
|
||||
export function carEntities(hass: HomeAssistant, spot: Pick<Furniture, "entity" | "car">): CarEntities {
|
||||
const choice = spot.car ?? {};
|
||||
const seed = chosen(choice.device) ?? chosen(spot.entity);
|
||||
const deviceId = seed ? hass.entities?.[seed]?.device_id : null;
|
||||
const siblings = deviceId && hass.entities ? Object.values(hass.entities).filter((e) => e.device_id === deviceId).map((e) => e.entity_id) : [];
|
||||
|
||||
const attribute = (id: string, name: string) => String(hass.states[id]?.attributes[name] ?? "");
|
||||
const nameOf = (id: string) => `${id} ${attribute(id, "friendly_name")} ${hass.entities?.[id]?.translation_key ?? ""}`.toLowerCase().replace(/[\s-]+/g, "_");
|
||||
const byName = (role: Role, domains: string[], accept: (id: string) => boolean = () => true) =>
|
||||
siblings.find((id) => domains.includes(id.split(".")[0]) && ROLE_NAME[role].test(nameOf(id)) && accept(id)) ?? null;
|
||||
const byClass = (domain: string, deviceClass: string) => siblings.find((id) => id.startsWith(`${domain}.`) && attribute(id, "device_class") === deviceClass) ?? null;
|
||||
const firstOf = (domain: string) => siblings.find((id) => id.startsWith(`${domain}.`)) ?? null;
|
||||
const unit = (id: string) => attribute(id, "unit_of_measurement");
|
||||
|
||||
return {
|
||||
soc: chosen(choice.soc) ?? byClass("sensor", "battery") ?? byName("soc", ["sensor"], (id) => unit(id) === "%"),
|
||||
range: chosen(choice.range) ?? byName("range", ["sensor"], (id) => /km|mi/.test(unit(id))) ?? byName("range", ["sensor"]),
|
||||
charging: chosen(choice.charging) ?? byName("charging", ["sensor"], (id) => WATTS.test(unit(id))) ?? byName("charging", ["binary_sensor", "switch"]),
|
||||
plugged: chosen(choice.plugged) ?? byClass("binary_sensor", "plug") ?? byName("plugged", ["binary_sensor"]),
|
||||
lock: chosen(choice.lock) ?? firstOf("lock") ?? byName("lock", ["binary_sensor"]),
|
||||
climate: chosen(choice.climate) ?? firstOf("climate") ?? byName("climate", ["switch", "binary_sensor"]),
|
||||
tracker: chosen(choice.tracker) ?? firstOf("device_tracker"),
|
||||
};
|
||||
}
|
||||
|
||||
/** What the car reports right now; null for anything it does not tell. */
|
||||
export interface CarState {
|
||||
entities: CarEntities;
|
||||
soc: number | null;
|
||||
range: number | null;
|
||||
rangeUnit: string;
|
||||
/** Charging power in W, when a power sensor reports it. */
|
||||
chargingW: number | null;
|
||||
charging: boolean;
|
||||
plugged: boolean | null;
|
||||
locked: boolean | null;
|
||||
climateOn: boolean | null;
|
||||
/** The zone the car is in when not at home; "" for plain away, null when at home or unknown. */
|
||||
away: string | null;
|
||||
}
|
||||
|
||||
export function carState(hass: HomeAssistant, spot: Pick<Furniture, "entity" | "car">): CarState {
|
||||
const entities = carEntities(hass, spot);
|
||||
const stateOf = (id: string | null) => (id ? hass.states[id] : undefined);
|
||||
const numberOf = (id: string | null): number | null => {
|
||||
const value = Number(stateOf(id)?.state);
|
||||
return id && Number.isFinite(value) ? value : null;
|
||||
};
|
||||
|
||||
const chargeSensor = stateOf(entities.charging);
|
||||
const chargeUnit = String(chargeSensor?.attributes.unit_of_measurement ?? "");
|
||||
const chargingW = chargeSensor && WATTS.test(chargeUnit) ? (numberOf(entities.charging) ?? 0) * (chargeUnit === "kW" ? 1000 : 1) : null;
|
||||
// over 50 W counts as charging; without a power reading the sensor's own word decides
|
||||
const charging = chargingW !== null ? chargingW > 50 : !!chargeSensor && ["on", "charging", "laden"].includes(chargeSensor.state.toLowerCase());
|
||||
|
||||
const soc = numberOf(entities.soc);
|
||||
const plug = stateOf(entities.plugged);
|
||||
const lock = stateOf(entities.lock);
|
||||
const climate = stateOf(entities.climate);
|
||||
const tracker = stateOf(entities.tracker);
|
||||
const zone = tracker?.state.toLowerCase() ?? "";
|
||||
return {
|
||||
entities,
|
||||
soc: soc === null ? null : Math.max(0, Math.min(100, soc)),
|
||||
range: numberOf(entities.range),
|
||||
rangeUnit: String(stateOf(entities.range)?.attributes.unit_of_measurement ?? "km"),
|
||||
chargingW,
|
||||
charging,
|
||||
plugged: plug ? plug.state === "on" : null,
|
||||
locked: lock ? (lock.entity_id.startsWith("lock.") ? lock.state === "locked" : lock.state === "on") : null,
|
||||
climateOn: climate ? (climate.entity_id.startsWith("climate.") ? !["off", "unavailable"].includes(climate.state) : climate.state === "on") : null,
|
||||
away: tracker && zone !== "home" && !isUnavailable(tracker) ? (zone === "not_home" ? "" : tracker.state) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Every entity the car's state depends on, so changes can be noticed. */
|
||||
export function carWatched(hass: HomeAssistant, floors: readonly Floor[]): string[] {
|
||||
const spots = floors.flatMap((floor) => floor.furniture).filter((f) => f.type === "parking" && f.car);
|
||||
return spots.flatMap((spot) => Object.values(carEntities(hass, spot))).filter((id): id is string => !!id);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity, hassOf } from "./fixtures.ts";
|
||||
import { coverPosition, coverReaches } from "./covers.ts";
|
||||
import { emptyBuilding, newFloor, type Furniture } from "../model.ts";
|
||||
import { setPacks, type PackItem } from "../packs.ts";
|
||||
|
||||
test("a cover's position comes from its attribute, else from open / closed", () => {
|
||||
const hass = hassOf([
|
||||
entity("cover.a", "open", { current_position: 40 }),
|
||||
entity("cover.b", "open"),
|
||||
entity("cover.c", "closed"),
|
||||
entity("cover.d", "closing"),
|
||||
entity("cover.e", "unavailable"),
|
||||
]);
|
||||
assert.equal(coverPosition(hass, "cover.a"), 40);
|
||||
assert.equal(coverPosition(hass, "cover.b"), 100);
|
||||
assert.equal(coverPosition(hass, "cover.c"), 0);
|
||||
assert.equal(coverPosition(hass, "cover.d"), 50);
|
||||
assert.equal(coverPosition(hass, "cover.e"), null);
|
||||
assert.equal(coverPosition(hass, null), null);
|
||||
});
|
||||
|
||||
test("an awning with the reversed direction extends where the cover reports closed (#100)", () => {
|
||||
const awning: PackItem = { id: "awning", name: { en: "awning" }, size: [3, 2, 1], cover: "extends", parts: [{ shape: "box", x: 0, z: 0, w: 1, d: 1, y: 0, h: 1, color: "body", move: "out" }] };
|
||||
setPacks([{ id: "p", name: "p", publisher: "p", items: [awning] }]);
|
||||
const fl = newFloor("f", "F", 0);
|
||||
const mk = (id: string, extra: Partial<Furniture>): Furniture => ({ id, type: "pack:p:awning", x: 1, z: 1, rotation: 0, w: 3, d: 1, h: 2, variant: null, ...extra } as Furniture);
|
||||
fl.furniture = [mk("a", { cover_entity: "cover.m" }), mk("b", { cover_entity: "cover.m", cover_inverted: true })];
|
||||
const hass = hassOf([entity("cover.m", "open", { current_position: 100 })]);
|
||||
const reach = coverReaches(hass, { ...emptyBuilding(), floors: [fl] });
|
||||
assert.equal(reach.get("a"), 1, "open 100 % extends the awning");
|
||||
assert.equal(reach.get("b"), 0, "reversed: open 100 % brings it in");
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
// Pack items with moving parts (curtains, roller screens, awnings, gates) and the cover entity they follow.
|
||||
|
||||
import type { Building } from "../model.ts";
|
||||
import { coverReach, hasMovingParts, packItem } from "../packs.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { isUnavailable } from "./kinds.ts";
|
||||
|
||||
/** How far open a cover is in percent: its position, else 100 / 0 from open / closed (moving counts half). Null when unknown. */
|
||||
export function coverPosition(hass: HomeAssistant, id: string | null | undefined): number | null {
|
||||
const st = id ? hass.states[id] : undefined;
|
||||
if (!st || isUnavailable(st)) return null;
|
||||
const position = st.attributes.current_position;
|
||||
if (typeof position === "number") return Math.min(100, Math.max(0, position));
|
||||
if (st.state === "open") return 100;
|
||||
if (st.state === "closed") return 0;
|
||||
return st.state === "opening" || st.state === "closing" ? 50 : null;
|
||||
}
|
||||
|
||||
/** How far out the moving parts of every such item are (0 … 1, by furniture id). */
|
||||
export function coverReaches(hass: HomeAssistant, b: Building): Map<string, number> {
|
||||
const out = new Map<string, number>();
|
||||
for (const f of b.floors.flatMap((floor) => floor.furniture)) {
|
||||
const item = packItem(f.type);
|
||||
if (!item || !hasMovingParts(item)) continue;
|
||||
const position = f.cover_entity ? coverPosition(hass, f.cover_entity) : null;
|
||||
out.set(f.id, coverReach(item, position !== null && f.cover_inverted ? 100 - position : position));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// Ceiling fans: how fast their blades turn in 3D.
|
||||
|
||||
/** Turns per second of a ceiling fan's blades: faster with its speed, still while it is off. */
|
||||
export function fanSpin(st: { state: string; attributes: Record<string, unknown> } | undefined): number {
|
||||
if (!st || st.state !== "on") return 0;
|
||||
const pct = typeof st.attributes.percentage === "number" ? st.attributes.percentage : 60;
|
||||
return pct <= 0 ? 0 : 0.2 + (0.6 * Math.min(100, pct)) / 100;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Small builders for the tests of the entities/ modules.
|
||||
|
||||
import { newFloor, type Floor, type Opening, type Room } from "../model.ts";
|
||||
import type { HassEntity, HomeAssistant } from "../types.ts";
|
||||
|
||||
export const entity = (entity_id: string, state: string, attributes: Record<string, unknown> = {}): HassEntity => ({ entity_id, state, attributes });
|
||||
|
||||
interface RegistryEntry {
|
||||
area_id?: string | null;
|
||||
device_id?: string | null;
|
||||
hidden?: boolean;
|
||||
entity_category?: string | null;
|
||||
name?: string | null;
|
||||
translation_key?: string | null;
|
||||
platform?: string | null;
|
||||
}
|
||||
|
||||
/** A Home Assistant with the given states and registry entries (entry key = entity id). */
|
||||
export function hassOf(states: HassEntity[], registry: Record<string, RegistryEntry> = {}, extra: Record<string, unknown> = {}): HomeAssistant {
|
||||
return {
|
||||
language: "en",
|
||||
states: Object.fromEntries(states.map((s) => [s.entity_id, s])),
|
||||
entities: Object.fromEntries(Object.entries(registry).map(([id, e]) => [id, { entity_id: id, ...e }])),
|
||||
devices: {},
|
||||
areas: {},
|
||||
callService: async () => undefined,
|
||||
...extra,
|
||||
} as unknown as HomeAssistant;
|
||||
}
|
||||
|
||||
export const box = (id: string, x0: number, z0: number, x1: number, z1: number, area: string | null = null): Room => ({
|
||||
id,
|
||||
name: id,
|
||||
area_id: area,
|
||||
points: [[x0, z0], [x1, z0], [x1, z1], [x0, z1]],
|
||||
floor_material: "wood",
|
||||
});
|
||||
|
||||
export function floorWith(rooms: Room[], extra: Partial<Floor> = {}): Floor {
|
||||
return { ...newFloor("g", "Ground", 0), rooms, ...extra };
|
||||
}
|
||||
|
||||
export const opening = (id: string, room: string, type: Opening["type"], extra: Partial<Opening> = {}): Opening =>
|
||||
({ id, room_id: room, edge: 0, offset: 1, width: 1, type, sill: 0.9, height: 1.2, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null, ...extra }) as Opening;
|
||||
@@ -0,0 +1,210 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { setPacks } from "../packs.ts";
|
||||
import type { Furniture } from "../model.ts";
|
||||
import { box, entity, floorWith, hassOf, opening } from "./fixtures.ts";
|
||||
import { confirmEntities, coolingTemps, deviceTempOf, fridgeDoors, furnitureEntities, hasScreen, isCooling, isMediaFurniture, outsideEntities, pictureRuleMatches, roomPanelEntities } from "./furniture-links.ts";
|
||||
|
||||
const piece = (id: string, type: string, extra: Partial<Furniture> = {}): Furniture => ({ id, type, x: 1, z: 1, rotation: 0, w: 1, d: 1, h: 1, variant: null, entity: null, power: null, ...extra });
|
||||
const room = box("r", 0, 0, 4, 3, "area");
|
||||
const inRoom = (...ids: string[]) => Object.fromEntries(ids.map((id) => [id, { area_id: "area" }]));
|
||||
|
||||
test("a TV takes the media player of its room, a real TV before another player", () => {
|
||||
const hass = hassOf([entity("media_player.speaker", "idle"), entity("media_player.living_tv", "off", { device_class: "tv" })], inRoom("media_player.speaker", "media_player.living_tv"));
|
||||
const floor = floorWith([room], { furniture: [piece("tv", "tv_board")] });
|
||||
assert.equal(furnitureEntities(hass, [floor]).get("tv")?.entity, "media_player.living_tv");
|
||||
});
|
||||
|
||||
test("a desk's monitor does not take a smart speaker, but a TV board takes any player", () => {
|
||||
const hass = hassOf([entity("media_player.speaker", "idle")], inRoom("media_player.speaker"));
|
||||
assert.equal(furnitureEntities(hass, [floorWith([room], { furniture: [piece("desk", "desk")] })]).get("desk"), undefined);
|
||||
assert.equal(furnitureEntities(hass, [floorWith([room], { furniture: [piece("tv", "tv_board")] })]).get("tv")?.entity, "media_player.speaker");
|
||||
});
|
||||
|
||||
test("appliances look for a switch or player with a fitting name, and power on the same device or by name", () => {
|
||||
const hass = hassOf(
|
||||
[entity("switch.dishwasher_plug", "on"), entity("switch.lamp_plug", "on"), entity("sensor.dishwasher_power", "5", { device_class: "power" })],
|
||||
{ "switch.dishwasher_plug": { area_id: "area", device_id: "dw" }, "switch.lamp_plug": { area_id: "area" }, "sensor.dishwasher_power": { area_id: "area", device_id: "dw" } },
|
||||
);
|
||||
const links = furnitureEntities(hass, [floorWith([room], { furniture: [piece("dw", "dishwasher")] })]).get("dw");
|
||||
assert.deepEqual(links, { entity: "switch.dishwasher_plug", power: "sensor.dishwasher_power" });
|
||||
});
|
||||
|
||||
test("a power sensor can be found by name when the entity has none on its device", () => {
|
||||
const hass = hassOf([entity("sensor.fridge_power", "40", { device_class: "power" })], inRoom("sensor.fridge_power"));
|
||||
assert.deepEqual(furnitureEntities(hass, [floorWith([room], { furniture: [piece("f", "fridge")] })]).get("f"), { entity: null, power: "sensor.fridge_power" });
|
||||
});
|
||||
|
||||
test("lamps take a light of the room, preferring a fitting name, and each light is used once", () => {
|
||||
const hass = hassOf([entity("light.floor_standing", "on"), entity("light.main_ceiling", "on")], inRoom("light.floor_standing", "light.main_ceiling"));
|
||||
const floor = floorWith([room], { furniture: [piece("a", "lamp_ceiling"), piece("b", "lamp_ceiling")] });
|
||||
const links = furnitureEntities(hass, [floor]);
|
||||
assert.equal(links.get("a")?.entity, "light.main_ceiling");
|
||||
assert.equal(links.get("b")?.entity, "light.floor_standing");
|
||||
});
|
||||
|
||||
test("entities set by hand and placed devices are never taken by another piece", () => {
|
||||
const hass = hassOf([entity("light.one", "on"), entity("light.two", "on")], inRoom("light.one", "light.two"));
|
||||
const floor = floorWith([room], { furniture: [piece("a", "lamp_ceiling", { entity: "light.one" }), piece("b", "lamp_ceiling")], placements: [] });
|
||||
assert.equal(furnitureEntities(hass, [floor]).get("b")?.entity, "light.two");
|
||||
const placed = floorWith([room], { furniture: [piece("c", "lamp_ceiling")], placements: [{ entity_id: "light.one", x: 0, z: 0, y: null, mount: null }] });
|
||||
assert.equal(furnitureEntities(hass, [placed]).get("c")?.entity, "light.two");
|
||||
});
|
||||
|
||||
test("'none' keeps a piece unlinked and a piece outside every room finds nothing", () => {
|
||||
const hass = hassOf([entity("light.one", "on")], inRoom("light.one"));
|
||||
assert.equal(furnitureEntities(hass, [floorWith([room], { furniture: [piece("a", "lamp_ceiling", { entity: "none" })] })]).get("a"), undefined);
|
||||
assert.equal(furnitureEntities(hass, [floorWith([room], { furniture: [piece("a", "lamp_ceiling", { x: 20, z: 20 })] })]).get("a"), undefined);
|
||||
});
|
||||
|
||||
test("a robot vacuum and a radiator find their own kind in the room's area", () => {
|
||||
const hass = hassOf([entity("vacuum.rob", "docked"), entity("climate.heater", "heat"), entity("climate.other", "off")], { "vacuum.rob": { area_id: "area" }, "climate.heater": { area_id: "area" }, "climate.other": { area_id: "elsewhere" } });
|
||||
const links = furnitureEntities(hass, [floorWith([room], { furniture: [piece("v", "robot_vacuum"), piece("r", "radiator")] })]);
|
||||
assert.equal(links.get("v")?.entity, "vacuum.rob");
|
||||
assert.equal(links.get("r")?.entity, "climate.heater");
|
||||
});
|
||||
|
||||
test("a climate pack item finds a climate entity in its room's area", () => {
|
||||
setPacks([
|
||||
{
|
||||
id: "test.hvac",
|
||||
name: "HVAC",
|
||||
publisher: "Test",
|
||||
items: [
|
||||
{
|
||||
id: "mini_split",
|
||||
name: { en: "Mini split" },
|
||||
size: [0.9, 0.22, 0.28],
|
||||
climate: true,
|
||||
parts: [{ shape: "box", x: 0, z: 0, w: 1, d: 1, y: 0, h: 1, color: "body" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
const hass = hassOf(
|
||||
[entity("climate.ac", "cool"), entity("switch.plug", "on")],
|
||||
inRoom("climate.ac", "switch.plug"),
|
||||
);
|
||||
const floor = floorWith([room], {
|
||||
furniture: [piece("ac", "pack:test.hvac:mini_split")],
|
||||
});
|
||||
assert.equal(furnitureEntities(hass, [floor]).get("ac")?.entity, "climate.ac");
|
||||
setPacks([]);
|
||||
});
|
||||
|
||||
test("screens: built-in TVs and a few devices have one", () => {
|
||||
assert.equal(isMediaFurniture("tv_wall"), true);
|
||||
assert.equal(isMediaFurniture("sofa"), false);
|
||||
assert.equal(hasScreen("desk"), true);
|
||||
assert.equal(hasScreen("fridge_smart"), true);
|
||||
assert.equal(hasScreen("sofa"), false);
|
||||
});
|
||||
|
||||
test("picture rules: equal, contained (3+ letters), wildcard, attribute, missing", () => {
|
||||
const hass = hassOf([entity("media_player.tv", "playing", { app_name: "YouTube TV", volume: 0.5 })]);
|
||||
const rule = (state: string, attribute?: string) => ({ entity: "media_player.tv", state, attribute });
|
||||
assert.equal(pictureRuleMatches(hass, rule("playing")), true);
|
||||
assert.equal(pictureRuleMatches(hass, rule("PLAY")), true);
|
||||
assert.equal(pictureRuleMatches(hass, rule("pl")), false, "too short to match inside");
|
||||
assert.equal(pictureRuleMatches(hass, rule("*")), true);
|
||||
assert.equal(pictureRuleMatches(hass, rule("youtube", "app_name")), true);
|
||||
assert.equal(pictureRuleMatches(hass, rule("x", "nothing")), false);
|
||||
assert.equal(pictureRuleMatches(hass, { entity: "media_player.gone", state: "*" }), false);
|
||||
});
|
||||
|
||||
test("entities that ask first: placed devices, linked furniture and marked blinds", () => {
|
||||
const hass = hassOf([entity("light.a", "on"), entity("cover.blind", "open", { device_class: "shutter" }), entity("switch.s", "on")], { "light.a": { area_id: "area" }, "cover.blind": { area_id: "area" }, "switch.s": { area_id: "area" } });
|
||||
const floor = floorWith([room], {
|
||||
placements: [{ entity_id: "light.a", x: 0, z: 0, y: null, mount: null, confirm: true }],
|
||||
openings: [opening("w", "r", "window", { confirm: true } as never)],
|
||||
furniture: [piece("sw", "kitchen", { entity: "switch.s", confirm: true })],
|
||||
});
|
||||
assert.deepEqual([...confirmEntities(hass, [floor])].sort(), ["cover.blind", "light.a", "switch.s"]);
|
||||
});
|
||||
|
||||
test("a smart fridge's doors follow their sensors, unset or none means closed", () => {
|
||||
const hass = hassOf([entity("binary_sensor.l", "on"), entity("binary_sensor.r", "open"), entity("binary_sensor.x", "off")]);
|
||||
const floor = floorWith([room], { furniture: [piece("f1", "fridge_smart", { door_left: "binary_sensor.l", door_right: "none" }), piece("f2", "fridge_smart", { door_right: "binary_sensor.r" }), piece("f3", "fridge")] });
|
||||
const doors = fridgeDoors(hass, [floor]);
|
||||
assert.deepEqual(doors.get("f1"), { left: true, right: false });
|
||||
assert.deepEqual(doors.get("f2"), { left: false, right: true });
|
||||
assert.equal(doors.has("f3"), false);
|
||||
});
|
||||
|
||||
test("the room panel shows placed and linked entities, own picks and door sensors, minus hidden ones", () => {
|
||||
const hass = hassOf(
|
||||
[entity("light.placed", "on"), entity("light.lamp", "on", { friendly_name: "Ceiling lamp" }), entity("light.picked", "on"), entity("light.hidden", "on"), entity("binary_sensor.door", "off", { device_class: "door" }), entity("sensor.rest", "1", { device_class: "temperature" })],
|
||||
inRoom("light.placed", "light.lamp", "light.picked", "light.hidden", "binary_sensor.door", "sensor.rest"),
|
||||
);
|
||||
const r = { ...room, panel: ["light.picked", "light.gone"], hidden: ["light.hidden"] };
|
||||
const floor = floorWith([r], { placements: [{ entity_id: "light.placed", x: 1, z: 1, y: null, mount: null }], furniture: [piece("l", "lamp_ceiling")], openings: [opening("d", "r", "door")] });
|
||||
const { shown, more } = roomPanelEntities(hass, floor, r);
|
||||
assert.deepEqual(shown.sort(), ["binary_sensor.door", "light.lamp", "light.picked", "light.placed"]);
|
||||
assert.deepEqual(more, ["sensor.rest"]);
|
||||
});
|
||||
|
||||
test("a fridge shows its compartments' temperatures and warns when one is too warm", () => {
|
||||
const fmt = (c: number) => `${c.toFixed(1)} °C`;
|
||||
const hass = hassOf([
|
||||
entity("sensor.fridge", "4.2", { unit_of_measurement: "°C" }),
|
||||
entity("sensor.freezer", "-18", { unit_of_measurement: "°C" }),
|
||||
entity("sensor.warm", "9.1", { unit_of_measurement: "°C" }),
|
||||
entity("sensor.thawing", "-10", { unit_of_measurement: "°C" }),
|
||||
entity("sensor.fahrenheit", "50", { unit_of_measurement: "°F" }),
|
||||
entity("sensor.gone", "unavailable"),
|
||||
]);
|
||||
assert.deepEqual(coolingTemps(hass, { temp_entity: "sensor.fridge", temp_entity2: "sensor.freezer" }, fmt), { text: "4.2 °C · -18.0 °C", warm: false });
|
||||
assert.equal(coolingTemps(hass, { temp_entity: "sensor.warm" }, fmt)?.warm, true);
|
||||
assert.equal(coolingTemps(hass, { temp_entity2: "sensor.thawing" }, fmt)?.warm, true);
|
||||
// 50 °F are 10 °C: too warm for a fridge
|
||||
assert.deepEqual(coolingTemps(hass, { temp_entity: "sensor.fahrenheit" }, fmt), { text: "10.0 °C", warm: true });
|
||||
assert.equal(coolingTemps(hass, { temp_entity: "sensor.gone" }, fmt), null);
|
||||
assert.equal(coolingTemps(hass, { temp_entity: "none" }, fmt), null);
|
||||
assert.equal(isCooling("fridge"), true);
|
||||
assert.equal(isCooling("pack:nextfloor.a_kueche:fridge_freezer"), true);
|
||||
assert.equal(isCooling("pack:nextfloor.a_kueche:oven"), false);
|
||||
});
|
||||
|
||||
test("Outside lists what stands outside the rooms and what belongs to it; the room below no longer counts a roof device", () => {
|
||||
const hass = hassOf([entity("switch.valve", "off"), entity("sensor.weather", "12"), entity("light.inside", "on")]);
|
||||
const floor = floorWith([room], {
|
||||
placements: [
|
||||
{ entity_id: "switch.valve", x: 9, z: 9, y: null, mount: null },
|
||||
{ entity_id: "sensor.weather", x: 1, z: 1, y: null, mount: null, outside: true },
|
||||
{ entity_id: "light.inside", x: 2, z: 2, y: null, mount: null },
|
||||
],
|
||||
});
|
||||
assert.deepEqual(outsideEntities(hass, [floor]).sort(), ["sensor.weather", "switch.valve"]);
|
||||
assert.deepEqual(outsideEntities(hass, [floor], ["switch.valve"]), ["sensor.weather"], "a hidden device is left out (#83)");
|
||||
assert.deepEqual(roomPanelEntities(hass, floor, room).shown, ["light.inside"], "the weather station is not the room's");
|
||||
});
|
||||
|
||||
test("Outside lists the devices of the areas linked to gardens and pools, and a pool's pump", () => {
|
||||
const hass = hassOf([entity("light.terrace", "on"), entity("switch.pool_pump", "off"), entity("sensor.pool_water", "24", { device_class: "temperature" })], { "light.terrace": { area_id: "terrasse" } });
|
||||
const floor = floorWith([box("r", 0, 0, 4, 4)], {
|
||||
outdoor: [
|
||||
{ id: "t", type: "terrace", points: [[5, 0], [8, 0], [8, 3], [5, 3]], area_id: "terrasse" },
|
||||
{ id: "p", type: "pool", points: [[9, 0], [12, 0], [12, 3], [9, 3]], pump_entity: "switch.pool_pump", temp_entity: "sensor.pool_water" },
|
||||
],
|
||||
});
|
||||
assert.deepEqual(outsideEntities(hass, [floor]).sort(), ["light.terrace", "sensor.pool_water", "switch.pool_pump"]);
|
||||
});
|
||||
|
||||
test("a smart speaker takes the only free media player of its room, not a TV (#104)", () => {
|
||||
setPacks([{ id: "test.hifi", name: "Hifi", publisher: "Test", items: [{ id: "smart_speaker_ball", name: { en: "Smart speaker" }, size: [0.12, 0.12, 0.12], electric: true, parts: [{ shape: "box", x: 0, z: 0, w: 1, d: 1, y: 0, h: 1, color: "body" }] }] }]);
|
||||
const speaker = piece("sp", "pack:test.hifi:smart_speaker_ball");
|
||||
const only = hassOf([entity("media_player.echo", "idle")], inRoom("media_player.echo"));
|
||||
assert.equal(furnitureEntities(only, [floorWith([room], { furniture: [speaker] })]).get("sp")?.entity, "media_player.echo");
|
||||
const two = hassOf([entity("media_player.echo", "idle"), entity("media_player.other", "idle")], inRoom("media_player.echo", "media_player.other"));
|
||||
assert.equal(furnitureEntities(two, [floorWith([room], { furniture: [speaker] })]).get("sp")?.entity ?? null, null, "two players: no guess");
|
||||
setPacks([]);
|
||||
});
|
||||
|
||||
test("a device's own thermometer reads in Celsius, Fahrenheit turned over, nothing without a number (#112)", () => {
|
||||
const hass = hassOf([entity("sensor.inverter_temp", "41.5", { unit_of_measurement: "°C" }), entity("sensor.pc_temp", "122", { unit_of_measurement: "°F" }), entity("sensor.gone", "unavailable")]);
|
||||
assert.equal(deviceTempOf(hass, "sensor.inverter_temp"), 41.5);
|
||||
assert.equal(deviceTempOf(hass, "sensor.pc_temp"), 50);
|
||||
assert.equal(deviceTempOf(hass, "sensor.gone"), null);
|
||||
assert.equal(deviceTempOf(hass, "none"), null);
|
||||
assert.equal(deviceTempOf(hass, null), null);
|
||||
});
|
||||
@@ -0,0 +1,279 @@
|
||||
// Electric furniture and the entities it is linked to: TVs, fridges, lamps, a robot vacuum. Links can be set by
|
||||
// hand; otherwise they are found among the entities of the room the piece stands in, by their names.
|
||||
|
||||
import { pointInPolygon, type EntityRef, type Floor, type Room } from "../model.ts";
|
||||
import { isClimateFurniture, packItem, packScreen } from "../packs.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { entityName, kindOf } from "./kinds.ts";
|
||||
import { openingEntities } from "./openings.ts";
|
||||
import { areaEntities, roomEntities, entityAreaId, isPower, powerSensorsOf, primaryEntities } from "./registry.ts";
|
||||
|
||||
const TV_NAME = /\b(tv|fernseh|television|fire ?tv|apple ?tv|chromecast|shield)/i;
|
||||
const COOLING_NAME = /(kühl|fridge|gefrier|freezer)/i;
|
||||
const DISHWASHER_NAME = /(spülmaschine|geschirrspül|dishwasher)/i;
|
||||
const HOB_NAME = /(kochfeld|herd|induktion|cooktop)/i;
|
||||
|
||||
/** Name patterns of the entities that belong to a piece of electric furniture. */
|
||||
const FURNITURE_NAMES: Record<string, RegExp> = {
|
||||
robot_vacuum: /(saug|vacuum|robo|roomba|roborock|dreame|ecovacs|deebot)/i,
|
||||
tv_board: TV_NAME,
|
||||
tv_wall: TV_NAME,
|
||||
desk: /\b(pc|computer|rechner|desktop|monitor|workstation)/i,
|
||||
fridge: COOLING_NAME,
|
||||
fridge_smart: COOLING_NAME,
|
||||
stove: /(herd|kochfeld|cooktop|stove|induktion)/i,
|
||||
kitchen_tall: /(backofen|oven|ofen)/i,
|
||||
dishwasher: DISHWASHER_NAME,
|
||||
washer: /(waschmaschine|washer|washing)/i,
|
||||
dryer: /(trockner|dryer)/i,
|
||||
kitchen: /(kaffee|coffee|wasserkocher|kettle)/i,
|
||||
island: HOB_NAME,
|
||||
sink: DISHWASHER_NAME,
|
||||
radiator: /(heiz|radiator|thermostat|climate|hk|trv)/i,
|
||||
};
|
||||
|
||||
/** Name hints for choosing a lamp's light: one that fits the name wins, else any free one. */
|
||||
const LAMP_NAMES: Record<string, RegExp> = {
|
||||
lamp_ceiling: /(decke|ceiling|haupt|main)/i,
|
||||
lamp_downlight: /(spot|strahler|downlight|einbau)/i,
|
||||
lamp_spot: /(spot|strahler)/i,
|
||||
lamp_panel: /(panel|decke|ceiling)/i,
|
||||
lamp_uplight: /(fluter|uplight|steh)/i,
|
||||
lamp_bollard: /(weg|garten|garden|path|poller|außen|aussen|outdoor)/i,
|
||||
lamp_garden: /(garten|garden|spot|außen|aussen|outdoor|baum|tree)/i,
|
||||
lamp_pendant: /(pendel|pendant|hänge|esstisch|dining)/i,
|
||||
ceiling_fan: /(ventilator|fan)/i,
|
||||
lamp_floor: /(steh|floor)/i,
|
||||
lamp_table: /(tisch|nacht|table|bedside|lese|reading)/i,
|
||||
lamp_wall: /(wand|wall)/i,
|
||||
led_strip: /(led|strip|streifen|leiste|band)/i,
|
||||
};
|
||||
|
||||
const TV_FURNITURE = new Set(["tv_board", "tv_wall"]);
|
||||
|
||||
export interface FurnitureLinks {
|
||||
entity: string | null;
|
||||
power: string | null;
|
||||
/** Ceiling fan: its fan entity. */
|
||||
fan?: string | null;
|
||||
}
|
||||
|
||||
/** Whether a rule of a screen picture holds now: the state or attribute equals the value or contains it (3+ letters); "*" always. */
|
||||
export function pictureRuleMatches(hass: HomeAssistant, rule: { entity: string; attribute?: string | null; state: string }): boolean {
|
||||
const state = hass.states[rule.entity];
|
||||
if (!state) return false;
|
||||
const raw = rule.attribute ? state.attributes[rule.attribute] : state.state;
|
||||
if (raw === undefined || raw === null) return false;
|
||||
const wanted = rule.state.trim().toLowerCase();
|
||||
const actual = String(raw).toLowerCase();
|
||||
return wanted === "*" || actual === wanted || (wanted.length >= 3 && actual.includes(wanted));
|
||||
}
|
||||
|
||||
/** Furniture that shows a media player on a screen: the built-in TVs and pack items with a screen part. */
|
||||
export const isMediaFurniture = (type: string): boolean => TV_FURNITURE.has(type) || !!packScreen(type);
|
||||
|
||||
/** Speakers without a screen (smart speakers, hi-fi, multiroom): they link to a media player for volume and playback. */
|
||||
export const isSpeakerFurniture = (type: string): boolean => !!packItem(type)?.electric && /speaker|multiroom|soundbar/.test(type.split(":").pop() ?? type);
|
||||
|
||||
/** Furniture whose screen can show a media player or a picture rule: media furniture, a desk's monitor, a smart fridge's display. */
|
||||
export const hasScreen = (type: string): boolean => isMediaFurniture(type) || type === "desk" || type === "fridge_smart";
|
||||
|
||||
const isSet = (ref: string | null | undefined): ref is string => !!ref && ref !== "none";
|
||||
|
||||
/** The power sensor of an entity: itself, or another power sensor on its device. */
|
||||
function powerOfDevice(hass: HomeAssistant, id: string): string | null {
|
||||
if (isPower(hass, id)) return id;
|
||||
const device = hass.entities?.[id]?.device_id;
|
||||
return device ? (powerSensorsOf(hass, device).find((e) => e !== id) ?? null) : null;
|
||||
}
|
||||
|
||||
const roomOf = (floor: Floor, x: number, z: number): Room | undefined => floor.rooms.find((r) => r.points.length >= 3 && pointInPolygon([x, z], r.points));
|
||||
|
||||
/** The best-fitting free entity of a kind for a name pattern; with `fallback`, the first free one when none fits. */
|
||||
function pickByName(candidates: string[], pattern: RegExp | undefined, describe: (id: string) => string, fallback: boolean): string | null {
|
||||
return candidates.find((id) => pattern?.test(describe(id))) ?? (fallback ? (candidates[0] ?? null) : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The entities of electric furniture. Set by hand, or (when unset) found in the area of the room the piece stands in:
|
||||
* lamps get a light, radiators a thermostat, TVs a media player (a real TV first), other appliances an entity whose
|
||||
* name fits. The power sensor comes from the same device or from a sensor whose name fits. Every entity is used once.
|
||||
*/
|
||||
export function furnitureEntities(hass: HomeAssistant, floors: readonly Floor[]): Map<string, FurnitureLinks> {
|
||||
const links = new Map<string, FurnitureLinks>();
|
||||
for (const floor of floors) {
|
||||
// entities set by hand and devices placed in the plan (an Echo Show in the corner) are taken already
|
||||
const used = new Set<string>(
|
||||
[...floor.furniture.flatMap((f) => [f.entity, f.power, f.fan_entity]), ...floor.placements.map((p) => p.entity_id)].filter(isSet),
|
||||
);
|
||||
for (const piece of floor.furniture) {
|
||||
const isLamp = piece.type in LAMP_NAMES;
|
||||
const isClimate = isClimateFurniture(piece.type);
|
||||
const pattern = isLamp ? LAMP_NAMES[piece.type] : FURNITURE_NAMES[piece.type];
|
||||
if (!pattern && !isClimate && !isSpeakerFurniture(piece.type) && piece.entity == null && piece.power == null) continue;
|
||||
const room = roomOf(floor, piece.x, piece.z);
|
||||
const free = (room ? primaryEntities(hass, roomEntities(hass, room)) : []).filter((id) => !used.has(id));
|
||||
const describe = (id: string) => `${id} ${entityName(hass, id)}`;
|
||||
const ofKind = (kind: string) => free.filter((id) => kindOf(id) === kind);
|
||||
|
||||
let entity: string | null = piece.entity === "none" ? null : (piece.entity ?? null);
|
||||
if (piece.entity == null) {
|
||||
if (piece.type === "ceiling_fan") {
|
||||
// the fan's light kit: a light on the same device as a free fan, or one whose name fits (a fan without light takes none)
|
||||
const all = (room ? roomEntities(hass, room) : []).filter((id) => !used.has(id));
|
||||
const devices = new Set(all.filter((id) => kindOf(id) === "fan").map((id) => hass.entities?.[id]?.device_id).filter(Boolean));
|
||||
entity = all.find((id) => kindOf(id) === "light" && devices.has(hass.entities?.[id]?.device_id)) ?? pickByName(ofKind("light"), pattern, describe, false);
|
||||
} else if (isLamp) entity = pickByName(ofKind("light"), pattern, describe, true);
|
||||
else if (piece.type === "robot_vacuum") {
|
||||
// vacuums are not a device kind of their own, so they are looked up in the room's area directly
|
||||
const area = room?.area_id ?? null;
|
||||
entity = Object.keys(hass.entities ?? {}).find((id) => id.startsWith("vacuum.") && !used.has(id) && entityAreaId(hass, id) === area) ?? null;
|
||||
} else if (piece.type === "radiator" || isClimate) entity = pickByName(ofKind("climate"), pattern, describe, true);
|
||||
else if (isMediaFurniture(piece.type)) {
|
||||
const players = ofKind("media");
|
||||
// a TV takes the TV (or any player of the room); a monitor or smart speaker only a player whose name fits
|
||||
entity = players.find((id) => hass.states[id]?.attributes.device_class === "tv") ?? pickByName(players, pattern, describe, TV_FURNITURE.has(piece.type));
|
||||
} else if (isSpeakerFurniture(piece.type)) {
|
||||
// a speaker takes a player whose name fits, else the only free player of its room (#104)
|
||||
const players = ofKind("media").filter((id) => hass.states[id]?.attributes.device_class !== "tv");
|
||||
entity = pickByName(players, pattern, describe, false) ?? (players.length === 1 ? players[0] : null);
|
||||
} else if (pattern) entity = free.find((id) => ["switch", "media", "fan"].includes(kindOf(id) ?? "") && pattern.test(describe(id))) ?? null;
|
||||
if (entity) used.add(entity);
|
||||
}
|
||||
|
||||
let power: string | null = piece.power === "none" ? null : (piece.power ?? null);
|
||||
if (piece.power == null) {
|
||||
power = entity ? powerOfDevice(hass, entity) : null;
|
||||
if (!power && pattern && room && !isLamp) power = roomEntities(hass, room).find((id) => isPower(hass, id) && !used.has(id) && pattern.test(describe(id))) ?? null;
|
||||
if (power) used.add(power);
|
||||
}
|
||||
// a ceiling fan's fan: on the light's device first, else a free fan of the room
|
||||
let fan: string | null = null;
|
||||
if (piece.type === "ceiling_fan") {
|
||||
fan = piece.fan_entity === "none" ? null : (piece.fan_entity ?? null);
|
||||
if (piece.fan_entity == null) {
|
||||
// every fan of the area: the light kit's device may count as one device with the light, which only keeps one of them
|
||||
const fans = (room ? roomEntities(hass, room) : []).filter((id) => kindOf(id) === "fan" && !used.has(id));
|
||||
const device = entity ? hass.entities?.[entity]?.device_id : undefined;
|
||||
fan = (device ? fans.find((id) => hass.entities?.[id]?.device_id === device) : undefined) ?? fans[0] ?? null;
|
||||
if (fan) used.add(fan);
|
||||
}
|
||||
}
|
||||
if (entity || power || fan) links.set(piece.id, { entity, power, ...(piece.type === "ceiling_fan" ? { fan } : {}) });
|
||||
}
|
||||
}
|
||||
return links;
|
||||
}
|
||||
|
||||
/** Entities that ask before they are switched: placed devices, and furniture, blinds and garage doors marked "ask first". */
|
||||
export function confirmEntities(hass: HomeAssistant, floors: readonly Floor[]): Set<string> {
|
||||
const asking = new Set<string>();
|
||||
const furnitureLinks = furnitureEntities(hass, floors);
|
||||
const openingLinks = floors.some((f) => f.openings.some((o) => o.confirm)) ? openingEntities(hass, floors) : null;
|
||||
for (const floor of floors) {
|
||||
for (const placed of floor.placements) if (placed.confirm) asking.add(placed.entity_id);
|
||||
for (const opening of floor.openings) {
|
||||
const cover = opening.confirm ? openingLinks?.get(opening.id)?.cover : null;
|
||||
if (isSet(cover)) asking.add(cover);
|
||||
}
|
||||
for (const piece of floor.furniture) {
|
||||
const entity = piece.confirm ? furnitureLinks.get(piece.id)?.entity : null;
|
||||
if (isSet(entity)) asking.add(entity);
|
||||
}
|
||||
}
|
||||
return asking;
|
||||
}
|
||||
|
||||
/** Fridges and freezers (also pack items named so): they can show the temperatures of their compartments. */
|
||||
export const isCooling = (type: string): boolean => type === "fridge" || type === "fridge_smart" || /(fridge|freezer|kuehl|gefrier|chest_freezer)/.test(type.slice(type.lastIndexOf(":") + 1));
|
||||
|
||||
/** Above these a fridge and a freezer count as too warm (°C). */
|
||||
export const FRIDGE_WARM = 8;
|
||||
export const FREEZER_WARM = -12;
|
||||
|
||||
/**
|
||||
* The temperatures a fridge shows: its fridge and freezer compartment ("4.2 °C · −18.0 °C"), and whether one is too warm.
|
||||
* Null when no sensor is set or none tells a number.
|
||||
*/
|
||||
export function coolingTemps(hass: HomeAssistant, piece: { temp_entity?: string | null; temp_entity2?: string | null }, format: (celsius: number) => string): { text: string; warm: boolean } | null {
|
||||
const read = (id: string | null | undefined): number | null => {
|
||||
if (!isSet(id)) return null;
|
||||
const st = hass.states[id];
|
||||
const value = st ? Number(st.state) : NaN;
|
||||
if (!Number.isFinite(value)) return null;
|
||||
// a sensor in Fahrenheit is turned into Celsius, so the limits hold
|
||||
return st!.attributes.unit_of_measurement === "°F" ? ((value - 32) * 5) / 9 : value;
|
||||
};
|
||||
const fridge = read(piece.temp_entity);
|
||||
const freezer = read(piece.temp_entity2);
|
||||
if (fridge === null && freezer === null) return null;
|
||||
const parts = [fridge, freezer].filter((v): v is number => v !== null).map(format);
|
||||
return { text: parts.join(" · "), warm: (fridge !== null && fridge > FRIDGE_WARM) || (freezer !== null && freezer > FREEZER_WARM) };
|
||||
}
|
||||
|
||||
/** A device runs hot from this temperature (°C): its pin is marked like a running one (#112). */
|
||||
export const DEVICE_HOT = 60;
|
||||
|
||||
/** A device's own thermometer in °C (a sensor in Fahrenheit is turned into Celsius); null when none is set or it tells no number. */
|
||||
export function deviceTempOf(hass: HomeAssistant, id: string | null | undefined): number | null {
|
||||
if (!isSet(id)) return null;
|
||||
const st = hass.states[id];
|
||||
const value = st ? Number(st.state) : NaN;
|
||||
if (!Number.isFinite(value)) return null;
|
||||
return st!.attributes.unit_of_measurement === "°F" ? ((value - 32) * 5) / 9 : value;
|
||||
}
|
||||
|
||||
/** Which doors of each smart fridge stand open now (a door sensor that says "on" or "open"). */
|
||||
export function fridgeDoors(hass: HomeAssistant, floors: readonly Floor[]): Map<string, { left: boolean; right: boolean }> {
|
||||
const isOpen = (sensor: EntityRef | undefined) => isSet(sensor) && ["on", "open"].includes(hass.states[sensor]?.state ?? "");
|
||||
const doors = new Map<string, { left: boolean; right: boolean }>();
|
||||
for (const piece of floors.flatMap((f) => f.furniture)) if (piece.type === "fridge_smart") doors.set(piece.id, { left: isOpen(piece.door_left), right: isOpen(piece.door_right) });
|
||||
return doors;
|
||||
}
|
||||
|
||||
/**
|
||||
* The entities of a room's panel: what the plan shows in the room (placed devices, linked furniture, the blinds and
|
||||
* contacts of its doors and windows) plus those picked for the panel. `more` are the other entities of the room's
|
||||
* area, offered on request. Entities the editor hid for the room never appear.
|
||||
*/
|
||||
export function roomPanelEntities(hass: HomeAssistant, floor: Floor, room: Room): { shown: string[]; more: string[] } {
|
||||
const inside = (x: number, z: number) => pointInPolygon([x, z], room.points);
|
||||
const furnitureLinks = furnitureEntities(hass, [floor]);
|
||||
const openingLinks = openingEntities(hass, [floor]);
|
||||
const hidden = new Set(room.hidden ?? []);
|
||||
const candidates = [
|
||||
...floor.placements.filter((p) => !p.outside && inside(p.x, p.z)).map((p) => p.entity_id),
|
||||
...floor.furniture.filter((f) => inside(f.x, f.z)).flatMap((f) => [furnitureLinks.get(f.id)?.entity, furnitureLinks.get(f.id)?.power]),
|
||||
...floor.openings
|
||||
.filter((o) => o.room_id === room.id)
|
||||
.flatMap((o) => {
|
||||
const e = openingLinks.get(o.id);
|
||||
return e ? [e.cover, e.contact, e.tilt, e.contact2] : [];
|
||||
}),
|
||||
...(room.panel ?? []),
|
||||
];
|
||||
const shown = [...new Set(candidates.filter((id): id is string => !!id && !!hass.states[id]))].filter((id) => !hidden.has(id));
|
||||
const isShown = new Set(shown);
|
||||
return { shown, more: roomEntities(hass, room).filter((id) => !isShown.has(id) && !hidden.has(id)) };
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Outside: the devices placed outside every room outline (the garden's valves and lights, a mower, the grid connection
|
||||
* outside), and those marked as belonging to Outside wherever they stand (a weather station on the roof), on all floors.
|
||||
*/
|
||||
export function outsideEntities(hass: HomeAssistant, floors: readonly Floor[], hidden: readonly string[] = []): string[] {
|
||||
const out: (string | null | undefined)[] = [];
|
||||
for (const floor of floors) {
|
||||
const indoors = (x: number, z: number) => floor.rooms.some((room) => room.points.length >= 3 && pointInPolygon([x, z], room.points));
|
||||
const links = furnitureEntities(hass, [floor]);
|
||||
out.push(...floor.placements.filter((p) => p.outside || !indoors(p.x, p.z)).map((p) => p.entity_id));
|
||||
out.push(...floor.furniture.filter((f) => !indoors(f.x, f.z)).flatMap((f) => [links.get(f.id)?.entity, links.get(f.id)?.power]));
|
||||
// gardens, terraces and pools linked to a Home Assistant area bring that area's devices, and a pool its pump and thermometer
|
||||
for (const a of floor.outdoor ?? []) {
|
||||
if (a.area_id) out.push(...primaryEntities(hass, areaEntities(hass, a.area_id)));
|
||||
out.push(a.pump_entity, a.temp_entity);
|
||||
}
|
||||
}
|
||||
return [...new Set(out.filter((id): id is string => !!id && !!hass.states[id] && !hidden.includes(id)))];
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity, hassOf } from "./fixtures.ts";
|
||||
import { gangEntities, gangGlows } from "./gangs.ts";
|
||||
|
||||
const hass = hassOf([
|
||||
entity("light.ceiling", "on", { brightness: 255, rgb_color: [255, 0, 0] }),
|
||||
entity("light.off", "off"),
|
||||
entity("switch.kettle", "on", { current_power_w: 1600 }),
|
||||
entity("switch.lamp", "on", { current_power_w: 4 }),
|
||||
entity("switch.gone", "unavailable"),
|
||||
]);
|
||||
|
||||
test("a button linked to a light glows in the light's colour; one that is off stays dark", () => {
|
||||
const glows = gangGlows(hass, ["light.ceiling", "light.off"], false);
|
||||
assert.equal(glows.length, 1);
|
||||
assert.equal(glows[0].gang, 0);
|
||||
assert.deepEqual(glows[0].color.map((c) => Math.round(c * 10) / 10), [1, 0, 0]);
|
||||
});
|
||||
|
||||
test("a socket glows green, brighter the more it draws", () => {
|
||||
const [kettle, lamp] = gangGlows(hass, ["switch.kettle", "switch.lamp"], true);
|
||||
assert.deepEqual([kettle.gang, lamp.gang], [0, 1]);
|
||||
assert.ok(kettle.color[1] > kettle.color[0], "green");
|
||||
assert.ok(kettle.level > lamp.level);
|
||||
});
|
||||
|
||||
test("empty, 'none' and unavailable buttons are left out but keep the others in place", () => {
|
||||
const glows = gangGlows(hass, [null, "none", "switch.gone", "switch.kettle"], false);
|
||||
assert.deepEqual(glows.map((g) => g.gang), [3]);
|
||||
assert.deepEqual(gangEntities([null, "switch.a", "none", "switch.b", "switch.c"], 4), ["switch.a", "switch.b"]);
|
||||
assert.deepEqual(gangEntities(undefined, 2), []);
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
// Light switches and sockets with several buttons (gangs): which of them glow, and in what colour.
|
||||
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { isActive, isUnavailable, kindOf, lightGlow, type Rgb } from "./kinds.ts";
|
||||
|
||||
export interface GangGlow {
|
||||
gang: number;
|
||||
color: Rgb;
|
||||
level: number;
|
||||
}
|
||||
|
||||
const SOCKET_GREEN: Rgb = [0.25, 0.9, 0.45];
|
||||
const SWITCH_WARM: Rgb = [1, 0.82, 0.55];
|
||||
|
||||
/** The power a socket's entity draws, if it reports one (W): its own state for a power sensor, else a power attribute. */
|
||||
function drawn(hass: HomeAssistant, id: string): number | null {
|
||||
const st = hass.states[id];
|
||||
const value = Number(st?.attributes.current_power_w ?? st?.attributes.power ?? NaN);
|
||||
return Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The glowing buttons of a switch plate or socket. A button linked to a light glows in the light's colour and brightness; anything
|
||||
* else that is on glows warm on a switch and green on a socket, brighter the more it draws.
|
||||
*/
|
||||
export function gangGlows(hass: HomeAssistant, entities: readonly (string | null | undefined)[], socket: boolean): GangGlow[] {
|
||||
const out: GangGlow[] = [];
|
||||
entities.forEach((id, gang) => {
|
||||
if (!id || id === "none") return;
|
||||
const st = hass.states[id];
|
||||
if (!st || isUnavailable(st)) return;
|
||||
if (kindOf(id) === "light") {
|
||||
const lit = lightGlow(st);
|
||||
if (lit) out.push({ gang, color: lit.color, level: lit.level });
|
||||
return;
|
||||
}
|
||||
if (!isActive(st) && st.state !== "on") return;
|
||||
const watts = socket ? drawn(hass, id) : null;
|
||||
const level = watts === null ? 0.8 : Math.min(1, 0.45 + Math.sqrt(Math.max(0, watts)) / 40);
|
||||
out.push({ gang, color: socket ? SOCKET_GREEN : SWITCH_WARM, level });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The entities of a plate that can be switched, in button order. */
|
||||
export const gangEntities = (entities: readonly (string | null | undefined)[] | undefined, gangs: number): string[] =>
|
||||
(entities ?? []).slice(0, gangs).filter((id): id is string => !!id && id !== "none");
|
||||
@@ -0,0 +1,19 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { emptyBuilding, newFloor, type OutdoorArea } from "../model.ts";
|
||||
import { entity, hassOf } from "./fixtures.ts";
|
||||
import { gateStates } from "./gates.ts";
|
||||
|
||||
test("a gate is open while its entity says open, on or unlocked, or its contact is on", () => {
|
||||
const b = emptyBuilding();
|
||||
const f = newFloor("g", "G", 0);
|
||||
f.outdoor = [{ id: "z", type: "fence", points: [[0, 0], [8, 0], [8, 4], [0, 4]], gates: [
|
||||
{ id: "a", edge: 0, offset: 2, width: 1, kind: "single", entity: "cover.tor" },
|
||||
{ id: "b", edge: 1, offset: 2, width: 1, kind: "single", contact: "binary_sensor.tor_kontakt" },
|
||||
{ id: "c", edge: 2, offset: 2, width: 1, kind: "sliding", entity: "switch.schiebetor", contact: "binary_sensor.x" },
|
||||
{ id: "d", edge: 3, offset: 2, width: 1, kind: "single" },
|
||||
] } as OutdoorArea];
|
||||
b.floors = [f];
|
||||
const states = gateStates(hassOf([entity("cover.tor", "open"), entity("binary_sensor.tor_kontakt", "on"), entity("switch.schiebetor", "off"), entity("binary_sensor.x", "off")]), b);
|
||||
assert.deepEqual([...states], [["a", true], ["b", true], ["c", false]], "a gate without any entity has no state");
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
// Gates in fences: whether each is open, from the entity that drives it (cover open, switch on, lock unlocked) or its contact (on = open).
|
||||
|
||||
import type { Building } from "../model.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
|
||||
/** Gate id → open, for every gate of every fence that has an entity or a contact with a state. */
|
||||
export function gateStates(hass: HomeAssistant, building: Building): Map<string, boolean> {
|
||||
const out = new Map<string, boolean>();
|
||||
for (const floor of building.floors) {
|
||||
for (const area of floor.outdoor ?? []) {
|
||||
for (const gate of area.gates ?? []) {
|
||||
const driver = gate.entity ? hass.states[gate.entity]?.state : undefined;
|
||||
const contact = gate.contact ? hass.states[gate.contact]?.state : undefined;
|
||||
if (driver === undefined && contact === undefined) continue;
|
||||
const byDriver = driver === "open" || driver === "opening" || driver === "on" || driver === "unlocked" || driver === "unlocking";
|
||||
out.set(gate.id, byDriver || contact === "on");
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity, hassOf } from "./fixtures.ts";
|
||||
import { hasPost, pickupDays, plantThirst, remainingMinutes } from "./household.ts";
|
||||
|
||||
const now = new Date(2026, 9, 26, 9, 30).getTime(); // Monday 26 October 2026
|
||||
|
||||
test("a bin's next pickup from all the ways sensors write it", () => {
|
||||
assert.equal(pickupDays(entity("sensor.bin", "3"), now), 3);
|
||||
assert.equal(pickupDays(entity("sensor.bin", "irgendwas", { daysTo: 2 }), now), 2, "Waste Collection Schedule's daysTo");
|
||||
assert.equal(pickupDays(entity("sensor.bin", "Heute"), now), 0);
|
||||
assert.equal(pickupDays(entity("sensor.bin", "morgen"), now), 1);
|
||||
assert.equal(pickupDays(entity("sensor.bin", "Übermorgen"), now), 2);
|
||||
assert.equal(pickupDays(entity("sensor.bin", "Mo, 02.11.2026"), now), 7, "a date with numbers in it is a date, not 2 days");
|
||||
assert.equal(pickupDays(entity("sensor.bin", "2026-10-29"), now), 3);
|
||||
assert.equal(pickupDays(entity("sensor.bin", "29.10."), now), 3);
|
||||
assert.equal(pickupDays(entity("sensor.bin", "Restabfall in 4 Tagen"), now), 4);
|
||||
assert.equal(pickupDays(entity("sensor.bin", "unknown"), now), null);
|
||||
assert.equal(pickupDays(entity("sensor.bin", "keine Termine"), now), null);
|
||||
});
|
||||
|
||||
test("post in the mailbox", () => {
|
||||
assert.equal(hasPost(entity("binary_sensor.mail", "on")), true);
|
||||
assert.equal(hasPost(entity("binary_sensor.mail", "off")), false);
|
||||
assert.equal(hasPost(entity("sensor.mail", "Post")), true);
|
||||
assert.equal(hasPost(entity("sensor.mail", "unavailable")), false);
|
||||
});
|
||||
|
||||
test("a plant is thirsty below its threshold", () => {
|
||||
assert.deepEqual(plantThirst(entity("sensor.soil", "12")), { moisture: 12, thirsty: true });
|
||||
assert.deepEqual(plantThirst(entity("sensor.soil", "35")), { moisture: 35, thirsty: false });
|
||||
assert.equal(plantThirst(entity("sensor.soil", "35"), 40)?.thirsty, true);
|
||||
assert.equal(plantThirst(entity("sensor.soil", "unknown")), null);
|
||||
});
|
||||
|
||||
test("an appliance's time left from a duration or an end time on its device", () => {
|
||||
const hass = hassOf([
|
||||
entity("sensor.washer_remaining_time", "25", { unit_of_measurement: "min" }),
|
||||
entity("sensor.dryer_programmende", new Date(now + 90 * 60000).toISOString(), { device_class: "timestamp" }),
|
||||
entity("sensor.dish_rest", "1:05:00"),
|
||||
entity("sensor.washer_power", "1800", { unit_of_measurement: "W" }),
|
||||
]);
|
||||
assert.equal(remainingMinutes(hass, ["sensor.washer_power", "sensor.washer_remaining_time"], now), 25);
|
||||
assert.equal(remainingMinutes(hass, ["sensor.dryer_programmende"], now), 90);
|
||||
assert.equal(remainingMinutes(hass, ["sensor.dish_rest"], now), 65);
|
||||
assert.equal(remainingMinutes(hass, ["sensor.washer_power"], now), null, "a power sensor is no time left");
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
// The household: waste bins that know their next pickup, a mailbox with post in it, thirsty plants, and the time a washer, dryer or
|
||||
// dishwasher has left. Pure readings of entity states; the 3D view turns them into pins, texts and glows.
|
||||
|
||||
import type { HassEntity, HomeAssistant } from "../types.ts";
|
||||
import { isUnavailable } from "./kinds.ts";
|
||||
|
||||
const DAY = 86_400_000;
|
||||
const startOfDay = (t: number) => {
|
||||
const d = new Date(t);
|
||||
d.setHours(0, 0, 0, 0);
|
||||
return d.getTime();
|
||||
};
|
||||
|
||||
/** A date written in a state: ISO (2026-10-29), German (29.10.2026, 29.10.) or US (10/29/2026); null when there is none. */
|
||||
function dateIn(text: string, now: number): number | null {
|
||||
let m = /(\d{4})-(\d{2})-(\d{2})/.exec(text);
|
||||
if (m) return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])).getTime();
|
||||
m = /(\d{1,2})\.(\d{1,2})\.(\d{4}|\d{2})?/.exec(text);
|
||||
if (m) {
|
||||
const year = m[3] ? (m[3].length === 2 ? 2000 + Number(m[3]) : Number(m[3])) : new Date(now).getFullYear();
|
||||
let t = new Date(year, Number(m[2]) - 1, Number(m[1])).getTime();
|
||||
// "29.10." without a year in the past means next year
|
||||
if (!m[3] && t < startOfDay(now)) t = new Date(year + 1, Number(m[2]) - 1, Number(m[1])).getTime();
|
||||
return t;
|
||||
}
|
||||
m = /(\d{1,2})\/(\d{1,2})\/(\d{4})/.exec(text);
|
||||
if (m) return new Date(Number(m[3]), Number(m[1]) - 1, Number(m[2])).getTime();
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Days until a waste bin is collected (0 = today), from its sensor: a number of days, a daysTo attribute (Waste Collection Schedule),
|
||||
* "today"/"tomorrow" (also German), a date, or a text with a number of days in it. Null when the sensor says nothing usable.
|
||||
*/
|
||||
export function pickupDays(st: HassEntity | undefined, now = Date.now()): number | null {
|
||||
if (!st || isUnavailable(st)) return null;
|
||||
const attr = Number(st.attributes.daysTo);
|
||||
if (st.attributes.daysTo !== undefined && Number.isFinite(attr)) return Math.max(0, Math.round(attr));
|
||||
const state = String(st.state).trim();
|
||||
if (/^-?\d+(\.\d+)?$/.test(state)) return Math.max(0, Math.round(Number(state)));
|
||||
const lower = state.toLowerCase();
|
||||
if (/\b(heute|today)\b/.test(lower)) return 0;
|
||||
// (no \b here: for JavaScript, "ü" is no word character)
|
||||
if (lower.includes("übermorgen") || lower.includes("uebermorgen")) return 2;
|
||||
if (/\b(morgen|tomorrow)\b/.test(lower)) return 1;
|
||||
// a date goes before a number in the text ("Mon, 26.10.2026" holds numbers that are no day count)
|
||||
const date = dateIn(state, now) ?? (st.attributes.device_class === "timestamp" || st.attributes.device_class === "date" ? Date.parse(state) : null);
|
||||
if (date !== null && Number.isFinite(date)) return Math.max(0, Math.round((startOfDay(date) - startOfDay(now)) / DAY));
|
||||
const days = /(\d+)\s*(tag|tage|tagen|day|days)\b/i.exec(state);
|
||||
return days ? Number(days[1]) : null;
|
||||
}
|
||||
|
||||
/** Whether there is post in the mailbox: its sensor is on (a binary sensor) or says so. */
|
||||
export function hasPost(st: HassEntity | undefined): boolean {
|
||||
if (!st || isUnavailable(st)) return false;
|
||||
return st.state === "on" || /^(post|mail|yes|ja|true|voll|full|detected)$/i.test(st.state.trim());
|
||||
}
|
||||
|
||||
/** A plant's soil moisture in percent, and whether it is thirsty (below `below`, 20 % by default). */
|
||||
export function plantThirst(st: HassEntity | undefined, below = 20): { moisture: number; thirsty: boolean } | null {
|
||||
if (!st || isUnavailable(st)) return null;
|
||||
const moisture = Number(st.state);
|
||||
if (!Number.isFinite(moisture)) return st.entity_id.startsWith("binary_sensor.") ? { moisture: NaN, thirsty: st.state === "on" } : null;
|
||||
return { moisture, thirsty: moisture < below };
|
||||
}
|
||||
|
||||
const REMAINING = /remain|rest|verbleib|time_left|timeleft|finish|end_time|fertig|programmende|program_end|done_at/i;
|
||||
|
||||
/**
|
||||
* Minutes a washer, dryer or dishwasher has left, from a sensor on its device: a duration (minutes, hours, seconds, or h:mm:ss) or a
|
||||
* timestamp of the end. Null when the device has no such sensor or it is not running.
|
||||
*/
|
||||
export function remainingMinutes(hass: HomeAssistant, deviceEntities: readonly string[], now = Date.now()): number | null {
|
||||
for (const id of deviceEntities) {
|
||||
if (!id.startsWith("sensor.") || !REMAINING.test(`${id} ${hass.states[id]?.attributes.friendly_name ?? ""}`)) continue;
|
||||
const st = hass.states[id];
|
||||
if (!st || isUnavailable(st)) continue;
|
||||
const a = st.attributes;
|
||||
if (a.device_class === "timestamp") {
|
||||
const end = Date.parse(st.state);
|
||||
if (Number.isFinite(end) && end > now) return Math.ceil((end - now) / 60000);
|
||||
continue;
|
||||
}
|
||||
const clock = /^(\d+):(\d{2})(?::(\d{2}))?$/.exec(st.state.trim());
|
||||
if (clock) {
|
||||
const mins = clock[3] !== undefined ? Number(clock[1]) * 60 + Number(clock[2]) + Number(clock[3]) / 60 : Number(clock[1]) * 60 + Number(clock[2]);
|
||||
if (mins > 0) return Math.ceil(mins);
|
||||
continue;
|
||||
}
|
||||
const value = Number(st.state);
|
||||
if (!Number.isFinite(value) || value <= 0) continue;
|
||||
const unit = String(a.unit_of_measurement ?? "min").toLowerCase();
|
||||
return Math.ceil(unit === "h" ? value * 60 : unit === "s" ? value / 60 : value);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The other entities of an entity's device (its remaining-time sensor sits next to its switch or power sensor). */
|
||||
export function deviceSiblings(hass: HomeAssistant, id: string | null | undefined): string[] {
|
||||
const device = id ? hass.entities?.[id]?.device_id : null;
|
||||
return device && hass.entities ? Object.values(hass.entities).filter((e) => e.device_id === device).map((e) => e.entity_id) : [];
|
||||
}
|
||||
|
||||
/** Minutes as "25 min" or "1 h 05 min". */
|
||||
export const minutesText = (m: number): string => (m < 60 ? `${m} min` : `${Math.floor(m / 60)} h ${String(m % 60).padStart(2, "0")} min`);
|
||||
@@ -0,0 +1,146 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { appColor, assumedCover, defaultHeight, domainOf, entityName, fixtureGlow, groupCovers, fromCelsius, isActive, isPlaceable, isStatusSensor, isUnavailable, kelvinToRgb, kindOf, markerKind, lightGlow, tempUnit, toCelsius } from "./kinds.ts";
|
||||
import { entity, hassOf } from "./fixtures.ts";
|
||||
|
||||
test("the domain decides the kind; unknown domains have none", () => {
|
||||
assert.equal(domainOf("light.kitchen"), "light");
|
||||
assert.equal(kindOf("input_boolean.party"), "switch");
|
||||
assert.equal(kindOf("binary_sensor.door"), "binary");
|
||||
assert.equal(kindOf("vacuum.robot"), null);
|
||||
assert.equal(isPlaceable("scene"), false);
|
||||
assert.equal(isPlaceable("light"), true);
|
||||
assert.equal(isPlaceable(null), false);
|
||||
});
|
||||
|
||||
test("unavailable and unknown count as unavailable, a missing entity too", () => {
|
||||
assert.equal(isUnavailable(entity("a.b", "unavailable")), true);
|
||||
assert.equal(isUnavailable(entity("a.b", "unknown")), true);
|
||||
assert.equal(isUnavailable(undefined), true);
|
||||
assert.equal(isUnavailable(entity("a.b", "on")), false);
|
||||
});
|
||||
|
||||
test("a name loses the area it starts with, but not when nothing would be left", () => {
|
||||
const hass = hassOf([entity("light.a", "on", { friendly_name: "Lounge ceiling light" }), entity("light.b", "on", { friendly_name: "Lounge" }), entity("light.c", "on", { friendly_name: "Hall lamp" })]);
|
||||
assert.equal(entityName(hass, "light.a", "Lounge"), "Ceiling light");
|
||||
assert.equal(entityName(hass, "light.b", "Lounge"), "Lounge");
|
||||
assert.equal(entityName(hass, "light.c", "Lounge"), "Hall lamp");
|
||||
assert.equal(entityName(hass, "light.a"), "Lounge ceiling light");
|
||||
assert.equal(entityName(hass, "light.missing"), "light.missing");
|
||||
});
|
||||
|
||||
test("a friendly name that is a number (set in YAML) still reads as text", () => {
|
||||
const hass = hassOf([entity("lock.door", "locked", { friendly_name: 12 })]);
|
||||
assert.equal(entityName(hass, "lock.door"), "12");
|
||||
assert.equal(entityName(hass, "lock.door", "Hall"), "12");
|
||||
});
|
||||
|
||||
test("what counts as active for each kind", () => {
|
||||
assert.equal(isActive(entity("light.a", "on")), true);
|
||||
assert.equal(isActive(entity("cover.a", "opening")), true);
|
||||
assert.equal(isActive(entity("cover.a", "closed")), false);
|
||||
assert.equal(isActive(entity("climate.a", "heat", { hvac_action: "heating" })), true);
|
||||
assert.equal(isActive(entity("climate.a", "heat", { hvac_action: "idle" })), false);
|
||||
assert.equal(isActive(entity("media_player.a", "playing")), true);
|
||||
assert.equal(isActive(entity("media_player.a", "paused")), false);
|
||||
assert.equal(isActive(entity("lock.a", "unlocked")), true);
|
||||
assert.equal(isActive(entity("vacuum.a", "returning")), true);
|
||||
assert.equal(isActive(entity("vacuum.a", "docked")), false);
|
||||
assert.equal(isActive(undefined), false);
|
||||
});
|
||||
|
||||
test("a status sensor is active while it works, a plain sensor never", () => {
|
||||
const printer = entity("sensor.printer", "Printing", { device_class: "enum" });
|
||||
assert.equal(isStatusSensor(printer), true);
|
||||
assert.equal(isActive(printer), true);
|
||||
assert.equal(isActive(entity("sensor.printer", "idle", { device_class: "enum" })), false);
|
||||
assert.equal(isActive(entity("sensor.temp", "running", { device_class: "temperature" })), false);
|
||||
});
|
||||
|
||||
test("a light glows with its colour and a perceptual brightness, off lights do not glow", () => {
|
||||
assert.equal(lightGlow(entity("light.a", "off")), null);
|
||||
assert.deepEqual(lightGlow(entity("light.a", "on", { brightness: 255, rgb_color: [255, 0, 0], color_mode: "rgb" })), { color: [1, 0, 0], level: 1 });
|
||||
const dim = lightGlow(entity("light.a", "on", { brightness: 26 }))!;
|
||||
assert.ok(dim.level > 0.4 && dim.level < 0.55, String(dim.level));
|
||||
assert.deepEqual(lightGlow(entity("light.a", "on"))!.color, [1, 0.71, 0.28]);
|
||||
});
|
||||
|
||||
test("a white light uses its colour temperature, not a stale rgb colour", () => {
|
||||
const warm = lightGlow(entity("light.a", "on", { color_mode: "color_temp", rgb_color: [0, 0, 255], color_temp_kelvin: 2200 }))!;
|
||||
assert.deepEqual(warm.color, kelvinToRgb(2200));
|
||||
assert.ok(kelvinToRgb(6500)[2] > kelvinToRgb(2200)[2], "cool light has more blue");
|
||||
assert.deepEqual(kelvinToRgb(1000), kelvinToRgb(2200), "clamped at the warm end");
|
||||
});
|
||||
|
||||
test("a relay's lamp takes colour and brightness from the bulb, unless the bulb is unavailable", () => {
|
||||
const relay = entity("switch.relay", "on");
|
||||
const bulb = entity("light.bulb", "on", { brightness: 255, rgb_color: [0, 0, 255], color_mode: "rgb" });
|
||||
assert.deepEqual(lightGlow(relay, bulb)!.color, [0, 0, 1]);
|
||||
assert.deepEqual(lightGlow(relay, entity("light.bulb", "unavailable"))!.color, [1, 0.71, 0.28]);
|
||||
assert.equal(lightGlow(entity("switch.relay", "off"), bulb), null);
|
||||
});
|
||||
|
||||
test("default heights: lamps by mount, the rest by kind", () => {
|
||||
assert.ok(Math.abs(defaultHeight("light", 2.6) - 2.35) < 1e-9);
|
||||
assert.equal(defaultHeight("light", 2.6, "table"), 1.25);
|
||||
assert.equal(defaultHeight("cover", 3), 2);
|
||||
assert.equal(defaultHeight("sensor", 2.6), 1.4);
|
||||
assert.equal(defaultHeight("lock", 2.6), 1.05);
|
||||
});
|
||||
|
||||
test("TV glow follows the running app and is off when the TV is", () => {
|
||||
assert.deepEqual(appColor(entity("media_player.tv", "playing", { app_name: "Netflix" })), [0.9, 0.04, 0.08]);
|
||||
assert.deepEqual(appColor(entity("media_player.tv", "playing", { source: "Disney+" })), [0.2, 0.35, 1]);
|
||||
assert.deepEqual(appColor(entity("media_player.tv", "playing", { app_name: "Something" })), [0.22, 0.88, 1]);
|
||||
assert.equal(appColor(entity("media_player.tv", "off")), null);
|
||||
assert.equal(appColor(entity("media_player.tv", "unavailable")), null);
|
||||
});
|
||||
|
||||
test("temperature units convert both ways", () => {
|
||||
assert.equal(toCelsius(212, "°F"), 100);
|
||||
assert.equal(toCelsius(273.15, "K"), 0);
|
||||
assert.equal(toCelsius(21, "°C"), 21);
|
||||
const us = hassOf([], {}, { config: { unit_system: { temperature: "°F" } } });
|
||||
assert.equal(tempUnit(us), "°F");
|
||||
assert.equal(fromCelsius(us, 100), 212);
|
||||
assert.equal(tempUnit(hassOf([])), "°C");
|
||||
assert.equal(fromCelsius(hassOf([]), 20), 20);
|
||||
});
|
||||
|
||||
test("a cover that only sends commands stays unknown but still counts as usable", () => {
|
||||
assert.equal(assumedCover(entity("cover.garage", "unknown", { assumed_state: true })), true);
|
||||
assert.equal(assumedCover(entity("cover.garage", "unknown")), false);
|
||||
assert.equal(assumedCover(entity("cover.garage", "unavailable", { assumed_state: true })), false);
|
||||
assert.equal(assumedCover(entity("switch.x", "unknown", { assumed_state: true })), false);
|
||||
assert.equal(assumedCover(undefined), false);
|
||||
});
|
||||
|
||||
test("a marker's kind: its entity's, or NextFloor's own markers", () => {
|
||||
assert.equal(markerKind("light.kitchen"), "light");
|
||||
assert.equal(markerKind("lamp:f1"), "light");
|
||||
assert.equal(markerKind("sensor.x", true), "light");
|
||||
assert.equal(markerKind("tap:f2"), "tap");
|
||||
assert.equal(markerKind("gang:f3"), "switch");
|
||||
assert.equal(markerKind("grid"), "sensor");
|
||||
assert.equal(markerKind("binary_sensor.door"), "binary");
|
||||
assert.equal(markerKind("vacuum.robot"), "other");
|
||||
assert.equal(markerKind("script.x"), "other");
|
||||
});
|
||||
|
||||
test("open all / close all take a garage remote along, but never a cover that asks first", () => {
|
||||
const blind = entity("cover.blind", "closed");
|
||||
const remote = entity("cover.remote", "unknown", { assumed_state: true });
|
||||
const garage = entity("cover.garage", "unknown", { assumed_state: true });
|
||||
const lost = entity("cover.lost", "unavailable");
|
||||
const silent = entity("cover.silent", "unknown");
|
||||
assert.deepEqual(groupCovers([blind, remote, garage, lost, silent], new Set(["cover.garage"])), ["cover.blind", "cover.remote"]);
|
||||
assert.deepEqual(groupCovers([blind, garage], null), ["cover.blind", "cover.garage"]);
|
||||
});
|
||||
|
||||
test("a fixture with several bulbs glows with its main light, else dimmer with another one that is on", () => {
|
||||
const main = { entity_id: "light.main", state: "off", attributes: {} };
|
||||
const night = { entity_id: "light.night", state: "on", attributes: { brightness: 255, rgb_color: [255, 0, 0], color_mode: "rgb" } };
|
||||
assert.deepEqual(fixtureGlow(main, [undefined, night]), { color: [1, 0, 0], level: 0.6 });
|
||||
assert.equal(fixtureGlow({ ...main, state: "on" }, [night])?.level, 1, "the main light wins");
|
||||
assert.equal(fixtureGlow(main, [{ ...night, state: "off" }]), null);
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
// What kind of device an entity is, whether it is "on", how a light glows, and a few unit helpers.
|
||||
// Pure functions: no Lit, no three.js.
|
||||
|
||||
import type { LampMount } from "../model.ts";
|
||||
import type { HassEntity, HomeAssistant } from "../types.ts";
|
||||
|
||||
export type DeviceKind = "light" | "switch" | "fan" | "cover" | "climate" | "media" | "lock" | "sensor" | "binary" | "scene" | "script";
|
||||
|
||||
/** The Home Assistant domain, i.e. the part of the id before the dot. */
|
||||
export const domainOf = (entityId: string): string => entityId.slice(0, entityId.indexOf("."));
|
||||
|
||||
const KIND_OF_DOMAIN: Record<string, DeviceKind> = {
|
||||
light: "light",
|
||||
switch: "switch",
|
||||
input_boolean: "switch",
|
||||
// a water valve (irrigation, the main water) opens and closes like a switch turns on and off
|
||||
valve: "switch",
|
||||
fan: "fan",
|
||||
cover: "cover",
|
||||
climate: "climate",
|
||||
media_player: "media",
|
||||
lock: "lock",
|
||||
sensor: "sensor",
|
||||
binary_sensor: "binary",
|
||||
// a wall button or remote: its state is the time of its last press, shown like a reading
|
||||
event: "sensor",
|
||||
scene: "scene",
|
||||
script: "script",
|
||||
};
|
||||
|
||||
export const kindOf = (entityId: string): DeviceKind | null => KIND_OF_DOMAIN[domainOf(entityId)] ?? null;
|
||||
|
||||
/** The order kinds are listed in. */
|
||||
export const KIND_ORDER: DeviceKind[] = ["light", "cover", "climate", "media", "switch", "fan", "lock", "binary", "sensor", "scene", "script"];
|
||||
|
||||
/** The kinds of markers one can choose to see outside the opened room: device kinds, furniture with an own tap action, and the rest. */
|
||||
export type MarkerKind = Exclude<DeviceKind, "scene" | "script"> | "tap" | "other";
|
||||
export const MARKER_KINDS: MarkerKind[] = ["light", "cover", "climate", "media", "switch", "fan", "lock", "binary", "sensor", "tap", "other"];
|
||||
|
||||
/** The kind of a marker by its id: an entity, or one of NextFloor's own (a lamp without light, a light switch plate, a tap action, the grid). */
|
||||
export function markerKind(id: string, lamp = false): MarkerKind {
|
||||
if (lamp || id.startsWith("lamp:")) return "light";
|
||||
if (id.startsWith("tap:")) return "tap";
|
||||
if (id.startsWith("gang:")) return "switch";
|
||||
if (id === "grid") return "sensor";
|
||||
const kind = kindOf(id);
|
||||
return kind && kind !== "scene" && kind !== "script" ? kind : "other";
|
||||
}
|
||||
|
||||
/** Kinds a tap on the marker can switch. */
|
||||
export const TOGGLE_KINDS = new Set<DeviceKind>(["light", "switch", "fan"]);
|
||||
|
||||
/** Scenes and scripts live in the room panel; they have no place in the room. */
|
||||
export const isPlaceable = (kind: DeviceKind | null): boolean => kind !== null && kind !== "scene" && kind !== "script";
|
||||
|
||||
/** Gone or unknown; an event entity (a wall button) is "unknown" until its first press and is there all the same. */
|
||||
export const isUnavailable = (st: HassEntity | undefined): boolean => !st || st.state === "unavailable" || (st.state === "unknown" && !st.entity_id.startsWith("event."));
|
||||
|
||||
const MOTION_CLASSES = new Set(["motion", "occupancy", "presence", "moving"]);
|
||||
|
||||
/** A binary sensor that tells motion, occupancy or presence. */
|
||||
export const isMotionSensor = (hass: HomeAssistant | undefined, entityId: string): boolean =>
|
||||
entityId.startsWith("binary_sensor.") && MOTION_CLASSES.has(String(hass?.states[entityId]?.attributes.device_class ?? ""));
|
||||
|
||||
/** A cover that only sends commands (assumed state, a garage remote) and so stays unknown: its buttons still work. */
|
||||
export const assumedCover = (st: HassEntity | undefined): boolean => !!st && st.entity_id.startsWith("cover.") && st.state === "unknown" && st.attributes.assumed_state === true;
|
||||
|
||||
/** The covers "open all" / "close all" move at once: those that answer (a garage remote included), but never one that asks first. */
|
||||
export const groupCovers = (covers: readonly HassEntity[], asking: ReadonlySet<string> | null | undefined): string[] =>
|
||||
covers.filter((c) => (!isUnavailable(c) || assumedCover(c)) && !asking?.has(c.entity_id)).map((c) => c.entity_id);
|
||||
|
||||
/** The entity's name without the area in front of it: "Lounge Ceiling light" in the Lounge reads "Ceiling light". */
|
||||
export function entityName(hass: HomeAssistant | undefined, entityId: string, areaName?: string): string {
|
||||
// a friendly_name set in YAML can be a number: the name is always text
|
||||
const name = String(hass?.states[entityId]?.attributes.friendly_name ?? hass?.entities?.[entityId]?.name ?? entityId);
|
||||
if (!areaName || name.length <= areaName.length + 1) return name;
|
||||
if (!name.toLowerCase().startsWith(`${areaName.toLowerCase()} `)) return name;
|
||||
const rest = name.slice(areaName.length + 1);
|
||||
return rest[0].toUpperCase() + rest.slice(1);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- is it on?
|
||||
|
||||
/** Sensor states (a printer, a washing machine) that say the device is at work. */
|
||||
const AT_WORK = new Set(["running", "printing", "prepare", "preparing", "slicing", "heating", "busy", "working", "active", "washing", "rinsing", "spinning", "drying", "cleaning", "in_progress", "in progress", "on"]);
|
||||
|
||||
/** A status sensor reports a fixed set of words (running, idle, finished ...) and furniture can follow it. */
|
||||
export const isStatusSensor = (st: HassEntity | undefined): boolean => !!st && st.entity_id.startsWith("sensor.") && st.attributes.device_class === "enum";
|
||||
|
||||
/** "Active" lights a marker up: a lamp that is on, an open cover, a heater heating, a playing player, an open window ... */
|
||||
export function isActive(st: HassEntity | undefined): boolean {
|
||||
if (!st) return false;
|
||||
// a robot vacuum counts as active while it cleans or drives back to its dock
|
||||
if (st.entity_id.startsWith("vacuum.")) return ["cleaning", "returning"].includes(st.state);
|
||||
if (st.entity_id.startsWith("valve.")) return st.state === "open" || st.state === "opening";
|
||||
const kind = kindOf(st.entity_id);
|
||||
if (kind === "light" || kind === "switch" || kind === "fan" || kind === "binary") return st.state === "on";
|
||||
if (kind === "cover") return st.state === "open" || st.state === "opening";
|
||||
if (kind === "climate") return ["heating", "cooling"].includes(String(st.attributes.hvac_action));
|
||||
if (kind === "media") return st.state === "playing";
|
||||
if (kind === "lock") return st.state === "unlocked" || st.state === "open";
|
||||
if (kind === "sensor") return isStatusSensor(st) && AT_WORK.has(st.state.toLowerCase());
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- light colour
|
||||
|
||||
export type Rgb = [number, number, number];
|
||||
|
||||
const clamp01 = (v: number) => Math.min(1, Math.max(0, v));
|
||||
|
||||
/** A rough colour for a colour temperature (2200 K warm to 6500 K cool), kept soft on the dark floor. */
|
||||
export function kelvinToRgb(kelvin: number): Rgb {
|
||||
const t = clamp01((kelvin - 2200) / (6500 - 2200));
|
||||
const warm: Rgb = [1, 0.66, 0.26];
|
||||
const cool: Rgb = [0.78, 0.9, 1];
|
||||
return [0, 1, 2].map((i) => warm[i] + (cool[i] - warm[i]) * t) as Rgb;
|
||||
}
|
||||
|
||||
/**
|
||||
* Colour (channels 0..1) and strength (0..1) of a lit lamp, or null when it is off. `colorFrom` is the bulb itself
|
||||
* when a relay switches the light and only the bulb knows its colour and brightness.
|
||||
*/
|
||||
export function lightGlow(st: HassEntity | undefined, colorFrom?: HassEntity): { color: Rgb; level: number } | null {
|
||||
if (!st || st.state !== "on") return null;
|
||||
const source = colorFrom && !["unavailable", "unknown"].includes(colorFrom.state) ? colorFrom.attributes : st.attributes;
|
||||
// perceptual curve: a lamp at 10 % still looks on (about 0.45), full brightness is 1
|
||||
const level = typeof source.brightness === "number" ? 0.2 + 0.8 * Math.sqrt(clamp01(source.brightness / 255)) : 1;
|
||||
const rgb = source.rgb_color as Rgb | undefined;
|
||||
const whiteModes = ["color_temp", "brightness", "onoff"];
|
||||
if (rgb && !whiteModes.includes(String(source.color_mode))) return { color: [rgb[0] / 255, rgb[1] / 255, rgb[2] / 255], level };
|
||||
if (typeof source.color_temp_kelvin === "number") return { color: kelvinToRgb(source.color_temp_kelvin), level };
|
||||
return { color: [1, 0.71, 0.28], level }; // the default warm amber
|
||||
}
|
||||
|
||||
/**
|
||||
* A fixture with several bulbs (a main light, a night light, an ambient ring): it glows with its main light, and while that is off
|
||||
* with the first other light that is on, a little dimmer.
|
||||
*/
|
||||
export function fixtureGlow(main: HassEntity | undefined, others: (HassEntity | undefined)[], colorFrom?: HassEntity): { color: Rgb; level: number } | null {
|
||||
const own = lightGlow(main, colorFrom);
|
||||
if (own) return own;
|
||||
for (const st of others) {
|
||||
const glow = lightGlow(st);
|
||||
if (glow) return { color: glow.color, level: glow.level * 0.6 };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Default height of a marker above the floor, in metres. */
|
||||
export function defaultHeight(kind: DeviceKind, floorHeight: number, mount: LampMount | null = null): number {
|
||||
if (kind === "light" && mount === "floor") return 1.95;
|
||||
if (kind === "light" && mount === "table") return 1.25;
|
||||
if (kind === "light" && mount === "wall") return 1.95;
|
||||
switch (kind) {
|
||||
case "light":
|
||||
return Math.max(0.5, floorHeight - 0.25);
|
||||
case "cover":
|
||||
return Math.min(2, floorHeight - 0.3);
|
||||
case "climate":
|
||||
return 0.6;
|
||||
case "media":
|
||||
return 0.9;
|
||||
case "binary":
|
||||
case "sensor":
|
||||
return 1.4;
|
||||
default:
|
||||
return 1.05;
|
||||
}
|
||||
}
|
||||
|
||||
/** Glow colour of a TV for the app that is running (the apps' brand colours). */
|
||||
export function appColor(st: HassEntity | undefined): Rgb | null {
|
||||
if (!st || isUnavailable(st) || st.state === "off" || st.state === "standby") return null;
|
||||
const { app_name, source, app_id } = st.attributes;
|
||||
const text = `${app_name ?? ""} ${source ?? ""} ${app_id ?? ""}`.toLowerCase();
|
||||
const brands: [string[], Rgb][] = [
|
||||
[["netflix"], [0.9, 0.04, 0.08]],
|
||||
[["youtube"], [1, 0.1, 0.15]],
|
||||
[["prime", "amazon"], [0.1, 0.6, 0.95]],
|
||||
[["disney"], [0.2, 0.35, 1]],
|
||||
[["spotify"], [0.12, 0.85, 0.4]],
|
||||
[["zdf", "ard", "mediathek"], [1, 0.5, 0.1]],
|
||||
];
|
||||
return brands.find(([words]) => words.some((w) => text.includes(w)))?.[1] ?? [0.22, 0.88, 1];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- temperature units
|
||||
|
||||
/** The temperature unit Home Assistant uses: "°F" for US units, else "°C". */
|
||||
export const tempUnit = (hass: HomeAssistant): "°C" | "°F" => (hass.config?.unit_system?.temperature === "°F" ? "°F" : "°C");
|
||||
|
||||
/** A reading in its unit (°F, K, anything else counts as °C) converted to °C. */
|
||||
export function toCelsius(value: number, unit: unknown): number {
|
||||
if (unit === "°F") return ((value - 32) * 5) / 9;
|
||||
if (unit === "K") return value - 273.15;
|
||||
return value;
|
||||
}
|
||||
|
||||
/** °C converted to the unit Home Assistant shows. */
|
||||
export const fromCelsius = (hass: HomeAssistant, celsius: number): number => (tempUnit(hass) === "°F" ? (celsius * 9) / 5 + 32 : celsius);
|
||||
@@ -0,0 +1,117 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { centroid, pointInPolygon } from "../model.ts";
|
||||
import { box, entity, floorWith, hassOf } from "./fixtures.ts";
|
||||
import { autoPlace, favoriteCall, floorControls, ownButtonOn, robotRoom, robotRoomSensor, roomKey, runButton } from "./misc.ts";
|
||||
|
||||
const ids = (n: number, prefix = "sensor.s") => Array.from({ length: n }, (_, i) => `${prefix}${i}`);
|
||||
|
||||
test("auto placement keeps everything inside the room, apart, and off the label", () => {
|
||||
const room = box("r", 0, 0, 5, 4);
|
||||
const placed = autoPlace(room, ids(6));
|
||||
assert.equal(placed.length, 6);
|
||||
const label = centroid(room.points);
|
||||
for (const p of placed) {
|
||||
assert.ok(pointInPolygon([p.x, p.z], room.points));
|
||||
assert.ok(Math.hypot(p.x - label[0], p.z - label[1]) >= 0.5, "off the label");
|
||||
}
|
||||
for (let i = 0; i < placed.length; i++) for (let j = i + 1; j < placed.length; j++) assert.ok(Math.hypot(placed[i].x - placed[j].x, placed[i].z - placed[j].z) > 0.3);
|
||||
});
|
||||
|
||||
test("lights go towards the middle, other devices towards a wall", () => {
|
||||
const room = box("r", 0, 0, 6, 5);
|
||||
const [light] = autoPlace(room, ["light.a"]);
|
||||
const [sensor] = autoPlace(room, ["sensor.a"]);
|
||||
const label = centroid(room.points);
|
||||
assert.ok(Math.hypot(light.x - label[0], light.z - label[1]) < Math.hypot(sensor.x - label[0], sensor.z - label[1]));
|
||||
});
|
||||
|
||||
test("placement is deterministic, avoids taken spots, and copes with tiny rooms", () => {
|
||||
const room = box("r", 0, 0, 4, 4);
|
||||
assert.deepEqual(autoPlace(room, ids(3)), autoPlace(room, ids(3)));
|
||||
const taken = autoPlace(room, ["sensor.x"])[0];
|
||||
const next = autoPlace(room, ["sensor.y"], [[taken.x, taken.z]])[0];
|
||||
assert.ok(Math.hypot(next.x - taken.x, next.z - taken.z) > 0.5);
|
||||
const tiny = autoPlace(box("t", 0, 0, 0.6, 0.6), ids(2));
|
||||
assert.equal(tiny.length, 2);
|
||||
assert.deepEqual(autoPlace({ ...room, points: [[0, 0], [1, 1]] }, ids(1)), []);
|
||||
assert.deepEqual(autoPlace(room, []), []);
|
||||
});
|
||||
|
||||
test("room names compare without case, accents and umlaut spelling", () => {
|
||||
assert.equal(roomKey("Küche"), roomKey("kueche"));
|
||||
assert.equal(roomKey("Küche"), roomKey("Kuche"));
|
||||
assert.equal(roomKey("Straße"), "strasse");
|
||||
assert.equal(roomKey("Living-Room 2"), "livingroom2");
|
||||
});
|
||||
|
||||
test("the robot's room sensor: chosen, 'none', or found on the vacuum's device", () => {
|
||||
const hass = hassOf([entity("vacuum.rob", "cleaning"), entity("sensor.rob_current_room", "Kitchen"), entity("sensor.rob_battery", "80")], {
|
||||
"vacuum.rob": { device_id: "r" },
|
||||
"sensor.rob_current_room": { device_id: "r" },
|
||||
"sensor.rob_battery": { device_id: "r" },
|
||||
});
|
||||
assert.equal(robotRoomSensor(hass, "vacuum.rob", undefined), "sensor.rob_current_room");
|
||||
assert.equal(robotRoomSensor(hass, "vacuum.rob", "sensor.mine"), "sensor.mine");
|
||||
assert.equal(robotRoomSensor(hass, "vacuum.rob", "none"), null);
|
||||
assert.equal(robotRoomSensor(hass, null, undefined), null);
|
||||
});
|
||||
|
||||
test("the robot's room is matched by room or area name, exactly first, then loosely", () => {
|
||||
const rooms = [{ name: "Küche", area_id: "kitchen" }, { name: "Bad", area_id: null }, { name: "Wohnzimmer", area_id: "living" }];
|
||||
const hass = hassOf([entity("sensor.room", "kitchen"), entity("vacuum.rob", "cleaning", { current_room: "Wohnzimmer unten" })], {}, { areas: { kitchen: { area_id: "kitchen", name: "Kitchen" }, living: { area_id: "living", name: "Living room" } } });
|
||||
assert.equal(robotRoom(hass, rooms, null, "sensor.room")?.name, "Küche");
|
||||
assert.equal(robotRoom(hass, rooms, "vacuum.rob", null)?.name, "Wohnzimmer");
|
||||
hass.states["sensor.room"].state = "unknown";
|
||||
assert.equal(robotRoom(hass, rooms, null, "sensor.room"), null);
|
||||
hass.states["sensor.room"].state = "Garage";
|
||||
assert.equal(robotRoom(hass, rooms, null, "sensor.room"), null);
|
||||
});
|
||||
|
||||
test("floor controls: lights and blinds of the floor, no garage doors, no hidden entities", () => {
|
||||
const hass = hassOf(
|
||||
[entity("light.a", "on"), entity("light.hidden", "on"), entity("cover.blind", "open", { device_class: "shutter" }), entity("cover.garage", "closed", { device_class: "garage" }), entity("light.placed", "on"), entity("light.linked", "off")],
|
||||
{ "light.a": { area_id: "x" }, "light.hidden": { area_id: "x" }, "cover.blind": { area_id: "x" }, "cover.garage": { area_id: "x" } },
|
||||
);
|
||||
const room = { ...box("r", 0, 0, 4, 3, "x"), hidden: ["light.hidden"] };
|
||||
const floor = floorWith([room], {
|
||||
placements: [{ entity_id: "light.placed", x: 1, z: 1, y: null, mount: null }, { entity_id: "cover.garage", x: 1, z: 1, y: null, mount: null }],
|
||||
furniture: [{ id: "l", type: "lamp_floor", x: 1, z: 1, rotation: 0, w: 1, d: 1, h: 1, variant: null, entity: "light.linked", power: null }],
|
||||
});
|
||||
const controls = floorControls(hass, floor);
|
||||
assert.deepEqual(controls.lights.sort(), ["light.a", "light.linked", "light.placed"]);
|
||||
assert.deepEqual(controls.covers, ["cover.blind"]);
|
||||
});
|
||||
|
||||
test("a favourite starts scenes and scripts, triggers automations, presses buttons and toggles the rest", () => {
|
||||
assert.deepEqual(favoriteCall("scene.movie"), ["scene", "turn_on"]);
|
||||
assert.deepEqual(favoriteCall("script.go"), ["script", "turn_on"]);
|
||||
assert.deepEqual(favoriteCall("automation.x"), ["automation", "trigger"]);
|
||||
assert.deepEqual(favoriteCall("input_button.b"), ["input_button", "press"]);
|
||||
assert.deepEqual(favoriteCall("light.a"), ["homeassistant", "toggle"]);
|
||||
});
|
||||
|
||||
test("own buttons call a service or fire the DOM event, and ignore incomplete ones", () => {
|
||||
const calls: unknown[][] = [];
|
||||
const events: { name: string; detail: unknown }[] = [];
|
||||
const hass = hassOf([], {}, { callService: async (...a: unknown[]) => void calls.push(a) });
|
||||
const from = { dispatchEvent: (e: CustomEvent) => void events.push({ name: e.type, detail: e.detail }) } as unknown as HTMLElement;
|
||||
runButton(hass, from, { action: "service", target: "light.turn_on", data: { entity_id: "light.a" } });
|
||||
assert.deepEqual(calls[0], ["light", "turn_on", { entity_id: "light.a" }]);
|
||||
runButton(hass, from, { action: "fire_dom_event", data: { browser_mod: { command: "popup" } } });
|
||||
assert.deepEqual(events[0], { name: "ll-custom", detail: { browser_mod: { command: "popup" } } });
|
||||
runButton(hass, from, { action: "more_info", target: "light.a" });
|
||||
assert.deepEqual(events[1], { name: "hass-more-info", detail: { entityId: "light.a" } });
|
||||
runButton(hass, from, { action: "service", target: "nodot" });
|
||||
runButton(hass, from, { action: "more_info", target: "" });
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(events.length, 2);
|
||||
});
|
||||
|
||||
test("an own button lights up while its entity is on", () => {
|
||||
const hass = hassOf([entity("switch.party", "on"), entity("light.hall", "off")]);
|
||||
assert.equal(ownButtonOn(hass, { action: "service", target: "switch.toggle", data: { entity_id: "switch.party" } }), true);
|
||||
assert.equal(ownButtonOn(hass, { action: "more_info", target: "light.hall" }), false);
|
||||
assert.equal(ownButtonOn(hass, { action: "navigate", target: "/lovelace/0", state_entity: "switch.party" }), true, "named by hand");
|
||||
assert.equal(ownButtonOn(hass, { action: "service", target: "script.x", data: { entity_id: ["switch.party"] } }), false, "several entities tell nothing");
|
||||
});
|
||||
@@ -0,0 +1,195 @@
|
||||
// Smaller helpers around devices: automatic placement in a room, the robot vacuum's room, the central "all lights"
|
||||
// controls of a floor, favourites and own buttons.
|
||||
|
||||
import { centroid, pointInPolygon, type Floor, type Placement, type Room, type Vec2 } from "../model.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { kindOf } from "./kinds.ts";
|
||||
import { roomEntities, primaryEntities } from "./registry.ts";
|
||||
|
||||
// ---------------------------------------------------------------- automatic placement
|
||||
|
||||
function distanceToOutline(p: Vec2, outline: readonly Vec2[]): number {
|
||||
return Math.min(
|
||||
...outline.map((a, i) => {
|
||||
const b = outline[(i + 1) % outline.length];
|
||||
const [dx, dz] = [b[0] - a[0], b[1] - a[1]];
|
||||
const along = Math.min(1, Math.max(0, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / (dx * dx + dz * dz || 1)));
|
||||
return Math.hypot(p[0] - a[0] - dx * along, p[1] - a[1] - dz * along);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Places entities in a room without overlapping each other or what is there already. Lights go towards the middle, spread
|
||||
* apart; everything else along the walls. The room label at the centre stays free. The result is deterministic: the same
|
||||
* room always gets the same layout.
|
||||
*/
|
||||
export function autoPlace(room: Room, entityIds: readonly string[], taken: readonly Vec2[] = []): Placement[] {
|
||||
const outline = room.points;
|
||||
if (outline.length < 3 || entityIds.length === 0) return [];
|
||||
const xs = outline.map((p) => p[0]);
|
||||
const zs = outline.map((p) => p[1]);
|
||||
const [minX, maxX, minZ, maxZ] = [Math.min(...xs), Math.max(...xs), Math.min(...zs), Math.max(...zs)];
|
||||
const extent = Math.min(maxX - minX, maxZ - minZ);
|
||||
const step = Math.max(0.1, Math.min(0.25, extent / 8));
|
||||
const wallMargin = Math.min(0.35, extent / 5);
|
||||
const labelClearance = Math.min(0.7, extent / 4);
|
||||
const label = centroid(outline);
|
||||
|
||||
// a grid of free spots, away from the walls
|
||||
const spots: { at: Vec2; wallDistance: number }[] = [];
|
||||
for (let x = minX + step / 2; x < maxX; x += step) {
|
||||
for (let z = minZ + step / 2; z < maxZ; z += step) {
|
||||
const at: Vec2 = [x, z];
|
||||
if (!pointInPolygon(at, outline)) continue;
|
||||
const wallDistance = distanceToOutline(at, outline);
|
||||
if (wallDistance >= wallMargin) spots.push({ at, wallDistance });
|
||||
}
|
||||
}
|
||||
if (spots.length === 0) spots.push({ at: label, wallDistance: 0 });
|
||||
|
||||
const occupied: Vec2[] = [...taken];
|
||||
return entityIds.map((entity_id) => {
|
||||
const isLight = kindOf(entity_id) === "light";
|
||||
let best = spots[0].at;
|
||||
let bestScore = -Infinity;
|
||||
for (const { at, wallDistance } of spots) {
|
||||
const nearestNeighbour = occupied.length ? Math.min(...occupied.map((o) => Math.hypot(at[0] - o[0], at[1] - o[1]))) : 3;
|
||||
const fromLabel = Math.hypot(at[0] - label[0], at[1] - label[1]);
|
||||
// room to breathe is good (up to 3 m); the label's spot is taboo except for lights; lights like the middle, others a wall
|
||||
let score = Math.min(nearestNeighbour, 3) * 2;
|
||||
if (fromLabel < labelClearance && !isLight) score -= 10;
|
||||
score -= isLight ? fromLabel * 0.35 : wallDistance * 1.2;
|
||||
if (score > bestScore + 1e-9) {
|
||||
bestScore = score;
|
||||
best = at;
|
||||
}
|
||||
}
|
||||
const chosen: Vec2 = [Math.round(best[0] * 100) / 100, Math.round(best[1] * 100) / 100];
|
||||
occupied.push(chosen);
|
||||
return { entity_id, x: chosen[0], z: chosen[1], y: null, mount: null };
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- robot vacuum
|
||||
|
||||
const ROOM_SENSOR_NAME = /(^|_)(current_room|current_segment|aktueller_raum|current_area)($|_)/;
|
||||
|
||||
/** The sensor that names the room a robot vacuum is cleaning: the chosen one, else one on the vacuum's device. */
|
||||
export function robotRoomSensor(hass: HomeAssistant, vacuum: string | null, chosen: string | null | undefined): string | null {
|
||||
if (chosen === "none") return null;
|
||||
if (chosen) return chosen;
|
||||
const device = vacuum ? hass.entities?.[vacuum]?.device_id : null;
|
||||
if (!device || !hass.entities) return null;
|
||||
const match = Object.values(hass.entities).find((e) => e.device_id === device && e.entity_id.startsWith("sensor.") && (ROOM_SENSOR_NAME.test(e.translation_key ?? "") || ROOM_SENSOR_NAME.test(e.entity_id.split(".")[1])));
|
||||
return match?.entity_id ?? null;
|
||||
}
|
||||
|
||||
/** A name without case, accents or umlaut spelling: "Küche", "kueche" and "Kuche" are the same. */
|
||||
export function roomKey(name: string): string {
|
||||
return name
|
||||
.toLowerCase()
|
||||
.replace(/ä/g, "a")
|
||||
.replace(/ö/g, "o")
|
||||
.replace(/ü/g, "u")
|
||||
.replace(/ß/g, "ss")
|
||||
.replace(/ae/g, "a")
|
||||
.replace(/oe/g, "o")
|
||||
.replace(/ue/g, "u")
|
||||
.normalize("NFD")
|
||||
.replace(/[^a-z0-9]/g, "");
|
||||
}
|
||||
|
||||
/** The room the robot reports (the sensor's state, else the vacuum's current_room attribute), matched by room or area name. */
|
||||
export function robotRoom<R extends { name: string; area_id?: string | null }>(hass: HomeAssistant, rooms: readonly R[], vacuum: string | null, sensor: string | null): R | null {
|
||||
const reported = sensor ? hass.states[sensor]?.state : vacuum ? hass.states[vacuum]?.attributes.current_room : undefined;
|
||||
if (typeof reported !== "string" || ["", "unknown", "unavailable"].includes(reported)) return null;
|
||||
const wanted = roomKey(reported);
|
||||
if (!wanted) return null;
|
||||
const keysOf = (room: R) => [room.name, room.area_id ?? "", (room.area_id && hass.areas?.[room.area_id]?.name) || ""].map(roomKey).filter(Boolean);
|
||||
const exact = rooms.find((room) => keysOf(room).includes(wanted));
|
||||
return exact ?? rooms.find((room) => keysOf(room).some((k) => k.length >= 3 && (k.includes(wanted) || wanted.includes(k)))) ?? null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- floor controls, favourites, buttons
|
||||
|
||||
/** Covers that are doors, not blinds: the central "close all" leaves them alone. */
|
||||
const DOOR_COVER_CLASSES = new Set(["garage", "gate", "door"]);
|
||||
|
||||
/**
|
||||
* The lights and blinds of a floor for the central "all on / all off": the main entities of its rooms' areas (except those a
|
||||
* room hides), placed devices and linked furniture. Garage doors and gates are no blinds and stay out.
|
||||
*/
|
||||
export function floorControls(hass: HomeAssistant, floor: Floor): { lights: string[]; covers: string[] } {
|
||||
const lights = new Set<string>();
|
||||
const covers = new Set<string>();
|
||||
const consider = (id: string | null | undefined) => {
|
||||
if (!id || id === "none" || !hass.states[id]) return;
|
||||
const kind = kindOf(id);
|
||||
if (kind === "light") lights.add(id);
|
||||
if (kind === "cover" && !DOOR_COVER_CLASSES.has(String(hass.states[id].attributes.device_class ?? ""))) covers.add(id);
|
||||
};
|
||||
for (const room of floor.rooms) {
|
||||
const hidden = new Set(room.hidden ?? []);
|
||||
primaryEntities(hass, roomEntities(hass, room)).filter((id) => !hidden.has(id)).forEach(consider);
|
||||
}
|
||||
floor.placements.forEach((p) => consider(p.entity_id));
|
||||
floor.furniture.forEach((f) => consider(f.entity));
|
||||
return { lights: [...lights], covers: [...covers] };
|
||||
}
|
||||
|
||||
/** The service a favourite runs when tapped: scenes and scripts start, buttons are pressed, the rest is toggled. */
|
||||
export function favoriteCall(entityId: string): [domain: string, service: string] {
|
||||
const domain = entityId.split(".")[0];
|
||||
switch (domain) {
|
||||
case "scene":
|
||||
case "script":
|
||||
return [domain, "turn_on"];
|
||||
case "automation":
|
||||
return [domain, "trigger"];
|
||||
case "button":
|
||||
case "input_button":
|
||||
return [domain, "press"];
|
||||
default:
|
||||
return ["homeassistant", "toggle"];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs an own button from an element inside the dashboard: navigate, open more-info, call a service, or fire a DOM
|
||||
* event ("ll-custom" is what Home Assistant's fire-dom-event sends, and what browser_mod listens for).
|
||||
*/
|
||||
export function runButton(hass: HomeAssistant, from: HTMLElement, button: { action: string; target?: string | null; data?: Record<string, unknown> | null }): void {
|
||||
const target = button.target?.trim() ?? "";
|
||||
const fire = (name: string, detail: unknown) => from.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));
|
||||
switch (button.action) {
|
||||
case "navigate":
|
||||
if (!target) return;
|
||||
history.pushState(null, "", target);
|
||||
window.dispatchEvent(new CustomEvent("location-changed", { detail: { replace: false } }));
|
||||
return;
|
||||
case "more_info":
|
||||
if (target) fire("hass-more-info", { entityId: target });
|
||||
return;
|
||||
case "service": {
|
||||
if (!target.includes(".")) return;
|
||||
const [domain, service] = target.split(".", 2);
|
||||
void hass.callService(domain, service, button.data ?? {});
|
||||
return;
|
||||
}
|
||||
case "fire_dom_event":
|
||||
fire("ll-custom", button.data ?? {});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an own button's entity is on, so the button lights up: the entity the button names itself (`state_entity`), else the one
|
||||
* it opens (more-info) or the single entity its service is called for. Off, unknown, or none to tell: false.
|
||||
*/
|
||||
export function ownButtonOn(hass: HomeAssistant | undefined, button: { action: string; target?: string | null; data?: Record<string, unknown> | null; state_entity?: string | null }): boolean {
|
||||
const data = button.data?.entity_id;
|
||||
const id = button.state_entity || (button.action === "more_info" ? button.target : null) || (button.action === "service" && typeof data === "string" ? data : null);
|
||||
const st = id ? hass?.states[id] : undefined;
|
||||
return !!st && ["on", "open", "playing", "home", "heat", "cool", "unlocked"].includes(st.state);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, entity, floorWith, hassOf, opening } from "./fixtures.ts";
|
||||
import { DOOR_DEFAULT_OPEN, isUnlocked, openingEntities, openingState, windowPosition } from "./openings.ts";
|
||||
|
||||
const sensors = [
|
||||
entity("cover.blind", "open", { device_class: "shutter" }),
|
||||
entity("binary_sensor.win1", "off", { device_class: "window" }),
|
||||
entity("binary_sensor.win2", "on", { device_class: "window" }),
|
||||
entity("binary_sensor.door", "off", { device_class: "door" }),
|
||||
entity("cover.garage", "closed", { device_class: "garage" }),
|
||||
entity("binary_sensor.garage_contact", "on", { device_class: "garage_door" }),
|
||||
];
|
||||
const registry = Object.fromEntries(sensors.map((s) => [s.entity_id, { area_id: "a" }]));
|
||||
|
||||
test("windows are matched in order with the contacts of their area, one blind serves all", () => {
|
||||
const hass = hassOf(sensors, registry);
|
||||
const floor = floorWith([box("r", 0, 0, 5, 4, "a")], { openings: [opening("w2", "r", "window", { offset: 3 }), opening("w1", "r", "window", { offset: 1 })] });
|
||||
const links = openingEntities(hass, [floor]);
|
||||
assert.equal(links.get("w1")?.contact, "binary_sensor.win1");
|
||||
assert.equal(links.get("w2")?.contact, "binary_sensor.win2");
|
||||
assert.equal(links.get("w1")?.cover, "cover.blind");
|
||||
assert.equal(links.get("w2")?.cover, "cover.blind");
|
||||
});
|
||||
|
||||
test("doors and garage doors find their own kind of entity", () => {
|
||||
const hass = hassOf(sensors, registry);
|
||||
const floor = floorWith([box("r", 0, 0, 5, 4, "a")], { openings: [opening("d", "r", "door"), opening("g", "r", "garage")] });
|
||||
const links = openingEntities(hass, [floor]);
|
||||
assert.equal(links.get("d")?.contact, "binary_sensor.door");
|
||||
assert.equal(links.get("d")?.cover, null);
|
||||
assert.equal(links.get("g")?.cover, "cover.garage");
|
||||
assert.equal(links.get("g")?.contact, "binary_sensor.garage_contact");
|
||||
});
|
||||
|
||||
test("what was set by hand wins, and 'none' switches a link off", () => {
|
||||
const hass = hassOf(sensors, registry);
|
||||
const floor = floorWith([box("r", 0, 0, 5, 4, "a")], {
|
||||
openings: [opening("w", "r", "window", { cover: "none", contact: "binary_sensor.door", tilt: "binary_sensor.win2" }), opening("x", "r", "window", { contact: "none" })],
|
||||
});
|
||||
const links = openingEntities(hass, [floor]);
|
||||
assert.equal(links.get("w")?.cover, null);
|
||||
assert.equal(links.get("w")?.contact, "binary_sensor.door");
|
||||
assert.equal(links.get("w")?.tilt, "binary_sensor.win2");
|
||||
assert.equal(links.get("x")?.contact, null);
|
||||
});
|
||||
|
||||
test("a window with a handle sensor gets no automatic plain contact", () => {
|
||||
const hass = hassOf(sensors, registry);
|
||||
const floor = floorWith([box("r", 0, 0, 5, 4, "a")], { openings: [opening("w", "r", "window", { sensor: "handle" } as never)] });
|
||||
assert.equal(openingEntities(hass, [floor]).get("w")?.contact, null);
|
||||
});
|
||||
|
||||
test("only a two-leaf opening has second-leaf sensors", () => {
|
||||
const hass = hassOf(sensors, registry);
|
||||
const make = (leaves: number) => floorWith([box("r", 0, 0, 5, 4, "a")], { openings: [opening("w", "r", "window", { leaves, contact2: "binary_sensor.win2", tilt2: "none" } as never)] });
|
||||
assert.equal(openingEntities(hass, [make(1)]).get("w")?.contact2, null);
|
||||
assert.equal(openingEntities(hass, [make(2)]).get("w")?.contact2, "binary_sensor.win2");
|
||||
assert.equal(openingEntities(hass, [make(2)]).get("w")?.tilt2, null);
|
||||
});
|
||||
|
||||
test("window position from plain contacts, handle words (also German) and a window_state attribute", () => {
|
||||
assert.equal(windowPosition(entity("binary_sensor.a", "on")), "open");
|
||||
assert.equal(windowPosition(entity("binary_sensor.a", "off")), "closed");
|
||||
assert.equal(windowPosition(entity("sensor.handle", "tilted")), "tilted");
|
||||
assert.equal(windowPosition(entity("sensor.handle", "Gekippt")), "tilted");
|
||||
assert.equal(windowPosition(entity("sensor.handle", "geschlossen")), "closed");
|
||||
assert.equal(windowPosition(entity("sensor.handle", "offen")), "open");
|
||||
assert.equal(windowPosition(entity("binary_sensor.a", "off", { window_state: "tilted" })), "tilted");
|
||||
assert.equal(windowPosition(entity("sensor.handle", "banana")), null);
|
||||
assert.equal(windowPosition(entity("sensor.handle", "unavailable")), null);
|
||||
assert.equal(windowPosition(undefined), null);
|
||||
});
|
||||
|
||||
const plain = (extra: Record<string, unknown> = {}) => ({ cover: null, contact: null, tilt: null, ...extra });
|
||||
|
||||
test("a window: open by contact, tilted by a tilt sensor, and tilting wins over open", () => {
|
||||
const hass = hassOf([entity("binary_sensor.c", "on"), entity("binary_sensor.t", "on")]);
|
||||
assert.deepEqual({ ...openingState(hass, plain({ contact: "binary_sensor.c" })) }, { open: 1, open2: 0, tilt: 0, tilt2: 0, cover: null, sensed: true });
|
||||
const both = openingState(hass, plain({ contact: "binary_sensor.c", tilt: "binary_sensor.t" }));
|
||||
assert.deepEqual([both.open, both.tilt], [0, 1]);
|
||||
});
|
||||
|
||||
test("a tilt angle sensor tilts as far as it reports, with maximum, offset and sign", () => {
|
||||
const hass = hassOf([entity("sensor.angle", "7.5")]);
|
||||
assert.equal(openingState(hass, plain({ tiltAngle: "sensor.angle", tiltMax: 15 })).tilt, 0.5);
|
||||
assert.equal(openingState(hass, plain({ tiltAngle: "sensor.angle", tiltMax: 15, tiltOffset: 7.5 })).tilt, 0, "offset removes it");
|
||||
assert.equal(openingState(hass, plain({ tiltAngle: "sensor.angle", tiltInvert: true })).tilt, 0, "inverted negative clamps to 0");
|
||||
assert.equal(openingState(hass, plain({ tiltAngle: "sensor.angle", tiltMax: 5 })).tilt, 1, "more than the maximum is fully tilted");
|
||||
assert.equal(openingState(hass, plain({ tiltAngle: "sensor.angle", tiltMax: 15, tiltOffset: 7 })).tilt, 0, "a small angle (under 8 %) counts as closed");
|
||||
});
|
||||
|
||||
test("blinds: position sensor (percent or fraction), else the cover's own position or state", () => {
|
||||
const hass = hassOf([entity("sensor.pos", "30", { unit_of_measurement: "%" }), entity("sensor.frac", "0.25"), entity("cover.a", "open", { current_position: 80 }), entity("cover.b", "closed"), entity("cover.c", "closing"), entity("cover.d", "open")]);
|
||||
assert.equal(openingState(hass, plain({ position: "sensor.pos" })).cover, 0.7);
|
||||
assert.equal(openingState(hass, plain({ position: "sensor.frac" })).cover, 0.75);
|
||||
assert.equal(openingState(hass, plain({ position: "sensor.pos", positionInverted: true })).cover, 0.3);
|
||||
assert.ok(Math.abs(openingState(hass, plain({ cover: "cover.a" })).cover! - 0.2) < 1e-9);
|
||||
assert.equal(openingState(hass, plain({ cover: "cover.b" })).cover, 1);
|
||||
assert.equal(openingState(hass, plain({ cover: "cover.c" })).cover, 0.5);
|
||||
assert.equal(openingState(hass, plain({ cover: "cover.d" })).cover, 0);
|
||||
assert.equal(openingState(hass, plain({ cover: "cover.missing" })).cover, 0);
|
||||
assert.equal(openingState(hass, plain()).cover, null);
|
||||
});
|
||||
|
||||
test("a door follows its contact, or stands half open, or is shut when told so", () => {
|
||||
const hass = hassOf([entity("binary_sensor.d", "on"), entity("binary_sensor.closed", "off")]);
|
||||
assert.equal(openingState(hass, plain({ contact: "binary_sensor.d" }), "door").open, 1);
|
||||
assert.equal(openingState(hass, plain({ contact: "binary_sensor.closed" }), "door").open, 0);
|
||||
assert.equal(openingState(hass, plain(), "door").open, DOOR_DEFAULT_OPEN);
|
||||
assert.equal(openingState(hass, plain({ shut: true }), "door").open, 0);
|
||||
});
|
||||
|
||||
test("a door with its own opening angle stands at it without a sensor, but is not taken for open", () => {
|
||||
const hass = hassOf([entity("binary_sensor.closed", "off")]);
|
||||
const free = openingState(hass, plain({ angled: true }), "door");
|
||||
assert.equal(free.open, 1);
|
||||
assert.equal(free.assumed, true);
|
||||
assert.equal(openingState(hass, plain({ angled: true, shut: true }), "door").open, 0);
|
||||
const sensed = openingState(hass, plain({ angled: true, contact: "binary_sensor.closed" }), "door");
|
||||
assert.equal(sensed.open, 0);
|
||||
assert.equal(sensed.assumed, false);
|
||||
});
|
||||
|
||||
test("a door with a roller shutter reports the blind as well", () => {
|
||||
const hass = hassOf([entity("cover.shutter", "open", { current_position: 25 })]);
|
||||
const state = openingState(hass, plain({ cover: "cover.shutter", shut: true }), "door");
|
||||
assert.equal(state.cover, 0.75);
|
||||
assert.equal(state.sensed, true);
|
||||
});
|
||||
|
||||
test("a garage door shows its cover, else its contact, else closed", () => {
|
||||
const hass = hassOf([entity("cover.g", "open", { current_position: 100 }), entity("binary_sensor.gc", "on")]);
|
||||
assert.equal(openingState(hass, plain({ cover: "cover.g" }), "garage").cover, 0);
|
||||
assert.equal(openingState(hass, plain({ contact: "binary_sensor.gc" }), "garage").cover, 0);
|
||||
assert.equal(openingState(hass, plain(), "garage").cover, 1);
|
||||
assert.equal(openingState(hass, plain(), "garage").sensed, false);
|
||||
});
|
||||
|
||||
test("a garage door whose cover is unknown (a remote without feedback) follows its contact", () => {
|
||||
const hass = hassOf([entity("cover.remote", "unknown", { assumed_state: true }), entity("binary_sensor.shut", "off"), entity("binary_sensor.gc", "on")]);
|
||||
assert.equal(openingState(hass, plain({ cover: "cover.remote", contact: "binary_sensor.shut" }), "garage").cover, 1);
|
||||
assert.equal(openingState(hass, plain({ cover: "cover.remote", contact: "binary_sensor.gc" }), "garage").cover, 0);
|
||||
assert.equal(openingState(hass, plain({ cover: "cover.remote" }), "garage").cover, 0, "without a contact it stays as before");
|
||||
});
|
||||
|
||||
test("the second leaf of a double window has contact and tilt of its own and stays closed without sensors", () => {
|
||||
const hass = hassOf([entity("binary_sensor.c2", "on"), entity("binary_sensor.t2", "on")]);
|
||||
assert.deepEqual([openingState(hass, plain({ contact2: "binary_sensor.c2" })).open2, openingState(hass, plain()).open2], [1, 0]);
|
||||
const tilted = openingState(hass, plain({ contact2: "binary_sensor.c2", tilt2: "binary_sensor.t2" }));
|
||||
assert.deepEqual([tilted.open2, tilted.tilt2], [0, 1]);
|
||||
});
|
||||
|
||||
test("'sensed' says whether any sensor answered", () => {
|
||||
const hass = hassOf([entity("binary_sensor.c", "unavailable"), entity("binary_sensor.d", "off")]);
|
||||
assert.equal(openingState(hass, plain({ contact: "binary_sensor.c" })).sensed, false);
|
||||
assert.equal(openingState(hass, plain({ contact: "binary_sensor.d" })).sensed, true);
|
||||
assert.equal(openingState(hass, plain()).sensed, false);
|
||||
});
|
||||
|
||||
test("a door's smart lock is linked by hand and says when it stands unlocked", () => {
|
||||
const locks = [entity("lock.front", "unlocked"), entity("lock.back", "locked"), entity("lock.side", "jammed")];
|
||||
const hass = hassOf([...sensors, ...locks], registry);
|
||||
const floor = floorWith([box("r", 0, 0, 5, 4, "a")], {
|
||||
openings: [opening("d", "r", "door", { lock: "lock.front" }), opening("e", "r", "door", { lock: "lock.back" }), opening("w", "r", "window", { lock: "lock.front" })],
|
||||
});
|
||||
const links = openingEntities(hass, [floor]);
|
||||
assert.equal(links.get("d")?.lock, "lock.front");
|
||||
assert.equal(links.get("w")?.lock, null, "only doors take a lock");
|
||||
assert.equal(openingState(hass, links.get("d")!, "door").unlocked, true);
|
||||
assert.equal(openingState(hass, links.get("e")!, "door").unlocked, false);
|
||||
assert.equal(isUnlocked(hass, "lock.side"), false, "a jammed lock does not glow");
|
||||
assert.equal(isUnlocked(hass, null), false);
|
||||
});
|
||||
|
||||
test("a wide window's second blind and a venetian blind's slats", () => {
|
||||
const hass = hassOf([
|
||||
entity("cover.left", "open", { current_position: 100, current_tilt_position: 30 }),
|
||||
entity("cover.right", "closed", { current_position: 0 }),
|
||||
]);
|
||||
const state = openingState(hass, { cover: "cover.left", contact: null, tilt: null, cover2: "cover.right" });
|
||||
assert.equal(state.cover, 0);
|
||||
assert.equal(state.cover2, 1);
|
||||
assert.equal(state.slats, 0.3);
|
||||
assert.equal(openingState(hass, { cover: "cover.right", contact: null, tilt: null }).cover2, undefined, "no second blind");
|
||||
});
|
||||
@@ -0,0 +1,237 @@
|
||||
// Doors, windows and garage doors: which entities belong to each opening, and what state they are in.
|
||||
|
||||
import type { Floor, Opening } from "../model.ts";
|
||||
import type { HassEntity, HomeAssistant } from "../types.ts";
|
||||
import { isUnavailable, kindOf } from "./kinds.ts";
|
||||
import { roomEntities } from "./registry.ts";
|
||||
|
||||
export interface OpeningEntities {
|
||||
cover: string | null;
|
||||
contact: string | null;
|
||||
tilt: string | null;
|
||||
/** Contact and tilt sensor of the second leaf of a double door or window. */
|
||||
contact2?: string | null;
|
||||
tilt2?: string | null;
|
||||
/** A sensor with the blind's position while it moves (0-100 % or 0-1, open is high). */
|
||||
position?: string | null;
|
||||
positionInverted?: boolean;
|
||||
/** A sensor with the sash's tilt angle in degrees, the angle that counts as fully tilted, an offset and the sign. */
|
||||
tiltAngle?: string | null;
|
||||
tiltMax?: number | null;
|
||||
tiltOffset?: number | null;
|
||||
tiltInvert?: boolean;
|
||||
/** A door without a sensor is drawn closed. */
|
||||
shut?: boolean;
|
||||
/** A door with its own opening angle stands at that angle without a sensor, instead of half open. */
|
||||
angled?: boolean;
|
||||
/** A door's smart lock. */
|
||||
lock?: string | null;
|
||||
/** A second blind of a wide window (its right half, seen from the room). */
|
||||
cover2?: string | null;
|
||||
}
|
||||
|
||||
const BLIND_CLASSES = new Set([undefined, "shutter", "blind", "awning", "shade", "curtain", "window"]);
|
||||
const GARAGE_COVER_CLASSES = new Set(["garage", "gate"]);
|
||||
const WINDOW_CONTACT_CLASSES = new Set(["window", "opening"]);
|
||||
|
||||
/** The n-th opening gets the n-th entity. With `shared`, one single entity serves every opening. */
|
||||
function assign(openings: Opening[], entities: string[], shared = false): Map<string, string> {
|
||||
const result = new Map<string, string>();
|
||||
openings.forEach((opening, i) => {
|
||||
const entity = shared && entities.length === 1 ? entities[0] : entities[i];
|
||||
if (entity) result.set(opening.id, entity);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
/** An explicit choice ("none" switches it off) wins over the automatic match. */
|
||||
const chosenOr = (choice: string | null, automatic: string | undefined): string | null => (choice === "none" ? null : (choice ?? automatic ?? null));
|
||||
const unlessNone = (ref: string | null | undefined): string | null => (ref && ref !== "none" ? ref : null);
|
||||
|
||||
/**
|
||||
* The entities of every door and window: those set by hand, otherwise matched automatically with the covers and
|
||||
* contact sensors of the room's area, in the order the openings sit along the room's outline.
|
||||
*/
|
||||
export function openingEntities(hass: HomeAssistant, floors: readonly Floor[]): Map<string, OpeningEntities> {
|
||||
const result = new Map<string, OpeningEntities>();
|
||||
for (const floor of floors) {
|
||||
for (const room of floor.rooms) {
|
||||
const openings = floor.openings.filter((o) => o.room_id === room.id).sort((a, b) => a.edge - b.edge || a.offset - b.offset);
|
||||
if (openings.length === 0) continue;
|
||||
const entities = roomEntities(hass, room);
|
||||
const deviceClass = (id: string) => hass.states[id]?.attributes.device_class as string | undefined;
|
||||
const binaries = (classes: (cls: string) => boolean) => entities.filter((id) => kindOf(id) === "binary" && classes(deviceClass(id) ?? ""));
|
||||
const ofType = (type: Opening["type"]) => openings.filter((o) => o.type === type);
|
||||
|
||||
// one blind for the whole room (a group, say) serves every window; a contact belongs to one window
|
||||
const windowBlind = assign(ofType("window"), entities.filter((id) => kindOf(id) === "cover" && BLIND_CLASSES.has(deviceClass(id))), true);
|
||||
const windowContact = assign(ofType("window"), binaries((c) => WINDOW_CONTACT_CLASSES.has(c)));
|
||||
const doorContact = assign(ofType("door"), binaries((c) => c === "door"));
|
||||
const garageCover = assign(ofType("garage"), entities.filter((id) => kindOf(id) === "cover" && GARAGE_COVER_CLASSES.has(deviceClass(id) ?? "")));
|
||||
const garageContact = assign(ofType("garage"), binaries((c) => c === "garage_door"));
|
||||
|
||||
for (const o of openings) {
|
||||
const covers = o.type === "window" ? windowBlind : o.type === "garage" ? garageCover : null;
|
||||
const contacts = o.type === "window" ? windowContact : o.type === "garage" ? garageContact : doorContact;
|
||||
const secondLeaf = o.leaves === 2;
|
||||
result.set(o.id, {
|
||||
cover: chosenOr(o.cover, covers?.get(o.id)),
|
||||
// a window with a handle sensor gets no plain contact automatically
|
||||
contact: o.sensor === "handle" && o.contact == null ? null : chosenOr(o.contact, contacts.get(o.id)),
|
||||
tilt: o.tilt === "none" ? null : o.tilt,
|
||||
contact2: secondLeaf ? unlessNone(o.contact2) : null,
|
||||
tilt2: secondLeaf ? unlessNone(o.tilt2) : null,
|
||||
position: unlessNone(o.position),
|
||||
positionInverted: !!o.position_inverted,
|
||||
tiltAngle: unlessNone(o.tilt_angle),
|
||||
tiltMax: o.tilt_max ?? null,
|
||||
tiltOffset: o.tilt_offset ?? null,
|
||||
tiltInvert: !!o.tilt_invert,
|
||||
shut: !!o.shut,
|
||||
angled: o.type === "door" && !!o.open_angle,
|
||||
lock: o.type === "door" ? unlessNone(o.lock) : null,
|
||||
cover2: o.type === "garage" ? null : unlessNone(o.cover2),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
type SashPosition = "open" | "tilted" | "closed";
|
||||
|
||||
const POSITION_WORDS: [RegExp, SashPosition][] = [
|
||||
[/^(tilted|tilt|gekippt|kipp)/i, "tilted"],
|
||||
[/^(open|opened|offen|geöffnet|on)$/i, "open"],
|
||||
[/^(closed|close|geschlossen|zu|off)$/i, "closed"],
|
||||
];
|
||||
|
||||
/**
|
||||
* Whether a window or door is open, tilted or closed, from its contact. Understands plain contacts (on is open),
|
||||
* handle sensors with three states (also in German), and contacts that report it in a `window_state` attribute.
|
||||
* Null when the sensor says nothing usable.
|
||||
*/
|
||||
export function windowPosition(st: HassEntity | undefined): SashPosition | null {
|
||||
if (!st || isUnavailable(st)) return null;
|
||||
const fromAttribute = st.attributes.window_state;
|
||||
for (const text of [typeof fromAttribute === "string" ? fromAttribute : "", st.state]) {
|
||||
const word = text.trim();
|
||||
const match = word && POSITION_WORDS.find(([pattern]) => pattern.test(word));
|
||||
if (match) return match[1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A door leaf without a contact sensor stands half open, so the doorway stays readable. */
|
||||
export const DOOR_DEFAULT_OPEN = 0.5;
|
||||
|
||||
/** How far a blind is open according to a position sensor: a percentage or a 0-1 fraction. Null when unknown. */
|
||||
function reportedPosition(hass: HomeAssistant, id: string | null | undefined): number | null {
|
||||
const st = id ? hass.states[id] : undefined;
|
||||
const value = st && !isUnavailable(st) ? Number(st.state) : NaN;
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const isPercent = st!.attributes.unit_of_measurement === "%" || value > 1;
|
||||
return Math.min(1, Math.max(0, isPercent ? value / 100 : value));
|
||||
}
|
||||
|
||||
/** How closed the blind is (0 open, 1 closed) from the position sensor, else from the cover entity. Null without cover data. */
|
||||
/** How far a cover entity is closed (0 up, 1 down), or null without one. */
|
||||
function coverClosed(hass: HomeAssistant, id: string | null | undefined): number | null {
|
||||
const cover = id ? hass.states[id] : undefined;
|
||||
if (!cover || isUnavailable(cover)) return id ? 0 : null;
|
||||
const percent = cover.attributes.current_position;
|
||||
if (typeof percent === "number") return 1 - Math.min(100, Math.max(0, percent)) / 100;
|
||||
if (cover.state === "closed") return 1;
|
||||
return cover.state === "opening" || cover.state === "closing" ? 0.5 : 0;
|
||||
}
|
||||
|
||||
/** How far the slats of a venetian blind are open (0 shut, 1 level), from its tilt position; null when it reports none. */
|
||||
function slatsOpen(hass: HomeAssistant, id: string | null | undefined): number | null {
|
||||
const tilt = id ? hass.states[id]?.attributes.current_tilt_position : undefined;
|
||||
return typeof tilt === "number" ? Math.min(100, Math.max(0, tilt)) / 100 : null;
|
||||
}
|
||||
|
||||
function blindClosedFraction(hass: HomeAssistant, e: OpeningEntities): number | null {
|
||||
const reported = reportedPosition(hass, e.position);
|
||||
if (reported !== null) return e.positionInverted ? reported : 1 - reported;
|
||||
const cover = e.cover ? hass.states[e.cover] : undefined;
|
||||
if (cover && !isUnavailable(cover)) {
|
||||
const percent = cover.attributes.current_position;
|
||||
if (typeof percent === "number") return 1 - Math.min(100, Math.max(0, percent)) / 100;
|
||||
if (cover.state === "closed") return 1;
|
||||
return cover.state === "opening" || cover.state === "closing" ? 0.5 : 0;
|
||||
}
|
||||
return e.cover ? 0 : null;
|
||||
}
|
||||
|
||||
/** A smart lock that stands unlocked or open (unlocking counts once it has happened, jammed and unknown do not). */
|
||||
export function isUnlocked(hass: HomeAssistant, lock: string | null | undefined): boolean {
|
||||
const state = lock ? hass.states[lock]?.state : undefined;
|
||||
return state === "unlocked" || state === "open" || state === "opening";
|
||||
}
|
||||
|
||||
export interface OpeningState {
|
||||
open: number;
|
||||
open2: number;
|
||||
tilt: number;
|
||||
tilt2: number;
|
||||
cover: number | null;
|
||||
sensed: boolean;
|
||||
/** A door whose smart lock is unlocked (or open). */
|
||||
unlocked?: boolean;
|
||||
/** A door leaf drawn where it is assumed to stand, as no sensor tells: it does not glow as open. */
|
||||
assumed?: boolean;
|
||||
/** The second blind of a wide window (its right half): how far it is closed. */
|
||||
cover2?: number | null;
|
||||
/** Venetian blinds: how far the slats are open (0 shut, 1 level), from the cover's tilt position. */
|
||||
slats?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The look of an opening from its entities. Windows: sash open or tilted, and how far the blind is closed. Doors: leaf
|
||||
* open (contact) or half open. Garage doors: closed fraction from the cover or the contact.
|
||||
*/
|
||||
export function openingState(hass: HomeAssistant, e: OpeningEntities, type: Opening["type"] = "window"): OpeningState {
|
||||
const isOn = (id: string | null | undefined) => !!id && hass.states[id]?.state === "on";
|
||||
const isKnown = (id: string | null | undefined) => !!id && !!hass.states[id] && !isUnavailable(hass.states[id]);
|
||||
const positionOf = (id: string | null | undefined) => (id ? windowPosition(hass.states[id]) : null);
|
||||
const cover = blindClosedFraction(hass, e);
|
||||
|
||||
if (type === "door") {
|
||||
// a door with a roller shutter (front door, patio door): the blind comes down over it
|
||||
const leaf = positionOf(e.contact);
|
||||
const open = leaf === null ? (e.shut ? 0 : e.angled ? 1 : DOOR_DEFAULT_OPEN) : leaf === "closed" ? 0 : 1;
|
||||
return { open, open2: positionOf(e.contact2) === "open" ? 1 : 0, tilt: 0, tilt2: 0, cover, sensed: leaf !== null || cover !== null, unlocked: isUnlocked(hass, e.lock), assumed: leaf === null };
|
||||
}
|
||||
if (type === "garage") {
|
||||
// a garage door without a cover shows its contact: open or closed; so does one whose cover cannot tell (a remote without
|
||||
// feedback stays unknown)
|
||||
const sensed = cover !== null || isKnown(e.contact);
|
||||
const coverTells = reportedPosition(hass, e.position) !== null || isKnown(e.cover);
|
||||
const fromContact = isKnown(e.contact) ? (isOn(e.contact) ? 0 : 1) : null;
|
||||
return { open: 0, open2: 0, tilt: 0, tilt2: 0, cover: (coverTells ? cover : (fromContact ?? cover)) ?? 1, sensed };
|
||||
}
|
||||
|
||||
// a window: the second leaf stays closed without a sensor and tilts like the first
|
||||
const secondTilted = isOn(e.tilt2) || positionOf(e.tilt2) === "tilted" || positionOf(e.contact2) === "tilted";
|
||||
let tilted = isOn(e.tilt) || positionOf(e.tilt) === "tilted" || positionOf(e.contact) === "tilted";
|
||||
let tiltAmount = tilted ? 1 : 0;
|
||||
// an angle sensor tilts the sash as far as it reports, as a share of the angle that counts as fully tilted
|
||||
const rawAngle = e.tiltAngle ? Number(hass.states[e.tiltAngle]?.state) : NaN;
|
||||
if (Number.isFinite(rawAngle)) {
|
||||
const degrees = (rawAngle - (e.tiltOffset ?? 0)) * (e.tiltInvert ? -1 : 1);
|
||||
tiltAmount = Math.min(1, Math.max(0, degrees / (e.tiltMax || 15)));
|
||||
if (tiltAmount < 0.08) tiltAmount = 0;
|
||||
tilted = tiltAmount > 0;
|
||||
}
|
||||
return {
|
||||
open: positionOf(e.contact) === "open" && !tilted ? 1 : 0,
|
||||
open2: positionOf(e.contact2) === "open" && !secondTilted ? 1 : 0,
|
||||
tilt: tiltAmount,
|
||||
tilt2: secondTilted ? 1 : 0,
|
||||
cover,
|
||||
sensed: isKnown(e.contact) || isKnown(e.tilt) || Number.isFinite(rawAngle),
|
||||
...(e.cover2 ? { cover2: coverClosed(hass, e.cover2) } : {}),
|
||||
...(slatsOpen(hass, e.cover) !== null ? { slats: slatsOpen(hass, e.cover) } : {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity, hassOf } from "./fixtures.ts";
|
||||
import { pictureUrl, storedPictureId } from "./pictures.ts";
|
||||
|
||||
test("a frame's photo from a stored picture, a URL or an entity's picture", () => {
|
||||
const hass = hassOf([entity("image.photo_of_the_day", "2026-11-02", { entity_picture: "/api/image_proxy/image.photo_of_the_day?token=1" }), entity("camera.door", "idle")]);
|
||||
const stored = (id: string) => (id === "img_1" ? "data:image/jpeg;base64,AAA" : null);
|
||||
assert.equal(pictureUrl(hass, "image:img_1", stored), "data:image/jpeg;base64,AAA");
|
||||
assert.equal(pictureUrl(hass, "image:img_2", stored), null, "not loaded yet");
|
||||
assert.equal(pictureUrl(hass, "/local/holiday.jpg", stored), "/local/holiday.jpg");
|
||||
assert.equal(pictureUrl(hass, "https://example.org/a.png", stored), "https://example.org/a.png");
|
||||
assert.equal(pictureUrl(hass, "image.photo_of_the_day", stored), "/api/image_proxy/image.photo_of_the_day?token=1");
|
||||
assert.equal(pictureUrl(hass, "camera.door", stored), null, "an entity without a picture");
|
||||
assert.equal(pictureUrl(hass, "", stored), null);
|
||||
assert.equal(storedPictureId("image:img_1"), "img_1");
|
||||
assert.equal(storedPictureId("/local/a.jpg"), null);
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
// Where a picture frame's photo comes from: a picture stored with the plan ("image:<id>"), a URL (/local/…, https://…), or an
|
||||
// image, camera or media player entity whose picture it shows (a photo of the day, the doorbell camera, the album cover).
|
||||
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
|
||||
/** The prefix of a picture stored with the plan. */
|
||||
export const STORED_PICTURE = "image:";
|
||||
|
||||
/** The URL of a frame's photo, or null when there is none (yet): `stored` turns a stored picture's id into its data. */
|
||||
export function pictureUrl(hass: HomeAssistant | undefined, value: string | null | undefined, stored: (id: string) => string | null): string | null {
|
||||
const v = (value ?? "").trim();
|
||||
if (!v) return null;
|
||||
if (v.startsWith(STORED_PICTURE)) return stored(v.slice(STORED_PICTURE.length));
|
||||
if (/^(https?:\/\/|\/)/.test(v)) return v;
|
||||
if (/^[a-z_]+\.[a-z0-9_]+$/.test(v)) {
|
||||
const picture = hass?.states[v]?.attributes.entity_picture;
|
||||
return typeof picture === "string" && picture ? picture : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The id of a stored picture a frame shows, or null (a URL or an entity is no stored picture). */
|
||||
export const storedPictureId = (value: string | null | undefined): string | null => (value?.startsWith(STORED_PICTURE) ? value.slice(STORED_PICTURE.length) : null);
|
||||
@@ -0,0 +1,201 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity, floorWith, box, hassOf } from "./fixtures.ts";
|
||||
import { registerPlugin, resetPlugins } from "../plugins/registry.ts";
|
||||
import { areaEntities, entityAreaId, entityKind, groupByDevice, isHubDevice, isRelevant, isRoomClimateSensor, otherAreaEntities, powerSensorsOf, primaryEntities, roomClimateSensors, roomClimateValue, unassignedEntities } from "./registry.ts";
|
||||
|
||||
const lounge = hassOf(
|
||||
[
|
||||
entity("light.ceiling", "on"),
|
||||
entity("light.standing", "off"),
|
||||
entity("switch.hidden", "on"),
|
||||
entity("switch.firmware", "off"),
|
||||
entity("sensor.temp", "21", { device_class: "temperature" }),
|
||||
entity("sensor.battery", "80", { device_class: "battery", unit_of_measurement: "%" }),
|
||||
entity("vacuum.robot", "docked"),
|
||||
],
|
||||
{
|
||||
"light.ceiling": { area_id: "lounge" },
|
||||
"light.standing": { device_id: "d1" },
|
||||
"switch.hidden": { area_id: "lounge", hidden: true },
|
||||
"switch.firmware": { area_id: "lounge", entity_category: "config" },
|
||||
"sensor.temp": { area_id: "lounge" },
|
||||
"sensor.battery": { area_id: "lounge" },
|
||||
"vacuum.robot": { area_id: "lounge" },
|
||||
},
|
||||
{ areas: { lounge: { area_id: "lounge", name: "Lounge" } }, devices: { d1: { id: "d1", area_id: "lounge" } } },
|
||||
);
|
||||
|
||||
test("an entity's area is its own, else its device's", () => {
|
||||
assert.equal(entityAreaId(lounge, "light.ceiling"), "lounge");
|
||||
assert.equal(entityAreaId(lounge, "light.standing"), "lounge");
|
||||
assert.equal(entityAreaId(lounge, "light.unknown"), null);
|
||||
});
|
||||
|
||||
test("an area lists visible entities of handled kinds, lights before sensors", () => {
|
||||
const ids = areaEntities(lounge, "lounge");
|
||||
assert.deepEqual(ids, ["light.ceiling", "light.standing", "sensor.temp"]);
|
||||
assert.deepEqual(areaEntities(lounge, null), []);
|
||||
assert.deepEqual(areaEntities(lounge, "attic"), []);
|
||||
});
|
||||
|
||||
test("meters and air sensors are shown, battery and signal sensors are not", () => {
|
||||
const hass = hassOf([entity("sensor.gas", "12", { unit_of_measurement: "m³" }), entity("sensor.rssi", "-60", { device_class: "signal_strength" }), entity("sensor.co2", "700", { device_class: "carbon_dioxide" })]);
|
||||
assert.equal(isRelevant(hass, "sensor.gas"), true);
|
||||
assert.equal(isRelevant(hass, "sensor.co2"), true);
|
||||
assert.equal(isRelevant(hass, "sensor.rssi"), false);
|
||||
assert.equal(isRelevant(hass, "light.missing"), false);
|
||||
});
|
||||
|
||||
test("a binary sensor without a class shows only when it was given an area by hand", () => {
|
||||
const hass = hassOf([entity("binary_sensor.flag", "on"), entity("binary_sensor.noise", "on")], { "binary_sensor.flag": { area_id: "x" }, "binary_sensor.noise": {} });
|
||||
assert.equal(isRelevant(hass, "binary_sensor.flag"), true);
|
||||
assert.equal(isRelevant(hass, "binary_sensor.noise"), false);
|
||||
});
|
||||
|
||||
test("entities without an area are offered separately, including ones missing from the registry", () => {
|
||||
const hass = hassOf(
|
||||
[entity("light.template", "on"), entity("sensor.counter", "5", { unit_of_measurement: "pcs" }), entity("sensor.rssi", "-60", { device_class: "signal_strength", unit_of_measurement: "dBm" }), entity("scene.movie", "off")],
|
||||
{ "light.template": {}, "sensor.counter": {}, "sensor.rssi": {}, "scene.movie": {} },
|
||||
);
|
||||
assert.deepEqual(unassignedEntities(hass), ["light.template", "sensor.counter"]);
|
||||
});
|
||||
|
||||
test("other areas are listed by name with their placeable entities only", () => {
|
||||
const hass = hassOf(
|
||||
[entity("light.a", "on"), entity("scene.a", "off"), entity("light.b", "on")],
|
||||
{ "light.a": { area_id: "kitchen" }, "scene.a": { area_id: "kitchen" }, "light.b": { area_id: "bath" } },
|
||||
{ areas: { kitchen: { area_id: "kitchen", name: "Kitchen" }, bath: { area_id: "bath", name: "Bath" } } },
|
||||
);
|
||||
const others = otherAreaEntities(hass, "bath");
|
||||
assert.deepEqual(others, [{ areaId: "kitchen", name: "Kitchen", ids: ["light.a"] }]);
|
||||
});
|
||||
|
||||
test("devices are grouped: the entity without a name of its own is the main one", () => {
|
||||
const hass = hassOf(
|
||||
[entity("light.strip", "on"), entity("sensor.strip_power", "5"), entity("light.solo", "off")],
|
||||
{ "light.strip": { device_id: "d" }, "sensor.strip_power": { device_id: "d", name: "Power" }, "light.solo": {} },
|
||||
);
|
||||
const groups = groupByDevice(hass, ["sensor.strip_power", "light.strip", "light.solo"]);
|
||||
assert.deepEqual(groups, [{ primary: "light.strip", others: ["sensor.strip_power"] }, { primary: "light.solo", others: [] }]);
|
||||
assert.deepEqual(primaryEntities(hass, ["sensor.strip_power", "light.strip", "light.solo"]), ["light.strip", "light.solo"]);
|
||||
});
|
||||
|
||||
test("power sensors are found per device, and a device in several areas is a hub", () => {
|
||||
const hass = hassOf(
|
||||
[entity("sensor.p1", "1", { device_class: "power" }), entity("light.k", "on"), entity("light.b", "on")],
|
||||
{ "sensor.p1": { device_id: "dev" }, "light.k": { device_id: "hub", area_id: "kitchen" }, "light.b": { device_id: "hub", area_id: "bath" } },
|
||||
);
|
||||
assert.deepEqual(powerSensorsOf(hass, "dev"), ["sensor.p1"]);
|
||||
assert.deepEqual(powerSensorsOf(hass, "nothing"), []);
|
||||
assert.equal(isHubDevice(hass, "hub"), true);
|
||||
assert.equal(isHubDevice(hass, "dev"), false);
|
||||
});
|
||||
|
||||
test("the lookups follow the registry: a new registry is read again, same objects are not", () => {
|
||||
const first = hassOf([entity("light.a", "on")], { "light.a": { area_id: "x" } });
|
||||
assert.deepEqual(areaEntities(first, "x"), ["light.a"]);
|
||||
const second = { ...first, entities: { "light.a": { entity_id: "light.a", area_id: "y" } } } as typeof first;
|
||||
assert.deepEqual(areaEntities(second, "x"), []);
|
||||
assert.deepEqual(areaEntities(second, "y"), ["light.a"]);
|
||||
// an entity that appears later in the states is noticed
|
||||
const third = { ...second, states: { ...second.states, "light.b": entity("light.b", "on") }, entities: { ...second.entities, "light.b": { entity_id: "light.b", area_id: "y" } } } as typeof first;
|
||||
assert.deepEqual(areaEntities(third, "y"), ["light.a", "light.b"]);
|
||||
});
|
||||
|
||||
test("room sensors skip device temperatures: by the device's other entities and by name", () => {
|
||||
const hass = hassOf(
|
||||
[entity("sensor.room_t", "21", { device_class: "temperature" }), entity("sensor.printer_nozzle", "200", { device_class: "temperature" }), entity("sensor.heater_t", "40", { device_class: "temperature" }), entity("climate.heater", "heat"), entity("sensor.flow_temp", "35", { device_class: "temperature" })],
|
||||
{ "sensor.room_t": { area_id: "a", device_id: "d1" }, "sensor.printer_nozzle": { area_id: "a", device_id: "d2" }, "sensor.heater_t": { area_id: "a", device_id: "d3" }, "climate.heater": { device_id: "d3" }, "sensor.flow_temp": { area_id: "a" } },
|
||||
);
|
||||
assert.equal(isRoomClimateSensor(hass, "sensor.room_t"), true);
|
||||
assert.equal(isRoomClimateSensor(hass, "sensor.printer_nozzle"), false, "name says nozzle");
|
||||
assert.equal(isRoomClimateSensor(hass, "sensor.heater_t"), false, "its device is a heater");
|
||||
assert.equal(isRoomClimateSensor(hass, "sensor.flow_temp"), false, "heating flow");
|
||||
});
|
||||
|
||||
test("a room's climate: automatic from the area, or a chosen sensor, or none", () => {
|
||||
const room = box("r", 0, 0, 4, 3, "a");
|
||||
const hass = hassOf(
|
||||
[entity("sensor.t1", "20", { device_class: "temperature" }), entity("sensor.t2", "70", { device_class: "temperature", unit_of_measurement: "°F" }), entity("sensor.h", "50", { device_class: "humidity" }), entity("sensor.chosen", "10", { device_class: "temperature" })],
|
||||
{ "sensor.t1": { area_id: "a" }, "sensor.t2": { area_id: "a" }, "sensor.h": { area_id: "a" }, "sensor.chosen": { area_id: "b" } },
|
||||
);
|
||||
assert.deepEqual(roomClimateSensors(hass, null, room, "temperature"), ["sensor.t1", "sensor.t2"]);
|
||||
assert.ok(Math.abs(roomClimateValue(hass, null, room, "temperature")! - (20 + (70 - 32) * 5 / 9) / 2) < 1e-9, "Fahrenheit is converted");
|
||||
assert.equal(roomClimateValue(hass, null, room, "humidity"), 50);
|
||||
assert.equal(roomClimateValue(hass, null, room, "co2"), null);
|
||||
assert.deepEqual(roomClimateSensors(hass, null, { ...room, climate: { temperature: "sensor.chosen" } }, "temperature"), ["sensor.chosen"]);
|
||||
assert.deepEqual(roomClimateSensors(hass, null, { ...room, climate: { temperature: "none" } }, "temperature"), []);
|
||||
assert.deepEqual(roomClimateSensors(hass, null, { ...room, climate: { temperature: ["sensor.t1", "sensor.chosen", "sensor.gone"] } }, "temperature"), ["sensor.t1", "sensor.chosen"], "several chosen sensors are all read");
|
||||
});
|
||||
|
||||
test("a sensor of the area placed in another room counts there, one placed inside counts here", () => {
|
||||
const here = box("here", 0, 0, 4, 3, "a");
|
||||
const there = box("there", 5, 0, 9, 3, "a");
|
||||
const hass = hassOf(
|
||||
[entity("sensor.in_area", "20", { device_class: "temperature" }), entity("sensor.placed_here", "22", { device_class: "temperature" })],
|
||||
{ "sensor.in_area": { area_id: "a" }, "sensor.placed_here": { area_id: "other" } },
|
||||
);
|
||||
const floor = floorWith([here, there], { placements: [{ entity_id: "sensor.in_area", x: 6, z: 1, y: null, mount: null }, { entity_id: "sensor.placed_here", x: 1, z: 1, y: null, mount: null }] });
|
||||
assert.deepEqual(roomClimateSensors(hass, floor, here, "temperature"), ["sensor.placed_here"]);
|
||||
assert.deepEqual(roomClimateSensors(hass, floor, there, "temperature"), ["sensor.in_area"]);
|
||||
});
|
||||
|
||||
test("a hub's room sensors still count, although its other entities are lights", () => {
|
||||
const hass = hassOf(
|
||||
[entity("sensor.bus_t_k", "21", { device_class: "temperature" }), entity("light.bus_k", "on"), entity("light.bus_b", "on")],
|
||||
{ "sensor.bus_t_k": { area_id: "k", device_id: "bus" }, "light.bus_k": { area_id: "k", device_id: "bus" }, "light.bus_b": { area_id: "b", device_id: "bus" } },
|
||||
);
|
||||
assert.equal(isRoomClimateSensor(hass, "sensor.bus_t_k"), true);
|
||||
});
|
||||
|
||||
test("entities a plugin gives a kind are offered like the others, in their area and without one", () => {
|
||||
registerPlugin({ id: "robot", apiVersion: 1, devices: [{ match: (id) => id.startsWith("vacuum."), kind: "switch" }] });
|
||||
try {
|
||||
const hass = hassOf(
|
||||
[entity("vacuum.rob", "docked"), entity("vacuum.loose", "docked"), entity("lawn_mower.x", "docked"), entity("light.a", "on")],
|
||||
{ "vacuum.rob": { area_id: "kitchen" }, "vacuum.loose": {}, "lawn_mower.x": {}, "light.a": { area_id: "kitchen" } },
|
||||
{ areas: { kitchen: { area_id: "kitchen", name: "Kitchen" } } },
|
||||
);
|
||||
assert.deepEqual(areaEntities(hass, "kitchen"), ["light.a", "vacuum.rob"]);
|
||||
assert.deepEqual(unassignedEntities(hass), ["vacuum.loose"]);
|
||||
assert.equal(entityKind(hass, "vacuum.rob"), "switch");
|
||||
assert.equal(entityKind(hass, "lawn_mower.x"), null);
|
||||
} finally {
|
||||
resetPlugins();
|
||||
}
|
||||
});
|
||||
|
||||
test("wall buttons and doorbells (event entities) are offered, other events are not", () => {
|
||||
const hass = hassOf([entity("event.hall_button", "unknown", { device_class: "button" }), entity("event.bell", "unknown", { device_class: "doorbell" }), entity("event.remote", "unknown"), entity("event.motion", "unknown", { device_class: "motion" })]);
|
||||
assert.equal(isRelevant(hass, "event.hall_button"), true);
|
||||
assert.equal(isRelevant(hass, "event.bell"), true);
|
||||
assert.equal(isRelevant(hass, "event.remote"), true);
|
||||
assert.equal(isRelevant(hass, "event.motion"), false);
|
||||
});
|
||||
|
||||
test("an NVR's camera that a plugin takes on leads its device, before the device's motion sensors", () => {
|
||||
registerPlugin({ id: "cams-test", name: "Cams", version: "1.0.0", apiVersion: 1, devices: [{ match: (id: string) => id.startsWith("camera."), kind: "sensor" }] } as never);
|
||||
const nvr = { area_id: "ext", device_id: "nvr" };
|
||||
const hass = hassOf(
|
||||
[entity("binary_sensor.nvr_motion_1", "off", { device_class: "motion" }), entity("binary_sensor.nvr_person_1", "off", { device_class: "occupancy" }), entity("camera.camera_1_live", "idle")],
|
||||
{ "binary_sensor.nvr_motion_1": nvr, "binary_sensor.nvr_person_1": nvr, "camera.camera_1_live": nvr } as never,
|
||||
);
|
||||
const ids = areaEntities(hass, "ext");
|
||||
assert.equal(ids[0], "camera.camera_1_live");
|
||||
assert.equal(groupByDevice(hass, ids)[0].primary, "camera.camera_1_live");
|
||||
resetPlugins();
|
||||
});
|
||||
|
||||
test("a sensor a plugin handles is listed whatever its device class, and leads its device", () => {
|
||||
registerPlugin({ id: "printer-test", name: "Printer", version: "1.0.0", apiVersion: 1, devices: [{ match: (id: string) => id.endsWith("_current_print_state"), kind: "sensor" }] } as never);
|
||||
const printer = { area_id: "work", device_id: "voron" };
|
||||
const hass = hassOf(
|
||||
[entity("sensor.voron_current_print_state", "printing", { device_class: "enum" }), entity("sensor.voron_extruder", "210", { device_class: "temperature", unit_of_measurement: "°C" }), entity("sensor.other_status", "ok", { device_class: "enum" })],
|
||||
{ "sensor.voron_current_print_state": printer, "sensor.voron_extruder": printer, "sensor.other_status": { area_id: "work" } } as never,
|
||||
);
|
||||
assert.equal(isRelevant(hass, "sensor.voron_current_print_state"), true);
|
||||
assert.equal(isRelevant(hass, "sensor.other_status"), false, "an enum sensor no plugin handles stays hidden");
|
||||
assert.equal(groupByDevice(hass, areaEntities(hass, "work"))[0].primary, "sensor.voron_current_print_state");
|
||||
resetPlugins();
|
||||
});
|
||||
@@ -0,0 +1,268 @@
|
||||
// Lookups over Home Assistant's entity registry: which entities belong to an area, which are worth showing,
|
||||
// which sensors measure a room, which power sensor goes with a device. The registry is indexed once and the index
|
||||
// is reused, because every state change would otherwise walk thousands of entities for every room.
|
||||
|
||||
import { pointInPolygon, type Floor, type Room } from "../model.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { onPluginsChanged, pluginKind } from "../plugins/registry.ts";
|
||||
import { domainOf, entityName, isPlaceable, isUnavailable, KIND_ORDER, kindOf, toCelsius, type DeviceKind } from "./kinds.ts";
|
||||
|
||||
/** Sensor classes that get a marker: room climate, air quality, power and energy, meters, light. */
|
||||
const SHOWN_SENSOR_CLASSES = new Set([
|
||||
"temperature", "humidity", "power", "carbon_dioxide", "energy", "gas", "water", "volume", "volume_storage", "volume_flow_rate", "illuminance",
|
||||
"pressure", "atmospheric_pressure", "pm1", "pm25", "pm10", "volatile_organic_compounds", "volatile_organic_compounds_parts",
|
||||
"carbon_monoxide", "nitrogen_dioxide", "moisture", "sound_pressure",
|
||||
]);
|
||||
/** A sensor without a class still counts when its unit is a meter's. */
|
||||
const METER_UNITS = new Set(["m³", "m3", "L", "l", "kWh", "Wh", "MWh", "lx"]);
|
||||
const SHOWN_BINARY_CLASSES = new Set(["door", "window", "opening", "garage_door", "motion", "occupancy", "presence", "smoke", "moisture", "gas", "carbon_monoxide"]);
|
||||
/** Sensor classes that describe the device itself and never make a marker. */
|
||||
const DIAGNOSTIC_CLASSES = new Set(["battery", "signal_strength", "timestamp", "date", "duration", "data_rate", "data_size", "frequency", "enum"]);
|
||||
|
||||
/** The area an entity is in: its own, else its device's. */
|
||||
export function entityAreaId(hass: HomeAssistant, entityId: string): string | null {
|
||||
const entry = hass.entities?.[entityId];
|
||||
if (!entry) return null;
|
||||
return entry.area_id || (entry.device_id ? hass.devices?.[entry.device_id]?.area_id : null) || null;
|
||||
}
|
||||
|
||||
const isHiddenOrConfig = (hass: HomeAssistant, entityId: string): boolean => {
|
||||
const entry = hass.entities?.[entityId];
|
||||
return !!(entry?.hidden || entry?.entity_category);
|
||||
};
|
||||
|
||||
/** The kind of an entity: by its domain, else the one a plugin gives it (a robot vacuum shown as a switch). */
|
||||
export const entityKind = (hass: HomeAssistant, entityId: string): DeviceKind | null => kindOf(entityId) ?? pluginKind(entityId, hass.states[entityId]);
|
||||
|
||||
/** Whether an entity is shown at all: visible, not a configuration entity, and of a kind that is handled. */
|
||||
export function isRelevant(hass: HomeAssistant, entityId: string): boolean {
|
||||
const state = hass.states[entityId];
|
||||
if (!state || isHiddenOrConfig(hass, entityId)) return false;
|
||||
// an entity a plugin takes care of is shown, whatever its domain or class (a printer's enum status sensor)
|
||||
if (pluginKind(entityId, state) !== null) return true;
|
||||
const kind = kindOf(entityId);
|
||||
if (!kind) return false;
|
||||
const deviceClass = state.attributes.device_class as string | undefined;
|
||||
// wall buttons, remotes and doorbells (event entities) count, other events are integration internals
|
||||
if (entityId.startsWith("event.")) return !deviceClass || deviceClass === "button" || deviceClass === "doorbell";
|
||||
if (kind === "sensor") return deviceClass ? SHOWN_SENSOR_CLASSES.has(deviceClass) : METER_UNITS.has(String(state.attributes.unit_of_measurement ?? ""));
|
||||
// a binary sensor without a class is mostly integration noise, unless someone gave that entity an area by hand
|
||||
if (kind === "binary") return deviceClass ? SHOWN_BINARY_CLASSES.has(deviceClass) : !!hass.entities?.[entityId]?.area_id;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** A numeric sensor with a unit: offered for devices without an area even when its class is unknown. */
|
||||
function isLooseSensor(hass: HomeAssistant, entityId: string): boolean {
|
||||
const state = hass.states[entityId];
|
||||
if (kindOf(entityId) !== "sensor" || !state?.attributes.unit_of_measurement || isHiddenOrConfig(hass, entityId)) return false;
|
||||
if (DIAGNOSTIC_CLASSES.has(String(state.attributes.device_class ?? ""))) return false;
|
||||
return Number.isFinite(Number(state.state)) || isUnavailable(state);
|
||||
}
|
||||
|
||||
/** A power sensor: a `sensor.` with the device class power. */
|
||||
export const isPower = (hass: HomeAssistant, id: string): boolean => id.startsWith("sensor.") && hass.states[id]?.attributes.device_class === "power";
|
||||
|
||||
interface Index {
|
||||
entities: HomeAssistant["entities"];
|
||||
devices: HomeAssistant["devices"];
|
||||
states: HomeAssistant["states"];
|
||||
stateCount: number;
|
||||
byArea: Map<string, string[]>;
|
||||
powerByDevice: Map<string, string[]>;
|
||||
/** Placeable entities that have no area. */
|
||||
withoutArea: string[];
|
||||
/** Per device: the domains of its visible entities (tells a 3D printer from a thermometer). */
|
||||
domainsByDevice: Map<string, Set<string>>;
|
||||
/** Devices whose entities sit in several areas, such as one bus device for a whole house. */
|
||||
hubs: Set<string>;
|
||||
}
|
||||
|
||||
let cached: Index | null = null;
|
||||
// a plugin can give a kind to entities of unknown domains: they are offered from then on
|
||||
onPluginsChanged(() => (cached = null));
|
||||
|
||||
function bucket<K, V>(map: Map<K, V[]>, key: K): V[] {
|
||||
let list = map.get(key);
|
||||
if (!list) map.set(key, (list = []));
|
||||
return list;
|
||||
}
|
||||
|
||||
function build(hass: HomeAssistant): Index {
|
||||
const byArea = new Map<string, string[]>();
|
||||
const powerByDevice = new Map<string, string[]>();
|
||||
const domainsByDevice = new Map<string, Set<string>>();
|
||||
const areasOfDevice = new Map<string, Set<string>>();
|
||||
const withoutArea: string[] = [];
|
||||
const offerWithoutArea = (id: string) => {
|
||||
if ((isRelevant(hass, id) || isLooseSensor(hass, id)) && isPlaceable(entityKind(hass, id))) withoutArea.push(id);
|
||||
};
|
||||
|
||||
for (const [id, entry] of Object.entries(hass.entities ?? {})) {
|
||||
const device = entry.device_id;
|
||||
if (device && entry.area_id) (areasOfDevice.get(device) ?? areasOfDevice.set(device, new Set()).get(device)!).add(entry.area_id);
|
||||
if (device && isPower(hass, id)) bucket(powerByDevice, device).push(id);
|
||||
if (device && !entry.hidden && !entry.entity_category) (domainsByDevice.get(device) ?? domainsByDevice.set(device, new Set()).get(device)!).add(domainOf(id));
|
||||
const area = entityAreaId(hass, id);
|
||||
if (area === null) offerWithoutArea(id);
|
||||
else if (isRelevant(hass, id)) bucket(byArea, area).push(id);
|
||||
}
|
||||
// entities that are not in the registry (YAML without a unique_id, a USB camera) have no area either
|
||||
if (hass.entities) for (const id of Object.keys(hass.states)) if (!hass.entities[id]) offerWithoutArea(id);
|
||||
|
||||
// an entity a plugin takes on (an NVR's camera, a printer's status) comes before the plain sensors of its device, so it is
|
||||
// the device's main entry
|
||||
const pluginRank = KIND_ORDER.indexOf("binary") - 0.5;
|
||||
const rank = (id: string) => {
|
||||
const kind = kindOf(id);
|
||||
const own = kind ? KIND_ORDER.indexOf(kind) : pluginRank;
|
||||
return own > pluginRank && pluginKind(id, hass.states[id]) !== null ? pluginRank : own;
|
||||
};
|
||||
withoutArea.sort((a, b) => rank(a) - rank(b) || entityName(hass, a).localeCompare(entityName(hass, b)));
|
||||
for (const [areaId, ids] of byArea) {
|
||||
const areaName = hass.areas?.[areaId]?.name;
|
||||
ids.sort((a, b) => rank(a) - rank(b) || entityName(hass, a, areaName).localeCompare(entityName(hass, b, areaName)));
|
||||
}
|
||||
const hubs = new Set<string>();
|
||||
for (const [device, areas] of areasOfDevice) if (areas.size > 1) hubs.add(device);
|
||||
return { entities: hass.entities, devices: hass.devices, states: hass.states, stateCount: Object.keys(hass.states).length, byArea, powerByDevice, withoutArea, domainsByDevice, hubs };
|
||||
}
|
||||
|
||||
/**
|
||||
* The index for a registry. Home Assistant swaps `entities`, `devices` and `states` for new objects when they change,
|
||||
* so object identity is the cache key. A different number of states (entities appearing after the registry) also
|
||||
* triggers a rebuild.
|
||||
*/
|
||||
function indexOf(hass: HomeAssistant): Index {
|
||||
const hit = cached;
|
||||
if (hit && hit.entities === hass.entities && hit.devices === hass.devices) {
|
||||
if (hit.states === hass.states) return hit;
|
||||
hit.states = hass.states;
|
||||
if (Object.keys(hass.states).length === hit.stateCount) return hit;
|
||||
}
|
||||
return (cached = build(hass));
|
||||
}
|
||||
|
||||
/** The shown entities of an area, by kind and name. The array is shared: do not change it. */
|
||||
/** The entities of a room: those of its area and of the areas that are parts of it (a corner, a shelf with an area of its own). */
|
||||
export function roomEntities(hass: HomeAssistant, room: { area_id: string | null; sub_areas?: string[] | null }): string[] {
|
||||
const own = areaEntities(hass, room.area_id);
|
||||
if (!room.sub_areas?.length) return own;
|
||||
return [...new Set([...own, ...room.sub_areas.flatMap((a) => areaEntities(hass, a))])];
|
||||
}
|
||||
|
||||
export function areaEntities(hass: HomeAssistant, areaId: string | null): string[] {
|
||||
if (!areaId || !hass.entities) return [];
|
||||
return indexOf(hass).byArea.get(areaId) ?? [];
|
||||
}
|
||||
|
||||
/** Placeable entities of all areas but one, grouped by area name: for placing a device that lives elsewhere. */
|
||||
export function otherAreaEntities(hass: HomeAssistant, exceptArea: string | null): { areaId: string; name: string; ids: string[] }[] {
|
||||
if (!hass.entities) return [];
|
||||
const groups: { areaId: string; name: string; ids: string[] }[] = [];
|
||||
for (const [areaId, all] of indexOf(hass).byArea) {
|
||||
const ids = all.filter((id) => isPlaceable(entityKind(hass, id)));
|
||||
if (areaId !== exceptArea && ids.length > 0) groups.push({ areaId, name: hass.areas?.[areaId]?.name ?? areaId, ids });
|
||||
}
|
||||
return groups.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** Placeable entities without an area (templates, groups, helpers, any numeric sensor with a unit). */
|
||||
export const unassignedEntities = (hass: HomeAssistant): string[] => (hass.entities ? indexOf(hass).withoutArea : []);
|
||||
|
||||
/** Whether a device is a hub: its entities lie in several areas. */
|
||||
export const isHubDevice = (hass: HomeAssistant, deviceId: string): boolean => !!hass.entities && indexOf(hass).hubs.has(deviceId);
|
||||
|
||||
/** The power sensors of a device. The array is shared: do not change it. */
|
||||
export const powerSensorsOf = (hass: HomeAssistant, deviceId: string): string[] => (hass.entities ? (indexOf(hass).powerByDevice.get(deviceId) ?? []) : []);
|
||||
|
||||
// ---------------------------------------------------------------- one entity per device
|
||||
|
||||
export interface DeviceGroup {
|
||||
/** The device's main entity (the one without a name of its own), or the entity itself. */
|
||||
primary: string;
|
||||
/** Other entities of the same device: indicators, effects, extra channels. */
|
||||
others: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups entities by their device. Home Assistant's convention makes the device's main feature the entity without a
|
||||
* name of its own; failing that, the first one. Groups come in the order of their main entities within `ids`.
|
||||
*/
|
||||
export function groupByDevice(hass: HomeAssistant, ids: readonly string[]): DeviceGroup[] {
|
||||
const members = new Map<string, string[]>();
|
||||
for (const id of ids) bucket(members, hass.entities?.[id]?.device_id ?? `entity:${id}`).push(id);
|
||||
const position = new Map(ids.map((id, i) => [id, i]));
|
||||
return [...members.values()]
|
||||
.map((list) => {
|
||||
const primary = list.find((id) => !hass.entities?.[id]?.name) ?? list[0];
|
||||
return { primary, others: list.filter((id) => id !== primary) };
|
||||
})
|
||||
.sort((a, b) => position.get(a.primary)! - position.get(b.primary)!);
|
||||
}
|
||||
|
||||
/** One entity per device: the main ones. */
|
||||
export const primaryEntities = (hass: HomeAssistant, ids: readonly string[]): string[] => groupByDevice(hass, ids).map((g) => g.primary);
|
||||
|
||||
// ---------------------------------------------------------------- room climate
|
||||
|
||||
/** Device classes of the three room values. */
|
||||
export const CLIMATE_CLASSES = { temperature: "temperature", humidity: "humidity", co2: "carbon_dioxide" } as const;
|
||||
export type ClimateKey = keyof typeof CLIMATE_CLASSES;
|
||||
|
||||
/** A device with one of these domains is not a room sensor: a heat pump, a printer, a TV. */
|
||||
const APPLIANCE_DOMAINS = new Set(["climate", "water_heater", "switch", "button", "camera", "media_player", "vacuum", "light", "fan", "lawn_mower"]);
|
||||
/** Words in a name (English and German) that mark a temperature that is not the room's: pipes, printers, chips, outdoors, cold appliances. */
|
||||
const NOT_THE_ROOM_WORDS = [
|
||||
"vorlauf", "r(ü|ue)cklauf", "flow", "return", // heating pipes
|
||||
"d(ü|ue)se", "nozzle", "hotend", "extruder", "druckbett", "heatbed", "(^|[^a-z])bed($|[^a-z])", "chamber", // 3D printers
|
||||
"cpu", "gpu", "chip", "soc", "akku", "batter", // electronics
|
||||
"wasser", "water", "kessel", "boiler", "au(ß|ss)en", "outdoor", "outside", // water, outdoors
|
||||
"abgas", "exhaust", "sole", "brine", "verdampfer", "kondensat", "verdichter", "compressor", "motor", // heat pumps
|
||||
"k(ü|ue)hl", "freezer", "fridge", "gefrier", // cold appliances
|
||||
];
|
||||
const NOT_THE_ROOM = new RegExp(`(${NOT_THE_ROOM_WORDS.join("|")})`, "i");
|
||||
|
||||
/** Whether a sensor measures the room itself rather than the inside of some device. */
|
||||
export function isRoomClimateSensor(hass: HomeAssistant, entityId: string): boolean {
|
||||
const device = hass.entities?.[entityId]?.device_id;
|
||||
// a hub's entities are scattered over the house, so what else it offers says nothing about this sensor
|
||||
const domains = device && !isHubDevice(hass, device) ? indexOf(hass).domainsByDevice.get(device) : undefined;
|
||||
if (domains && [...domains].some((d) => APPLIANCE_DOMAINS.has(d))) return false;
|
||||
return !NOT_THE_ROOM.test(`${entityId} ${hass.states[entityId]?.attributes.friendly_name ?? ""}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The sensors a room's temperature, humidity or CO₂ is read from. An explicit choice wins ("none" means no sensor).
|
||||
* Otherwise: the room sensors of the room's area plus those placed inside the room; a sensor of this area that is
|
||||
* placed in another room counts there instead.
|
||||
*/
|
||||
export function roomClimateSensors(hass: HomeAssistant, floor: Floor | null, room: Room, key: ClimateKey): string[] {
|
||||
const chosen = room.climate?.[key];
|
||||
if (chosen === "none") return [];
|
||||
// one sensor, or several that are averaged
|
||||
if (chosen) return [chosen].flat().filter((id) => hass.states[id]);
|
||||
const placedSensors = (floor?.placements ?? []).filter((p) => p.entity_id.startsWith("sensor."));
|
||||
const inside = placedSensors.filter((p) => pointInPolygon([p.x, p.z], room.points)).map((p) => p.entity_id);
|
||||
const insideElsewhere = new Set(placedSensors.filter((p) => !pointInPolygon([p.x, p.z], room.points)).map((p) => p.entity_id));
|
||||
const candidates = new Set([...roomEntities(hass, room).filter((id) => !insideElsewhere.has(id)), ...inside]);
|
||||
return [...candidates].filter((id) => id.startsWith("sensor.") && hass.states[id]?.attributes.device_class === CLIMATE_CLASSES[key] && isRoomClimateSensor(hass, id));
|
||||
}
|
||||
|
||||
/** The average of the room's sensors, or null when none reports. Temperatures are always °C, whatever the sensor's unit. */
|
||||
export function roomClimateValue(hass: HomeAssistant, floor: Floor | null, room: Room, key: ClimateKey): number | null {
|
||||
const readings = roomClimateSensors(hass, floor, room, key)
|
||||
.map((id) => {
|
||||
const reading = Number(hass.states[id]?.state);
|
||||
return key === "temperature" ? toCelsius(reading, hass.states[id]?.attributes.unit_of_measurement) : reading;
|
||||
})
|
||||
.filter(Number.isFinite);
|
||||
if (readings.length) return readings.reduce((sum, v) => sum + v, 0) / readings.length;
|
||||
// no room sensor: a thermostat of the room's area tells its temperature and humidity (heating curves, the heat map)
|
||||
if (key === "co2" || room.climate?.[key] === "none") return null;
|
||||
const attr = key === "temperature" ? "current_temperature" : "current_humidity";
|
||||
const climates = roomEntities(hass, room)
|
||||
.filter((id) => id.startsWith("climate."))
|
||||
.map((id) => hass.states[id]?.attributes[attr])
|
||||
.filter((v): v is number => typeof v === "number" && Number.isFinite(v));
|
||||
return climates.length ? climates.reduce((sum, v) => sum + v, 0) / climates.length : null;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { emptyBuilding, newFloor, type Furniture } from "../model.ts";
|
||||
import { entity, hassOf } from "./fixtures.ts";
|
||||
import { furnitureShown, hiddenFurniture, withoutHidden } from "./visibility.ts";
|
||||
|
||||
const piece = (id: string, show_when?: Furniture["show_when"]): Furniture => ({ id, type: "plant", x: 0, z: 0, rotation: 0, w: 1, d: 1, h: 1, variant: null, show_when });
|
||||
|
||||
test("a piece shows while its entity is on, or in the state asked for", () => {
|
||||
const hass = hassOf([entity("input_boolean.xmas", "on"), entity("input_select.season", "Winter"), entity("switch.off", "off"), entity("sensor.gone", "unavailable")]);
|
||||
assert.equal(furnitureShown(hass, piece("a")), true, "no condition: always");
|
||||
assert.equal(furnitureShown(hass, piece("a", { entity: "input_boolean.xmas" })), true);
|
||||
assert.equal(furnitureShown(hass, piece("a", { entity: "switch.off" })), false);
|
||||
assert.equal(furnitureShown(hass, piece("a", { entity: "switch.off", invert: true })), true, "shown while off");
|
||||
assert.equal(furnitureShown(hass, piece("a", { entity: "input_select.season", state: "summer, winter" })), true, "one of several states, any case");
|
||||
assert.equal(furnitureShown(hass, piece("a", { entity: "input_select.season", state: "summer" })), false);
|
||||
assert.equal(furnitureShown(hass, piece("a", { entity: "sensor.gone" })), true, "an unavailable entity hides nothing");
|
||||
assert.equal(furnitureShown(hass, piece("a", { entity: "sensor.missing" })), true);
|
||||
});
|
||||
|
||||
test("hidden pieces are left out of the building, which stays the same object without any", () => {
|
||||
const b = emptyBuilding();
|
||||
const floor = newFloor("f", "F", 0);
|
||||
floor.furniture = [piece("tree", { entity: "switch.off" }), piece("sofa")];
|
||||
b.floors = [floor];
|
||||
const hass = hassOf([entity("switch.off", "off")]);
|
||||
const hidden = hiddenFurniture(hass, b);
|
||||
assert.deepEqual(hidden, ["tree"]);
|
||||
assert.deepEqual(withoutHidden(b, hidden).floors[0].furniture.map((f) => f.id), ["sofa"]);
|
||||
assert.equal(withoutHidden(b, []), b);
|
||||
assert.equal(b.floors[0].furniture.length, 2, "the plan itself keeps the piece");
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
// Visibility conditions: a piece of furniture that only shows while an entity is in a state (seasonal decoration
|
||||
// behind an input_boolean, the Christmas tree in December, a tent while a calendar says "camping"). Pure functions;
|
||||
// the 3D view leaves hidden pieces out of the scene.
|
||||
|
||||
import type { Building, Furniture } from "../model.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { isUnavailable } from "./kinds.ts";
|
||||
|
||||
/** A visibility condition: the piece shows while `entity` is in `state` (null: while it is on), or the other way round. */
|
||||
export interface ShowWhen {
|
||||
entity: string;
|
||||
/** The state to match (several separated by commas, compared without case); null = "on", "home", "open" or "true". */
|
||||
state?: string | null;
|
||||
/** Shown while the condition is NOT met. */
|
||||
invert?: boolean;
|
||||
}
|
||||
|
||||
const ON = new Set(["on", "home", "open", "true", "active", "playing", "heat", "heating"]);
|
||||
|
||||
/** Whether a piece of furniture is shown now. Without a condition, or while its entity is missing or unavailable, it is shown. */
|
||||
export function furnitureShown(hass: HomeAssistant | undefined, f: Pick<Furniture, "show_when">): boolean {
|
||||
const cond = f.show_when;
|
||||
if (!cond?.entity || !hass) return true;
|
||||
const st = hass.states[cond.entity];
|
||||
if (!st || isUnavailable(st)) return true;
|
||||
const state = String(st.state).toLowerCase();
|
||||
const want = (cond.state ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
|
||||
const met = want.length ? want.includes(state) : ON.has(state) || (Number.isFinite(Number(state)) && Number(state) > 0);
|
||||
return cond.invert ? !met : met;
|
||||
}
|
||||
|
||||
/** Ids of the pieces hidden by their condition right now, sorted (a key that only changes when one appears or goes). */
|
||||
export function hiddenFurniture(hass: HomeAssistant | undefined, b: Building): string[] {
|
||||
const out: string[] = [];
|
||||
for (const floor of b.floors) for (const f of floor.furniture) if (!furnitureShown(hass, f)) out.push(f.id);
|
||||
return out.sort();
|
||||
}
|
||||
|
||||
/** The building without the hidden pieces (the same object when nothing is hidden). */
|
||||
export function withoutHidden(b: Building, hidden: readonly string[]): Building {
|
||||
if (!hidden.length) return b;
|
||||
const set = new Set(hidden);
|
||||
return { ...b, floors: b.floors.map((floor) => (floor.furniture.some((f) => set.has(f.id)) ? { ...floor, furniture: floor.furniture.filter((f) => !set.has(f.id)) } : floor)) };
|
||||
}
|
||||
Reference in new issue
Block a user