first push
This commit is contained in:
commit
2a81b4a502
845 files changed
+356635
No files matched your search
@@ -0,0 +1,34 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity, floorWith } from "../entities/fixtures.ts";
|
||||
import { allOffPlan, floorSwitchables } from "./all-off.ts";
|
||||
|
||||
test("everything off switches what is on and its undo brings the lights back as they were", () => {
|
||||
const plan = allOffPlan([
|
||||
entity("light.a", "on", { brightness: 120, color_mode: "color_temp", color_temp_kelvin: 2700 }),
|
||||
entity("light.b", "off"),
|
||||
entity("switch.tv_socket", "on"),
|
||||
entity("fan.ceiling", "on"),
|
||||
entity("media_player.speaker", "playing"),
|
||||
entity("media_player.tv", "on"),
|
||||
entity("lock.door", "locked"),
|
||||
undefined,
|
||||
]);
|
||||
assert.equal(plan.count, 5);
|
||||
assert.deepEqual(plan.off[0], { domain: "light", service: "turn_off", data: { entity_id: ["light.a"] } });
|
||||
assert.deepEqual(plan.undo[0], { domain: "light", service: "turn_on", data: { entity_id: "light.a", brightness: 120, color_temp_kelvin: 2700 } });
|
||||
assert.ok(plan.off.some((c) => c.domain === "media_player" && c.service === "media_pause"));
|
||||
assert.ok(plan.undo.some((c) => c.domain === "media_player" && c.service === "media_play"));
|
||||
assert.ok(plan.undo.some((c) => c.domain === "fan" && c.service === "turn_on"));
|
||||
assert.ok(!plan.off.some((c) => c.domain === "lock"));
|
||||
assert.equal(allOffPlan([entity("light.b", "off")]).count, 0);
|
||||
});
|
||||
|
||||
test("a floor offers the switchable entities of its pins and furniture", () => {
|
||||
const floor = {
|
||||
...floorWith([]),
|
||||
placements: [{ entity_id: "light.ceiling", x: 0, z: 0, y: null, mount: null }, { entity_id: "sensor.temp", x: 0, z: 0, y: null, mount: null }],
|
||||
furniture: [{ id: "tv", type: "tv", x: 1, z: 1, rotation: 0, w: 1, d: 0.1, h: 0.6, variant: null, entity: "media_player.tv", extra_lights: ["light.ambilight"] }],
|
||||
};
|
||||
assert.deepEqual(floorSwitchables(floor as never).sort(), ["light.ambilight", "light.ceiling", "media_player.tv"]);
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
// Everything off: the lights, switches, fans and media of a room or a floor in one tap, and the calls that bring them back as they
|
||||
// were (lights with their brightness and colour), for the few seconds the undo is offered.
|
||||
|
||||
import type { Floor } from "../model.ts";
|
||||
import type { HassEntity } from "../types.ts";
|
||||
import { lightSetting, moodCalls } from "./moods.ts";
|
||||
|
||||
export interface ServiceCall {
|
||||
domain: string;
|
||||
service: string;
|
||||
data: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const domainOf = (id: string) => id.slice(0, id.indexOf("."));
|
||||
const SWITCHES = new Set(["switch", "fan", "input_boolean"]);
|
||||
|
||||
/** The calls that switch off what is on, and those that undo it. `count` is how many things it switches. */
|
||||
export function allOffPlan(states: readonly (HassEntity | undefined)[]): { off: ServiceCall[]; undo: ServiceCall[]; count: number } {
|
||||
const lights: HassEntity[] = [];
|
||||
const switches = new Map<string, string[]>();
|
||||
const pause: string[] = [];
|
||||
const shut: string[] = [];
|
||||
for (const st of states) {
|
||||
if (!st) continue;
|
||||
const domain = domainOf(st.entity_id);
|
||||
if (domain === "light" && st.state === "on") lights.push(st);
|
||||
else if (SWITCHES.has(domain) && st.state === "on") switches.set(domain, [...(switches.get(domain) ?? []), st.entity_id]);
|
||||
else if (domain === "media_player" && st.state === "playing") pause.push(st.entity_id);
|
||||
else if (domain === "media_player" && (st.state === "on" || st.state === "idle")) shut.push(st.entity_id);
|
||||
}
|
||||
const off: ServiceCall[] = [];
|
||||
const undo: ServiceCall[] = [];
|
||||
if (lights.length) {
|
||||
off.push({ domain: "light", service: "turn_off", data: { entity_id: lights.map((l) => l.entity_id) } });
|
||||
undo.push(...moodCalls(lights.map(lightSetting)).map((c) => ({ domain: "light", service: c.service, data: c.data })));
|
||||
}
|
||||
for (const [domain, ids] of switches) {
|
||||
off.push({ domain, service: "turn_off", data: { entity_id: ids } });
|
||||
undo.push({ domain, service: "turn_on", data: { entity_id: ids } });
|
||||
}
|
||||
if (pause.length) {
|
||||
off.push({ domain: "media_player", service: "media_pause", data: { entity_id: pause } });
|
||||
undo.push({ domain: "media_player", service: "media_play", data: { entity_id: pause } });
|
||||
}
|
||||
if (shut.length) {
|
||||
off.push({ domain: "media_player", service: "turn_off", data: { entity_id: shut } });
|
||||
undo.push({ domain: "media_player", service: "turn_on", data: { entity_id: shut } });
|
||||
}
|
||||
const count = lights.length + [...switches.values()].reduce((n, ids) => n + ids.length, 0) + pause.length + shut.length;
|
||||
return { off, undo, count };
|
||||
}
|
||||
|
||||
/** What the plan shows on a floor that "everything off" may switch: device pins and the entities of furniture (lamps, TVs, sockets). */
|
||||
export function floorSwitchables(floor: Floor): string[] {
|
||||
const ids = new Set<string>();
|
||||
const take = (id: unknown) => {
|
||||
if (typeof id === "string" && /^(light|switch|fan|input_boolean|media_player)\./.test(id)) ids.add(id);
|
||||
};
|
||||
for (const p of floor.placements) take(p.entity_id);
|
||||
for (const m of floor.furniture) {
|
||||
take(m.entity);
|
||||
for (const e of m.extra_lights ?? []) take(e);
|
||||
}
|
||||
return [...ids];
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, entity, floorWith, hassOf } from "../entities/fixtures.ts";
|
||||
import { canAnnounce, claim, forThisScreen, roomHasSpeaker, roomSpeaker, showFor } from "./announce.ts";
|
||||
|
||||
test("an announcement goes to every screen, or only to the ones named; a muted screen hears none", () => {
|
||||
assert.equal(forThisScreen({ screens: [] }, null), true);
|
||||
assert.equal(forThisScreen({ screens: ["Hallway"] }, " hallway "), true);
|
||||
assert.equal(forThisScreen({ screens: ["Hallway"] }, "Kitchen"), false);
|
||||
assert.equal(forThisScreen({ screens: ["Hallway"] }, null), false);
|
||||
assert.equal(forThisScreen({ screens: [] }, "Hallway", true), false);
|
||||
});
|
||||
|
||||
test("several views on a page show an announcement once", () => {
|
||||
const a = { time: "2026-11-01T12:00:00Z", message: "Dinner!" };
|
||||
assert.equal(claim(a), true);
|
||||
assert.equal(claim({ ...a }), false);
|
||||
assert.equal(claim({ ...a, time: "2026-11-01T12:00:05Z" }), true);
|
||||
});
|
||||
|
||||
test("a message stays long enough to read, between 6 and 30 seconds", () => {
|
||||
assert.equal(showFor("Dinner!"), 6000);
|
||||
assert.equal(showFor(Array(100).fill("word").join(" ")), 30000);
|
||||
});
|
||||
|
||||
test("the room's speaker: chosen, else placed in the room, else a satellite, an Echo or a speaker of the area; never a TV", () => {
|
||||
const states = [
|
||||
entity("media_player.radio", "idle"),
|
||||
entity("media_player.tv", "on", { device_class: "tv" }),
|
||||
entity("media_player.off", "off"),
|
||||
entity("assist_satellite.voice", "idle"),
|
||||
entity("media_player.placed", "idle"),
|
||||
entity("notify.echo_announce", "unknown"),
|
||||
];
|
||||
const hass = hassOf(states, {
|
||||
"media_player.radio": { area_id: "kitchen" },
|
||||
"media_player.tv": { area_id: "living" },
|
||||
"media_player.off": { area_id: "living" },
|
||||
"assist_satellite.voice": { area_id: "kitchen" },
|
||||
"notify.echo_announce": { area_id: "hall", platform: "alexa_devices" },
|
||||
});
|
||||
const kitchen = box("kitchen", 0, 0, 4, 3, "kitchen");
|
||||
const living = box("living", 4, 0, 8, 3, "living");
|
||||
const hall = box("hall", 0, 3, 4, 6, "hall");
|
||||
const floor = floorWith([kitchen, living, hall]);
|
||||
assert.equal(roomSpeaker(hass, floor, kitchen), "assist_satellite.voice");
|
||||
assert.equal(roomSpeaker(hass, floor, living), null);
|
||||
assert.equal(roomSpeaker(hass, floor, hall), "notify.echo_announce");
|
||||
floor.placements.push({ entity_id: "media_player.placed", x: 6, z: 1, mount: null, rotation: 0 } as (typeof floor.placements)[number]);
|
||||
assert.equal(roomSpeaker(hass, floor, living), "media_player.placed");
|
||||
assert.equal(roomSpeaker(hass, floor, { ...kitchen, announce_speaker: "media_player.off" }), "media_player.off");
|
||||
assert.equal(roomHasSpeaker(hass, floor, { ...kitchen, announce_speaker: "none" }), false);
|
||||
});
|
||||
|
||||
test("announcements are offered only where Home Assistant knows the action", () => {
|
||||
assert.equal(canAnnounce(hassOf([])), false);
|
||||
assert.equal(canAnnounce(hassOf([], {}, { services: { nextfloor: { announce: {} } } })), true);
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
// Announcements on this screen and from a room: the action nextfloor.announce (announce.py) speaks in the rooms and sends
|
||||
// every announcement to the open NextFloor screens, which show it big, play a chime and speak it.
|
||||
|
||||
import { pointInPolygon, type Floor, type Room } from "../model.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
|
||||
export interface Announcement {
|
||||
message: string;
|
||||
/** Only the screens with these names; empty: every screen. */
|
||||
screens: string[];
|
||||
/** The message spoken by Home Assistant's text-to-speech, or null (the browser's own voice speaks then). */
|
||||
audio: string | null;
|
||||
time: string;
|
||||
}
|
||||
|
||||
/** Whether an announcement is meant for this screen: every screen, or this one by its name. A muted screen hears none. */
|
||||
export function forThisScreen(a: Pick<Announcement, "screens">, name: string | null | undefined, muted = false): boolean {
|
||||
if (muted) return false;
|
||||
if (!Array.isArray(a.screens) || !a.screens.length) return true;
|
||||
const own = (name ?? "").trim().toLocaleLowerCase();
|
||||
return !!own && a.screens.some((s) => s.trim().toLocaleLowerCase() === own);
|
||||
}
|
||||
|
||||
/** Several views on one page (the panel and cards) hear the same announcement: only the first one shows and speaks it. */
|
||||
const claimed: Set<string> = ((globalThis as Record<string, unknown>).__nfAnnounced as Set<string> | undefined) ?? new Set<string>();
|
||||
(globalThis as Record<string, unknown>).__nfAnnounced = claimed;
|
||||
|
||||
export function claim(a: Pick<Announcement, "time" | "message">): boolean {
|
||||
const key = `${a.time}|${a.message}`;
|
||||
if (claimed.has(key)) return false;
|
||||
claimed.add(key);
|
||||
if (claimed.size > 50) claimed.delete(claimed.values().next().value as string);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** How long the message stays on screen: long enough to read it, at least 6 s, at most 30 s. */
|
||||
export const showFor = (message: string): number => Math.min(30_000, Math.max(6_000, message.split(/\s+/).length * 600 + 2_000));
|
||||
|
||||
/** A soft two-tone chime, made by the browser (no sound file). Resolves when it has played (or could not). */
|
||||
export function chime(): Promise<void> {
|
||||
try {
|
||||
const Ctx = (globalThis as { AudioContext?: typeof AudioContext; webkitAudioContext?: typeof AudioContext }).AudioContext ?? (globalThis as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
|
||||
if (!Ctx) return Promise.resolve();
|
||||
const ctx = new Ctx();
|
||||
const tone = (freq: number, start: number) => {
|
||||
const osc = ctx.createOscillator();
|
||||
const gain = ctx.createGain();
|
||||
osc.type = "sine";
|
||||
osc.frequency.value = freq;
|
||||
gain.gain.setValueAtTime(0.0001, ctx.currentTime + start);
|
||||
gain.gain.exponentialRampToValueAtTime(0.25, ctx.currentTime + start + 0.03);
|
||||
gain.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + start + 0.9);
|
||||
osc.connect(gain).connect(ctx.destination);
|
||||
osc.start(ctx.currentTime + start);
|
||||
osc.stop(ctx.currentTime + start + 1);
|
||||
};
|
||||
tone(880, 0);
|
||||
tone(660, 0.35);
|
||||
return new Promise((done) =>
|
||||
setTimeout(() => {
|
||||
void ctx.close().catch(() => undefined);
|
||||
done();
|
||||
}, 1400),
|
||||
);
|
||||
} catch {
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
/** Speak with the browser's own voice in the user's language (when Home Assistant gave no audio). */
|
||||
function speakInBrowser(hass: HomeAssistant, message: string): void {
|
||||
const synth = (globalThis as { speechSynthesis?: SpeechSynthesis }).speechSynthesis;
|
||||
const Utterance = (globalThis as { SpeechSynthesisUtterance?: typeof SpeechSynthesisUtterance }).SpeechSynthesisUtterance;
|
||||
if (!synth || !Utterance) return;
|
||||
const u = new Utterance(message);
|
||||
u.lang = hass.language || "en";
|
||||
synth.cancel();
|
||||
synth.speak(u);
|
||||
}
|
||||
|
||||
/** Chime, then the message: Home Assistant's audio when there is one, else the browser's voice. Browsers may block sound until the page was tapped once. */
|
||||
export async function playAnnouncement(hass: HomeAssistant, a: Announcement): Promise<void> {
|
||||
await chime();
|
||||
if (a.audio) {
|
||||
try {
|
||||
const url = a.audio.startsWith("/") && hass.hassUrl ? hass.hassUrl(a.audio) : a.audio;
|
||||
await new Audio(url).play();
|
||||
return;
|
||||
} catch {
|
||||
// blocked or failed: the browser's voice tries instead
|
||||
}
|
||||
}
|
||||
speakInBrowser(hass, a.message);
|
||||
}
|
||||
|
||||
/** Subscribes this screen to the announcements; resolves to the unsubscribe function (or a no-op with an older backend). */
|
||||
export function subscribeAnnouncements(hass: HomeAssistant, onAnnouncement: (a: Announcement) => void): Promise<() => void> {
|
||||
return hass.connection.subscribeMessage<Announcement>(onAnnouncement, { type: "nextfloor/announcements/subscribe" }).then(
|
||||
(stop) => () => void stop().catch(() => undefined),
|
||||
() => () => undefined,
|
||||
);
|
||||
}
|
||||
|
||||
const SPEAKER_DOMAINS = /^(media_player|assist_satellite)\./;
|
||||
|
||||
/** Every entity of an area, its own or its device's (NextFloor's area lists leave out what it does not draw, like voice satellites). */
|
||||
function inArea(hass: HomeAssistant, areaId: string | null | undefined): string[] {
|
||||
if (!areaId) return [];
|
||||
return Object.values(hass.entities ?? {})
|
||||
.filter((e) => !e.hidden && (e.area_id ?? (e.device_id ? hass.devices?.[e.device_id]?.area_id : null)) === areaId)
|
||||
.map((e) => e.entity_id);
|
||||
}
|
||||
|
||||
/** Whether a speaker may speak by itself: no TV, not off or gone (as announce.py decides it). */
|
||||
function usable(hass: HomeAssistant, id: string): boolean {
|
||||
const st = hass.states[id];
|
||||
if (!st || st.state === "unavailable") return false;
|
||||
if (id.startsWith("notify.")) return hass.entities?.[id]?.platform === "alexa_devices" && id.endsWith("_announce");
|
||||
if (st.state === "off" || st.state === "unknown") return false;
|
||||
return st.attributes.device_class !== "tv";
|
||||
}
|
||||
|
||||
/**
|
||||
* The speaker an announcement in the room goes to, picked as announce.py picks it: chosen in the plan, else placed in the
|
||||
* room, else a voice satellite, an Echo or a speaker of its area (sorted by id). Null: the room cannot speak.
|
||||
*/
|
||||
export function roomSpeaker(hass: HomeAssistant, floor: Floor | null, room: Room): string | null {
|
||||
if (room.announce_speaker === "none") return null;
|
||||
if (room.announce_speaker) return room.announce_speaker;
|
||||
if (floor && room.points.length >= 3) {
|
||||
const placed = [
|
||||
...floor.placements.filter((p) => SPEAKER_DOMAINS.test(p.entity_id)).map((p) => ({ id: p.entity_id, x: p.x, z: p.z })),
|
||||
...floor.furniture.filter((f) => f.entity && SPEAKER_DOMAINS.test(f.entity)).map((f) => ({ id: f.entity!, x: f.x, z: f.z })),
|
||||
];
|
||||
const inside = placed.find((p) => pointInPolygon([p.x, p.z], room.points) && usable(hass, p.id));
|
||||
if (inside) return inside.id;
|
||||
}
|
||||
const area = inArea(hass, room.area_id);
|
||||
for (const domain of ["assist_satellite.", "notify.", "media_player."]) {
|
||||
const found = area.filter((id) => id.startsWith(domain) && usable(hass, id)).sort()[0];
|
||||
if (found) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Whether the room panel offers announcements for the room. */
|
||||
export const roomHasSpeaker = (hass: HomeAssistant, floor: Floor | null, room: Room): boolean => roomSpeaker(hass, floor, room) !== null;
|
||||
|
||||
/** Whether Home Assistant offers the action (NextFloor is set up and its backend knows announcements). */
|
||||
export const canAnnounce = (hass: HomeAssistant | undefined): boolean => !!hass?.services?.nextfloor?.announce;
|
||||
@@ -0,0 +1,19 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, entity, floorWith, hassOf, opening } from "../entities/fixtures.ts";
|
||||
import { emptyBuilding } from "../model.ts";
|
||||
import { batteryOf, planBatteries } from "./batteries.ts";
|
||||
|
||||
test("a device's battery comes from the battery sensor next to it, else from the entity's attribute", () => {
|
||||
const hass = hassOf(
|
||||
[entity("binary_sensor.window", "off"), entity("sensor.window_battery", "12", { device_class: "battery" }), entity("lock.door", "locked", { battery_level: 64 }), entity("light.ceiling", "on")],
|
||||
{ "binary_sensor.window": { device_id: "w" }, "sensor.window_battery": { device_id: "w" } },
|
||||
);
|
||||
assert.equal(batteryOf(hass, "binary_sensor.window"), 12);
|
||||
assert.equal(batteryOf(hass, "lock.door"), 64);
|
||||
assert.equal(batteryOf(hass, "light.ceiling"), null);
|
||||
const room = box("k", 0, 0, 4, 4);
|
||||
const floor = { ...floorWith([room]), openings: [opening("o", "k", "window", { contact: "binary_sensor.window" }), opening("d", "k", "door", { lock: "lock.door" })], placements: [{ entity_id: "light.ceiling", x: 1, z: 1, y: null, mount: null }] };
|
||||
const list = planBatteries(hass, { ...emptyBuilding(), floors: [floor] });
|
||||
assert.deepEqual(list.map((b) => [b.entity, b.level, b.roomId]), [["binary_sensor.window", 12, "k"], ["lock.door", 64, "k"]]);
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
// Low batteries: the battery level of the devices the plan links – device pins, the sensors of doors and windows, linked furniture –
|
||||
// from a battery sensor on the same device or the entity's own battery attribute, each device once.
|
||||
|
||||
import { pointInPolygon, type Building, type Floor, type Room } from "../model.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
|
||||
/** Below this level (%) a battery counts as low. */
|
||||
export const LOW_BATTERY = 20;
|
||||
|
||||
export interface BatteryLevel {
|
||||
/** The entity of the plan the battery belongs to (its name is shown). */
|
||||
entity: string;
|
||||
level: number;
|
||||
floorId: string;
|
||||
roomId: string | null;
|
||||
}
|
||||
|
||||
/** Battery sensors by device, worked out once per registry (the registry object changes when entities do). */
|
||||
const batteryIndex = new WeakMap<object, Map<string, string>>();
|
||||
function batterySensors(hass: HomeAssistant): Map<string, string> {
|
||||
const registry = hass.entities ?? {};
|
||||
let index = batteryIndex.get(registry);
|
||||
if (!index) {
|
||||
index = new Map();
|
||||
for (const [id, entry] of Object.entries(registry)) {
|
||||
if (entry.device_id && id.startsWith("sensor.") && hass.states[id]?.attributes.device_class === "battery" && !index.has(entry.device_id)) index.set(entry.device_id, id);
|
||||
}
|
||||
batteryIndex.set(registry, index);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
/** The battery level of an entity's device (a battery sensor next to it), else its own battery attribute; null when it has none. */
|
||||
export function batteryOf(hass: HomeAssistant, entityId: string): number | null {
|
||||
const device = hass.entities?.[entityId]?.device_id;
|
||||
const sensor = device ? batterySensors(hass).get(device) : undefined;
|
||||
if (sensor) {
|
||||
const v = Number(hass.states[sensor]?.state);
|
||||
if (Number.isFinite(v)) return v;
|
||||
}
|
||||
const attr = hass.states[entityId]?.attributes;
|
||||
if (!attr || (attr.battery_level === undefined && attr.battery === undefined)) return null;
|
||||
const v = Number(attr.battery_level ?? attr.battery);
|
||||
return Number.isFinite(v) ? v : null;
|
||||
}
|
||||
|
||||
/** Every entity of a floor the plan links, with where it is. */
|
||||
function linkedEntities(floor: Floor): { entity: string; x: number; z: number; room: string | null }[] {
|
||||
const out: { entity: string; x: number; z: number; room: string | null }[] = [];
|
||||
const looks = (v: unknown): v is string => typeof v === "string" && /^[a-z_]+\.[a-z0-9_]+$/.test(v);
|
||||
for (const p of floor.placements) out.push({ entity: p.entity_id, x: p.x, z: p.z, room: null });
|
||||
for (const m of floor.furniture) for (const v of [m.entity, m.power]) if (looks(v)) out.push({ entity: v, x: m.x, z: m.z, room: null });
|
||||
for (const o of floor.openings) for (const v of [o.contact, o.contact2, o.tilt, o.tilt2, o.cover, o.cover2, o.lock]) if (looks(v)) out.push({ entity: v, x: NaN, z: NaN, room: o.room_id });
|
||||
return out;
|
||||
}
|
||||
|
||||
const roomAt = (floor: Floor, x: number, z: number): Room | undefined => floor.rooms.find((r) => r.points.length >= 3 && pointInPolygon([x, z], r.points));
|
||||
|
||||
/** The batteries of the plan's devices, lowest first; each device counted once. */
|
||||
export function planBatteries(hass: HomeAssistant, building: Building): BatteryLevel[] {
|
||||
const seen = new Set<string>();
|
||||
const out: BatteryLevel[] = [];
|
||||
for (const floor of building.floors) {
|
||||
for (const link of linkedEntities(floor)) {
|
||||
const key = hass.entities?.[link.entity]?.device_id ?? link.entity;
|
||||
if (seen.has(key)) continue;
|
||||
const level = batteryOf(hass, link.entity);
|
||||
if (level === null) continue;
|
||||
seen.add(key);
|
||||
out.push({ entity: link.entity, level, floorId: floor.id, roomId: link.room ?? roomAt(floor, link.x, link.z)?.id ?? null });
|
||||
}
|
||||
}
|
||||
return out.sort((a, b) => a.level - b.level);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity, hassOf } from "../entities/fixtures.ts";
|
||||
import { departureText, kmBetween, readCar } from "./car.ts";
|
||||
|
||||
test("a departure time from the ways cars and helpers write it", () => {
|
||||
assert.equal(departureText(entity("input_datetime.go", "7:30:00")), "07:30");
|
||||
assert.equal(departureText(entity("sensor.dep", "450")), "07:30", "minutes after midnight");
|
||||
assert.equal(departureText(entity("sensor.dep", new Date(2026, 10, 3, 6, 45).toISOString())), "06:45");
|
||||
assert.equal(departureText(entity("sensor.dep", "unknown")), null);
|
||||
});
|
||||
|
||||
test("away, the car tells how far it is and which parts stand open", () => {
|
||||
assert.ok(Math.abs(kmBetween(50.11, 8.68, 50.04, 8.56) - 11.6) < 0.5, "Frankfurt to its airport");
|
||||
const reg = { device_id: "car" };
|
||||
const hass = hassOf(
|
||||
[
|
||||
entity("device_tracker.tesla", "not_home", { latitude: 50.04, longitude: 8.56, friendly_name: "Tesla Location" }),
|
||||
entity("sensor.tesla_battery", "64", { unit_of_measurement: "%", device_class: "battery", friendly_name: "Tesla Battery" }),
|
||||
entity("binary_sensor.tesla_trunk", "on", { friendly_name: "Tesla Trunk" }),
|
||||
entity("binary_sensor.tesla_door_fl", "off", { device_class: "door", friendly_name: "Tesla Door" }),
|
||||
entity("zone.home", "0", { latitude: 50.11, longitude: 8.68 }),
|
||||
],
|
||||
{ "device_tracker.tesla": reg, "sensor.tesla_battery": reg, "binary_sensor.tesla_trunk": reg, "binary_sensor.tesla_door_fl": reg },
|
||||
);
|
||||
const car = readCar(hass, { entity: "device_tracker.tesla", car: null })!;
|
||||
assert.equal(car.home, false);
|
||||
assert.ok(car.distance !== null && Math.abs(car.distance - 11.6) < 0.5);
|
||||
assert.deepEqual(car.open, ["Trunk"]);
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* NextFloor's car: what a parking spot's car reports, found by itself among the entities of the car's device.
|
||||
*
|
||||
* The spot names the car through its presence entity (a device_tracker, a binary sensor …) or through the links set
|
||||
* in the editor (`car` on the spot). Everything else is looked for on the same device: the charge level (a battery
|
||||
* sensor), the range (a distance sensor), the charging power, whether it charges and is plugged in, the lock, the
|
||||
* climate and the charge switch. Works with TeslaMate (MQTT), Tesla Fleet, and the car integrations that put their
|
||||
* entities on one device (VW, BMW, Hyundai/Kia, Renault, Polestar …).
|
||||
*/
|
||||
import type { Furniture } from "../model.ts";
|
||||
import type { HassEntity, HomeAssistant } from "../types.ts";
|
||||
|
||||
export interface CarInfo {
|
||||
/** The car is in its spot (else it is on the road). */
|
||||
home: boolean;
|
||||
soc: number | null;
|
||||
range: number | null;
|
||||
rangeUnit: string;
|
||||
/** Charging power in W (null: unknown). */
|
||||
chargingW: number | null;
|
||||
charging: boolean;
|
||||
plugged: boolean | null;
|
||||
locked: boolean | null;
|
||||
climateOn: boolean | null;
|
||||
/** Inside temperature (°C) when the car reports it. */
|
||||
inside: number | null;
|
||||
/** Where it is when it is away: the zone or the tracker's text. */
|
||||
where: string | null;
|
||||
/** Away: how far it is from home (km, as the crow flies), from the tracker's position. */
|
||||
distance: number | null;
|
||||
/** Doors, hatches, windows and the charge port that stand open (their names). */
|
||||
open: string[];
|
||||
/** The planned departure ("07:30"), from a departure time the car or a helper reports. */
|
||||
departure: string | null;
|
||||
entities: { lock: string | null; climate: string | null; charge: string | null; tracker: string | null };
|
||||
}
|
||||
|
||||
const ref = (v: string | null | undefined) => (v && v !== "none" ? v : null);
|
||||
const num = (st: HassEntity | undefined) => {
|
||||
const n = Number(st?.state);
|
||||
return st && Number.isFinite(n) ? n : null;
|
||||
};
|
||||
const attr = (st: HassEntity | undefined, k: string) => st?.attributes?.[k];
|
||||
const word = (id: string, ...parts: string[]) => parts.some((p) => id.includes(p));
|
||||
|
||||
/** All entities on the device of `entity` (the entity itself included). */
|
||||
function siblings(hass: HomeAssistant, entity: string | null): string[] {
|
||||
if (!entity) return [];
|
||||
const device = hass.entities?.[entity]?.device_id;
|
||||
if (!device) return [entity];
|
||||
return Object.values(hass.entities ?? {})
|
||||
.filter((e) => e.device_id === device && !e.hidden)
|
||||
.map((e) => e.entity_id)
|
||||
.filter((id) => hass.states[id]);
|
||||
}
|
||||
|
||||
/** The first entity that matches, preferring one set by hand. */
|
||||
function pick(hass: HomeAssistant, set: string | null, list: string[], match: (id: string, st: HassEntity) => boolean): string | null {
|
||||
if (set && hass.states[set]) return set;
|
||||
return list.find((id) => match(id, hass.states[id])) ?? null;
|
||||
}
|
||||
|
||||
/** Distance between two points on the earth in km (haversine). */
|
||||
export function kmBetween(lat1: number, lon1: number, lat2: number, lon2: number): number {
|
||||
const r = Math.PI / 180;
|
||||
const a = Math.sin(((lat2 - lat1) * r) / 2) ** 2 + Math.cos(lat1 * r) * Math.cos(lat2 * r) * Math.sin(((lon2 - lon1) * r) / 2) ** 2;
|
||||
return 12742 * Math.asin(Math.min(1, Math.sqrt(a)));
|
||||
}
|
||||
|
||||
/** "07:30" from a departure entity: a time ("07:30:00"), a date-time or timestamp (today's or tomorrow's), or minutes after midnight. */
|
||||
export function departureText(st: HassEntity | undefined): string | null {
|
||||
if (!st || ["unknown", "unavailable", "", "none", "off"].includes(String(st.state).toLowerCase())) return null;
|
||||
const s = String(st.state);
|
||||
let m = /^(\d{1,2}):(\d{2})/.exec(s);
|
||||
if (m) return `${m[1].padStart(2, "0")}:${m[2]}`;
|
||||
const t = Date.parse(s);
|
||||
if (Number.isFinite(t) && /\d{4}-\d{2}-\d{2}/.test(s)) {
|
||||
const d = new Date(t);
|
||||
return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
|
||||
}
|
||||
m = /^(\d{1,4})$/.exec(s);
|
||||
if (m && Number(m[1]) < 1440) return `${String(Math.floor(Number(m[1]) / 60)).padStart(2, "0")}:${String(Number(m[1]) % 60).padStart(2, "0")}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function readCar(hass: HomeAssistant, spot: Pick<Furniture, "entity" | "car">): CarInfo | null {
|
||||
const links = spot.car ?? {};
|
||||
const anchor = ref(links.device) ?? ref(links.tracker) ?? ref(spot.entity);
|
||||
const all = siblings(hass, anchor);
|
||||
if (!all.length && !ref(links.soc)) return null;
|
||||
const domain = (id: string) => id.split(".")[0];
|
||||
const dc = (st: HassEntity) => String(attr(st, "device_class") ?? "");
|
||||
const unit = (st: HassEntity) => String(attr(st, "unit_of_measurement") ?? "");
|
||||
|
||||
const socId = pick(hass, ref(links.soc), all, (id, st) => domain(id) === "sensor" && unit(st) === "%" && (dc(st) === "battery" || word(id, "battery_level", "soc", "state_of_charge", "ladezustand")) && !word(id, "usable"));
|
||||
const rangeId = pick(hass, ref(links.range), all, (id, st) => domain(id) === "sensor" && (dc(st) === "distance" || word(id, "range", "reichweite")) && !word(id, "odometer", "ideal", "elevation", "kilometerstand"));
|
||||
const powerId = pick(hass, null, all, (id, st) => domain(id) === "sensor" && dc(st) === "power" && word(id, "charg", "lade"));
|
||||
const chargingSet = ref(links.charging);
|
||||
const chargingBin = pick(hass, chargingSet && domain(chargingSet) === "binary_sensor" ? chargingSet : null, all, (id, st) => domain(id) === "binary_sensor" && (dc(st) === "battery_charging" || word(id, "charging", "charger", "laden")));
|
||||
const pluggedId = pick(hass, ref(links.plugged), all, (id, st) => domain(id) === "binary_sensor" && (dc(st) === "plug" || word(id, "plug", "cable", "kabel")));
|
||||
const lockId = pick(hass, ref(links.lock), all, (id) => domain(id) === "lock");
|
||||
const climateId = pick(hass, ref(links.climate), all, (id) => domain(id) === "climate");
|
||||
const chargeSwitch = pick(hass, chargingSet && /^(switch|input_boolean)\./.test(chargingSet) ? chargingSet : null, all, (id) => domain(id) === "switch" && word(id, "charg", "laden") && !word(id, "port", "klappe"));
|
||||
const trackerId = pick(hass, ref(links.tracker), all, (id) => domain(id) === "device_tracker") ?? (ref(spot.entity)?.startsWith("device_tracker.") ? ref(spot.entity) : null);
|
||||
const insideId = pick(hass, null, all, (id, st) => domain(id) === "sensor" && dc(st) === "temperature" && word(id, "inside", "innen", "interior", "cabin"));
|
||||
const departureId = pick(hass, ref(links.departure), all, (id) => /^(sensor|input_datetime|time|datetime)$/.test(domain(id)) && word(id, "departure", "abfahrt", "depart"));
|
||||
// doors, trunk, frunk, windows and the charge port: binary sensors of the car that report open
|
||||
const opened = all.filter((id) => {
|
||||
const s = hass.states[id];
|
||||
return domain(id) === "binary_sensor" && s?.state === "on" && (["door", "opening", "window", "garage_door"].includes(dc(s)) || word(id, "trunk", "frunk", "kofferraum", "tailgate", "hatch", "klappe", "charge_port", "ladeklappe"));
|
||||
});
|
||||
|
||||
const st = (id: string | null) => (id ? hass.states[id] : undefined);
|
||||
const soc = num(st(socId));
|
||||
const rangeSt = st(rangeId);
|
||||
// charging power: a power sensor (W or kW), else a "charging" sensor that reports power
|
||||
let chargingW: number | null = null;
|
||||
const p = st(powerId) ?? (chargingSet && domain(chargingSet) === "sensor" ? st(chargingSet) : undefined);
|
||||
if (p) {
|
||||
const v = num(p);
|
||||
if (v !== null) chargingW = Math.max(0, unit(p).toLowerCase() === "kw" ? v * 1000 : v);
|
||||
}
|
||||
const chargingState = st(chargingBin)?.state ?? st(chargeSwitch)?.state;
|
||||
const charging = chargingState === "on" || (chargingW !== null && chargingW > 50);
|
||||
const pluggedState = st(pluggedId)?.state;
|
||||
const lockState = st(lockId)?.state;
|
||||
const climate = st(climateId);
|
||||
const tracker = st(trackerId);
|
||||
// home: the spot's presence entity says so (the car stands in the 3D spot); else the tracker
|
||||
const presence = st(ref(spot.entity));
|
||||
const home = presence ? ["on", "home", "true", "present", "occupied", "detected", "parked"].includes(presence.state.toLowerCase()) : tracker?.state === "home";
|
||||
const zone = tracker && tracker.state !== "home" && tracker.state !== "not_home" ? tracker.state : null;
|
||||
const zoneName = zone ? String(st(`zone.${zone}`)?.attributes.friendly_name ?? zone) : null;
|
||||
return {
|
||||
home,
|
||||
soc,
|
||||
range: num(rangeSt),
|
||||
rangeUnit: rangeSt ? unit(rangeSt) || "km" : "km",
|
||||
chargingW,
|
||||
charging,
|
||||
plugged: pluggedState === undefined ? null : pluggedState === "on",
|
||||
locked: lockState === undefined ? null : lockState === "locked",
|
||||
climateOn: climate ? climate.state !== "off" && climate.state !== "unavailable" : null,
|
||||
inside: num(st(insideId)),
|
||||
where: home ? null : zoneName,
|
||||
distance: home ? null : distanceHome(hass, tracker),
|
||||
open: opened.map((id) => carPartName(hass, id, all)),
|
||||
departure: departureText(st(departureId)),
|
||||
entities: { lock: lockId, climate: climateId, charge: chargeSwitch, tracker: trackerId },
|
||||
};
|
||||
}
|
||||
|
||||
/** How far a tracker is from home in km, or null without positions. */
|
||||
function distanceHome(hass: HomeAssistant, tracker: HassEntity | undefined): number | null {
|
||||
const home = hass.states["zone.home"]?.attributes;
|
||||
const lat = Number(tracker?.attributes?.latitude);
|
||||
const lon = Number(tracker?.attributes?.longitude);
|
||||
const hl = Number(home?.latitude ?? hass.config?.latitude);
|
||||
const ho = Number(home?.longitude ?? hass.config?.longitude);
|
||||
if (![lat, lon, hl, ho].every(Number.isFinite)) return null;
|
||||
return Math.round(kmBetween(lat, lon, hl, ho) * 10) / 10;
|
||||
}
|
||||
|
||||
/** The short name of a car's part (the car's name taken off: "Model 3 Trunk" → "Trunk"). */
|
||||
function carPartName(hass: HomeAssistant, id: string, all: string[]): string {
|
||||
const name = String(hass.states[id]?.attributes.friendly_name ?? id.split(".")[1]);
|
||||
const device = all.map((e) => String(hass.states[e]?.attributes.friendly_name ?? "")).reduce((common, n) => {
|
||||
let k = 0;
|
||||
while (k < common.length && k < n.length && common[k] === n[k]) k++;
|
||||
return common.slice(0, k);
|
||||
});
|
||||
const rest = name.slice(device.length).trim();
|
||||
return rest.length >= 2 ? rest : name;
|
||||
}
|
||||
|
||||
/** The charge level's colour: red when low, amber in the middle, green when well charged. */
|
||||
export function socColor(soc: number | null): string {
|
||||
if (soc === null) return "#8aa0c8";
|
||||
if (soc < 20) return "#f87171";
|
||||
if (soc < 50) return "#facc15";
|
||||
return "#4ade80";
|
||||
}
|
||||
@@ -0,0 +1,628 @@
|
||||
/**
|
||||
* NextFloor's floating glass cards: they hang over a point of the plan (the viewer reports where that point is
|
||||
* on screen after every frame, see setLiveAnchors) and tell what is going on there.
|
||||
*
|
||||
* - "house": the energy balance – sun, house, battery, grid – with the share of the house running on its own power
|
||||
* - "car": a parked car's charge, range and charging, with buttons for lock, climate and charging; away it tells where
|
||||
* - "media": what a speaker or TV plays – cover, title, artist – with play/pause, skip and the volume
|
||||
*
|
||||
* Cards are rendered by Lit; their position is set directly on the element by the 3D view (no render per frame).
|
||||
*/
|
||||
import { css, html, nothing, svg, type TemplateResult } from "lit";
|
||||
import type { EnergySummary } from "../energy.ts";
|
||||
import { socColor, type CarInfo } from "./car.ts";
|
||||
import type { MediaNow } from "./media.ts";
|
||||
import { formatNumber, translate } from "../i18n.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { curvePath } from "./day-curves.ts";
|
||||
import type { PrinterInfo } from "./printer.ts";
|
||||
import type { HeatPumpInfo } from "./heat-pump.ts";
|
||||
import type { PlanPoint } from "../viewer/live-energy.ts";
|
||||
|
||||
export interface HouseCard {
|
||||
kind: "house";
|
||||
at: PlanPoint;
|
||||
summary: EnergySummary;
|
||||
autarky: number | null;
|
||||
/** Solar and consumption over the last 24 hours (quarter hours), when the history could be loaded. */
|
||||
curves?: { solar: (number | null)[]; use: (number | null)[] };
|
||||
/** Solar and consumption per day over the last seven days (kWh), from the long-term statistics. */
|
||||
week?: { days: number[]; solar: (number | null)[]; use: (number | null)[] };
|
||||
/** Gas and water meters: their icon, name and what they read now. */
|
||||
meters?: { icon: string; label: string; value: string }[];
|
||||
}
|
||||
|
||||
export interface CarCard {
|
||||
kind: "car";
|
||||
at: PlanPoint;
|
||||
spot: string;
|
||||
name: string;
|
||||
car: CarInfo;
|
||||
}
|
||||
|
||||
export interface MediaCard {
|
||||
kind: "media";
|
||||
at: PlanPoint;
|
||||
media: MediaNow;
|
||||
}
|
||||
|
||||
export interface PrinterCard {
|
||||
kind: "printer";
|
||||
at: PlanPoint;
|
||||
name: string;
|
||||
printer: PrinterInfo;
|
||||
}
|
||||
|
||||
export interface HeatPumpCard {
|
||||
kind: "heatpump";
|
||||
at: PlanPoint;
|
||||
name: string;
|
||||
pump: HeatPumpInfo;
|
||||
}
|
||||
|
||||
export type LiveCard = HouseCard | CarCard | MediaCard | PrinterCard | HeatPumpCard;
|
||||
|
||||
/** A button on a card was pressed: the 3D view calls the service (with extra data such as the volume). */
|
||||
export type LiveCardAction = (domain: string, service: string, entity: string, data?: Record<string, unknown>) => void;
|
||||
|
||||
function watts(hass: HomeAssistant | undefined, w: number): string {
|
||||
const a = Math.abs(w);
|
||||
return a >= 1000 ? `${formatNumber(hass, a / 1000, a >= 10000 ? 1 : 2)} kW` : `${Math.round(a)} W`;
|
||||
}
|
||||
|
||||
/** A ring that fills with a share (0…1). */
|
||||
function ring(share: number, color: string): TemplateResult {
|
||||
const r = 22;
|
||||
const c = 2 * Math.PI * r;
|
||||
return html`<svg class="live-ring" viewBox="0 0 54 54" aria-hidden="true">
|
||||
${svg`<circle cx="27" cy="27" r=${r} class="live-ring-bg"></circle>
|
||||
<circle cx="27" cy="27" r=${r} stroke=${color} stroke-dasharray=${`${(c * Math.max(0, Math.min(1, share))).toFixed(1)} ${c.toFixed(1)}`} transform="rotate(-90 27 27)" class="live-ring-fg"></circle>`}
|
||||
</svg>`;
|
||||
}
|
||||
|
||||
/** The house card's fold: a small corner button shrinks it to its ring and the sun's power, on desktop and phones. */
|
||||
export interface LiveCardFold {
|
||||
folded: boolean;
|
||||
toggle: () => void;
|
||||
}
|
||||
|
||||
function houseCard(hass: HomeAssistant | undefined, c: HouseCard, i: number, fold?: LiveCardFold): TemplateResult {
|
||||
const s = c.summary;
|
||||
const t = (k: Parameters<typeof translate>[1]) => translate(hass, k);
|
||||
const own = c.autarky;
|
||||
const foldBtn = fold
|
||||
? html`<button class="live-fold" title=${t(fold.folded ? "live_unfold" : "live_fold")} aria-label=${t(fold.folded ? "live_unfold" : "live_fold")} aria-expanded=${!fold.folded} @click=${fold.toggle}>${fold.folded ? "+" : "−"}</button>`
|
||||
: nothing;
|
||||
if (fold?.folded) {
|
||||
const sun = s.solar !== null ? `☀ ${watts(hass, s.solar)}` : s.consumption !== null ? `⌂ ${watts(hass, s.consumption)}` : null;
|
||||
return html`<div class="live-card live-card-house live-folded" data-i=${i}>
|
||||
${own !== null
|
||||
? html`<div class="live-own">${ring(own, own > 0.95 ? "#4ade80" : own > 0.6 ? "#facc15" : "#f87171")}<div class="live-own-text"><b>${Math.round(own * 100)}%</b></div></div>`
|
||||
: nothing}
|
||||
${sun ? html`<b>${sun}</b>` : own === null ? html`<b>⌂</b>` : nothing}
|
||||
${foldBtn}
|
||||
</div>`;
|
||||
}
|
||||
const rows: TemplateResult[] = [];
|
||||
if (s.solar !== null) rows.push(html`<div class="live-row live-solar"><span>☀ ${t("energy_solar")}</span><b>${watts(hass, s.solar)}</b></div>`);
|
||||
if (s.consumption !== null) rows.push(html`<div class="live-row live-house"><span>⌂ ${t("energy_consumption")}</span><b>${watts(hass, s.consumption)}</b></div>`);
|
||||
if (s.rest !== undefined && s.rest !== null) rows.push(html`<div class="live-row live-house"><span>⌂ ${t("energy_rest")}</span><b>${watts(hass, s.rest)}</b></div>`);
|
||||
if (s.battery !== null || s.soc !== null) {
|
||||
const dir = s.battery === null || Math.abs(s.battery) < 15 ? "" : s.battery > 0 ? " ↓" : " ↑";
|
||||
rows.push(
|
||||
html`<div class="live-row live-battery"><span>▮ ${t("energy_battery")}${dir}</span><b>${s.soc !== null ? `${Math.round(s.soc)} %` : ""}${s.battery !== null && Math.abs(s.battery) >= 15 ? ` · ${watts(hass, s.battery)}` : ""}</b></div>`,
|
||||
);
|
||||
}
|
||||
if (s.grid !== null) {
|
||||
const exporting = s.grid < -15;
|
||||
rows.push(html`<div class="live-row ${exporting ? "live-export" : "live-import"}"><span>⇄ ${t(exporting ? "energy_grid_export" : "energy_grid_import")}</span><b>${watts(hass, s.grid)}</b></div>`);
|
||||
}
|
||||
for (const m of c.meters ?? []) rows.push(html`<div class="live-row live-meter"><span>${m.icon} ${m.label}</span><b>${m.value}</b></div>`);
|
||||
return html`<div class="live-card live-card-house" data-i=${i}>
|
||||
${foldBtn}
|
||||
${own !== null
|
||||
? html`<div class="live-own">${ring(own, own > 0.95 ? "#4ade80" : own > 0.6 ? "#facc15" : "#f87171")}<div class="live-own-text"><b>${Math.round(own * 100)} %</b><span>${t("live_autarky")}</span></div></div>`
|
||||
: nothing}
|
||||
<div class="live-rows">${rows}</div>
|
||||
${dayChart(hass, c.curves)} ${weekChart(hass, c.week)}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** The last seven days: a bar per day for solar (filled) and consumption (outlined), in kWh. */
|
||||
function weekChart(hass: HomeAssistant | undefined, week: HouseCard["week"]): TemplateResult | typeof nothing {
|
||||
if (!week) return nothing;
|
||||
const values = [...week.solar, ...week.use].filter((v): v is number => v !== null && v > 0);
|
||||
if (!values.length) return nothing;
|
||||
const top = Math.max(...values) * 1.1 || 1;
|
||||
const [w, h] = [150, 30];
|
||||
const slot = w / 7;
|
||||
const bar = (v: number | null, x: number, cls: string) => (v === null || v <= 0 ? nothing : svg`<rect x=${x.toFixed(1)} y=${(h - (v / top) * h).toFixed(1)} width=${(slot * 0.36).toFixed(1)} height=${((v / top) * h).toFixed(1)} class=${cls}></rect>`);
|
||||
const total = (list: (number | null)[]) => list.reduce<number>((a, b) => a + (b ?? 0), 0);
|
||||
return html`<div class="live-day live-week" title=${translate(hass, "live_week_hint", { solar: formatNumber(hass, total(week.solar), 0), use: formatNumber(hass, total(week.use), 0) })}>
|
||||
<svg viewBox=${`0 0 ${w} ${h}`} preserveAspectRatio="none" aria-hidden="true">
|
||||
${week.days.map((_, k) => svg`${bar(week.solar[k], k * slot + slot * 0.1, "live-week-solar")}${bar(week.use[k], k * slot + slot * 0.5, "live-week-use")}`)}
|
||||
</svg>
|
||||
<span>7 ${translate(hass, "live_days")}</span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** The day at a glance: solar as a filled curve, consumption as a line, over the last 24 hours. */
|
||||
function dayChart(hass: HomeAssistant | undefined, curves: HouseCard["curves"]): TemplateResult | typeof nothing {
|
||||
if (!curves) return nothing;
|
||||
const values = [...curves.solar, ...curves.use].filter((v): v is number => v !== null);
|
||||
if (values.length < 4) return nothing;
|
||||
const top = Math.max(...values) * 1.08 || 1;
|
||||
const [w, h] = [150, 34];
|
||||
const solar = curvePath(curves.solar, w, h, top);
|
||||
const use = curvePath(curves.use, w, h, top);
|
||||
return html`<div class="live-day" title=${translate(hass, "live_day_hint")}>
|
||||
<svg viewBox=${`0 0 ${w} ${h}`} preserveAspectRatio="none" aria-hidden="true">
|
||||
${solar ? svg`<path d=${`${solar}L${w},${h}L0,${h}Z`} class="live-day-solar"></path>` : nothing}
|
||||
${use ? svg`<path d=${use} class="live-day-use"></path>` : nothing}
|
||||
</svg>
|
||||
<span>24 h</span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function carCard(hass: HomeAssistant | undefined, c: CarCard, i: number, act: LiveCardAction): TemplateResult {
|
||||
const car = c.car;
|
||||
const t = (k: Parameters<typeof translate>[1], v?: Record<string, string | number>) => translate(hass, k, v);
|
||||
const color = socColor(car.soc);
|
||||
const status = !car.home
|
||||
? `${t("live_car_away")}${car.where ? ` · ${car.where}` : ""}${car.distance !== null ? ` · ${formatNumber(hass, car.distance, car.distance < 10 ? 1 : 0)} km` : ""}`
|
||||
: car.charging
|
||||
? `⚡ ${t("live_car_charging")}${car.chargingW ? ` · ${watts(hass, car.chargingW)}` : ""}`
|
||||
: car.plugged
|
||||
? `🔌 ${t("live_car_plugged")}`
|
||||
: "";
|
||||
const e = car.entities;
|
||||
const button = (on: boolean | null, label: string, icon: string, run: () => void) =>
|
||||
html`<button class="live-btn ${on ? "live-on" : ""}" title=${label} aria-label=${label} aria-pressed=${on ?? false} @click=${(ev: Event) => (ev.stopPropagation(), run())}>${icon}</button>`;
|
||||
return html`<div class="live-card live-card-car ${car.charging ? "live-charging" : ""} ${car.home ? "" : "live-away"}" data-i=${i} style=${`--live-soc:${color}`}>
|
||||
<div class="live-own">
|
||||
${ring((car.soc ?? 0) / 100, color)}
|
||||
<div class="live-own-text"><b>${car.soc !== null ? `${Math.round(car.soc)} %` : "–"}</b><span>${car.range !== null ? `${Math.round(car.range)} ${car.rangeUnit}` : ""}</span></div>
|
||||
</div>
|
||||
<div class="live-rows">
|
||||
<div class="live-title">${c.name}</div>
|
||||
${status ? html`<div class="live-status">${status}</div>` : nothing}
|
||||
${car.inside !== null ? html`<div class="live-status">🌡 ${formatNumber(hass, car.inside, 1)} °C</div>` : nothing}
|
||||
${car.departure ? html`<div class="live-status">⏰ ${t("live_car_departure", { time: car.departure })}</div>` : nothing}
|
||||
${car.open.length ? html`<div class="live-status live-warn">⚠ ${t("live_car_open", { parts: car.open.join(", ") })}</div>` : nothing}
|
||||
<div class="live-actions">
|
||||
${e.lock
|
||||
? button(car.locked, t(car.locked ? "live_car_unlock" : "live_car_lock"), car.locked ? "🔒" : "🔓", () => {
|
||||
if (car.locked && !confirm(t("live_car_unlock_confirm", { name: c.name }))) return;
|
||||
act("lock", car.locked ? "unlock" : "lock", e.lock!);
|
||||
})
|
||||
: nothing}
|
||||
${e.climate ? button(car.climateOn, t("live_car_climate"), "❄", () => act(e.climate!.split(".")[0], car.climateOn ? "turn_off" : "turn_on", e.climate!)) : nothing}
|
||||
${e.charge && car.home ? button(car.charging, t("live_car_charge"), "⚡", () => act(e.charge!.split(".")[0], "toggle", e.charge!)) : nothing}
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function mediaCard(hass: HomeAssistant | undefined, c: MediaCard, i: number, act: LiveCardAction): TemplateResult {
|
||||
const m = c.media;
|
||||
const t = (k: Parameters<typeof translate>[1]) => translate(hass, k);
|
||||
const color = `rgb(${m.color.join(",")})`;
|
||||
const btn = (label: string, icon: string, service: string) =>
|
||||
html`<button class="live-btn" title=${label} aria-label=${label} @click=${(ev: Event) => (ev.stopPropagation(), act("media_player", service, m.entity))}>${icon}</button>`;
|
||||
// compact (cover and title); a tap opens the controls
|
||||
return html`<div class="live-card live-card-media" data-i=${i} style=${`--live-soc:${color}`} @click=${(ev: Event) => (ev.currentTarget as HTMLElement).classList.toggle("live-open")}>
|
||||
${m.picture ? html`<img class="live-cover" src=${m.picture} alt="" loading="lazy" />` : html`<div class="live-cover live-cover-none">♪</div>`}
|
||||
<div class="live-rows">
|
||||
<div class="live-title" title=${m.title}>${m.title || m.name}</div>
|
||||
<div class="live-status">${m.artist || m.app || m.name}</div>
|
||||
<div class="live-actions">
|
||||
${btn(t("live_media_prev"), "⏮", "media_previous_track")} ${btn(t("live_media_playpause"), "⏯", "media_play_pause")} ${btn(t("live_media_next"), "⏭", "media_next_track")}
|
||||
${m.volume !== null
|
||||
? html`<input
|
||||
class="live-volume"
|
||||
type="range"
|
||||
min="0"
|
||||
max="100"
|
||||
.value=${String(Math.round(m.volume * 100))}
|
||||
aria-label=${t("live_media_volume")}
|
||||
@click=${(ev: Event) => ev.stopPropagation()}
|
||||
@change=${(ev: Event) => act("media_player", "volume_set", m.entity, { volume_level: Number((ev.target as HTMLInputElement).value) / 100 })}
|
||||
/>`
|
||||
: nothing}
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the cards from covering each other: after they were placed for a frame, a card that overlaps one placed
|
||||
* before it (lower on screen first) moves up above it. Its thread to the anchor stretches.
|
||||
*/
|
||||
export function unstackLhCards(root: ParentNode): void {
|
||||
const cards = [...root.querySelectorAll<HTMLElement>(".live-card")].filter((el) => el.style.visibility !== "hidden");
|
||||
const placed: { x0: number; x1: number; y0: number; y1: number }[] = [];
|
||||
// a card near the edge slides back into the view (on a phone it was cut off); its thread still points home
|
||||
const width = cards[0]?.parentElement?.clientWidth ?? 0;
|
||||
const items = cards
|
||||
.map((el) => {
|
||||
const [anchor, w] = [Number(el.dataset.x), el.offsetWidth];
|
||||
const x = !width ? anchor : width > w + 16 ? Math.min(Math.max(anchor, w / 2 + 8), width - w / 2 - 8) : width / 2;
|
||||
el.style.setProperty("--live-dx", `${Math.round(anchor - x)}px`);
|
||||
return { el, x, y: Number(el.dataset.y), w, h: el.offsetHeight };
|
||||
})
|
||||
.sort((a, b) => b.y - a.y);
|
||||
for (const it of items) {
|
||||
let bottom = it.y;
|
||||
for (let guard = 0; guard < 12; guard++) {
|
||||
const r = { x0: it.x - it.w / 2, x1: it.x + it.w / 2, y0: bottom - it.h, y1: bottom };
|
||||
const hit = placed.find((p) => r.x0 < p.x1 + 6 && r.x1 > p.x0 - 6 && r.y0 < p.y1 + 6 && r.y1 > p.y0 - 6);
|
||||
if (!hit) break;
|
||||
bottom = hit.y0 - 8;
|
||||
}
|
||||
placed.push({ x0: it.x - it.w / 2, x1: it.x + it.w / 2, y0: bottom - it.h, y1: bottom });
|
||||
const lift = it.y - bottom;
|
||||
it.el.style.transform = `translate(${Math.round(it.x)}px, ${Math.round(bottom)}px) translate(-50%, -100%)`;
|
||||
it.el.style.setProperty("--live-thread", `${Math.round(18 + lift)}px`);
|
||||
}
|
||||
}
|
||||
|
||||
/** A 3D printer's print: the model's picture, progress, when it is done, the layer, temperatures and the filaments. */
|
||||
function printerCard(hass: HomeAssistant | undefined, c: PrinterCard, i: number): TemplateResult {
|
||||
const p = c.printer;
|
||||
const t = (k: Parameters<typeof translate>[1], v?: Record<string, string | number>) => translate(hass, k, v);
|
||||
const pct = p.progress ?? 0;
|
||||
const clock = (ms: number) => new Intl.DateTimeFormat(hass?.language ?? navigator.language, { hour: "2-digit", minute: "2-digit" }).format(new Date(ms));
|
||||
const left = p.remaining !== null ? (p.remaining >= 60 ? `${Math.floor(p.remaining / 60)} h ${Math.round(p.remaining % 60)} min` : `${Math.round(p.remaining)} min`) : null;
|
||||
const temps = [p.nozzle !== null ? `${t("printer_nozzle")} ${Math.round(p.nozzle)}°` : null, p.bed !== null ? `${t("printer_bed")} ${Math.round(p.bed)}°` : null].filter(Boolean).join(" · ");
|
||||
return html`<div class="live-card live-card-printer ${p.printing ? "live-charging" : ""}" data-i=${i}>
|
||||
<div class="live-own">
|
||||
${p.picture ? html`<img class="live-print-pic" src=${p.picture} alt="" />` : ring(pct / 100, p.printing ? "#38bdf8" : "#8aa0c8")}
|
||||
<div class="live-own-text"><b>${p.progress !== null ? `${Math.round(pct)} %` : "–"}</b><span>${t(`printer_${p.printing ? "printing" : /finish|complete|fertig/.test(p.status) ? "done" : /pause/.test(p.status) ? "paused" : /error|fail/.test(p.status) ? "error" : "idle"}`)}</span></div>
|
||||
</div>
|
||||
<div class="live-rows">
|
||||
<div class="live-title">${c.name}</div>
|
||||
${p.job ? html`<div class="live-status">${p.job}</div>` : nothing}
|
||||
${p.printing && (p.endsAt || left) ? html`<div class="live-status">⏱ ${[left, p.endsAt ? t("printer_done_at", { time: clock(p.endsAt) }) : null].filter(Boolean).join(" · ")}</div>` : nothing}
|
||||
${p.layer !== null ? html`<div class="live-status">▤ ${t("printer_layer")} ${p.layer}${p.layers ? ` / ${p.layers}` : ""}</div>` : nothing}
|
||||
${temps ? html`<div class="live-status">🌡 ${temps}</div>` : nothing}
|
||||
${p.filaments.length ? html`<div class="live-filaments">${p.filaments.map((f) => html`<i style=${`background:${f}`}></i>`)}</div>` : nothing}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** A heat pump: what it does, flow and return, the outside, power and heat, and its COP as a ring (6 = full). */
|
||||
function heatPumpCard(hass: HomeAssistant | undefined, c: HeatPumpCard, i: number): TemplateResult {
|
||||
const p = c.pump;
|
||||
const t = (k: Parameters<typeof translate>[1]) => translate(hass, k);
|
||||
const deg = (v: number | null) => (v === null ? "–" : `${formatNumber(hass, v, 1)}°`);
|
||||
const icon = { heating: "🔥", water: "🚿", cooling: "❄", defrost: "🧊", idle: "⏸" }[p.mode];
|
||||
return html`<div class="live-card live-card-heatpump ${p.mode === "idle" ? "" : "live-charging"}" data-i=${i}>
|
||||
<div class="live-own">
|
||||
${ring(Math.min(1, (p.cop ?? 0) / 6), (p.cop ?? 0) >= 3.5 ? "#4ade80" : (p.cop ?? 0) >= 2.5 ? "#facc15" : "#fb923c")}
|
||||
<div class="live-own-text"><b>${p.cop !== null ? formatNumber(hass, p.cop, 1) : icon}</b><span>${p.cop !== null ? "COP" : ""}</span></div>
|
||||
</div>
|
||||
<div class="live-rows">
|
||||
<div class="live-title">${c.name}</div>
|
||||
<div class="live-status">${icon} ${t(`heatpump_${p.mode}`)}</div>
|
||||
${p.flow !== null || p.return !== null ? html`<div class="live-row live-heat"><span>${t("heatpump_flow_return")}</span><b>${deg(p.flow)} → ${deg(p.return)}</b></div>` : nothing}
|
||||
${p.heat !== null ? html`<div class="live-row live-heat"><span>${t("heatpump_heat")}</span><b>${watts(hass, p.heat)}</b></div>` : nothing}
|
||||
${p.power !== null ? html`<div class="live-row live-house"><span>${t("heatpump_power")}</span><b>${watts(hass, p.power)}</b></div>` : nothing}
|
||||
${p.outside !== null ? html`<div class="live-status">🌡 ${t("heatpump_outside")} ${deg(p.outside)}</div>` : nothing}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
export function renderLhCards(hass: HomeAssistant | undefined, cards: readonly LiveCard[], act: LiveCardAction, fold?: LiveCardFold): TemplateResult | typeof nothing {
|
||||
if (!cards.length) return nothing;
|
||||
return html`<div class="live-cards">
|
||||
${cards.map((c, i) => (c.kind === "house" ? houseCard(hass, c, i, fold) : c.kind === "car" ? carCard(hass, c, i, act) : c.kind === "printer" ? printerCard(hass, c, i) : c.kind === "heatpump" ? heatPumpCard(hass, c, i) : mediaCard(hass, c, i, act)))}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
export const liveCardStyles = css`
|
||||
.live-cards {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
overflow: hidden;
|
||||
z-index: 2;
|
||||
container-type: size;
|
||||
}
|
||||
/* a phone: the cards keep to the screen, the house card leaves its week out */
|
||||
@container (max-width: 480px) {
|
||||
.live-card {
|
||||
gap: 8px;
|
||||
padding: 8px 10px;
|
||||
font-size: 11.5px;
|
||||
}
|
||||
.live-card-house:not(.live-folded) {
|
||||
padding-right: 28px;
|
||||
}
|
||||
.live-card-house .live-week {
|
||||
display: none;
|
||||
}
|
||||
.live-rows {
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
.live-card {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
visibility: hidden;
|
||||
pointer-events: auto;
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
padding: 10px 14px;
|
||||
border-radius: calc(var(--nf-radius) + 4px);
|
||||
background: var(--nf-chrome);
|
||||
box-shadow: var(--nf-shadow);
|
||||
backdrop-filter: blur(8px);
|
||||
-webkit-backdrop-filter: blur(8px);
|
||||
color: var(--nf-text);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.35;
|
||||
white-space: nowrap;
|
||||
will-change: transform;
|
||||
}
|
||||
.live-card::after {
|
||||
/* a thin glowing thread down to the point the card belongs to */
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: clamp(12px, calc(50% + var(--live-dx, 0px)), calc(100% - 12px));
|
||||
bottom: calc(-1 * var(--live-thread, 18px));
|
||||
width: 1px;
|
||||
height: var(--live-thread, 18px);
|
||||
background: linear-gradient(color-mix(in srgb, var(--nf-text) 45%, transparent), transparent);
|
||||
}
|
||||
.live-fold {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 50%;
|
||||
background: color-mix(in srgb, var(--nf-text) 10%, transparent);
|
||||
color: var(--nf-text);
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
cursor: pointer;
|
||||
opacity: 0.7;
|
||||
}
|
||||
.live-fold:hover,
|
||||
.live-fold:focus-visible {
|
||||
opacity: 1;
|
||||
background: color-mix(in srgb, var(--nf-text) 20%, transparent);
|
||||
}
|
||||
.live-card-house:not(.live-folded) {
|
||||
padding-right: 30px;
|
||||
}
|
||||
.live-folded {
|
||||
padding: 6px 30px 6px 8px;
|
||||
gap: 8px;
|
||||
}
|
||||
.live-folded .live-own,
|
||||
.live-folded .live-ring {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
}
|
||||
.live-folded .live-own-text b {
|
||||
font-size: 11px;
|
||||
}
|
||||
.live-rows {
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
min-width: 150px;
|
||||
}
|
||||
.live-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 14px;
|
||||
}
|
||||
.live-day {
|
||||
position: relative;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.live-day svg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 34px;
|
||||
}
|
||||
.live-day-solar {
|
||||
fill: rgba(250, 204, 21, 0.35);
|
||||
stroke: #facc15;
|
||||
stroke-width: 1;
|
||||
vector-effect: non-scaling-stroke;
|
||||
}
|
||||
.live-week svg {
|
||||
height: 30px;
|
||||
}
|
||||
.live-week-solar {
|
||||
fill: rgba(250, 204, 21, 0.6);
|
||||
}
|
||||
.live-week-use {
|
||||
fill: rgba(232, 238, 255, 0.18);
|
||||
stroke: #e8eeff;
|
||||
stroke-width: 1;
|
||||
vector-effect: non-scaling-stroke;
|
||||
}
|
||||
.live-day-use {
|
||||
fill: none;
|
||||
stroke: #e8eeff;
|
||||
stroke-width: 1.4;
|
||||
vector-effect: non-scaling-stroke;
|
||||
}
|
||||
.live-day span {
|
||||
position: absolute;
|
||||
right: 2px;
|
||||
top: 0;
|
||||
font-size: 9px;
|
||||
opacity: 0.6;
|
||||
}
|
||||
.live-row span {
|
||||
opacity: 0.8;
|
||||
}
|
||||
.live-solar b {
|
||||
color: color-mix(in srgb, #ffd166 72%, var(--nf-text));
|
||||
}
|
||||
.live-battery b {
|
||||
color: color-mix(in srgb, #4ade80 72%, var(--nf-text));
|
||||
}
|
||||
.live-import b {
|
||||
color: color-mix(in srgb, #f87193 72%, var(--nf-text));
|
||||
}
|
||||
.live-export b {
|
||||
color: color-mix(in srgb, #38dcf5 72%, var(--nf-text));
|
||||
}
|
||||
.live-house b {
|
||||
color: color-mix(in srgb, #b6c2ff 72%, var(--nf-text));
|
||||
}
|
||||
.live-title {
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
}
|
||||
.live-status {
|
||||
opacity: 0.85;
|
||||
}
|
||||
.live-print-pic {
|
||||
width: 54px;
|
||||
height: 54px;
|
||||
border-radius: 12px;
|
||||
object-fit: cover;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.live-filaments {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.live-filaments i {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 50%;
|
||||
border: 1px solid rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
.live-warn {
|
||||
color: #fbbf24;
|
||||
opacity: 1;
|
||||
}
|
||||
.live-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.live-btn {
|
||||
font: inherit;
|
||||
font-size: 14px;
|
||||
width: 32px;
|
||||
height: 28px;
|
||||
border-radius: 9px;
|
||||
border: none;
|
||||
background: var(--nf-fill);
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.live-btn.live-on {
|
||||
background: color-mix(in srgb, var(--live-soc, #4ade80) 30%, transparent);
|
||||
border-color: var(--live-soc, #4ade80);
|
||||
}
|
||||
.live-card-car {
|
||||
border-color: color-mix(in srgb, var(--live-soc) 60%, transparent);
|
||||
box-shadow: 0 0 22px color-mix(in srgb, var(--live-soc) 30%, transparent), inset 0 0 18px rgba(120, 200, 255, 0.06);
|
||||
}
|
||||
.live-card-car.live-charging {
|
||||
animation: live-charge 1.6s ease-in-out infinite;
|
||||
}
|
||||
@keyframes live-charge {
|
||||
50% {
|
||||
box-shadow: 0 0 34px color-mix(in srgb, var(--live-soc) 55%, transparent), inset 0 0 18px rgba(120, 200, 255, 0.1);
|
||||
}
|
||||
}
|
||||
.live-card-car.live-away {
|
||||
opacity: 0.85;
|
||||
border-style: dashed;
|
||||
}
|
||||
/* phones: only the house and the car, the media cards would cover the rooms */
|
||||
.nf-narrow .live-card-media {
|
||||
display: none;
|
||||
}
|
||||
.live-card-media {
|
||||
border-color: color-mix(in srgb, var(--live-soc) 55%, transparent);
|
||||
box-shadow: 0 0 22px color-mix(in srgb, var(--live-soc) 28%, transparent), inset 0 0 18px rgba(120, 200, 255, 0.06);
|
||||
}
|
||||
.live-card-media .live-title {
|
||||
max-width: 190px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.live-card-media {
|
||||
cursor: pointer;
|
||||
padding: 7px 12px 7px 7px;
|
||||
}
|
||||
.live-card-media .live-actions {
|
||||
display: none;
|
||||
}
|
||||
.live-card-media.live-open .live-actions {
|
||||
display: flex;
|
||||
}
|
||||
.live-card-media.live-open {
|
||||
z-index: 5;
|
||||
}
|
||||
.live-cover {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 10px;
|
||||
object-fit: cover;
|
||||
box-shadow: 0 0 14px color-mix(in srgb, var(--live-soc) 40%, transparent);
|
||||
}
|
||||
.live-cover-none {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-size: 24px;
|
||||
background: color-mix(in srgb, var(--live-soc) 25%, transparent);
|
||||
}
|
||||
.live-volume {
|
||||
width: 80px;
|
||||
accent-color: var(--live-soc);
|
||||
}
|
||||
.live-own {
|
||||
position: relative;
|
||||
width: 54px;
|
||||
height: 54px;
|
||||
}
|
||||
.live-ring {
|
||||
width: 54px;
|
||||
height: 54px;
|
||||
}
|
||||
.live-ring-bg {
|
||||
fill: none;
|
||||
stroke: color-mix(in srgb, var(--nf-text) 10%, transparent);
|
||||
stroke-width: 5;
|
||||
}
|
||||
.live-ring-fg {
|
||||
fill: none;
|
||||
stroke-width: 5;
|
||||
stroke-linecap: round;
|
||||
transition: stroke-dasharray 0.6s ease;
|
||||
}
|
||||
.live-own-text {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-content: center;
|
||||
text-align: center;
|
||||
}
|
||||
.live-own-text b {
|
||||
font-size: 13px;
|
||||
}
|
||||
.live-own-text span {
|
||||
font-size: 8.5px;
|
||||
opacity: 0.75;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,37 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { curvePath, dayCurves, statesRead } from "./day-curves.ts";
|
||||
import { parseHistory } from "./time-travel.ts";
|
||||
|
||||
const hass = {
|
||||
states: {
|
||||
"sensor.pv": { entity_id: "sensor.pv", state: "800", attributes: {} },
|
||||
"sensor.grid": { entity_id: "sensor.grid", state: "200", attributes: {} },
|
||||
"sensor.other": { entity_id: "sensor.other", state: "1", attributes: {} },
|
||||
},
|
||||
} as unknown as HomeAssistant;
|
||||
const balance = (h: HomeAssistant) => {
|
||||
const solar = Number(h.states["sensor.pv"].state);
|
||||
return { solar, consumption: solar + Number(h.states["sensor.grid"].state) };
|
||||
};
|
||||
|
||||
test("the sensors a balance reads are the ones whose history is loaded", () => {
|
||||
assert.deepEqual(statesRead(hass, balance).sort(), ["sensor.grid", "sensor.pv"]);
|
||||
});
|
||||
|
||||
test("the balance is worked out again for every sample of the day", () => {
|
||||
const history = parseHistory({
|
||||
"sensor.pv": [{ s: "0", lu: 0 }, { s: "1000", lu: 50 }],
|
||||
"sensor.grid": [{ s: "300", lu: 0 }],
|
||||
});
|
||||
const c = dayCurves(hass, history, 0, 100_000, balance, 4);
|
||||
assert.deepEqual(c.solar, [0, 1000, 1000, 1000]);
|
||||
assert.deepEqual(c.use, [300, 1300, 1300, 1300]);
|
||||
});
|
||||
|
||||
test("a curve is a path scaled to its box; missing values break it", () => {
|
||||
assert.equal(curvePath([0, 50, 100], 100, 10, 100), "M0.0,10.0L50.0,5.0L100.0,0.0");
|
||||
assert.equal(curvePath([0, null, 100], 100, 10, 100), "M0.0,10.0M100.0,0.0");
|
||||
assert.equal(curvePath([1, 2], 10, 10, 0), "");
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
// Day curves for the house's energy card: solar and consumption over the last 24 hours. The history of exactly the sensors the
|
||||
// live balance reads is loaded, and the balance is worked out again for every quarter hour, so the curves always mean what the
|
||||
// numbers on the card mean (automatic sensors included).
|
||||
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { hassAt, type History } from "./time-travel.ts";
|
||||
|
||||
/** The entity ids a function reads from hass.states. */
|
||||
export function statesRead(hass: HomeAssistant, run: (hass: HomeAssistant) => unknown): string[] {
|
||||
const seen = new Set<string>();
|
||||
const states = new Proxy(hass.states, {
|
||||
get(target, key: string | symbol) {
|
||||
if (typeof key === "string") seen.add(key);
|
||||
return (target as Record<string | symbol, unknown>)[key];
|
||||
},
|
||||
});
|
||||
run({ ...hass, states } as HomeAssistant);
|
||||
return [...seen].filter((id) => id.includes(".") && id in hass.states);
|
||||
}
|
||||
|
||||
export interface DayCurves {
|
||||
solar: (number | null)[];
|
||||
use: (number | null)[];
|
||||
}
|
||||
|
||||
/** The balance at `samples` evenly spread moments between from and to, from the history of its sensors. */
|
||||
export function dayCurves(hass: HomeAssistant, history: History, from: number, to: number, balance: (hass: HomeAssistant) => { solar: number | null; consumption: number | null }, samples = 96): DayCurves {
|
||||
const solar: (number | null)[] = [];
|
||||
const use: (number | null)[] = [];
|
||||
for (let i = 0; i < samples; i++) {
|
||||
const t = from + ((to - from) * (i + 1)) / samples;
|
||||
const s = balance(hassAt(hass, history, t));
|
||||
solar.push(s.solar);
|
||||
use.push(s.consumption);
|
||||
}
|
||||
return { solar, use };
|
||||
}
|
||||
|
||||
/** An SVG path through the values (missing ones break the line), scaled into width × height with `top` as the highest value. */
|
||||
export function curvePath(values: readonly (number | null)[], width: number, height: number, top: number): string {
|
||||
if (top <= 0 || values.length < 2) return "";
|
||||
let d = "";
|
||||
let pen = false;
|
||||
values.forEach((v, i) => {
|
||||
if (v === null) {
|
||||
pen = false;
|
||||
return;
|
||||
}
|
||||
const x = (i / (values.length - 1)) * width;
|
||||
const y = height - (Math.max(0, Math.min(top, v)) / top) * height;
|
||||
d += `${pen ? "L" : "M"}${x.toFixed(1)},${y.toFixed(1)}`;
|
||||
pen = true;
|
||||
});
|
||||
return d;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { findConsumers } from "../energy.ts";
|
||||
import { emptyBuilding, newFloor, type Building, type Furniture } from "../model.ts";
|
||||
import type { HassEntity, HomeAssistant } from "../types.ts";
|
||||
import { ENERGY_COLORS, energyConnections, energyPicture, houseHub, routed } from "./energy-flow.ts";
|
||||
|
||||
const sensor = (entity_id: string, state: string): HassEntity => ({ entity_id, state, attributes: { device_class: "power" } });
|
||||
const hassOf = (list: HassEntity[]) => ({ states: Object.fromEntries(list.map((s) => [s.entity_id, s])), entities: {} }) as unknown as HomeAssistant;
|
||||
const meter = (id: string, x: number, extra: Partial<Furniture> = {}): Furniture => ({ id, type: "meter", x, z: 1, rotation: 0, w: 0.5, d: 0.2, h: 1, variant: null, entity: null, power: `sensor.${id}`, ...extra });
|
||||
|
||||
// ground floor with the main meter and both sub-meters; a consumer on each floor
|
||||
function flats(advanced: boolean): Building {
|
||||
const b = emptyBuilding();
|
||||
b.floors = ["g", "og", "dg"].map((id, i) => {
|
||||
const f = newFloor(id, id, i * 3);
|
||||
f.rooms = [{ id: `r${id}`, name: id, area_id: null, points: [[0, 0], [6, 0], [6, 4], [0, 4]], floor_material: "wood" }];
|
||||
f.placements = [{ entity_id: `sensor.use_${id}`, x: 4, z: 3, y: null, mount: null }];
|
||||
return f;
|
||||
});
|
||||
b.floors[0].furniture = [meter("og", 2, { parent_meter: "main", meter_floors: ["og"] }), meter("main", 1), meter("dg", 3, { parent_meter: "main", meter_floors: ["dg"] })];
|
||||
b.energy.advanced = advanced;
|
||||
return b;
|
||||
}
|
||||
|
||||
const hass = hassOf([sensor("sensor.main", "3000"), sensor("sensor.og", "900"), sensor("sensor.dg", "700"), sensor("sensor.use_g", "200"), sensor("sensor.use_og", "300"), sensor("sensor.use_dg", "400")]);
|
||||
const from = (pic: ReturnType<typeof energyPicture>, key: string) => pic.arcs.find((a) => a.key === key)?.from;
|
||||
|
||||
test("with the advanced energy mode off the first meter is the hub and feeds everything", () => {
|
||||
const b = flats(false);
|
||||
const plain = flats(false);
|
||||
for (const f of plain.floors[0].furniture) (delete f.parent_meter, delete f.meter_floors);
|
||||
assert.deepEqual(energyPicture(hass, b), energyPicture(hass, plain));
|
||||
assert.equal(houseHub(b)?.x, 2);
|
||||
assert.ok(!energyPicture(hass, b).arcs.some((a) => a.key.startsWith("meter:")));
|
||||
});
|
||||
|
||||
test("sub-meters draw from the main meter and feed the consumers on their floors", () => {
|
||||
const pic = energyPicture(hass, flats(true));
|
||||
assert.equal(houseHub(flats(true))?.x, 1);
|
||||
const og = pic.arcs.find((a) => a.key === "meter:og")!;
|
||||
assert.deepEqual([og.from.x, og.to.x, og.power], [1, 2, 900]);
|
||||
assert.equal(from(pic, "use:sensor.use_g")?.x, 1, "unassigned floors stay on the main meter");
|
||||
assert.equal(from(pic, "use:sensor.use_og")?.x, 2);
|
||||
assert.equal(from(pic, "use:sensor.use_dg")?.x, 3);
|
||||
assert.equal(pic.summary.rest, 3000 - 900 - 700);
|
||||
// the 3D view adds the meters' own sensors as consumers: a sub-meter gets its cable from its parent only
|
||||
const b = flats(true);
|
||||
const withMeter = [...findConsumers(hass, b), { id: "og", powerEntity: "sensor.og", floorId: "g", x: 2, z: 1, power: 900 }];
|
||||
assert.ok(!energyPicture(hass, b, withMeter).arcs.some((a) => a.key === "use:og"));
|
||||
});
|
||||
|
||||
// A multi-family house: roof plant at the main meter, a balcony plant behind the upper flat's meter (see energy.test.ts)
|
||||
function withPlants(advanced: boolean): Building {
|
||||
const b = flats(advanced);
|
||||
const at = (id: string, type: string, x: number, extra: Partial<Furniture> = {}) => ({ ...meter(id, x, extra), type });
|
||||
b.floors[0].furniture.push(at("roof", "inverter", 5));
|
||||
b.floors[1].furniture = [at("balcony", "inverter", 4, { parent_meter: "og" })];
|
||||
return b;
|
||||
}
|
||||
const plantHass = hassOf([sensor("sensor.main", "-1000"), sensor("sensor.roof", "1000"), sensor("sensor.og", "-300"), sensor("sensor.dg", "200"), sensor("sensor.balcony", "800"), sensor("sensor.use_g", "100"), sensor("sensor.use_og", "500"), sensor("sensor.use_dg", "200")]);
|
||||
|
||||
test("a balcony plant feeds its flat first and only the surplus flows back to the main meter", () => {
|
||||
const pic = energyPicture(plantHass, withPlants(true));
|
||||
const arc = (key: string) => pic.arcs.find((a) => a.key === key)!;
|
||||
assert.deepEqual([arc("inverter:balcony").from.floorId, arc("inverter:balcony").to.x, arc("inverter:balcony").power], ["og", 2, 800]);
|
||||
assert.deepEqual([arc("meter:og").from.x, arc("meter:og").to.x, arc("meter:og").power], [2, 1, 300]);
|
||||
assert.deepEqual(arc("meter:og").color, ENERGY_COLORS.solar);
|
||||
assert.deepEqual([arc("meter:dg").from.x, arc("meter:dg").to.x, arc("meter:dg").power], [1, 3, 200]);
|
||||
assert.deepEqual([arc("inverter").from.x, arc("inverter").power], [5, 1000], "the roof plant feeds the house");
|
||||
assert.deepEqual([arc("grid").from.x, arc("grid").power], [1, 1000], "the rest goes to the grid");
|
||||
assert.equal(arc("use:sensor.use_og").from.x, 2);
|
||||
assert.equal(pic.summary.rest, 100);
|
||||
});
|
||||
|
||||
test("with the mode off a balcony plant's meter is ignored", () => {
|
||||
const plain = withPlants(false);
|
||||
delete plain.floors[1].furniture[0].parent_meter;
|
||||
for (const f of plain.floors[0].furniture) (delete f.parent_meter, delete f.meter_floors);
|
||||
assert.deepEqual(energyPicture(plantHass, withPlants(false)), energyPicture(plantHass, plain));
|
||||
});
|
||||
|
||||
test("a connection with a cable route follows it, walked from the end nearer to where the power starts", () => {
|
||||
const b = flats(true);
|
||||
b.floors[0].furniture.push({ ...meter("bat", 5), type: "home_battery", power: "sensor.bat" });
|
||||
assert.ok(energyConnections(b).some((c) => c.key === "battery"));
|
||||
assert.ok(energyConnections(b).some((c) => c.key === "meter:og"));
|
||||
// the cable runs from the battery (x 5) along the wall to the hub (x 1), drawn starting at the battery's end
|
||||
b.energy.routes = [{ key: "battery", points: [{ floor_id: "g", x: 5, z: 4 }, { floor_id: "g", x: 1, z: 4 }], cable: true }];
|
||||
const hub = houseHub(b)!;
|
||||
const battery = { floorId: "g", x: 5, z: 1, y: 0.8 };
|
||||
const discharging = routed(b, { key: "battery", from: battery, to: hub, power: 500, color: ENERGY_COLORS.battery });
|
||||
assert.deepEqual(discharging.via?.map((p) => p.x), [5, 1]);
|
||||
assert.equal(discharging.cable, true);
|
||||
const charging = routed(b, { key: "battery", from: hub, to: battery, power: 500, color: ENERGY_COLORS.battery });
|
||||
assert.deepEqual(charging.via?.map((p) => p.x), [1, 5], "charging walks the same cable the other way");
|
||||
// other connections keep their arc
|
||||
assert.equal(routed(b, { key: "grid", from: hub, to: battery, power: 1, color: ENERGY_COLORS.import }).via, undefined);
|
||||
});
|
||||
@@ -0,0 +1,254 @@
|
||||
/**
|
||||
* Where the power goes right now, as NextFloor draws it (see viewer/live-energy.ts): arcs between the devices
|
||||
* placed in the plan, sparkling solar modules, and the numbers for the house card.
|
||||
*
|
||||
* - every solar field sends its share of the production to the inverter
|
||||
* - the battery charges from the house or discharges into it
|
||||
* - the grid connection delivers to the house or takes the export
|
||||
* - the house feeds every consumer that reports its power (a wallbox in its own colour)
|
||||
* - advanced energy mode: each sub-meter draws from the meter it hangs off (or feeds back into it) and feeds the
|
||||
* consumers on its floors; an inverter or battery behind a sub-meter works into that sub-meter
|
||||
*
|
||||
* "The house" is where the cables meet: the meter cabinet, else the inverter, else the middle of the ground floor.
|
||||
*/
|
||||
import { deviceMeter, deviceSensors, energySummary, findConsumers, oneBattery, readPower, subMeterIds, type Consumer, type EnergySummary } from "../energy.ts";
|
||||
import type { Building, EnergyRoute, Floor, Furniture, SolarField } from "../model.ts";
|
||||
import { fieldFace, fieldModules, roofFaces, topFloor, wallFaces, GROUND, groundFloor } from "../solar.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import type { EnergyArc, PlanPoint, SparkField } from "../viewer/live-energy.ts";
|
||||
|
||||
/** Colours of the particles: sun, battery, grid import and export, the house's own cables, the wallbox. */
|
||||
export const ENERGY_COLORS: Record<"solar" | "battery" | "import" | "export" | "house" | "wallbox", [number, number, number]> = {
|
||||
solar: [255, 196, 46],
|
||||
battery: [74, 222, 128],
|
||||
import: [248, 96, 120],
|
||||
export: [56, 220, 245],
|
||||
house: [150, 170, 255],
|
||||
wallbox: [80, 175, 255],
|
||||
};
|
||||
|
||||
/** Below this a flow is not drawn (standby noise). */
|
||||
const MIN_W = 15;
|
||||
|
||||
type Spot = PlanPoint & { id: string };
|
||||
|
||||
function spotsOf(b: Building, type: string): Spot[] {
|
||||
const out: Spot[] = [];
|
||||
for (const f of b.floors) for (const m of f.furniture) if (m.type === type) out.push({ id: m.id, floorId: f.id, x: m.x, z: m.z, y: Math.max(0.4, Math.min(1.4, m.h * 0.8)) });
|
||||
return out;
|
||||
}
|
||||
|
||||
function centre(floor: Floor | null): PlanPoint | null {
|
||||
if (!floor?.rooms.length) return null;
|
||||
let x = 0, z = 0, n = 0;
|
||||
for (const r of floor.rooms) for (const [px, pz] of r.points) (x += px), (z += pz), n++;
|
||||
return n ? { floorId: floor.id, x: x / n, z: z / n, y: 1 } : null;
|
||||
}
|
||||
|
||||
/** The point where the house's cables meet (a sub-meter of the advanced energy mode is not it). */
|
||||
export function houseHub(b: Building): PlanPoint | null {
|
||||
const subs = subMeterIds(b);
|
||||
return spotsOf(b, "meter").find((m) => !subs.has(m.id)) ?? spotsOf(b, "inverter")[0] ?? centre(groundFloor(b));
|
||||
}
|
||||
|
||||
/** Where the grid comes in: the grid connection point, else the meter, else the hub (then no grid arc is drawn). */
|
||||
function gridSpot(b: Building, hub: PlanPoint): PlanPoint | null {
|
||||
const g = spotsOf(b, "grid_point")[0];
|
||||
if (g) return g;
|
||||
// without a connection point the power comes "from the street": a little outside the hub's floor
|
||||
const floor = b.floors.find((f) => f.id === hub.floorId);
|
||||
if (!floor?.rooms.length) return null;
|
||||
let x0 = Infinity, x1 = -Infinity, z1 = -Infinity;
|
||||
for (const r of floor.rooms) for (const [x, z] of r.points) (x0 = Math.min(x0, x)), (x1 = Math.max(x1, x)), (z1 = Math.max(z1, z));
|
||||
return { floorId: hub.floorId, x: Math.max(x0, Math.min(x1, hub.x)), z: z1 + 3, y: 0.2 };
|
||||
}
|
||||
|
||||
const modulesOf = (f: SolarField) => Math.max(1, f.rows * f.cols - (f.skip?.length ?? 0));
|
||||
|
||||
/** How much every solar field makes now: its own sensor, else a share of the plant by module count. */
|
||||
export function fieldProduction(hass: HomeAssistant, b: Building, solar: number | null): Map<string, number> {
|
||||
const fields = b.settings.roof.solar ?? [];
|
||||
const out = new Map<string, number>();
|
||||
let known = 0;
|
||||
const rest: SolarField[] = [];
|
||||
for (const f of fields) {
|
||||
const own = f.entity && f.entity !== "none" ? readPower(hass.states[f.entity]) : null;
|
||||
if (own !== null) {
|
||||
out.set(f.id, Math.max(0, own));
|
||||
known += Math.max(0, own);
|
||||
} else rest.push(f);
|
||||
}
|
||||
const left = Math.max(0, (solar ?? 0) - known);
|
||||
const total = rest.reduce((n, f) => n + modulesOf(f), 0);
|
||||
for (const f of rest) out.set(f.id, total ? (left * modulesOf(f)) / total : 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The floor a solar field rides on (the roof follows the top floor, garden fields the ground floor). */
|
||||
function fieldFloor(b: Building, f: SolarField): string | null {
|
||||
if (f.face === GROUND) return groundFloor(b)?.id ?? null;
|
||||
const wall = /^wall:([^:]+):/.exec(f.face);
|
||||
if (wall) return wall[1];
|
||||
return topFloor(b)?.id ?? null;
|
||||
}
|
||||
|
||||
export interface EnergyPicture {
|
||||
arcs: EnergyArc[];
|
||||
sparks: SparkField[];
|
||||
summary: EnergySummary;
|
||||
/** Share of the house's consumption covered by sun and battery right now (0…1), null without a grid sensor. */
|
||||
autarky: number | null;
|
||||
}
|
||||
|
||||
/** `powerOf` says which power sensor a placed device uses (as in deviceSensors); by default its own field. */
|
||||
export function energyPicture(hass: HomeAssistant, b: Building, consumers: Consumer[] = findConsumers(hass, b), powerOf?: (f: Furniture) => string | null): EnergyPicture {
|
||||
const devices = powerOf ? deviceSensors(b, powerOf) : deviceSensors(b);
|
||||
const summary = energySummary(hass, b, consumers, devices);
|
||||
const arcs: EnergyArc[] = [];
|
||||
const sparks: SparkField[] = [];
|
||||
const hub = houseHub(b);
|
||||
const consumption = summary.consumption ?? 0;
|
||||
const autarky = summary.grid === null || consumption <= 0 ? null : Math.max(0, Math.min(1, 1 - Math.max(0, summary.grid) / consumption));
|
||||
if (!hub) return { arcs, sparks, summary, autarky };
|
||||
// advanced energy mode: inverters and batteries behind a sub-meter work into it, not into the house
|
||||
const behind = new Map(b.floors.flatMap((f) => f.furniture).flatMap((m) => (deviceMeter(b, m) ? [[m.id, deviceMeter(b, m)!] as const] : [])));
|
||||
const inverter = spotsOf(b, "inverter").find((s) => !behind.has(s.id)) ?? hub;
|
||||
const inverters = new Map(spotsOf(b, "inverter").map((s) => [s.id, s]));
|
||||
const strings = new Map((b.settings.roof.strings ?? []).map((s) => [s.id, s.inverter ?? null]));
|
||||
|
||||
// the sun: each field to the inverter, and its modules sparkle with what it makes
|
||||
const faces = [...roofFaces(b), ...wallFaces(b)];
|
||||
const production = fieldProduction(hass, b, summary.solar);
|
||||
for (const f of b.settings.roof.solar ?? []) {
|
||||
const face = fieldFace(b, f, faces);
|
||||
if (!face) continue;
|
||||
const modules = fieldModules(face, f);
|
||||
if (!modules.length) continue;
|
||||
const p = production.get(f.id) ?? 0;
|
||||
const peak = modulesOf(f) * (f.wp ?? 400);
|
||||
const level = p > MIN_W ? Math.pow(Math.min(1, p / peak), 0.6) : 0;
|
||||
const floorId = fieldFloor(b, f);
|
||||
sparks.push({ floorId, quads: modules.map((m) => m.corners), level });
|
||||
if (p <= MIN_W) continue;
|
||||
// the arc starts at the middle of the field (building heights: taken off the floor it rides on)
|
||||
let x = 0, y = 0, z = 0;
|
||||
for (const m of modules) for (const c of m.corners) (x += c[0]), (y += c[1]), (z += c[2]);
|
||||
const n = modules.length * 4;
|
||||
const base = b.floors.find((fl) => fl.id === floorId)?.elevation ?? 0;
|
||||
// advanced energy mode: a field goes to the inverter of its string (the balcony field to the balcony inverter)
|
||||
const own = b.energy.advanced ? inverters.get(strings.get(f.string ?? "") ?? "") : undefined;
|
||||
arcs.push({ key: `solar:${f.id}`, from: { floorId, x: x / n, y: y / n - base + 0.1, z: z / n }, to: own ?? inverter, power: p, color: ENERGY_COLORS.solar });
|
||||
}
|
||||
|
||||
// the battery (without those behind a sub-meter)
|
||||
const battery = spotsOf(b, "home_battery").find((s) => !behind.has(s.id));
|
||||
const houseBattery = summary.battery === null ? null : summary.battery - (summary.subMeters ?? []).reduce((sum, m) => sum + m.battery, 0);
|
||||
if (battery && houseBattery !== null && Math.abs(houseBattery) > MIN_W) {
|
||||
const discharging = houseBattery > 0;
|
||||
arcs.push({ key: "battery", from: discharging ? battery : hub, to: discharging ? hub : battery, power: Math.abs(houseBattery), color: ENERGY_COLORS.battery });
|
||||
}
|
||||
// the inverter feeds the house (when it is not the hub itself)
|
||||
const houseSolar = (summary.solar ?? 0) - (summary.subMeters ?? []).reduce((sum, m) => sum + m.solar, 0);
|
||||
if (inverter !== hub && houseSolar > MIN_W) {
|
||||
arcs.push({ key: "inverter", from: inverter, to: hub, power: houseSolar, color: ENERGY_COLORS.solar });
|
||||
}
|
||||
// the grid
|
||||
const grid = gridSpot(b, hub);
|
||||
if (grid && summary.grid !== null && Math.abs(summary.grid) > MIN_W) {
|
||||
const importing = summary.grid > 0;
|
||||
arcs.push({ key: "grid", from: importing ? grid : hub, to: importing ? hub : grid, power: Math.abs(summary.grid), color: importing ? ENERGY_COLORS.import : ENERGY_COLORS.export });
|
||||
}
|
||||
// advanced energy mode: each sub-meter draws from the meter it hangs off (or feeds back, with solar behind it),
|
||||
// and the consumers on its floors draw from it; the first sub-meter naming a floor wins. Its inverters and
|
||||
// batteries work into it, so its solar reaches its own consumers first and only the surplus flows back.
|
||||
const meters = new Map(spotsOf(b, "meter").map((m) => [m.id, m]));
|
||||
const sensorOf = powerOf ?? ((f: Furniture) => (f.power && f.power !== "none" ? f.power : null));
|
||||
for (const floor of b.floors) {
|
||||
for (const f of floor.furniture) {
|
||||
const at = meters.get(behind.get(f.id) ?? "");
|
||||
const spot = spotsOf(b, f.type).find((s) => s.id === f.id);
|
||||
if (!at || !spot) continue;
|
||||
const sensor = sensorOf(f);
|
||||
if (f.type === "inverter") {
|
||||
const w = Math.max(0, (sensor ? readPower(hass.states[sensor]) : null) ?? 0);
|
||||
if (w > MIN_W) arcs.push({ key: `inverter:${f.id}`, from: spot, to: at, power: w, color: ENERGY_COLORS.solar });
|
||||
} else if (f.type === "home_battery") {
|
||||
const charge = f.charge && f.charge !== "none" ? f.charge : null;
|
||||
const w = oneBattery(hass, { power: sensor, charge }, b.energy.battery_invert) ?? 0;
|
||||
if (Math.abs(w) > MIN_W) arcs.push({ key: `battery:${f.id}`, from: w > 0 ? spot : at, to: w > 0 ? at : spot, power: Math.abs(w), color: ENERGY_COLORS.battery });
|
||||
}
|
||||
}
|
||||
}
|
||||
const feeders = new Map<string, Spot>();
|
||||
const subSensors = new Set<string>();
|
||||
for (const m of devices.subMeters ?? []) {
|
||||
const at = meters.get(m.id);
|
||||
const parent = meters.get(m.parent);
|
||||
if (m.power) subSensors.add(m.power);
|
||||
for (const floorId of m.floors) if (at && !feeders.has(floorId)) feeders.set(floorId, at);
|
||||
const w = summary.subMeters?.find((s) => s.id === m.id)?.power ?? null;
|
||||
if (!at || !parent || w === null || Math.abs(w) <= MIN_W) continue;
|
||||
arcs.push({ key: `meter:${m.id}`, from: w > 0 ? parent : at, to: w > 0 ? at : parent, power: Math.abs(w), color: w > 0 ? ENERGY_COLORS.house : ENERGY_COLORS.solar });
|
||||
}
|
||||
// the house feeds its consumers
|
||||
const wallboxes = new Set(spotsOf(b, "wallbox").map((w) => `${w.floorId}:${w.x.toFixed(1)}:${w.z.toFixed(1)}`));
|
||||
for (const c of consumers) {
|
||||
if (c.power <= MIN_W || subSensors.has(c.powerEntity)) continue;
|
||||
const wallbox = c.wallbox || wallboxes.has(`${c.floorId}:${c.x.toFixed(1)}:${c.z.toFixed(1)}`);
|
||||
arcs.push({ key: `use:${c.id}`, from: feeders.get(c.floorId) ?? hub, to: { floorId: c.floorId, x: c.x, z: c.z, y: 0.9 }, power: c.power, color: wallbox ? ENERGY_COLORS.wallbox : ENERGY_COLORS.house });
|
||||
}
|
||||
return { arcs: arcs.map((arc) => routed(b, arc)), sparks, summary, autarky };
|
||||
}
|
||||
|
||||
/** How high above its floor a cable route runs (along the skirting). */
|
||||
const CABLE_Y = 0.25;
|
||||
|
||||
/** A connection whose cable can be routed: its key (as the arcs name it) and what it joins. */
|
||||
export interface EnergyConnection {
|
||||
key: string;
|
||||
kind: "solar" | "battery" | "inverter" | "grid" | "meter";
|
||||
/** The solar field, or the device behind a sub-meter, or the sub-meter. */
|
||||
id: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The connections of the plan that can get a cable route, whether power flows on them right now or not: each solar field to
|
||||
* its inverter, the battery, the inverter and the grid to the house, and in the advanced energy mode the devices behind a
|
||||
* sub-meter and the sub-meters. Consumers keep their arc.
|
||||
*/
|
||||
export function energyConnections(b: Building): EnergyConnection[] {
|
||||
const out: EnergyConnection[] = [];
|
||||
const hub = houseHub(b);
|
||||
if (!hub) return out;
|
||||
const behind = new Set(b.floors.flatMap((f) => f.furniture).filter((m) => deviceMeter(b, m)).map((m) => m.id));
|
||||
const inverter = spotsOf(b, "inverter").find((s) => !behind.has(s.id));
|
||||
for (const f of b.settings.roof.solar ?? []) out.push({ key: `solar:${f.id}`, kind: "solar", id: f.id });
|
||||
if (spotsOf(b, "home_battery").some((s) => !behind.has(s.id))) out.push({ key: "battery", kind: "battery", id: null });
|
||||
if (inverter && (inverter.floorId !== hub.floorId || inverter.x !== hub.x || inverter.z !== hub.z)) out.push({ key: "inverter", kind: "inverter", id: null });
|
||||
if (gridSpot(b, hub)) out.push({ key: "grid", kind: "grid", id: null });
|
||||
for (const f of b.floors.flatMap((fl) => fl.furniture)) {
|
||||
if (!behind.has(f.id)) continue;
|
||||
if (f.type === "inverter") out.push({ key: `inverter:${f.id}`, kind: "inverter", id: f.id });
|
||||
else if (f.type === "home_battery") out.push({ key: `battery:${f.id}`, kind: "battery", id: f.id });
|
||||
}
|
||||
for (const id of subMeterIds(b)) out.push({ key: `meter:${id}`, kind: "meter", id });
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The route of a connection, if one is drawn. */
|
||||
export const routeOf = (b: Building, key: string): EnergyRoute | undefined => b.energy.routes?.find((r) => r.key === key && r.points.length > 0);
|
||||
|
||||
/**
|
||||
* An arc with its cable route: the route's points in the order the power runs. A route is drawn once for a connection whose
|
||||
* flow can turn round (the battery charges and discharges), so it is walked from whichever end lies nearer to the arc's start.
|
||||
*/
|
||||
export function routed(b: Building, arc: EnergyArc): EnergyArc {
|
||||
const route = routeOf(b, arc.key);
|
||||
if (!route) return arc;
|
||||
const via: PlanPoint[] = route.points.map((p) => ({ floorId: p.floor_id, x: p.x, z: p.z, y: CABLE_Y }));
|
||||
const elevation = (id: string | null) => b.floors.find((f) => f.id === id)?.elevation ?? 0;
|
||||
const apart = (p: PlanPoint, q: PlanPoint) => Math.hypot(p.x - q.x, p.z - q.z) + Math.abs(elevation(p.floorId) + p.y - elevation(q.floorId) - q.y);
|
||||
const [first, last] = [via[0], via[via.length - 1]];
|
||||
if (apart(arc.from, last) + apart(arc.to, first) < apart(arc.from, first) + apart(arc.to, last)) via.reverse();
|
||||
return { ...arc, via, cable: !!route.cable };
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { conditionIcon, forecastDays } from "./forecast.ts";
|
||||
|
||||
const NOW = new Date(2026, 10, 8, 15, 0).getTime();
|
||||
const at = (day: number, hour = 12) => new Date(2026, 10, day, hour).toISOString();
|
||||
|
||||
test("the forecast turns into one row per day from today, as many as asked for", () => {
|
||||
const raw = [
|
||||
{ datetime: at(7), condition: "sunny", temperature: 9 },
|
||||
{ datetime: at(8), condition: "rainy", temperature: 11.4, templow: 4, precipitation: 3.2, precipitation_probability: 80 },
|
||||
{ datetime: at(8, 18), condition: "sunny", temperature: 30 },
|
||||
{ datetime: at(9), condition: "partlycloudy", temperature: "12", templow: "5" },
|
||||
{ datetime: at(10), condition: "snowy", temperature: 1 },
|
||||
];
|
||||
const days = forecastDays(raw, 2, NOW);
|
||||
assert.equal(days.length, 2, "yesterday left out, two days asked for");
|
||||
assert.deepEqual(days[0], { day: new Date(2026, 10, 8).getTime(), icon: "🌦️", high: 11.4, low: 4, rain: 3.2, chance: 80 });
|
||||
assert.equal(days[1].icon, "⛅");
|
||||
assert.deepEqual([days[1].high, days[1].low, days[1].rain, days[1].chance], [12, 5, null, null], "numbers as text count, missing ones stay empty");
|
||||
});
|
||||
|
||||
test("an answer without a forecast gives no rows, and an unknown condition a cloud", () => {
|
||||
assert.deepEqual(forecastDays(undefined, 5, NOW), []);
|
||||
assert.deepEqual(forecastDays([{ condition: "sunny" }], 5, NOW), [], "a day without a date is left out");
|
||||
assert.equal(conditionIcon("tornado"), "☁️");
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
// The weather forecast card: a few days from the plan's weather entity, with the high and low and the rain. Home Assistant hands
|
||||
// the forecast out through the `weather.get_forecasts` action (the state attributes no longer carry it); turning its answer into
|
||||
// card rows is a pure function.
|
||||
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
|
||||
/** One day of the card. */
|
||||
export interface ForecastDay {
|
||||
/** Midnight of the day, local time (ms). */
|
||||
day: number;
|
||||
/** The weather of the day as an emoji. */
|
||||
icon: string;
|
||||
high: number | null;
|
||||
low: number | null;
|
||||
/** Precipitation in the entity's unit (mm, in), null when not given. */
|
||||
rain: number | null;
|
||||
/** Chance of precipitation in %, null when not given. */
|
||||
chance: number | null;
|
||||
}
|
||||
|
||||
interface RawForecast {
|
||||
datetime?: string;
|
||||
condition?: string;
|
||||
temperature?: number | string;
|
||||
templow?: number | string;
|
||||
precipitation?: number | string;
|
||||
precipitation_probability?: number | string;
|
||||
}
|
||||
|
||||
const ICONS: Record<string, string> = {
|
||||
"clear-night": "🌙",
|
||||
cloudy: "☁️",
|
||||
exceptional: "⚠️",
|
||||
fog: "🌫️",
|
||||
hail: "🧊",
|
||||
lightning: "🌩️",
|
||||
"lightning-rainy": "⛈️",
|
||||
partlycloudy: "⛅",
|
||||
pouring: "🌧️",
|
||||
rainy: "🌦️",
|
||||
snowy: "❄️",
|
||||
"snowy-rainy": "🌨️",
|
||||
sunny: "☀️",
|
||||
windy: "💨",
|
||||
"windy-variant": "💨",
|
||||
};
|
||||
|
||||
/** The emoji of a Home Assistant weather condition (a cloud for one it does not know). */
|
||||
export const conditionIcon = (condition: string | undefined): string => ICONS[condition ?? ""] ?? "☁️";
|
||||
|
||||
const numberOr = (v: unknown): number | null => {
|
||||
const n = typeof v === "string" ? Number.parseFloat(v) : typeof v === "number" ? v : Number.NaN;
|
||||
return Number.isFinite(n) ? n : null;
|
||||
};
|
||||
|
||||
const midnight = (t: number): number => {
|
||||
const d = new Date(t);
|
||||
d.setHours(0, 0, 0, 0);
|
||||
return d.getTime();
|
||||
};
|
||||
|
||||
/** The days of the card, from today on: at most `days`, one row per day (the first entry of a day counts). */
|
||||
export function forecastDays(raw: unknown, days: number, now = Date.now()): ForecastDay[] {
|
||||
const today = midnight(now);
|
||||
const out: ForecastDay[] = [];
|
||||
for (const f of Array.isArray(raw) ? (raw as RawForecast[]) : []) {
|
||||
const at = f.datetime ? Date.parse(f.datetime) : Number.NaN;
|
||||
if (!Number.isFinite(at)) continue;
|
||||
const day = midnight(at);
|
||||
if (day < today || out.some((d) => d.day === day)) continue;
|
||||
out.push({ day, icon: conditionIcon(f.condition), high: numberOr(f.temperature), low: numberOr(f.templow), rain: numberOr(f.precipitation), chance: numberOr(f.precipitation_probability) });
|
||||
if (out.length >= days) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Asks Home Assistant for the daily forecast of a weather entity; an entity without one gives no days. */
|
||||
export async function loadForecast(hass: HomeAssistant, entity: string): Promise<unknown> {
|
||||
try {
|
||||
const answer = await hass.callWS<{ response?: Record<string, { forecast?: unknown }> }>({
|
||||
type: "call_service",
|
||||
domain: "weather",
|
||||
service: "get_forecasts",
|
||||
service_data: { type: "daily" },
|
||||
target: { entity_id: entity },
|
||||
return_response: true,
|
||||
});
|
||||
return answer?.response?.[entity]?.forecast ?? [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity, hassOf } from "../entities/fixtures.ts";
|
||||
import { isHeatPump, readHeatPump } from "./heat-pump.ts";
|
||||
|
||||
test("a heat pump's flow, return, power, heat, COP and mode from its device", () => {
|
||||
const d = { device_id: "hp" };
|
||||
const ids = ["climate.hp", "sensor.hp_vorlauftemperatur", "sensor.hp_rucklauftemperatur", "sensor.hp_heat_output", "sensor.hp_power", "sensor.hp_outdoor_temperature"];
|
||||
const hass = hassOf(
|
||||
[
|
||||
entity("climate.hp", "heat", { hvac_action: "heating" }),
|
||||
entity("sensor.hp_vorlauftemperatur", "34.5", { device_class: "temperature" }),
|
||||
entity("sensor.hp_rucklauftemperatur", "29", { device_class: "temperature" }),
|
||||
entity("sensor.hp_heat_output", "4.2", { device_class: "power", unit_of_measurement: "kW" }),
|
||||
entity("sensor.hp_power", "1000", { device_class: "power", unit_of_measurement: "W" }),
|
||||
entity("sensor.hp_outdoor_temperature", "3", { device_class: "temperature" }),
|
||||
],
|
||||
Object.fromEntries(ids.map((id) => [id, d])),
|
||||
);
|
||||
const hp = readHeatPump(hass, "climate.hp")!;
|
||||
assert.deepEqual(hp, { mode: "heating", flow: 34.5, return: 29, outside: 3, power: 1000, heat: 4200, cop: 4.2 });
|
||||
assert.equal(isHeatPump("pack:nextfloor.a_smart:heat_pump_outdoor"), true);
|
||||
assert.equal(isHeatPump("pack:nextfloor.kino:heat_pumpkin"), false);
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* NextFloor's heat pump: what it reports, found among the entities of its device (like the car and the printer): whether it heats,
|
||||
* makes hot water, cools or defrosts, the flow and return temperatures, the electric power it draws, the heat it delivers and its
|
||||
* COP. Works with the integrations that put these on one device (Daikin, Vaillant/myVaillant, Viessmann, Panasonic Aquarea, Nibe,
|
||||
* Stiebel Eltron, Luxtronik, Mitsubishi Ecodan, ESPHome builds …).
|
||||
*/
|
||||
import type { HassEntity, HomeAssistant } from "../types.ts";
|
||||
|
||||
export interface HeatPumpInfo {
|
||||
/** heating, water (hot water), cooling, defrost or idle. */
|
||||
mode: "heating" | "water" | "cooling" | "defrost" | "idle";
|
||||
flow: number | null;
|
||||
return: number | null;
|
||||
outside: number | null;
|
||||
/** Electric power drawn (W). */
|
||||
power: number | null;
|
||||
/** Heat delivered (W). */
|
||||
heat: number | null;
|
||||
cop: number | null;
|
||||
}
|
||||
|
||||
const num = (st: HassEntity | undefined) => {
|
||||
const n = Number(st?.state);
|
||||
return st && Number.isFinite(n) ? n : null;
|
||||
};
|
||||
const has = (id: string, ...words: string[]) => words.some((w) => id.includes(w));
|
||||
|
||||
/** Watts from a power sensor in W or kW. */
|
||||
function watts(st: HassEntity | undefined): number | null {
|
||||
const v = num(st);
|
||||
if (v === null) return null;
|
||||
return String(st!.attributes.unit_of_measurement ?? "W").toLowerCase() === "kw" ? v * 1000 : v;
|
||||
}
|
||||
|
||||
function siblings(hass: HomeAssistant, entity: string): string[] {
|
||||
const device = hass.entities?.[entity]?.device_id;
|
||||
if (!device) return hass.states[entity] ? [entity] : [];
|
||||
return Object.values(hass.entities ?? {})
|
||||
.filter((e) => e.device_id === device && !e.hidden)
|
||||
.map((e) => e.entity_id)
|
||||
.filter((id) => hass.states[id]);
|
||||
}
|
||||
|
||||
export function readHeatPump(hass: HomeAssistant, anchor: string | null): HeatPumpInfo | null {
|
||||
if (!anchor || !hass.states[anchor]) return null;
|
||||
const all = siblings(hass, anchor);
|
||||
const sensors = all.filter((id) => id.startsWith("sensor."));
|
||||
const find = (match: (id: string, s: HassEntity) => boolean) => sensors.find((id) => match(id, hass.states[id]));
|
||||
const temp = (s: HassEntity) => s.attributes.device_class === "temperature";
|
||||
const power = (s: HassEntity) => s.attributes.device_class === "power";
|
||||
const flowId = find((id, s) => temp(s) && has(id, "flow", "vorlauf", "supply", "leaving", "outlet") && !has(id, "target", "soll", "rate"));
|
||||
const returnId = find((id, s) => temp(s) && has(id, "return", "rucklauf", "rücklauf", "ruecklauf", "inlet", "entering") && !has(id, "target", "soll"));
|
||||
const outsideId = find((id, s) => temp(s) && has(id, "outdoor", "outside", "aussen", "außen", "ambient"));
|
||||
const heatId = find((id, s) => power(s) && has(id, "heat", "warme", "wärme", "thermal", "output", "heizleistung"));
|
||||
const powerId = find((id, s) => power(s) && id !== heatId && !has(id, "heat_output", "thermal"));
|
||||
const copId = find((id) => has(id, "cop", "leistungszahl"));
|
||||
if (!flowId && !returnId && !heatId && !copId) return null;
|
||||
// the mode: a climate entity's action, else a status sensor's words, else heat delivered
|
||||
const climate = all.map((id) => hass.states[id]).find((s) => s.entity_id.startsWith("climate."));
|
||||
const statusId = find((id, s) => !Number.isFinite(Number(s.state)) && has(id, "status", "mode", "betrieb", "operation", "state"));
|
||||
const words = `${String(climate?.attributes.hvac_action ?? "")} ${String(statusId ? hass.states[statusId].state : "")}`.toLowerCase();
|
||||
const heat = watts(hass.states[heatId ?? ""]);
|
||||
const mode: HeatPumpInfo["mode"] = /defrost|abtau/.test(words)
|
||||
? "defrost"
|
||||
: /water|dhw|warmwasser|tank/.test(words)
|
||||
? "water"
|
||||
: /cool|kühl/.test(words)
|
||||
? "cooling"
|
||||
: /heat|heiz/.test(words) || (heat ?? 0) > 100
|
||||
? "heating"
|
||||
: "idle";
|
||||
const pw = watts(hass.states[powerId ?? ""]);
|
||||
const cop = num(hass.states[copId ?? ""]) ?? (heat !== null && pw && pw > 50 ? Math.round((heat / pw) * 10) / 10 : null);
|
||||
return { mode, flow: num(hass.states[flowId ?? ""]), return: num(hass.states[returnId ?? ""]), outside: num(hass.states[outsideId ?? ""]), power: pw, heat, cop };
|
||||
}
|
||||
|
||||
/** Whether a piece of furniture is a heat pump (by its pack item's id). */
|
||||
export const isHeatPump = (type: string): boolean => /:heat_pump(_|$)/.test(type);
|
||||
@@ -0,0 +1,60 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { appColor, isLive, mediaNow, multiroom } from "./media.ts";
|
||||
|
||||
const at = { floorId: "eg", x: 1, y: 1, z: 1 };
|
||||
function hass(states: Record<string, { state: string; attributes: Record<string, unknown> }>): HomeAssistant {
|
||||
return {
|
||||
language: "de",
|
||||
connection: {} as HomeAssistant["connection"],
|
||||
callWS: async () => undefined as never,
|
||||
callService: async () => undefined,
|
||||
areas: {},
|
||||
devices: {},
|
||||
entities: {},
|
||||
states: Object.fromEntries(Object.entries(states).map(([id, s]) => [id, { entity_id: id, ...s }])),
|
||||
};
|
||||
}
|
||||
|
||||
test("players in the plan with what they play, in their app's colour", () => {
|
||||
const h = hass({
|
||||
"media_player.kueche": { state: "playing", attributes: { media_title: "Song", media_artist: "Band", app_name: "Spotify", volume_level: 0.4, group_members: ["media_player.kueche", "media_player.bad"] } },
|
||||
"media_player.bad": { state: "playing", attributes: { media_title: "Song", app_name: "Spotify" } },
|
||||
"media_player.tv": { state: "paused", attributes: { app_name: "Netflix" } },
|
||||
"light.x": { state: "on", attributes: {} },
|
||||
});
|
||||
const list = mediaNow(h, [
|
||||
{ entity: "media_player.kueche", name: "Küche", at },
|
||||
{ entity: "media_player.kueche", name: "doppelt", at },
|
||||
{ entity: "media_player.bad", name: "Bad", at },
|
||||
{ entity: "media_player.tv", name: "TV", at },
|
||||
{ entity: "light.x", name: "Licht", at },
|
||||
]);
|
||||
assert.deepEqual(list.map((m) => m.entity), ["media_player.kueche", "media_player.bad", "media_player.tv"]);
|
||||
assert.equal(list[0].title, "Song");
|
||||
assert.equal(list[0].volume, 0.4);
|
||||
assert.deepEqual(list[0].color, appColor("Spotify"));
|
||||
assert.equal(list[2].playing, false);
|
||||
assert.deepEqual(list[0].group, ["media_player.bad"]);
|
||||
assert.equal(multiroom(list).length, 1);
|
||||
assert.deepEqual(appColor("Netflix"), [229, 9, 20]);
|
||||
assert.deepEqual(appColor(null), appColor("Unbekannt"));
|
||||
});
|
||||
|
||||
test("a TV that is 'on' with a channel counts as live, without one it does not", () => {
|
||||
assert.equal(isLive({ state: "on", attributes: { media_title: "ITV1 HD" } }), true);
|
||||
assert.equal(isLive({ state: "on", attributes: { source: "HDMI 1" } }), true);
|
||||
assert.equal(isLive({ state: "on", attributes: {} }), false);
|
||||
assert.equal(isLive({ state: "paused", attributes: { media_title: "x" } }), false);
|
||||
assert.equal(isLive({ state: "playing", attributes: {} }), true);
|
||||
});
|
||||
|
||||
test("a player keeps the ring size its furniture or marker asks for, 1 when it sets none (#94)", () => {
|
||||
const h = hass({ "media_player.dot": { state: "playing", attributes: {} }, "media_player.show": { state: "playing", attributes: {} } });
|
||||
const list = mediaNow(h, [
|
||||
{ entity: "media_player.dot", name: "Dot", at, rings: 0 },
|
||||
{ entity: "media_player.show", name: "Show", at },
|
||||
]);
|
||||
assert.deepEqual(list.map((m) => m.rings), [0, 1]);
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* NextFloor's sound: the media players that play right now, where they stand in the plan, what they play, in the
|
||||
* colour of their app, and which of them play together (multiroom).
|
||||
*/
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import type { PlanPoint } from "../viewer/live-energy.ts";
|
||||
|
||||
export interface MediaNow {
|
||||
entity: string;
|
||||
name: string;
|
||||
at: PlanPoint;
|
||||
playing: boolean;
|
||||
title: string;
|
||||
artist: string;
|
||||
picture: string | null;
|
||||
/** 0…1, null when the player does not report it. */
|
||||
volume: number | null;
|
||||
color: [number, number, number];
|
||||
app: string | null;
|
||||
/** Other players playing the same (multiroom), as reported by the player. */
|
||||
group: string[];
|
||||
/** Size of its sound rings (1 = as usual, 0 = none). */
|
||||
rings: number;
|
||||
}
|
||||
|
||||
/** App colours: the ring around a speaker and the card's edge take the colour of what plays. */
|
||||
const APPS: [RegExp, [number, number, number]][] = [
|
||||
[/spotify/i, [30, 215, 96]],
|
||||
[/netflix/i, [229, 9, 20]],
|
||||
[/youtube/i, [255, 0, 51]],
|
||||
[/prime|amazon/i, [0, 168, 225]],
|
||||
[/disney/i, [17, 60, 207]],
|
||||
[/apple ?music|itunes/i, [250, 45, 72]],
|
||||
[/apple ?tv/i, [200, 200, 210]],
|
||||
[/plex/i, [229, 160, 13]],
|
||||
[/tidal/i, [0, 255, 255]],
|
||||
[/deezer/i, [162, 56, 255]],
|
||||
[/radio|tunein/i, [255, 140, 60]],
|
||||
];
|
||||
const DEFAULT: [number, number, number] = [34, 211, 238];
|
||||
|
||||
export function appColor(app: string | null): [number, number, number] {
|
||||
if (!app) return DEFAULT;
|
||||
return APPS.find(([re]) => re.test(app))?.[1] ?? DEFAULT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a player has something on its screen: it plays or is paused, or it is "on" with a title, input or app – many TV
|
||||
* integrations (Samsung, LG on live TV) only ever report "on".
|
||||
*/
|
||||
export function showsSomething(st: { state: string; attributes: Record<string, unknown> }): boolean {
|
||||
if (st.state === "playing" || st.state === "paused") return true;
|
||||
const str = (k: string) => typeof st.attributes[k] === "string" && (st.attributes[k] as string) !== "";
|
||||
return st.state === "on" && (str("media_title") || str("media_channel") || str("source") || str("app_name"));
|
||||
}
|
||||
|
||||
/** Whether a player is running now: playing, or a TV that is "on" with something showing (live TV, an input). */
|
||||
export const isLive = (st: { state: string; attributes: Record<string, unknown> }): boolean => st.state === "playing" || (st.state === "on" && showsSomething(st));
|
||||
|
||||
/** Media players placed in the plan (as a device, or linked to furniture such as a TV or a speaker). */
|
||||
export function mediaNow(hass: HomeAssistant, spots: readonly { entity: string; name: string; at: PlanPoint; rings?: number | null }[]): MediaNow[] {
|
||||
const out: MediaNow[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const s of spots) {
|
||||
if (!s.entity.startsWith("media_player.") || seen.has(s.entity)) continue;
|
||||
seen.add(s.entity);
|
||||
const st = hass.states[s.entity];
|
||||
if (!st) continue;
|
||||
const a = st.attributes as Record<string, unknown>;
|
||||
const str = (k: string) => (typeof a[k] === "string" ? (a[k] as string) : "");
|
||||
const app = str("app_name") || str("source") || str("app_id") || null;
|
||||
const vol = typeof a.volume_level === "number" ? a.volume_level : null;
|
||||
out.push({
|
||||
entity: s.entity,
|
||||
name: s.name,
|
||||
at: s.at,
|
||||
playing: isLive(st),
|
||||
title: str("media_title") || str("media_channel") || app || "",
|
||||
artist: str("media_artist") || str("media_album_name") || str("media_series_title"),
|
||||
picture: str("entity_picture") || null,
|
||||
volume: vol,
|
||||
color: appColor(app),
|
||||
app,
|
||||
group: Array.isArray(a.group_members) ? (a.group_members as unknown[]).filter((g): g is string => typeof g === "string" && g !== s.entity) : [],
|
||||
rings: s.rings ?? 1,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Pairs of playing players that play together (each pair once). */
|
||||
export function multiroom(list: readonly MediaNow[]): [MediaNow, MediaNow][] {
|
||||
const by = new Map(list.filter((m) => m.playing).map((m) => [m.entity, m]));
|
||||
const pairs: [MediaNow, MediaNow][] = [];
|
||||
const done = new Set<string>();
|
||||
for (const m of by.values()) {
|
||||
for (const g of m.group) {
|
||||
const o = by.get(g);
|
||||
const key = [m.entity, g].sort().join("|");
|
||||
if (o && !done.has(key)) {
|
||||
done.add(key);
|
||||
pairs.push([m, o]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return pairs;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity } from "../entities/fixtures.ts";
|
||||
import { carryMood, lightSetting, moodCalls } from "./moods.ts";
|
||||
|
||||
test("a mood is kept from the lights, set again, and carried over to another room", () => {
|
||||
const warm = lightSetting(entity("light.a", "on", { brightness: 128, color_mode: "color_temp", color_temp_kelvin: 2700 }));
|
||||
const red = lightSetting(entity("light.b", "on", { brightness: 255, color_mode: "rgb", rgb_color: [255, 0, 0] }));
|
||||
const off = lightSetting(entity("light.c", "off"));
|
||||
assert.deepEqual(warm, { entity: "light.a", on: true, brightness: 128, kelvin: 2700 });
|
||||
assert.deepEqual(moodCalls([warm, red, off]), [
|
||||
{ service: "turn_on", data: { entity_id: "light.a", brightness: 128, color_temp_kelvin: 2700 } },
|
||||
{ service: "turn_on", data: { entity_id: "light.b", brightness: 255, rgb_color: [255, 0, 0] } },
|
||||
{ service: "turn_off", data: { entity_id: ["light.c"] } },
|
||||
]);
|
||||
const carried = carryMood({ lights: [warm, red] }, ["light.x", "light.y", "light.z"]);
|
||||
assert.deepEqual(carried.map((s) => [s.entity, s.rgb ?? s.kelvin]), [["light.x", 2700], ["light.y", [255, 0, 0]], ["light.z", [255, 0, 0]]], "the extra light takes the brightest one");
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
// The light designer: a room's lights as they are now, kept as a mood of the room (in the plan), set again later, or carried over to
|
||||
// another room. Pure functions from light states to service calls.
|
||||
|
||||
import type { LightMood, LightSetting } from "../model.ts";
|
||||
import type { HassEntity } from "../types.ts";
|
||||
|
||||
/** How a light is now: off, or on with its brightness and colour (as `light.turn_on` takes them). */
|
||||
export function lightSetting(st: HassEntity): LightSetting {
|
||||
if (st.state !== "on") return { entity: st.entity_id, on: false };
|
||||
const a = st.attributes;
|
||||
const out: LightSetting = { entity: st.entity_id, on: true };
|
||||
if (typeof a.brightness === "number") out.brightness = a.brightness;
|
||||
const mode = String(a.color_mode ?? "");
|
||||
if (Array.isArray(a.rgb_color) && !["color_temp", "brightness", "onoff"].includes(mode)) out.rgb = (a.rgb_color as number[]).slice(0, 3) as [number, number, number];
|
||||
else if (typeof a.color_temp_kelvin === "number") out.kelvin = a.color_temp_kelvin;
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The calls that set a mood: one turn_on per light that is on (with its brightness and colour), one turn_off for the rest. */
|
||||
export function moodCalls(settings: readonly LightSetting[]): { service: "turn_on" | "turn_off"; data: Record<string, unknown> }[] {
|
||||
const off = settings.filter((s) => !s.on).map((s) => s.entity);
|
||||
const on = settings
|
||||
.filter((s) => s.on)
|
||||
.map((s) => ({
|
||||
service: "turn_on" as const,
|
||||
data: { entity_id: s.entity, ...(s.brightness !== undefined ? { brightness: s.brightness } : {}), ...(s.rgb ? { rgb_color: s.rgb } : s.kelvin ? { color_temp_kelvin: s.kelvin } : {}) },
|
||||
}));
|
||||
return [...on, ...(off.length ? [{ service: "turn_off" as const, data: { entity_id: off } }] : [])];
|
||||
}
|
||||
|
||||
/**
|
||||
* A mood carried over to another room's lights: they take the settings in order (the first light the first setting …); when the
|
||||
* other room has more lights, the rest takes the setting of the brightest light that is on.
|
||||
*/
|
||||
export function carryMood(mood: Pick<LightMood, "lights">, targets: readonly string[]): LightSetting[] {
|
||||
const lit = [...mood.lights].filter((s) => s.on).sort((a, b) => (b.brightness ?? 255) - (a.brightness ?? 255))[0];
|
||||
return targets.map((entity, i) => {
|
||||
const from = mood.lights[i] ?? lit ?? { entity, on: false };
|
||||
return { ...from, entity };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity, hassOf } from "../entities/fixtures.ts";
|
||||
import { readPrinter } from "./printer.ts";
|
||||
|
||||
test("a Bambu printer's print: progress, time left, layers, temperatures, picture and filaments", () => {
|
||||
const d = { device_id: "p1" };
|
||||
const hass = hassOf(
|
||||
[
|
||||
entity("sensor.p1s_print_progress", "42", { unit_of_measurement: "%" }),
|
||||
entity("sensor.p1s_print_status", "running"),
|
||||
entity("sensor.p1s_remaining_time", "1.5", { unit_of_measurement: "h" }),
|
||||
entity("sensor.p1s_current_layer", "120"),
|
||||
entity("sensor.p1s_total_layer_count", "300"),
|
||||
entity("sensor.p1s_nozzle_temperature", "220", { device_class: "temperature" }),
|
||||
entity("sensor.p1s_bed_temperature", "60", { device_class: "temperature" }),
|
||||
entity("sensor.p1s_task_name", "benchy"),
|
||||
entity("image.p1s_cover_image", "2026-11-02", { entity_picture: "/api/image_proxy/image.p1s_cover_image" }),
|
||||
entity("sensor.p1s_ams_1_tray_1", "PLA", { color: "#FF0000FF" }),
|
||||
entity("sensor.p1s_ams_1_tray_2", "PETG", { color: "#00FF00FF", active: true }),
|
||||
],
|
||||
Object.fromEntries(["sensor.p1s_print_progress", "sensor.p1s_print_status", "sensor.p1s_remaining_time", "sensor.p1s_current_layer", "sensor.p1s_total_layer_count", "sensor.p1s_nozzle_temperature", "sensor.p1s_bed_temperature", "sensor.p1s_task_name", "image.p1s_cover_image", "sensor.p1s_ams_1_tray_1", "sensor.p1s_ams_1_tray_2"].map((id) => [id, d])),
|
||||
);
|
||||
const p = readPrinter(hass, "sensor.p1s_print_progress")!;
|
||||
assert.equal(p.printing, true);
|
||||
assert.equal(p.progress, 42);
|
||||
assert.equal(p.remaining, 90);
|
||||
assert.deepEqual([p.layer, p.layers, p.nozzle, p.bed], [120, 300, 220, 60]);
|
||||
assert.equal(p.job, "benchy");
|
||||
assert.equal(p.picture, "/api/image_proxy/image.p1s_cover_image");
|
||||
assert.deepEqual(p.filaments, ["#00ff00", "#ff0000"], "the active tray first");
|
||||
});
|
||||
|
||||
test("a device without a print progress is no printer", () => {
|
||||
assert.equal(readPrinter(hassOf([entity("switch.plug", "on")]), "switch.plug"), null);
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* NextFloor's 3D printer: what a printer reports, found among the entities of its Home Assistant device – like the car. Works with
|
||||
* the Bambu Lab, OctoPrint, Moonraker (Klipper) and PrusaLink integrations, which name their sensors alike: a print progress in %,
|
||||
* the time left or the end time, the current and total layer, nozzle and bed temperatures, a cover picture of the model and, on a
|
||||
* Bambu printer with an AMS, the colour of each filament tray.
|
||||
*/
|
||||
import type { HassEntity, HomeAssistant } from "../types.ts";
|
||||
|
||||
export interface PrinterInfo {
|
||||
/** printing, paused, finished, idle, error or offline (lower case, from the print status). */
|
||||
status: string;
|
||||
printing: boolean;
|
||||
/** 0 … 100. */
|
||||
progress: number | null;
|
||||
/** Minutes left. */
|
||||
remaining: number | null;
|
||||
/** When it will be done (ms). */
|
||||
endsAt: number | null;
|
||||
layer: number | null;
|
||||
layers: number | null;
|
||||
nozzle: number | null;
|
||||
bed: number | null;
|
||||
/** Name of the file or job. */
|
||||
job: string | null;
|
||||
/** The model's picture (an image entity's or a camera's picture). */
|
||||
picture: string | null;
|
||||
/** Filament colours ("#rrggbb"), the active one first. */
|
||||
filaments: string[];
|
||||
}
|
||||
|
||||
const num = (st: HassEntity | undefined) => {
|
||||
const n = Number(st?.state);
|
||||
return st && Number.isFinite(n) ? n : null;
|
||||
};
|
||||
const has = (id: string, ...words: string[]) => words.some((w) => id.includes(w));
|
||||
|
||||
/** All entities of the device of `entity`. */
|
||||
function siblings(hass: HomeAssistant, entity: string): string[] {
|
||||
const device = hass.entities?.[entity]?.device_id;
|
||||
if (!device) return hass.states[entity] ? [entity] : [];
|
||||
return Object.values(hass.entities ?? {})
|
||||
.filter((e) => e.device_id === device && !e.hidden)
|
||||
.map((e) => e.entity_id)
|
||||
.filter((id) => hass.states[id]);
|
||||
}
|
||||
|
||||
/** Minutes from a duration state: minutes, hours (unit h), seconds (unit s), or "1:05:00". */
|
||||
function minutes(st: HassEntity | undefined): number | null {
|
||||
if (!st) return null;
|
||||
const s = String(st.state);
|
||||
const m = /^(\d+):(\d{2})(?::(\d{2}))?$/.exec(s);
|
||||
if (m) return Number(m[1]) * 60 + Number(m[2]);
|
||||
const v = Number(s);
|
||||
if (!Number.isFinite(v)) return null;
|
||||
const unit = String(st.attributes.unit_of_measurement ?? "min").toLowerCase();
|
||||
return unit === "h" ? v * 60 : unit === "s" ? v / 60 : unit === "d" ? v * 1440 : v;
|
||||
}
|
||||
|
||||
const ACTIVE = /print|running|busy|druck/;
|
||||
const STATUS_WORDS = ["print_status", "current_stage", "print_state", "printer_state", "current_state", "status", "state"];
|
||||
|
||||
export function readPrinter(hass: HomeAssistant, anchor: string | null): PrinterInfo | null {
|
||||
if (!anchor || !hass.states[anchor]) return null;
|
||||
const all = siblings(hass, anchor);
|
||||
const sensors = all.filter((id) => id.startsWith("sensor."));
|
||||
const st = (id: string | undefined) => (id ? hass.states[id] : undefined);
|
||||
const find = (match: (id: string, s: HassEntity) => boolean) => sensors.find((id) => match(id, hass.states[id]));
|
||||
const unit = (s: HassEntity) => String(s.attributes.unit_of_measurement ?? "");
|
||||
const dc = (s: HassEntity) => String(s.attributes.device_class ?? "");
|
||||
|
||||
const progressId = find((id, s) => unit(s) === "%" && has(id, "progress", "fortschritt", "completion"));
|
||||
if (!progressId) return null;
|
||||
const statusId = STATUS_WORDS.map((w) => find((id, s) => id.endsWith(w) && !Number.isFinite(Number(s.state)))).find(Boolean);
|
||||
const remainingId = find((id) => has(id, "remaining", "time_left", "restzeit", "print_time_left"));
|
||||
const endId = find((id, s) => dc(s) === "timestamp" && has(id, "end", "finish", "estimated", "ende"));
|
||||
const layerId = find((id) => has(id, "current_layer", "layer") && !has(id, "total"));
|
||||
const layersId = find((id) => has(id, "total_layer", "layer_count", "total_layers"));
|
||||
const nozzleId = find((id, s) => dc(s) === "temperature" && has(id, "nozzle", "hotend", "extruder", "tool0", "düse") && !has(id, "target"));
|
||||
const bedId = find((id, s) => dc(s) === "temperature" && has(id, "bed", "heater_bed", "druckbett") && !has(id, "target"));
|
||||
const jobId = find((id) => has(id, "file", "job", "task_name", "gcode", "print_name", "subtask"));
|
||||
const pictureId = all.find((id) => id.startsWith("image.") && has(id, "cover", "model", "thumbnail", "preview")) ?? all.find((id) => id.startsWith("camera.") && has(id, "thumbnail", "preview"));
|
||||
const statusText = String(st(statusId)?.state ?? "").toLowerCase();
|
||||
const progress = num(st(progressId));
|
||||
const printing = statusText ? ACTIVE.test(statusText) && !/finish|complete|idle|fertig/.test(statusText) : (progress ?? 0) > 0 && (progress ?? 0) < 100;
|
||||
const end = st(endId) ? Date.parse(String(st(endId)!.state)) : NaN;
|
||||
const remaining = minutes(st(remainingId));
|
||||
// Bambu: one sensor per AMS tray with its colour ("#RRGGBBAA"), the active one marked
|
||||
const trays = all
|
||||
.map((id) => hass.states[id])
|
||||
.filter((s) => typeof s?.attributes.color === "string" && /^#[0-9a-f]{6}/i.test(String(s.attributes.color)) && has(s.entity_id, "tray", "ams", "filament", "spool", "external"));
|
||||
trays.sort((a, b) => Number(!!b.attributes.active) - Number(!!a.attributes.active));
|
||||
const picture = st(pictureId)?.attributes.entity_picture;
|
||||
return {
|
||||
status: statusText || (printing ? "printing" : "idle"),
|
||||
printing,
|
||||
progress,
|
||||
remaining,
|
||||
endsAt: Number.isFinite(end) ? end : remaining !== null && printing ? Date.now() + remaining * 60_000 : null,
|
||||
layer: num(st(layerId)),
|
||||
layers: num(st(layersId)),
|
||||
nozzle: num(st(nozzleId)),
|
||||
bed: num(st(bedId)),
|
||||
job: st(jobId)?.state && !["unknown", "unavailable", ""].includes(String(st(jobId)!.state)) ? String(st(jobId)!.state) : null,
|
||||
picture: typeof picture === "string" ? picture : null,
|
||||
filaments: [...new Set(trays.map((s) => String(s.attributes.color).slice(0, 7).toLowerCase()))].slice(0, 8),
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether a piece of furniture is a 3D printer (by its pack item's id). */
|
||||
export const isPrinter3d = (type: string): boolean => /printer_(3d|cube|multi|large|open|resin|enclosed)$/.test(type);
|
||||
@@ -0,0 +1,31 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { airingNeed, comfortScore, isSummer, mouldRisk } from "./room-climate.ts";
|
||||
|
||||
test("mould risk grows with humidity at the cold wall", () => {
|
||||
assert.equal(mouldRisk(21, 45), 0, "a dry living room");
|
||||
assert.ok(mouldRisk(18, 70)! > 80, "a cool damp bedroom");
|
||||
assert.ok(mouldRisk(21, 60)! > 20 && mouldRisk(21, 60)! < 70);
|
||||
assert.equal(mouldRisk(null, 60), null);
|
||||
});
|
||||
|
||||
test("when to air a room, and the season", () => {
|
||||
assert.equal(airingNeed(1200, 50, 10), "co2");
|
||||
assert.equal(airingNeed(600, 68, 40), "humidity");
|
||||
assert.equal(airingNeed(600, 68, 90), "mould");
|
||||
assert.equal(airingNeed(600, 50, 0), null);
|
||||
assert.equal(isSummer(new Date(2026, 6, 1)), true);
|
||||
assert.equal(isSummer(new Date(2026, 0, 1)), false);
|
||||
assert.equal(isSummer(new Date(2026, 0, 1), -33), true, "January is summer in Sydney");
|
||||
});
|
||||
|
||||
test("the comfort score: full in the band, one bad value always shows", () => {
|
||||
assert.equal(comfortScore(21.5, 50, 600), 100);
|
||||
assert.equal(comfortScore(null, null, null), null);
|
||||
// 2 °C too cold costs 30
|
||||
assert.equal(comfortScore(18, null, null), 70);
|
||||
// fine air and temperature but 1400 ppm CO₂: never more than 30 above the worst part
|
||||
assert.equal(comfortScore(21, 50, 1400), 30);
|
||||
// 25 °C is fine in summer, not in winter
|
||||
assert.ok(comfortScore(25, 50, null, true)! > comfortScore(25, 50, null, false)!);
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
// Room climate beyond the raw values: the risk of mould on the coldest wall of a room, when to air it, and which temperature scale
|
||||
// fits the season. Pure functions over °C, % and ppm.
|
||||
|
||||
/** Saturation vapour pressure over water (hPa), Magnus formula. */
|
||||
const saturation = (t: number) => 6.112 * Math.exp((17.62 * t) / (243.12 + t));
|
||||
|
||||
/** How much colder than the air the coldest wall surface is (an outer wall in winter, a corner behind a wardrobe). */
|
||||
export const WALL_DROP = 4;
|
||||
|
||||
/**
|
||||
* Mould risk of a room, 0 … 100: the relative humidity the air would have at its coldest wall (`drop` °C colder). Mould grows from
|
||||
* about 70 % at the surface and quickly above 80 %; below 65 % there is none.
|
||||
*/
|
||||
export function mouldRisk(temp: number | null, humidity: number | null, drop = WALL_DROP): number | null {
|
||||
if (temp === null || humidity === null) return null;
|
||||
const surface = Math.min(100, (humidity * saturation(temp)) / saturation(temp - drop));
|
||||
return Math.round(Math.min(100, Math.max(0, ((surface - 65) / (85 - 65)) * 100)));
|
||||
}
|
||||
|
||||
/** Why a room should be aired, if it should: too much CO₂, too damp, or both (null: all fine). */
|
||||
export function airingNeed(co2: number | null, humidity: number | null, risk: number | null): "co2" | "humidity" | "mould" | null {
|
||||
if (risk !== null && risk >= 70) return "mould";
|
||||
if (co2 !== null && co2 >= 1000) return "co2";
|
||||
if (humidity !== null && humidity >= 65) return "humidity";
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Summer from May to September (in the southern hemisphere the other way round): rooms may be warmer before they count as hot. */
|
||||
export function isSummer(now = new Date(), latitude = 50): boolean {
|
||||
const m = now.getMonth();
|
||||
const north = m >= 4 && m <= 8;
|
||||
return latitude < 0 ? !north : north;
|
||||
}
|
||||
|
||||
/**
|
||||
* How comfortable a room is, 0 … 100, from what its sensors say: the temperature in its band (20–23 °C, 22–26 °C in summer), the
|
||||
* humidity between 40 and 60 %, CO₂ up to 800 ppm. The average of the parts that are known, but never more than 30 above the worst,
|
||||
* so one bad value always shows. Null without any reading.
|
||||
*/
|
||||
export function comfortScore(temp: number | null, humidity: number | null, co2: number | null, summer = false): number | null {
|
||||
const parts: number[] = [];
|
||||
if (temp !== null) {
|
||||
const [lo, hi] = summer ? [22, 26] : [20, 23];
|
||||
const off = temp < lo ? lo - temp : temp > hi ? temp - hi : 0;
|
||||
parts.push(Math.max(0, 100 - off * 15));
|
||||
}
|
||||
if (humidity !== null) {
|
||||
const off = humidity < 40 ? 40 - humidity : humidity > 60 ? humidity - 60 : 0;
|
||||
parts.push(Math.max(0, 100 - off * 4));
|
||||
}
|
||||
if (co2 !== null) parts.push(Math.max(0, Math.min(100, 100 - ((co2 - 800) / 600) * 100)));
|
||||
if (!parts.length) return null;
|
||||
const mean = parts.reduce((a, b) => a + b, 0) / parts.length;
|
||||
return Math.round(Math.min(mean, Math.min(...parts) + 30));
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { energyCost, monthStart, roomEnergyFromStats } from "./room-energy.ts";
|
||||
import { dayStart } from "./week-bars.ts";
|
||||
|
||||
test("today and the month come from the daily mean power of the room's sensors", () => {
|
||||
const now = new Date(2026, 10, 3, 12, 0).getTime();
|
||||
const iso = (t: number) => new Date(t).toISOString();
|
||||
const stats = {
|
||||
"sensor.tv": [
|
||||
{ start: iso(dayStart(now, 2)), mean: 100 },
|
||||
{ start: iso(dayStart(now, 1)), mean: 50 },
|
||||
{ start: iso(dayStart(now)), mean: 200 },
|
||||
],
|
||||
"sensor.lamp": [{ start: iso(dayStart(now)), mean: -5 }],
|
||||
};
|
||||
const e = roomEnergyFromStats(stats, ["sensor.tv", "sensor.lamp"], now)!;
|
||||
// today: 200 W for the 12 hours gone; the month: 2.4 + 1.2 + 2.4 kWh
|
||||
assert.equal(e.today, 2.4);
|
||||
assert.equal(e.month, 6);
|
||||
assert.equal(roomEnergyFromStats({}, ["sensor.tv"], now), null);
|
||||
assert.equal(new Date(monthStart(now)).getDate(), 1);
|
||||
});
|
||||
|
||||
test("the cost follows the tariff's unit", () => {
|
||||
assert.deepEqual(energyCost(10, { value: 0.31, unit: "EUR/kWh" }), { value: 3.1, currency: "€" });
|
||||
assert.deepEqual(energyCost(10, { value: 31, unit: "ct/kWh" }), { value: 3.1, currency: "€" });
|
||||
assert.deepEqual(energyCost(10, { value: 0.25, unit: "CHF/kWh" }), { value: 2.5, currency: "CHF" });
|
||||
assert.equal(energyCost(10, { value: 5, unit: "W" }), null);
|
||||
assert.equal(energyCost(10, null), null);
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
// What a room used today and this month: from Home Assistant's long-term statistics of the power sensors of its devices (their daily
|
||||
// mean × the hours of the day), one small request per room panel opening; and what it cost with the house's tariff.
|
||||
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { dayStart } from "./week-bars.ts";
|
||||
|
||||
export interface RoomEnergy {
|
||||
/** kWh used today so far, and since the first of the month. */
|
||||
today: number;
|
||||
month: number;
|
||||
}
|
||||
|
||||
type Stats = Record<string, { start: number | string; mean?: number | null }[]>;
|
||||
|
||||
const DAY = 86_400_000;
|
||||
const HOUR = 3_600_000;
|
||||
|
||||
/** Midnight of the first of the month `now` falls in. */
|
||||
export function monthStart(now: number): number {
|
||||
const d = new Date(dayStart(now));
|
||||
d.setDate(1);
|
||||
return d.getTime();
|
||||
}
|
||||
|
||||
/** kWh today and this month from the daily mean power (W) of the sensors; today counts the hours gone so far. Null without data. */
|
||||
export function roomEnergyFromStats(stats: Stats, ids: readonly string[], now: number): RoomEnergy | null {
|
||||
const today = dayStart(now);
|
||||
let [day, month, any] = [0, 0, false];
|
||||
for (const id of ids) {
|
||||
for (const row of stats[id] ?? []) {
|
||||
if (typeof row.mean !== "number") continue;
|
||||
const start = new Date(row.start).getTime();
|
||||
const hours = Math.min(24, Math.max(0, (Math.min(now, start + DAY) - start) / HOUR));
|
||||
const kwh = (Math.max(0, row.mean) * hours) / 1000;
|
||||
month += kwh;
|
||||
if (Math.abs(start - today) < 3 * HOUR) day += kwh;
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
const round = (v: number) => Math.round(v * 100) / 100;
|
||||
return any ? { today: round(day), month: round(month) } : null;
|
||||
}
|
||||
|
||||
export async function loadRoomEnergy(hass: HomeAssistant, ids: readonly string[], now = Date.now()): Promise<RoomEnergy | null> {
|
||||
if (!ids.length) return null;
|
||||
const stats = await hass.callWS<Stats>({
|
||||
type: "recorder/statistics_during_period",
|
||||
start_time: new Date(monthStart(now)).toISOString(),
|
||||
end_time: new Date(now).toISOString(),
|
||||
statistic_ids: [...ids],
|
||||
period: "day",
|
||||
types: ["mean"],
|
||||
units: { power: "W" },
|
||||
});
|
||||
return roomEnergyFromStats(stats, ids, now);
|
||||
}
|
||||
|
||||
/** The cost of some kWh with a tariff state ("0.31" in "EUR/kWh", "ct/kWh" …); null when the tariff is not per kWh. */
|
||||
export function energyCost(kwh: number, tariff: { value: number; unit: string } | null): { value: number; currency: string } | null {
|
||||
if (!tariff || !Number.isFinite(tariff.value)) return null;
|
||||
const m = /^\s*([^/\s]+)\s*\/\s*kWh\s*$/i.exec(tariff.unit);
|
||||
if (!m) return null;
|
||||
const cents = /^(ct|cent|cents|c)$/i.test(m[1]);
|
||||
const currency = cents || /^eur$/i.test(m[1]) ? "€" : m[1];
|
||||
return { value: Math.round(kwh * tariff.value * (cents ? 1 : 100)) / 100, currency };
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { bearing, chosenEffects, readSkyWeather, windKmh, withDensity } from "./sky-weather.ts";
|
||||
|
||||
function hassWith(state: string, attributes: Record<string, unknown> = {}): HomeAssistant {
|
||||
return {
|
||||
language: "de",
|
||||
connection: {} as HomeAssistant["connection"],
|
||||
callWS: async () => undefined as never,
|
||||
callService: async () => undefined,
|
||||
areas: {},
|
||||
devices: {},
|
||||
entities: {},
|
||||
states: { "weather.home": { entity_id: "weather.home", state, attributes } },
|
||||
};
|
||||
}
|
||||
|
||||
test("each condition has a look; missing or unknown states give no weather", () => {
|
||||
const rain = readSkyWeather(hassWith("pouring"), "weather.home")!;
|
||||
assert.equal(rain.rain, 1);
|
||||
assert.ok(rain.cloud >= 0.9);
|
||||
assert.equal(readSkyWeather(hassWith("lightning-rainy"), "weather.home")!.lightning, true);
|
||||
assert.equal(readSkyWeather(hassWith("hail"), "weather.home")!.hail > 0, true);
|
||||
assert.equal(readSkyWeather(hassWith("unavailable"), "weather.home"), null);
|
||||
assert.equal(readSkyWeather(hassWith("sunny"), null), null);
|
||||
assert.equal(readSkyWeather(hassWith("something-new"), "weather.home"), null);
|
||||
});
|
||||
|
||||
test("cloud coverage, wind speed, gusts and bearing refine the look", () => {
|
||||
const w = readSkyWeather(hassWith("partlycloudy", { cloud_coverage: 70, wind_speed: 10, wind_speed_unit: "m/s", wind_bearing: 225 }), "weather.home")!;
|
||||
assert.equal(w.cloud, 0.7);
|
||||
assert.ok(Math.abs(w.wind - 36 / 70) < 1e-9);
|
||||
assert.equal(w.windFrom, 225);
|
||||
const gusty = readSkyWeather(hassWith("sunny", { wind_speed: 5, wind_gust_speed: 90 }), "weather.home")!;
|
||||
assert.ok(gusty.wind >= 0.9);
|
||||
// rain under a clear sky report still comes with clouds
|
||||
assert.ok(readSkyWeather(hassWith("rainy", { cloud_coverage: 10 }), "weather.home")!.cloud >= 0.6);
|
||||
});
|
||||
|
||||
test("rain below freezing becomes sleet, heavy precipitation more streaks", () => {
|
||||
const sleet = readSkyWeather(hassWith("rainy", { temperature: -1 }), "weather.home")!;
|
||||
assert.ok(sleet.snow > 0 && sleet.rain < 0.5);
|
||||
const fahrenheit = readSkyWeather(hassWith("rainy", { temperature: 30, temperature_unit: "°F" }), "weather.home")!;
|
||||
assert.ok(fahrenheit.snow > 0);
|
||||
assert.equal(readSkyWeather(hassWith("rainy", { temperature: 12 }), "weather.home")!.snow, 0);
|
||||
assert.equal(readSkyWeather(hassWith("rainy", { precipitation: 8 }), "weather.home")!.rain, 1);
|
||||
});
|
||||
|
||||
test("units and compass bearings", () => {
|
||||
assert.equal(windKmh(10, "m/s"), 36);
|
||||
assert.ok(Math.abs(windKmh(10, "kn") - 18.52) < 1e-9);
|
||||
assert.equal(windKmh(20, "km/h"), 20);
|
||||
assert.equal(bearing("NW"), 315);
|
||||
assert.equal(bearing("SO"), 135);
|
||||
assert.equal(bearing(-90), 270);
|
||||
assert.equal(bearing("x"), null);
|
||||
});
|
||||
|
||||
test("only the chosen effects stay", () => {
|
||||
const storm = readSkyWeather(hassWith("lightning-rainy"), "weather.home")!;
|
||||
const only = chosenEffects({ ...storm, fog: 0.5 }, ["clouds"]);
|
||||
assert.equal(only.rain, 0);
|
||||
assert.equal(only.lightning, false);
|
||||
assert.equal(only.fog, 0);
|
||||
assert.ok(only.cloud > 0);
|
||||
assert.equal(chosenEffects({ ...storm, fog: 0.5 }, null).fog, 0);
|
||||
});
|
||||
|
||||
test("the density thins out rain, hail and snow, and leaves clouds and lightning alone", () => {
|
||||
const storm = readSkyWeather(hassWith("lightning-rainy"), "weather.home")!;
|
||||
const thin = withDensity(storm, 0.3);
|
||||
assert.equal(thin.rain, storm.rain * 0.3);
|
||||
assert.equal(thin.snow, storm.snow * 0.3);
|
||||
assert.equal(thin.cloud, storm.cloud);
|
||||
assert.equal(thin.lightning, storm.lightning);
|
||||
assert.equal(withDensity(storm, 1), storm);
|
||||
assert.equal(withDensity(storm, undefined), storm);
|
||||
// out of range: never less than a tenth, never more than the weather says
|
||||
assert.equal(withDensity(storm, 0).rain, storm.rain * 0.1);
|
||||
assert.equal(withDensity(storm, 5), storm);
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* Reads a Home Assistant `weather.*` entity into what NextFloor's weather layer draws (see viewer/live-weather.ts).
|
||||
*
|
||||
* The condition gives the kind of weather; the entity's attributes refine it where they exist: cloud coverage,
|
||||
* wind speed and bearing (rain and snow fall at an angle along the real wind), precipitation (more rain, more
|
||||
* streaks) and temperature (rain below freezing turns into sleet).
|
||||
*/
|
||||
import type { WeatherEffect } from "../model.ts";
|
||||
import type { SkyWeather } from "../viewer/live-weather.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
|
||||
type Base = Partial<Omit<SkyWeather, "windFrom">>;
|
||||
|
||||
/** What each of Home Assistant's conditions looks like before the attributes refine it. */
|
||||
const LOOK: Record<string, Base> = {
|
||||
sunny: { cloud: 0 },
|
||||
"clear-night": { cloud: 0 },
|
||||
partlycloudy: { cloud: 0.4 },
|
||||
cloudy: { cloud: 0.85 },
|
||||
fog: { fog: 0.9, cloud: 0.5 },
|
||||
rainy: { rain: 0.5, cloud: 0.8 },
|
||||
pouring: { rain: 1, cloud: 1, wind: 0.3 },
|
||||
"lightning-rainy": { rain: 0.75, cloud: 1, lightning: true, wind: 0.35 },
|
||||
lightning: { cloud: 0.85, lightning: true },
|
||||
hail: { hail: 0.8, rain: 0.3, cloud: 1 },
|
||||
snowy: { snow: 0.7, cloud: 0.85 },
|
||||
"snowy-rainy": { snow: 0.45, rain: 0.3, cloud: 0.95 },
|
||||
windy: { wind: 0.7, cloud: 0.25 },
|
||||
"windy-variant": { wind: 0.7, cloud: 0.65 },
|
||||
exceptional: { cloud: 0.6, wind: 0.5 },
|
||||
};
|
||||
|
||||
const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v)) ? Number(v) : null);
|
||||
const clamp = (v: number) => Math.min(1, Math.max(0, v));
|
||||
|
||||
/** Wind speed in km/h from the entity's value and unit. */
|
||||
export function windKmh(speed: number, unit: unknown): number {
|
||||
switch (unit) {
|
||||
case "m/s":
|
||||
return speed * 3.6;
|
||||
case "mph":
|
||||
return speed * 1.609;
|
||||
case "kn":
|
||||
return speed * 1.852;
|
||||
case "ft/s":
|
||||
return speed * 1.097;
|
||||
default:
|
||||
return speed;
|
||||
}
|
||||
}
|
||||
|
||||
/** A wind bearing: degrees, or a compass point such as "NW". */
|
||||
export function bearing(v: unknown): number | null {
|
||||
const n = num(v);
|
||||
if (n !== null) return ((n % 360) + 360) % 360;
|
||||
if (typeof v !== "string") return null;
|
||||
const points = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"];
|
||||
const i = points.indexOf(v.trim().toUpperCase().replace("O", "E"));
|
||||
return i < 0 ? null : i * 22.5;
|
||||
}
|
||||
|
||||
/** The weather to draw from an entity, or null when it is missing or reports nothing usable. */
|
||||
export function readSkyWeather(hass: HomeAssistant, entity: string | null): SkyWeather | null {
|
||||
const st = entity ? hass.states[entity] : undefined;
|
||||
if (!st || st.state === "unavailable" || st.state === "unknown") return null;
|
||||
const look = LOOK[st.state];
|
||||
if (!look) return null;
|
||||
const a = st.attributes as Record<string, unknown>;
|
||||
const w: SkyWeather = {
|
||||
rain: look.rain ?? 0,
|
||||
snow: look.snow ?? 0,
|
||||
hail: look.hail ?? 0,
|
||||
fog: look.fog ?? 0,
|
||||
cloud: look.cloud ?? 0,
|
||||
wind: look.wind ?? 0,
|
||||
windFrom: bearing(a.wind_bearing),
|
||||
lightning: look.lightning ?? false,
|
||||
};
|
||||
const coverage = num(a.cloud_coverage);
|
||||
if (coverage !== null) w.cloud = Math.max(clamp(coverage / 100), w.rain || w.snow ? 0.6 : 0);
|
||||
const speed = num(a.wind_speed);
|
||||
if (speed !== null) w.wind = Math.max(w.wind, clamp(windKmh(speed, a.wind_speed_unit) / 70));
|
||||
const gust = num(a.wind_gust_speed);
|
||||
if (gust !== null) w.wind = Math.max(w.wind, clamp(windKmh(gust, a.wind_speed_unit) / 100));
|
||||
// more rain per hour, denser streaks (only when the entity reports it for now)
|
||||
const precip = num(a.precipitation);
|
||||
if (precip !== null && precip > 0 && (w.rain > 0 || w.snow > 0)) {
|
||||
const strength = clamp(0.25 + precip / 8);
|
||||
if (w.rain > 0) w.rain = Math.max(w.rain * 0.6, strength);
|
||||
if (w.snow > 0) w.snow = Math.max(w.snow * 0.6, strength);
|
||||
}
|
||||
// below freezing, rain comes down as sleet: some of it snow
|
||||
const temp = num(a.temperature);
|
||||
const unit = a.temperature_unit ?? hass.config?.unit_system?.temperature;
|
||||
const celsius = temp === null ? null : unit === "°F" ? ((temp - 32) * 5) / 9 : temp;
|
||||
if (celsius !== null && celsius <= 0.5 && w.rain > 0 && w.snow === 0) {
|
||||
w.snow = w.rain * 0.6;
|
||||
w.rain *= 0.4;
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
/** Fewer drops and flakes: rain, hail and snow scaled by a density (0.1 … 1); clouds, fog and lightning stay. */
|
||||
export function withDensity(w: SkyWeather, density: number | null | undefined): SkyWeather {
|
||||
const d = density == null || !Number.isFinite(density) ? 1 : Math.min(1, Math.max(0.1, density));
|
||||
return d === 1 ? w : { ...w, rain: w.rain * d, hail: w.hail * d, snow: w.snow * d };
|
||||
}
|
||||
|
||||
/** Keeps only the effects chosen in the settings (null = the default set: all but fog). */
|
||||
export function chosenEffects(w: SkyWeather, effects: readonly WeatherEffect[] | null | undefined): SkyWeather {
|
||||
const on = new Set<string>(effects ?? ["rain", "snow", "clouds", "lightning", "sky"]);
|
||||
return {
|
||||
...w,
|
||||
rain: on.has("rain") ? w.rain : 0,
|
||||
hail: on.has("rain") ? w.hail : 0,
|
||||
snow: on.has("snow") ? w.snow : 0,
|
||||
fog: on.has("fog") ? w.fog : 0,
|
||||
cloud: on.has("clouds") ? w.cloud : 0,
|
||||
lightning: on.has("lightning") && w.lightning,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, floorWith, opening } from "../entities/fixtures.ts";
|
||||
import { emptyBuilding } from "../model.ts";
|
||||
import { compassOf, roomSun, roomSunYear, sunnyWindowsNow } from "./sun-hours.ts";
|
||||
|
||||
const BERLIN = { latitude: 52.5, longitude: 13.4, zone: "Europe/Berlin" };
|
||||
|
||||
function house(edge: number, north = 0) {
|
||||
const room = box("r", 0, 0, 4, 3);
|
||||
const floor = { ...floorWith([room]), openings: [opening("w", "r", "window", { edge, offset: edge % 2 ? 1.5 : 2 })] };
|
||||
const b = { ...emptyBuilding(), floors: [floor] };
|
||||
b.settings = { ...b.settings, north };
|
||||
return { b, floor, room };
|
||||
}
|
||||
|
||||
test("a south window gets the most sun in winter, a north window only summer mornings and evenings", () => {
|
||||
const south = house(2);
|
||||
const north = house(0);
|
||||
const winter = new Date("2026-12-21T12:00:00Z");
|
||||
const summer = new Date("2026-06-21T12:00:00Z");
|
||||
const s = roomSun(south.b, south.floor, south.room, BERLIN, winter);
|
||||
assert.deepEqual(s.facing, ["S"]);
|
||||
assert.ok(s.hours > 6 && s.hours < 8.5, `south in December: ${s.hours}`);
|
||||
assert.equal(roomSun(north.b, north.floor, north.room, BERLIN, winter).hours, 0);
|
||||
const n = roomSun(north.b, north.floor, north.room, BERLIN, summer);
|
||||
assert.ok(n.hours > 1 && n.hours < 6, `north in June: ${n.hours}`);
|
||||
// in June the sun stands north of east and west in the morning and evening: about 8½ hours on the south side
|
||||
assert.ok(roomSun(south.b, south.floor, south.room, BERLIN, summer).hours > 8);
|
||||
});
|
||||
|
||||
test("the plan's north turns the compass", () => {
|
||||
assert.equal(compassOf([0, -1], 0), "N");
|
||||
assert.equal(compassOf([1, 0], 0), "E");
|
||||
// north pointing to the right of the plan: "up" is west
|
||||
assert.equal(compassOf([0, -1], 90), "W");
|
||||
const turned = house(0, 180);
|
||||
assert.deepEqual(roomSun(turned.b, turned.floor, turned.room, BERLIN).facing, ["S"]);
|
||||
});
|
||||
|
||||
test("a room without outside windows has no sun", () => {
|
||||
const { b, floor, room } = house(0);
|
||||
floor.openings = [];
|
||||
assert.deepEqual(roomSun(b, floor, room, BERLIN), { hours: 0, facing: [] });
|
||||
});
|
||||
|
||||
test("over the year a north room gets sun only around midsummer", () => {
|
||||
const { b, floor, room } = house(0);
|
||||
const year = roomSunYear(b, floor, room, BERLIN, 2026);
|
||||
assert.equal(year.length, 12);
|
||||
assert.equal(year[11], 0);
|
||||
assert.ok(year[5] > year[2] && year[5] > year[8]);
|
||||
});
|
||||
|
||||
test("the sun stands on a south window at noon, never on a north one, and on none at night", () => {
|
||||
const noon = new Date("2026-07-15T11:00:00Z");
|
||||
const south = house(2);
|
||||
const north = house(0);
|
||||
assert.deepEqual(sunnyWindowsNow(south.b, south.floor, south.room, BERLIN, noon).map((o) => o.id), ["w"]);
|
||||
assert.deepEqual(sunnyWindowsNow(north.b, north.floor, north.room, BERLIN, noon), []);
|
||||
assert.deepEqual(sunnyWindowsNow(south.b, south.floor, south.room, BERLIN, new Date("2026-07-15T23:00:00Z")), []);
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
// Sun in the rooms: how many hours of a day the sun shines in through a room's outside windows, worked out from the plan, its
|
||||
// compass and the sun's path at the home's place. Neighbours, trees and the overhang of the roof are not counted.
|
||||
|
||||
import { generateWalls, locateOpening, openingHost, type Wall } from "../geometry/walls.ts";
|
||||
import type { Building, Floor, Opening, Room } from "../model.ts";
|
||||
import { sunPosition, todayAt } from "../sun-position.ts";
|
||||
|
||||
const DEG = Math.PI / 180;
|
||||
/** The sun has to stand this high to shine in (degrees), and this square onto the window (cosine of the angle). */
|
||||
const MIN_ELEVATION = 3;
|
||||
const MIN_FACING = 0.1;
|
||||
const STEP_HOURS = 1 / 6;
|
||||
|
||||
export interface RoomSun {
|
||||
/** Hours of sun through at least one window. */
|
||||
hours: number;
|
||||
/** The compass directions the room's outside windows look to ("S", "SW" …), each once. */
|
||||
facing: string[];
|
||||
}
|
||||
|
||||
/** The horizontal direction towards the sun in plan coordinates (x right, z down, "up" is -z), like the 3D view. */
|
||||
const toSun = (azimuth: number, north: number): [number, number] => [Math.sin((north + azimuth) * DEG), -Math.cos((north + azimuth) * DEG)];
|
||||
|
||||
const COMPASS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
|
||||
|
||||
/** The outward directions of a room's windows in outside walls, in plan coordinates. */
|
||||
export function windowNormals(floor: Floor, room: Room, walls: readonly Wall[]): [number, number][] {
|
||||
return outsideWindows(floor, room, walls).map((w) => w.normal);
|
||||
}
|
||||
|
||||
/** A room's windows (and glass doors) in outside walls, each with the direction it looks to. */
|
||||
export function outsideWindows(floor: Floor, room: Room, walls: readonly Wall[]): { opening: Opening; normal: [number, number] }[] {
|
||||
const out: { opening: Opening; normal: [number, number] }[] = [];
|
||||
for (const o of floor.openings) {
|
||||
if (o.room_id !== room.id || o.type === "garage") continue;
|
||||
const host = openingHost(o, floor.rooms, floor.walls ?? []);
|
||||
const at = host ? locateOpening(walls, o, host) : null;
|
||||
if (!at || !at.wall.exterior) continue;
|
||||
const { wall } = at;
|
||||
const len = Math.hypot(wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]);
|
||||
if (len < 1e-6) continue;
|
||||
// the room lies on the wall's left (its normal (-dz, dx)); the window looks the other way
|
||||
const left: [number, number] = [-(wall.b[1] - wall.a[1]) / len, (wall.b[0] - wall.a[0]) / len];
|
||||
const intoRoom = wall.roomLeft === room.id ? left : ([-left[0], -left[1]] as [number, number]);
|
||||
out.push({ opening: o, normal: [-intoRoom[0], -intoRoom[1]] });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The compass word of an outward direction in the plan, with the plan's north. */
|
||||
export function compassOf(dir: readonly [number, number], north: number): string {
|
||||
// plan "up" is -z; the bearing is clockwise from the plan's up, then turned by north
|
||||
const bearing = (((Math.atan2(dir[0], -dir[1]) / DEG - north) % 360) + 360) % 360;
|
||||
return COMPASS[Math.round(bearing / 45) % 8];
|
||||
}
|
||||
|
||||
const wallMemo = new WeakMap<Floor, Wall[]>();
|
||||
function wallsOf(b: Building, floor: Floor): Wall[] {
|
||||
let walls = wallMemo.get(floor);
|
||||
if (!walls) {
|
||||
walls = generateWalls(floor.rooms, { exterior: b.settings.wall_exterior, interior: b.settings.wall_interior }, floor.walls ?? []).walls;
|
||||
wallMemo.set(floor, walls);
|
||||
}
|
||||
return walls;
|
||||
}
|
||||
|
||||
/** Results per floor object (a new plan state is a new object) and day: the room panel and the heat map ask on every state change. */
|
||||
const sunMemo = new WeakMap<Floor, Map<string, RoomSun>>();
|
||||
|
||||
/** Hours of sun of a room on the day of `date` at the home's place (latitude, longitude, time zone). */
|
||||
export function roomSun(b: Building, floor: Floor, room: Room, place: { latitude: number; longitude: number; zone?: string | null }, date = new Date()): RoomSun {
|
||||
const key = `${room.id}|${date.toISOString().slice(0, 10)}|${b.settings.north ?? 0}|${place.latitude},${place.longitude},${place.zone ?? ""}`;
|
||||
let known = sunMemo.get(floor);
|
||||
if (!known) sunMemo.set(floor, (known = new Map()));
|
||||
const hit = known.get(key);
|
||||
if (hit) return hit;
|
||||
const result = computeRoomSun(b, floor, room, place, date);
|
||||
known.set(key, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
function computeRoomSun(b: Building, floor: Floor, room: Room, place: { latitude: number; longitude: number; zone?: string | null }, date: Date): RoomSun {
|
||||
const north = b.settings.north ?? 0;
|
||||
const normals = windowNormals(floor, room, wallsOf(b, floor));
|
||||
const facing = [...new Set(normals.map((n) => compassOf(n, north)))];
|
||||
if (!normals.length) return { hours: 0, facing };
|
||||
let steps = 0;
|
||||
for (let h = STEP_HOURS / 2; h < 24; h += STEP_HOURS) {
|
||||
const sun = sunPosition(todayAt(h, place.zone, date), place.latitude, place.longitude);
|
||||
if (sun.elevation < MIN_ELEVATION) continue;
|
||||
const s = toSun(sun.azimuth, north);
|
||||
// the cosine of the angle between the window's outward direction and the sun, on the ground plane
|
||||
if (normals.some((n) => n[0] * s[0] + n[1] * s[1] > MIN_FACING)) steps++;
|
||||
}
|
||||
return { hours: Math.round(steps * STEP_HOURS * 10) / 10, facing };
|
||||
}
|
||||
|
||||
/** Hours of sun of a room on the 15th of every month of `year` (January first), for the curve over the year. */
|
||||
export function roomSunYear(b: Building, floor: Floor, room: Room, place: { latitude: number; longitude: number; zone?: string | null }, year = new Date().getFullYear()): number[] {
|
||||
return Array.from({ length: 12 }, (_, month) => roomSun(b, floor, room, place, new Date(Date.UTC(year, month, 15, 12))).hours);
|
||||
}
|
||||
|
||||
/** The room's outside windows the sun shines on right now (none at night or with the sun low). */
|
||||
export function sunnyWindowsNow(b: Building, floor: Floor, room: Room, place: { latitude: number; longitude: number }, now = new Date()): Opening[] {
|
||||
const sun = sunPosition(now, place.latitude, place.longitude);
|
||||
if (sun.elevation < MIN_ELEVATION) return [];
|
||||
const s = toSun(sun.azimuth, b.settings.north ?? 0);
|
||||
return outsideWindows(floor, room, wallsOf(b, floor))
|
||||
.filter((w) => w.normal[0] * s[0] + w.normal[1] * s[1] > MIN_FACING)
|
||||
.map((w) => w.opening);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { changeAt, changeMoments, hassAt, parseHistory, replayable } from "./time-travel.ts";
|
||||
|
||||
const raw = {
|
||||
"light.kitchen": [
|
||||
{ s: "off", a: { friendly_name: "Kitchen" }, lu: 1000 },
|
||||
{ s: "on", a: { friendly_name: "Kitchen", brightness: 200 }, lu: 1100 },
|
||||
{ s: "off", lu: 1200 },
|
||||
],
|
||||
"binary_sensor.door": [{ s: "off", a: { device_class: "door" }, lu: 900 }, { s: "on", lu: 1150 }],
|
||||
};
|
||||
|
||||
test("the recorder's answer becomes sorted changes; attributes carry on until they change", () => {
|
||||
const h = parseHistory(raw);
|
||||
const kitchen = h.get("light.kitchen")!;
|
||||
assert.deepEqual(kitchen.map((c) => [c.t, c.state]), [[1_000_000, "off"], [1_100_000, "on"], [1_200_000, "off"]]);
|
||||
assert.equal(kitchen[2].attributes.brightness, 200);
|
||||
});
|
||||
|
||||
test("the state at a moment is the last change before it", () => {
|
||||
const kitchen = parseHistory(raw).get("light.kitchen")!;
|
||||
assert.equal(changeAt(kitchen, 999_999), null);
|
||||
assert.equal(changeAt(kitchen, 1_150_000)?.state, "on");
|
||||
assert.equal(changeAt(kitchen, 5_000_000)?.state, "off");
|
||||
});
|
||||
|
||||
test("hass at a moment shows the replayed entities as they were and leaves the rest alone", () => {
|
||||
const hass = { states: { "light.kitchen": { entity_id: "light.kitchen", state: "off", attributes: { friendly_name: "Kitchen", icon: "mdi:x" } }, "sensor.t": { entity_id: "sensor.t", state: "21", attributes: {} } } } as unknown as HomeAssistant;
|
||||
const then = hassAt(hass, parseHistory(raw), 1_150_000);
|
||||
assert.equal(then.states["light.kitchen"].state, "on");
|
||||
assert.equal(then.states["light.kitchen"].attributes.icon, "mdi:x", "attributes the history lacks stay");
|
||||
assert.equal(then.states["binary_sensor.door"].state, "on");
|
||||
assert.equal(then.states["sensor.t"].state, "21");
|
||||
assert.equal(hass.states["light.kitchen"].state, "off", "the live states are not touched");
|
||||
});
|
||||
|
||||
test("the timeline marks every change of state inside the span", () => {
|
||||
const h = parseHistory(raw);
|
||||
assert.deepEqual(changeMoments(h, 0, 2_000_000), [1_100_000, 1_150_000, 1_200_000]);
|
||||
assert.deepEqual(changeMoments(h, 1_120_000, 2_000_000), [1_150_000, 1_200_000]);
|
||||
assert.equal(changeMoments(h, 0, 2_000_000, 2).length, 2);
|
||||
});
|
||||
|
||||
test("only what switches, opens or moves is replayed", () => {
|
||||
assert.deepEqual(replayable(["light.a", "sensor.temp", "cover.b", "light.a", "binary_sensor.c", "weather.home"]), ["light.a", "cover.b", "binary_sensor.c"]);
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
// Time travel: the house as it was at an earlier moment, from Home Assistant's recorder. The history of the entities the 3D view shows
|
||||
// is loaded once for the chosen span; at any moment the view is fed a copy of hass whose states are the ones of that moment, so
|
||||
// lamps, blinds, doors and robots replay with the same code that shows them live.
|
||||
|
||||
import type { HassEntity, HomeAssistant } from "../types.ts";
|
||||
|
||||
/** The kinds of entities worth replaying: what switches, moves or opens. Sensors with values change too often to be useful. */
|
||||
const REPLAY = /^(light|switch|cover|binary_sensor|lock|media_player|vacuum|fan|climate|lawn_mower|input_boolean|person|device_tracker|alarm_control_panel)\./;
|
||||
const MAX_ENTITIES = 200;
|
||||
|
||||
export interface Change {
|
||||
/** Milliseconds since 1970. */
|
||||
t: number;
|
||||
state: string;
|
||||
attributes: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export type History = Map<string, Change[]>;
|
||||
|
||||
interface CompressedState {
|
||||
s: string;
|
||||
a?: Record<string, unknown>;
|
||||
/** Last changed / last updated, in seconds since 1970. */
|
||||
lc?: number;
|
||||
lu: number;
|
||||
}
|
||||
|
||||
/** The entities of the view that are replayed. */
|
||||
export const replayable = (ids: Iterable<string>): string[] => [...new Set([...ids].filter((id) => REPLAY.test(id)))].slice(0, MAX_ENTITIES);
|
||||
|
||||
/** Turns the recorder's compressed answer into sorted changes per entity; attributes carry on until they change. */
|
||||
export function parseHistory(raw: Record<string, CompressedState[]>): History {
|
||||
const out: History = new Map();
|
||||
for (const [id, list] of Object.entries(raw)) {
|
||||
let attributes: Record<string, unknown> = {};
|
||||
const changes: Change[] = [];
|
||||
for (const row of list) {
|
||||
if (row.a) attributes = row.a;
|
||||
changes.push({ t: Math.round((row.lu ?? row.lc ?? 0) * 1000), state: row.s, attributes });
|
||||
}
|
||||
changes.sort((p, q) => p.t - q.t);
|
||||
out.set(id, changes);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Loads the history of the replayed entities between two moments (ms). */
|
||||
export async function loadHistory(hass: HomeAssistant, ids: readonly string[], from: number, to: number, minimal = false): Promise<History> {
|
||||
if (ids.length === 0) return new Map();
|
||||
const raw = await hass.callWS<Record<string, CompressedState[]>>({
|
||||
type: "history/history_during_period",
|
||||
start_time: new Date(from).toISOString(),
|
||||
end_time: new Date(to).toISOString(),
|
||||
entity_ids: ids,
|
||||
include_start_time_state: true,
|
||||
significant_changes_only: false,
|
||||
// values only (day curves) or every attribute (time travel replays colours and positions)
|
||||
minimal_response: minimal,
|
||||
no_attributes: minimal,
|
||||
});
|
||||
return parseHistory(raw);
|
||||
}
|
||||
|
||||
/** The change in effect at moment t: the last one at or before it (null before the first). */
|
||||
export function changeAt(changes: readonly Change[], t: number): Change | null {
|
||||
let [lo, hi] = [0, changes.length - 1];
|
||||
let found: Change | null = null;
|
||||
while (lo <= hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if (changes[mid].t <= t) {
|
||||
found = changes[mid];
|
||||
lo = mid + 1;
|
||||
} else hi = mid - 1;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** A copy of hass whose replayed entities show their state at moment t; everything else stays as it is now. */
|
||||
export function hassAt(hass: HomeAssistant, history: History, t: number): HomeAssistant {
|
||||
const states: Record<string, HassEntity> = { ...hass.states };
|
||||
for (const [id, changes] of history) {
|
||||
const c = changeAt(changes, t);
|
||||
if (!c) continue;
|
||||
const now = hass.states[id];
|
||||
states[id] = { ...(now ?? { entity_id: id }), entity_id: id, state: c.state, attributes: { ...(now?.attributes ?? {}), ...c.attributes } } as HassEntity;
|
||||
}
|
||||
return { ...hass, states };
|
||||
}
|
||||
|
||||
/** The moments something switched, opened or moved, for the marks on the timeline (at most `max`, spread evenly). */
|
||||
export function changeMoments(history: History, from: number, to: number, max = 400): number[] {
|
||||
const moments: number[] = [];
|
||||
for (const changes of history.values()) {
|
||||
for (let i = 1; i < changes.length; i++) {
|
||||
if (changes[i].state !== changes[i - 1].state && changes[i].t >= from && changes[i].t <= to) moments.push(changes[i].t);
|
||||
}
|
||||
}
|
||||
moments.sort((a, b) => a - b);
|
||||
if (moments.length <= max) return moments;
|
||||
const step = moments.length / max;
|
||||
return Array.from({ length: max }, (_, i) => moments[Math.floor(i * step)]);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { agenda, sortDay } from "./today.ts";
|
||||
|
||||
test("the day's events as lines: times, all-day ones first, past ones marked", () => {
|
||||
const now = new Date(2026, 10, 3, 12, 0).getTime();
|
||||
const at = (h: number, m = 0) => new Date(2026, 10, 3, h, m).toISOString();
|
||||
const items = sortDay(
|
||||
agenda(
|
||||
[
|
||||
{ summary: "Zahnarzt", start: { dateTime: at(15, 30) }, end: { dateTime: at(16) } },
|
||||
{ summary: "Frühstück", start: { dateTime: at(8) }, end: { dateTime: at(9) } },
|
||||
{ summary: "Geburtstag Oma", start: { date: "2026-11-03" }, end: { date: "2026-11-04" } },
|
||||
{ summary: "", start: { dateTime: at(10) } },
|
||||
],
|
||||
"Familie",
|
||||
now,
|
||||
),
|
||||
);
|
||||
assert.deepEqual(items.map((i) => [i.time, i.title, !!i.past]), [["", "Geburtstag Oma", false], ["08:00", "Frühstück", true], ["15:30", "Zahnarzt", false]]);
|
||||
});
|
||||
|
||||
test("over several days each line knows its day, and the days come in order (#84)", () => {
|
||||
const now = new Date(2026, 10, 8, 10, 0).getTime();
|
||||
const iso = (d: number, h: number) => new Date(2026, 10, d, h).toISOString();
|
||||
const items = sortDay(
|
||||
agenda(
|
||||
[
|
||||
{ summary: "Dentist", start: iso(9, 9), end: iso(9, 10) },
|
||||
{ summary: "Holiday", start: { date: "2026-11-10" } },
|
||||
{ summary: "Lunch", start: iso(8, 12), end: iso(8, 13) },
|
||||
{ summary: "Market", start: { date: "2026-11-08" } },
|
||||
],
|
||||
"Family",
|
||||
now,
|
||||
),
|
||||
);
|
||||
assert.deepEqual(
|
||||
items.map((i) => [i.day, i.title]),
|
||||
[[0, "Market"], [0, "Lunch"], [1, "Dentist"], [2, "Holiday"]],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
// "Today" for the wall tablet: the day's appointments from the calendars chosen in the plan, and the waste bins collected today or
|
||||
// tomorrow. The events come from Home Assistant's calendar REST API; turning them into lines is a pure function.
|
||||
|
||||
import type { Building } from "../model.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { pickupDays } from "../entities/household.ts";
|
||||
import { householdKind } from "../packs.ts";
|
||||
|
||||
/** One line of the day: a time ("09:30", or "" for all day) and what it is. */
|
||||
export interface TodayItem {
|
||||
time: string;
|
||||
title: string;
|
||||
/** Where it comes from: a calendar's name, or a bin. */
|
||||
source: string;
|
||||
/** Sorts the day: minutes after midnight (-1 for all-day events and bins). */
|
||||
at: number;
|
||||
kind: "event" | "bin";
|
||||
/** Which day it is on: 0 today, 1 tomorrow … (the card can show several days). */
|
||||
day?: number;
|
||||
/** Already over (it stays listed, dimmed). */
|
||||
past?: boolean;
|
||||
}
|
||||
|
||||
interface RawEvent {
|
||||
summary?: string;
|
||||
start?: { dateTime?: string; date?: string } | string;
|
||||
end?: { dateTime?: string; date?: string } | string;
|
||||
}
|
||||
|
||||
const time = (d: Date) => `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
|
||||
const when = (v: RawEvent["start"]) => (typeof v === "string" ? { dateTime: v } : (v ?? {}));
|
||||
|
||||
const midnight = (t: number): number => {
|
||||
const d = new Date(t);
|
||||
d.setHours(0, 0, 0, 0);
|
||||
return d.getTime();
|
||||
};
|
||||
|
||||
/** Days from today to the day of `t` (0 = today), across a clock change too. */
|
||||
const dayOf = (t: number, now: number): number => Math.max(0, Math.round((midnight(t) - midnight(now)) / 86_400_000));
|
||||
|
||||
/** The events of one calendar as lines of the day, all-day events first. */
|
||||
export function agenda(raw: RawEvent[], source: string, now: number): TodayItem[] {
|
||||
return raw
|
||||
.map((e): TodayItem | null => {
|
||||
const s = when(e.start);
|
||||
const end = when(e.end);
|
||||
const title = (e.summary ?? "").trim();
|
||||
if (!title) return null;
|
||||
if (s.dateTime) {
|
||||
const d = new Date(s.dateTime);
|
||||
const until = end.dateTime ? new Date(end.dateTime).getTime() : d.getTime();
|
||||
return { time: time(d), title, source, at: d.getHours() * 60 + d.getMinutes(), kind: "event", past: until < now, day: dayOf(d.getTime(), now) };
|
||||
}
|
||||
// an all-day event is dated "YYYY-MM-DD": that is local midnight, not UTC
|
||||
const date = s.date ? /^(\d{4})-(\d{2})-(\d{2})$/.exec(s.date) : null;
|
||||
const day = date ? dayOf(new Date(Number(date[1]), Number(date[2]) - 1, Number(date[3])).getTime(), now) : 0;
|
||||
return { time: "", title, source, at: -1, kind: "event", day };
|
||||
})
|
||||
.filter((x): x is TodayItem => !!x);
|
||||
}
|
||||
|
||||
/** The bins collected today or tomorrow (from the household pieces of the plan). */
|
||||
export function binsDue(hass: HomeAssistant, b: Building, now: number, labels: { today: string; tomorrow: string }): TodayItem[] {
|
||||
const out: TodayItem[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const floor of b.floors)
|
||||
for (const f of floor.furniture) {
|
||||
const id = f.care_entity;
|
||||
if (!id || seen.has(id) || householdKind(f.type) !== "bin") continue;
|
||||
seen.add(id);
|
||||
const days = pickupDays(hass.states[id], now);
|
||||
if (days === null || days > 1) continue;
|
||||
const name = f.name || String(hass.states[id]?.attributes.friendly_name ?? id);
|
||||
out.push({ time: "", title: name, source: days === 0 ? labels.today : labels.tomorrow, at: -1, kind: "bin" });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** All lines, sorted: day by day, and in a day all-day things and bins first, then by time. */
|
||||
export function sortDay(items: TodayItem[]): TodayItem[] {
|
||||
return [...items].sort((a, b) => (a.day ?? 0) - (b.day ?? 0) || a.at - b.at || a.title.localeCompare(b.title));
|
||||
}
|
||||
|
||||
/** Loads the events of the chosen calendars from today's midnight over `days` days; a calendar that fails is left out. */
|
||||
export async function loadToday(hass: HomeAssistant, calendars: string[], days = 1, now = Date.now()): Promise<TodayItem[]> {
|
||||
if (!hass.fetchWithAuth || !calendars.length) return [];
|
||||
const start = new Date(now);
|
||||
start.setHours(0, 0, 0, 0);
|
||||
const end = new Date(start);
|
||||
// whole days by the calendar, so a clock change does not cut the last day short
|
||||
end.setDate(end.getDate() + Math.max(1, days));
|
||||
const lists = await Promise.all(
|
||||
calendars.map(async (id) => {
|
||||
try {
|
||||
const r = await hass.fetchWithAuth!(`/api/calendars/${encodeURIComponent(id)}?start=${encodeURIComponent(start.toISOString())}&end=${encodeURIComponent(end.toISOString())}`);
|
||||
if (!r.ok) return [];
|
||||
const name = String(hass.states[id]?.attributes.friendly_name ?? id.split(".")[1]);
|
||||
return agenda((await r.json()) as RawEvent[], name, now);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}),
|
||||
);
|
||||
return lists.flat();
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity, hassOf } from "../entities/fixtures.ts";
|
||||
import { calibrationFrom, calibrationFromRooms, gridMapper, gridPlaces, gridRooms, gridTurn, mapCamera, nudgeCalibration, readVacuum, type VacuumCalibration } from "./vacuum-map.ts";
|
||||
|
||||
/** Two decimals, so a test can compare pairs without float noise. */
|
||||
const r2 = (v: number) => Math.round(v * 100) / 100;
|
||||
const pair2 = (p: [number, number]) => p.map(r2);
|
||||
|
||||
/** 10 m of plan over 100 grid units, no turn: 0.1 m per unit. */
|
||||
const CAL: VacuumCalibration = { a: [0, 0], ga: [0, 0], b: [10, 0], gb: [100, 0] };
|
||||
|
||||
test("two places known in both frames tie the grid to the plan", () => {
|
||||
const map = gridMapper(CAL)!;
|
||||
assert.deepEqual(pair2(map([0, 0])), [0, 0]);
|
||||
assert.deepEqual(pair2(map([100, 0])), [10, 0]);
|
||||
assert.deepEqual(pair2(map([0, 50])), [0, 5], "grid +y runs along plan +z");
|
||||
assert.deepEqual(pair2(map([50, 50])), [5, 5], "and in between it scales as well");
|
||||
});
|
||||
|
||||
test("a grid that is turned relative to the plan turns with it", () => {
|
||||
// grid +x is plan +z: a quarter turn to the left
|
||||
const cal: VacuumCalibration = { a: [0, 0], ga: [0, 0], b: [0, 10], gb: [100, 0] };
|
||||
const map = gridMapper(cal)!;
|
||||
assert.deepEqual(pair2(map([100, 0])), [0, 10]);
|
||||
assert.deepEqual(pair2(map([0, 100])), [-10, 0]);
|
||||
assert.ok(Math.abs(gridTurn(cal)! - Math.PI / 2) < 1e-9);
|
||||
});
|
||||
|
||||
test("the plan points do not have to sit at the grid's origin", () => {
|
||||
// the same shape, shifted: a place at grid (0,0) is at plan (3,-2)
|
||||
const cal: VacuumCalibration = { a: [3, -2], ga: [0, 0], b: [13, -2], gb: [100, 0] };
|
||||
const map = gridMapper(cal)!;
|
||||
assert.deepEqual(pair2(map([0, 0])), [3, -2]);
|
||||
assert.deepEqual(pair2(map([100, 100])), [13, 8]);
|
||||
});
|
||||
|
||||
test("a mirrored map is met by mirroring its grid", () => {
|
||||
// the same two places, but this camera's y grows along plan -z: grid +y is plan -z
|
||||
const cal: VacuumCalibration = { ...CAL, mirror: true };
|
||||
const map = gridMapper(cal)!;
|
||||
assert.deepEqual(pair2(map([0, 0])), [0, 0]);
|
||||
assert.deepEqual(pair2(map([100, 0])), [10, 0], "the two calibration places still land where they belong");
|
||||
assert.deepEqual(pair2(map([0, 50])), [0, -5], "grid +y now runs along plan -z");
|
||||
assert.deepEqual(pair2(map([50, 50])), [5, -5]);
|
||||
assert.equal(gridTurn(cal), gridTurn(CAL), "the turn between the two places is unchanged");
|
||||
});
|
||||
|
||||
test("a mirrored map reads its facings the other way round", () => {
|
||||
const cal: VacuumCalibration = { ...CAL, mirror: true };
|
||||
// facing grid +y, which on this map is plan -z
|
||||
const hass = hassOf([entity("camera.map", "idle", { vacuum_position: { x: 0, y: 0, a: 90 } })]);
|
||||
const live = readVacuum(hass, "camera.map", cal)!;
|
||||
assert.ok(Math.abs(Math.abs(live.pose!.heading) - Math.PI) < 1e-9, `heading ${live.pose!.heading}`);
|
||||
});
|
||||
|
||||
test("two places on top of each other say nothing about scale or direction", () => {
|
||||
assert.equal(gridMapper({ ...CAL, b: [0, 0] }), null, "the same plan point twice");
|
||||
assert.equal(gridMapper({ ...CAL, gb: [0, 0] }), null, "the same grid point twice");
|
||||
assert.equal(gridMapper(null), null);
|
||||
assert.equal(gridMapper(undefined), null);
|
||||
});
|
||||
|
||||
test("the map camera is found by the attributes it carries, without being configured", () => {
|
||||
const hass = hassOf([entity("camera.a", "idle"), entity("camera.map", "idle", { vacuum_position: { x: 1, y: 2, a: 0 } })]);
|
||||
assert.equal(mapCamera(hass), "camera.map");
|
||||
assert.equal(mapCamera(hassOf([entity("camera.a", "idle")])), null, "nothing to find");
|
||||
});
|
||||
|
||||
test("the live map reads pose, dock and trail in plan metres", () => {
|
||||
const hass = hassOf([
|
||||
entity("camera.map", "idle", {
|
||||
vacuum_position: { x: 100, y: 50, a: 90 },
|
||||
charger: { x: 0, y: 0 },
|
||||
path: [
|
||||
[
|
||||
[0, 0],
|
||||
[100, 0],
|
||||
[100, 50],
|
||||
],
|
||||
],
|
||||
}),
|
||||
]);
|
||||
const live = readVacuum(hass, "camera.map", CAL)!;
|
||||
assert.ok(live, "the attributes are there");
|
||||
assert.deepEqual(pair2(live.pose ? [live.pose.x, live.pose.z] : [0, 0]), [10, 5]);
|
||||
// a heading of 90 in the grid faces grid +y, which is plan +z — and a heading of 0 faces +z
|
||||
assert.ok(Math.abs(live.pose!.heading) < 1e-9, `heading ${live.pose!.heading}`);
|
||||
assert.deepEqual(pair2(live.charger!), [0, 0]);
|
||||
assert.equal(live.path.length, 1, "one segment");
|
||||
assert.equal(live.path[0].length, 3, "three points in it");
|
||||
assert.deepEqual(pair2(live.path[0][2]), [10, 5], "the trail ends where the robot is");
|
||||
});
|
||||
|
||||
test("facing along the grid's x is a quarter turn on the plan", () => {
|
||||
const hass = hassOf([entity("camera.map", "idle", { vacuum_position: { x: 0, y: 0, a: 0 } })]);
|
||||
const live = readVacuum(hass, "camera.map", CAL)!;
|
||||
assert.ok(Math.abs(live.pose!.heading - Math.PI / 2) < 1e-9, "0 faces +z, so +x is a quarter turn");
|
||||
});
|
||||
|
||||
test("without a camera or without attributes there is nothing to draw", () => {
|
||||
const hass = hassOf([entity("camera.map", "idle", {})]);
|
||||
assert.equal(readVacuum(hass, "camera.map", CAL), null, "no attributes at all");
|
||||
assert.equal(readVacuum(hass, null, CAL), null, "no camera");
|
||||
assert.equal(readVacuum(hass, "camera.gone", CAL), null, "a camera that is not there");
|
||||
});
|
||||
|
||||
test("a trail of one point is no trail", () => {
|
||||
const hass = hassOf([entity("camera.map", "idle", { path: [[[0, 0]]] })]);
|
||||
assert.equal(readVacuum(hass, "camera.map", CAL), null, "a single point is nothing to draw");
|
||||
// a single point next to a pose still leaves no trail, but the robot itself is drawn
|
||||
const withPose = hassOf([entity("camera.map", "idle", { vacuum_position: { x: 0, y: 0, a: 0 }, path: [[[0, 0]]] })]);
|
||||
const live = readVacuum(withPose, "camera.map", CAL)!;
|
||||
assert.equal(live.path.length, 0, "a single point says nothing about a way");
|
||||
assert.ok(live.pose, "but the robot is there");
|
||||
});
|
||||
|
||||
test("a trail is read whether it comes as one run or as several", () => {
|
||||
// the map card's format: a single run of points
|
||||
const flat = hassOf([entity("camera.map", "idle", { vacuum_position: { x: 100, y: 50, a: 0 }, path: [[0, 0], [100, 0], [100, 50]] })]);
|
||||
const one = readVacuum(flat, "camera.map", CAL)!;
|
||||
assert.equal(one.path.length, 1, "one run");
|
||||
assert.equal(one.path[0].length, 3, "with all three points");
|
||||
assert.deepEqual(pair2(one.path[0][2]), [10, 5]);
|
||||
// NarwalIntegration's: two runs, a gap between them
|
||||
const split = hassOf([
|
||||
entity("camera.map", "idle", {
|
||||
vacuum_position: { x: 100, y: 50, a: 0 },
|
||||
path: [
|
||||
[[0, 0], [100, 0]],
|
||||
[[100, 50], [200, 50]],
|
||||
],
|
||||
}),
|
||||
]);
|
||||
const two = readVacuum(split, "camera.map", CAL)!;
|
||||
assert.equal(two.path.length, 2, "two runs");
|
||||
assert.deepEqual(pair2(two.path[1][1]), [20, 5]);
|
||||
});
|
||||
|
||||
test("a camera that only knows where the dock is still counts as a robot map", () => {
|
||||
const hass = hassOf([entity("camera.dock_only", "idle", { charger: { x: 10, y: 10 } })]);
|
||||
assert.equal(mapCamera(hass), "camera.dock_only");
|
||||
});
|
||||
|
||||
test("the dock and one place the robot is at are enough to calibrate", () => {
|
||||
const dock = { plan: [0, 0] as [number, number], grid: [100, 100] as [number, number] };
|
||||
// the robot is 4 m to plan +x, and its grid says +40 cells: 0.1 m per cell, no turn
|
||||
const res = calibrationFrom(dock, { plan: [4, 0], grid: [140, 100] }, false);
|
||||
assert.ok(res.cal, "a workable pair");
|
||||
const map = gridMapper(res.cal)!;
|
||||
assert.deepEqual(pair2(map([100, 100])), [0, 0], "the dock lands on the dock");
|
||||
assert.deepEqual(pair2(map([140, 100])), [4, 0], "and the robot where it was tapped");
|
||||
assert.deepEqual(pair2(map([140, 140])), [4, 4], "grid +y runs along plan +z without mirror");
|
||||
});
|
||||
|
||||
test("a mirrored map puts the same places on the other side", () => {
|
||||
const dock = { plan: [0, 0] as [number, number], grid: [100, 100] as [number, number] };
|
||||
const res = calibrationFrom(dock, { plan: [4, 0], grid: [140, 100] }, true);
|
||||
assert.ok(res.cal);
|
||||
assert.deepEqual(pair2(gridMapper(res.cal)!.call(null, [140, 140])), [4, -4], "grid +y runs along plan -z");
|
||||
});
|
||||
|
||||
test("places too close for the turn, or a scale that makes no sense, are refused", () => {
|
||||
const dock = { plan: [0, 0] as [number, number], grid: [100, 100] as [number, number] };
|
||||
const close = calibrationFrom(dock, { plan: [0.4, 0], grid: [104, 100] });
|
||||
assert.equal(close.cal, null, "half a metre apart is guesswork");
|
||||
assert.equal(close.cal === null && close.reason, "close");
|
||||
const same = calibrationFrom(dock, { plan: [4, 0], grid: [100, 100] });
|
||||
assert.equal(same.cal === null && same.reason, "close", "the robot has not moved on its map");
|
||||
const wild = calibrationFrom(dock, { plan: [4, 0], grid: [100.001, 100] });
|
||||
assert.equal(wild.cal === null && wild.reason, "scale", "4 m in a thousandth of a cell");
|
||||
});
|
||||
|
||||
test("the grid places come from the camera, and are null without one", () => {
|
||||
const hass = hassOf([entity("camera.map", "idle", { vacuum_position: { x: 12, y: 34, a: 90 }, charger: { x: 1, y: 2 } })]);
|
||||
assert.deepEqual(gridPlaces(hass, "camera.map"), { at: [12, 34], dock: [1, 2] });
|
||||
assert.deepEqual(gridPlaces(hass, null), { at: null, dock: null });
|
||||
assert.deepEqual(gridPlaces(hass, "camera.gone"), { at: null, dock: null });
|
||||
});
|
||||
|
||||
test("Dreame's map camera names the dock charger_position and may have no trail (#109)", () => {
|
||||
const hass = hassOf([entity("camera.dreame_map", "idle", { vacuum_position: { x: 100, y: 50, a: 0 }, charger_position: { x: 20, y: 10 } })]);
|
||||
assert.equal(mapCamera(hassOf([entity("camera.dreame_map", "idle", { charger_position: { x: 20, y: 10 } })])), "camera.dreame_map", "found by the dock alone");
|
||||
assert.deepEqual(gridPlaces(hass, "camera.dreame_map"), { at: [100, 50], dock: [20, 10] });
|
||||
const live = readVacuum(hass, "camera.dreame_map", CAL)!;
|
||||
assert.deepEqual(pair2(live.charger!), [2, 1]);
|
||||
assert.deepEqual(live.path, [], "no path attribute: no invented trail");
|
||||
});
|
||||
|
||||
/** The rooms of a real Dreame X50 Ultra map camera (#109), boxes in millimetres; the dock sits in the kitchen. */
|
||||
const DREAME_ROOMS = {
|
||||
"2": { x0: 800, y0: 1150, x1: 5700, y1: 4450, name: "Wohnzimmer" },
|
||||
"3": { x0: 1950, y0: -1750, x1: 5750, y1: 1150, name: "Flur" },
|
||||
"4": { x0: -2000, y0: -1050, x1: 1950, y1: 3900, name: "Küche" },
|
||||
"5": { x0: -1850, y0: -2650, x1: 50, y1: -1050, name: "Bad" },
|
||||
"6": { x0: 50, y0: -2700, x1: 1200, y1: -1050, name: "Flur 2" },
|
||||
"7": { x0: 2000, y0: -9600, x1: 6000, y1: -1750, name: "Büro" },
|
||||
"8": { x0: -1900, y0: -5600, x1: 1150, y1: -2700, name: "Schlafzimmer" },
|
||||
};
|
||||
const DREAME_DOCK = { x: -1752, y: 1556, a: 268 };
|
||||
|
||||
/** A plan drawn from the robot's boxes: millimetres to metres, y running against plan z, a quarter turn, shifted. */
|
||||
function planOf(rooms: typeof DREAME_ROOMS, rename: (n: string) => string = (n) => n) {
|
||||
const put = (x: number, y: number): [number, number] => [12 + (-y / 1000), 5 + (-x / 1000)];
|
||||
return Object.values(rooms).map((r) => ({ name: rename(r.name), points: [put(r.x0, r.y0), put(r.x1, r.y0), put(r.x1, r.y1), put(r.x0, r.y1)] }));
|
||||
}
|
||||
|
||||
test("a Dreame map is calibrated from the rooms both sides name, mirror and all, without the robot moving", () => {
|
||||
const hass = hassOf([entity("camera.x50_map", "idle", { rooms: DREAME_ROOMS, vacuum_position: DREAME_DOCK, charger_position: DREAME_DOCK })]);
|
||||
const robot = gridRooms(hass, "camera.x50_map");
|
||||
assert.equal(robot.length, 7);
|
||||
const res = calibrationFromRooms(planOf(DREAME_ROOMS, (n) => n.toUpperCase().replace(" ", "-")), robot);
|
||||
assert.ok(res.cal, "matched by name, whatever the case and spacing");
|
||||
assert.equal(res.matched.length, 7);
|
||||
assert.equal(res.cal.mirror, true, "three rooms or more tell a mirrored map from a turned one");
|
||||
// the docked robot lands where the plan puts the dock: the kitchen, 12 + -1.556, 5 + 1.752
|
||||
const live = readVacuum(hass, "camera.x50_map", res.cal)!;
|
||||
assert.deepEqual(pair2(live.charger!), [10.44, 6.75]);
|
||||
assert.deepEqual([r2(live.pose!.x), r2(live.pose!.z)], [10.44, 6.75]);
|
||||
});
|
||||
|
||||
test("rooms that do not match, or match the wrong way round, give no calibration", () => {
|
||||
const hass = hassOf([entity("camera.x50_map", "idle", { rooms: DREAME_ROOMS })]);
|
||||
const robot = gridRooms(hass, "camera.x50_map");
|
||||
assert.deepEqual(calibrationFromRooms(planOf(DREAME_ROOMS, (n) => `${n} OG`), robot), { cal: null, reason: "rooms", matched: [] });
|
||||
// the plan's office and bedroom swapped: no fit puts every room where the plan has it
|
||||
const swapped = planOf(DREAME_ROOMS, (n) => (n === "Büro" ? "Wohnzimmer" : n === "Wohnzimmer" ? "Büro" : n === "Bad" ? "Flur" : n === "Flur" ? "Bad" : n));
|
||||
assert.equal(calibrationFromRooms(swapped, robot).cal, null);
|
||||
});
|
||||
|
||||
test("a nudge moves, turns and scales the whole map by hand", () => {
|
||||
const cal: VacuumCalibration = { a: [0, 0], ga: [0, 0], b: [4, 0], gb: [4000, 0] };
|
||||
const moved = gridMapper(nudgeCalibration(cal, { move: [0.1, -0.2] }))!;
|
||||
assert.deepEqual(moved([2000, 0]).map((v) => Math.round(v * 1000) / 1000), [2.1, -0.2]);
|
||||
const turned = nudgeCalibration(cal, { turn: 90 });
|
||||
assert.deepEqual(turned.a, [2, -2]);
|
||||
assert.deepEqual(turned.b, [2, 2]);
|
||||
const grown = nudgeCalibration(cal, { grow: 1.5 });
|
||||
assert.deepEqual([grown.a, grown.b], [[-1, 0], [5, 0]]);
|
||||
assert.deepEqual(grown.ga, cal.ga);
|
||||
});
|
||||
@@ -0,0 +1,312 @@
|
||||
/**
|
||||
* A robot's own map, put into the plan's coordinates.
|
||||
*
|
||||
* A robot reports where it is and where it has been in its map's grid, which has nothing to do with the
|
||||
* plan's metres: the integration hands that out on the map camera's attributes (`vacuum_position`,
|
||||
* `charger` or Dreame's `charger_position`, `path` — the vacuum map card's names, shared by NarwalIntegration and the Xiaomi/Roborock map
|
||||
* extractors). Two places known in both frames are enough to tie the two together, as a similarity transform:
|
||||
* scale, rotation and shift. Everything else — the pose, the trail, the dock — follows from those two pairs.
|
||||
*
|
||||
* A map whose y grows along plan -z needs `mirror`: two places cannot tell a mirror from a turn, since
|
||||
* both put them exactly where they belong, so the caller has to say which one the map is.
|
||||
*/
|
||||
import type { VacuumCalibration } from "../model.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
|
||||
export type { VacuumCalibration };
|
||||
|
||||
export interface VacuumPose {
|
||||
x: number;
|
||||
z: number;
|
||||
/** Facing, in radians, the way the viewer turns a robot: 0 faces +z. */
|
||||
heading: number;
|
||||
}
|
||||
|
||||
export interface VacuumLive {
|
||||
pose: VacuumPose | null;
|
||||
/** The dock, in plan metres. */
|
||||
charger: [number, number] | null;
|
||||
/** The trail of the current clean, as segments in plan metres. */
|
||||
path: [number, number][][];
|
||||
}
|
||||
|
||||
const num = (v: unknown): number => Number(v);
|
||||
|
||||
/** A map position as a pair: the robot writes `{x, y}` for itself and `[x, y]` in its trail. */
|
||||
function pair(v: unknown): [number, number] | null {
|
||||
if (Array.isArray(v)) {
|
||||
const [px, py] = [num(v[0]), num(v[1])];
|
||||
return Number.isFinite(px) && Number.isFinite(py) ? [px, py] : null;
|
||||
}
|
||||
if (!v || typeof v !== "object") return null;
|
||||
const { x, y } = v as { x?: unknown; y?: unknown };
|
||||
const [px, py] = [num(x), num(y)];
|
||||
return Number.isFinite(px) && Number.isFinite(py) ? [px, py] : null;
|
||||
}
|
||||
|
||||
/** Where the dock is in the map's grid: `charger` (the map card's name), or `charger_position` (Dreame's map camera, #109). */
|
||||
function dockOf(attributes: Record<string, unknown> | undefined): [number, number] | null {
|
||||
return attributes ? (pair(attributes.charger) ?? pair(attributes.charger_position)) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The camera whose attributes describe a robot map: it reports where the robot is or where it docks, so it can
|
||||
* be found without being configured.
|
||||
*/
|
||||
export function mapCamera(hass: HomeAssistant): string | null {
|
||||
for (const [id, st] of Object.entries(hass.states)) {
|
||||
if (!id.startsWith("camera.")) continue;
|
||||
// where the robot is, or where it docks: either says this camera carries a robot's map
|
||||
if (pair(st.attributes?.vacuum_position) ?? dockOf(st.attributes)) return id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Whether a value is one grid point: `[x, y]`, or `{x, y}` as the robot writes its own position. */
|
||||
const isPoint = (v: unknown): boolean => (Array.isArray(v) ? typeof v[0] === "number" : !!v && typeof v === "object");
|
||||
|
||||
/** A grid point as the calibration sees it: mirrored onto the plan's side when the map runs backwards. */
|
||||
const asSeen = (g: [number, number], mirror: boolean): [number, number] => (mirror ? [g[0], -g[1]] : g);
|
||||
|
||||
/** How the grid turns and scales into the plan, or null while the two points are unusable. */
|
||||
export function gridMapper(cal: VacuumCalibration | null | undefined): ((g: [number, number]) => [number, number]) | null {
|
||||
if (!cal) return null;
|
||||
const mirror = cal.mirror === true;
|
||||
const [gax, gay] = asSeen(cal.ga, mirror);
|
||||
const [gbx, gby] = asSeen(cal.gb, mirror);
|
||||
const [ax, az] = cal.a;
|
||||
const [bx, bz] = cal.b;
|
||||
const [dgx, dgy] = [gbx - gax, gby - gay];
|
||||
const [dpx, dpz] = [bx - ax, bz - az];
|
||||
const dg = Math.hypot(dgx, dgy);
|
||||
const dp = Math.hypot(dpx, dpz);
|
||||
// two points on top of each other say nothing about scale or direction
|
||||
if (!(dg > 1e-6) || !(dp > 1e-6)) return null;
|
||||
const scale = dp / dg;
|
||||
const turn = Math.atan2(dpz, dpx) - Math.atan2(dgy, dgx);
|
||||
const [cos, sin] = [Math.cos(turn), Math.sin(turn)];
|
||||
return (g) => {
|
||||
const seen = asSeen(g, mirror);
|
||||
const [x, y] = [seen[0] - gax, seen[1] - gay];
|
||||
return [ax + scale * (x * cos - y * sin), az + scale * (x * sin + y * cos)];
|
||||
};
|
||||
}
|
||||
|
||||
/** The turn of the grid into the plan, in radians (for headings). */
|
||||
export function gridTurn(cal: VacuumCalibration | null | undefined): number | null {
|
||||
if (!cal) return null;
|
||||
const mirror = cal.mirror === true;
|
||||
const [gax, gay] = asSeen(cal.ga, mirror);
|
||||
const [gbx, gby] = asSeen(cal.gb, mirror);
|
||||
const turn = Math.atan2(cal.b[1] - cal.a[1], cal.b[0] - cal.a[0]) - Math.atan2(gby - gay, gbx - gax);
|
||||
return Number.isFinite(turn) ? turn : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The robot's live map, in plan metres. `camera` is the map camera (see `mapCamera`); without a
|
||||
* calibration the grid is passed through unchanged, which is wrong on the plan but keeps the shape.
|
||||
*/
|
||||
export function readVacuum(hass: HomeAssistant, camera: string | null, cal: VacuumCalibration | null | undefined): VacuumLive | null {
|
||||
if (!camera) return null;
|
||||
const attributes = hass.states[camera]?.attributes;
|
||||
if (!attributes) return null;
|
||||
const toPlan = gridMapper(cal) ?? ((g: [number, number]) => g);
|
||||
const turn = gridTurn(cal) ?? 0;
|
||||
// a mirrored map turns the other way, so a facing reads the other way too
|
||||
const facingSign = cal?.mirror === true ? -1 : 1;
|
||||
|
||||
const position = attributes.vacuum_position as { a?: unknown } | undefined;
|
||||
const at = pair(position);
|
||||
const pose = at
|
||||
? (() => {
|
||||
const [x, z] = toPlan(at);
|
||||
// the robot reports its facing in degrees, 0 = +x and 90 = +y; a heading of 0 faces +z here
|
||||
const facing = num(position?.a) * facingSign;
|
||||
if (!Number.isFinite(facing)) return { x, z, heading: 0 };
|
||||
const angle = (facing * Math.PI) / 180 + turn;
|
||||
return { x, z, heading: Math.atan2(Math.cos(angle), Math.sin(angle)) };
|
||||
})()
|
||||
: null;
|
||||
|
||||
const dock = dockOf(attributes);
|
||||
// `path` is one run of points in the map card's format, and a list of runs in NarwalIntegration's, where a
|
||||
// gap is a new run; take both, or a robot's whole trail would count as a single point and vanish
|
||||
const rawPath: unknown[] = Array.isArray(attributes.path) ? attributes.path : [];
|
||||
const runs: unknown[][] = rawPath.length > 0 && isPoint(rawPath[0]) ? [rawPath] : (rawPath as unknown[][]);
|
||||
const path: [number, number][][] = [];
|
||||
for (const segment of runs) {
|
||||
const points: [number, number][] = [];
|
||||
for (const raw of Array.isArray(segment) ? segment : []) {
|
||||
const g = pair(raw);
|
||||
if (g) points.push(toPlan(g));
|
||||
}
|
||||
if (points.length > 1) path.push(points);
|
||||
}
|
||||
// a camera that describes nothing (no pose, no dock, no trail) is no map to draw
|
||||
if (!pose && !dock && !path.length) return null;
|
||||
return { pose, charger: dock ? toPlan(dock) : null, path };
|
||||
}
|
||||
|
||||
/** Two places as a calibration needs them: a point on the plan, and the robot's grid point there. */
|
||||
export interface Place {
|
||||
plan: [number, number];
|
||||
grid: [number, number];
|
||||
}
|
||||
|
||||
/** Why a pair of places cannot be calibrated: they sit too close together, or the scale makes no sense. */
|
||||
export type CalibrationResult = { cal: VacuumCalibration } | { cal: null; reason: "close" | "scale" };
|
||||
|
||||
/** A believable scale: a robot counts in millimetres, or in cells of a few centimetres. */
|
||||
const MIN_SCALE = 0.0005;
|
||||
const MAX_SCALE = 2;
|
||||
/** How far apart the two places have to be, in the plan: closer and the turn is guesswork. */
|
||||
const MIN_BASELINE = 1.5;
|
||||
|
||||
/** Where the robot and its dock are in the map's grid, which is what a calibration is built from. */
|
||||
export function gridPlaces(hass: HomeAssistant, camera: string | null): { at: [number, number] | null; dock: [number, number] | null } {
|
||||
const attributes = camera ? hass.states[camera]?.attributes : undefined;
|
||||
return {
|
||||
at: attributes ? pair(attributes.vacuum_position) : null,
|
||||
dock: dockOf(attributes),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The calibration from two places: the dock, which the plan and the robot both know, and a place the robot is
|
||||
* at now, which is one tap. Two places fix scale and turn; `mirror` has to be given, since a mirror puts them
|
||||
* exactly where a turn would.
|
||||
*/
|
||||
export function calibrationFrom(dock: Place, here: Place, mirror = false): CalibrationResult {
|
||||
const plan = Math.hypot(here.plan[0] - dock.plan[0], here.plan[1] - dock.plan[1]);
|
||||
const grid = Math.hypot(here.grid[0] - dock.grid[0], here.grid[1] - dock.grid[1]);
|
||||
if (!(grid > 1e-6) || !(plan >= MIN_BASELINE)) return { cal: null, reason: "close" };
|
||||
const scale = plan / grid;
|
||||
if (!(scale >= MIN_SCALE && scale <= MAX_SCALE)) return { cal: null, reason: "scale" };
|
||||
return { cal: { a: dock.plan, ga: dock.grid, b: here.plan, gb: here.grid, mirror } };
|
||||
}
|
||||
|
||||
/** A room on the robot's map: its name and the middle of its box, in the map's grid. */
|
||||
export interface GridRoom {
|
||||
name: string;
|
||||
center: [number, number];
|
||||
}
|
||||
|
||||
/**
|
||||
* The rooms the robot knows, from the map camera's `rooms`: Dreame writes a box (`x0..y1`) and a name per room;
|
||||
* a room without a name cannot be matched to the plan, so it is left out.
|
||||
*/
|
||||
export function gridRooms(hass: HomeAssistant, camera: string | null): GridRoom[] {
|
||||
const raw = camera ? hass.states[camera]?.attributes?.rooms : undefined;
|
||||
if (!raw || typeof raw !== "object") return [];
|
||||
const out: GridRoom[] = [];
|
||||
for (const r of Object.values(raw as Record<string, unknown>)) {
|
||||
if (!r || typeof r !== "object") continue;
|
||||
const room = r as Record<string, unknown>;
|
||||
const name = typeof room.name === "string" ? room.name.trim() : "";
|
||||
const box = [room.x0, room.y0, room.x1, room.y1].map(num);
|
||||
if (!name || !box.every(Number.isFinite)) continue;
|
||||
out.push({ name, center: [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2] });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A room name as both sides are compared: case, spaces and punctuation do not count. */
|
||||
const roomKey = (name: string): string => name.toLocaleLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^\p{L}\p{N}]+/gu, "");
|
||||
|
||||
/** The least-squares similarity from grid points (already mirrored when the map runs backwards) onto the plan, and how far it misses on average. */
|
||||
function fitSimilarity(pairs: { plan: [number, number]; seen: [number, number] }[]): { map: (g: [number, number]) => [number, number]; scale: number; rms: number } | null {
|
||||
const n = pairs.length;
|
||||
const [gx, gy] = pairs.reduce((s, p) => [s[0] + p.seen[0] / n, s[1] + p.seen[1] / n], [0, 0]);
|
||||
const [px, pz] = pairs.reduce((s, p) => [s[0] + p.plan[0] / n, s[1] + p.plan[1] / n], [0, 0]);
|
||||
// the plan point is (a + ib)(grid point) in complex numbers, around both centroids: a and b by least squares
|
||||
let [sa, sb, sg] = [0, 0, 0];
|
||||
for (const p of pairs) {
|
||||
const [u, v] = [p.seen[0] - gx, p.seen[1] - gy];
|
||||
const [x, z] = [p.plan[0] - px, p.plan[1] - pz];
|
||||
sa += u * x + v * z;
|
||||
sb += u * z - v * x;
|
||||
sg += u * u + v * v;
|
||||
}
|
||||
if (!(sg > 1e-9)) return null;
|
||||
const [a, b] = [sa / sg, sb / sg];
|
||||
const map = (g: [number, number]): [number, number] => {
|
||||
const [u, v] = [g[0] - gx, g[1] - gy];
|
||||
return [px + a * u - b * v, pz + b * u + a * v];
|
||||
};
|
||||
const rms = Math.sqrt(pairs.reduce((s, p) => s + Math.hypot(map(p.seen)[0] - p.plan[0], map(p.seen)[1] - p.plan[1]) ** 2, 0) / n);
|
||||
return { map, scale: Math.hypot(a, b), rms };
|
||||
}
|
||||
|
||||
export type RoomCalibrationResult = { cal: VacuumCalibration; matched: string[]; rms: number } | { cal: null; reason: "rooms" | "scale" | "fit"; matched: string[] };
|
||||
|
||||
/**
|
||||
* The calibration from rooms both sides know by name: the robot's map names its rooms like the plan does, and
|
||||
* the middles of matching rooms tie the grid to the plan without the robot moving at all. Two rooms fix scale and
|
||||
* turn (with `mirror` as given); three or more also tell a mirrored map from a turned one, so the better fit wins.
|
||||
*/
|
||||
export function calibrationFromRooms(planRooms: { name: string; points: readonly [number, number][] }[], robotRooms: GridRoom[], mirror = false): RoomCalibrationResult {
|
||||
const byKey = new Map(robotRooms.map((r) => [roomKey(r.name), r] as const));
|
||||
const pairs: { name: string; plan: [number, number]; grid: [number, number] }[] = [];
|
||||
const used = new Set<string>();
|
||||
for (const room of planRooms) {
|
||||
const key = roomKey(room.name);
|
||||
const robot = byKey.get(key);
|
||||
if (!robot || used.has(key) || room.points.length < 3) continue;
|
||||
used.add(key);
|
||||
const xs = room.points.map((p) => p[0]);
|
||||
const zs = room.points.map((p) => p[1]);
|
||||
// the middle of the room's box, as the robot measures its rooms
|
||||
pairs.push({ name: room.name, plan: [(Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...zs) + Math.max(...zs)) / 2], grid: robot.center });
|
||||
}
|
||||
const matched = pairs.map((p) => p.name);
|
||||
if (pairs.length < 2) return { cal: null, reason: "rooms", matched };
|
||||
const fits = (pairs.length >= 3 ? [false, true] : [mirror]).flatMap((m) => {
|
||||
const fit = fitSimilarity(pairs.map((p) => ({ plan: p.plan, seen: asSeen(p.grid, m) })));
|
||||
return fit ? [{ mirror: m, ...fit }] : [];
|
||||
});
|
||||
const best = fits.sort((x, y) => x.rms - y.rms)[0];
|
||||
if (!best) return { cal: null, reason: "rooms", matched };
|
||||
if (!(best.scale >= MIN_SCALE && best.scale <= MAX_SCALE)) return { cal: null, reason: "scale", matched };
|
||||
// the plan spread of the rooms: a fit that misses by more than a quarter of it has matched the wrong rooms
|
||||
const spread = Math.max(...pairs.map((p) => Math.hypot(p.plan[0] - pairs[0].plan[0], p.plan[1] - pairs[0].plan[1])));
|
||||
if (!(best.rms <= Math.max(1, spread / 4))) return { cal: null, reason: "fit", matched };
|
||||
// stored as two places like a tapped calibration: the two rooms furthest apart, put where the fit puts them
|
||||
let [i, j, far] = [0, 1, -1];
|
||||
for (let p = 0; p < pairs.length; p++)
|
||||
for (let q = p + 1; q < pairs.length; q++) {
|
||||
const d = Math.hypot(pairs[p].grid[0] - pairs[q].grid[0], pairs[p].grid[1] - pairs[q].grid[1]);
|
||||
if (d > far) [i, j, far] = [p, q, d];
|
||||
}
|
||||
const [ga, gb] = [pairs[i].grid, pairs[j].grid];
|
||||
return {
|
||||
cal: { a: best.map(asSeen(ga, best.mirror)), ga, b: best.map(asSeen(gb, best.mirror)), gb, mirror: best.mirror },
|
||||
matched,
|
||||
rms: best.rms,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/** A hand correction of a calibration: moved in plan metres, turned in degrees, grown by a factor. */
|
||||
export interface CalibrationNudge {
|
||||
move?: [number, number];
|
||||
turn?: number;
|
||||
grow?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shifts, turns or scales a calibration around the middle of its two places, for when a fitted map sits a little
|
||||
* off: both places are moved in the plan, the robot's grid positions stay, so the whole map follows.
|
||||
*/
|
||||
export function nudgeCalibration(cal: VacuumCalibration, nudge: CalibrationNudge): VacuumCalibration {
|
||||
const [mx, mz] = [(cal.a[0] + cal.b[0]) / 2, (cal.a[1] + cal.b[1]) / 2];
|
||||
const rad = ((nudge.turn ?? 0) * Math.PI) / 180;
|
||||
const [cos, sin, grow] = [Math.cos(rad), Math.sin(rad), nudge.grow ?? 1];
|
||||
const [dx, dz] = nudge.move ?? [0, 0];
|
||||
const at = (p: [number, number]): [number, number] => {
|
||||
const [x, z] = [(p[0] - mx) * grow, (p[1] - mz) * grow];
|
||||
return [round(mx + x * cos - z * sin + dx), round(mz + x * sin + z * cos + dz)];
|
||||
};
|
||||
return { ...cal, a: at(cal.a), b: at(cal.b) };
|
||||
}
|
||||
|
||||
const round = (v: number): number => Math.round(v * 1000) / 1000;
|
||||
@@ -0,0 +1,19 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { dayStart, weekFromStats } from "./week-bars.ts";
|
||||
|
||||
test("kWh per day from daily mean power, consumption from the balance when no sensor tells", () => {
|
||||
const now = new Date(2026, 10, 2, 12, 0).getTime(); // noon: today counts 12 hours
|
||||
const day = (back: number) => new Date(dayStart(now, back)).toISOString();
|
||||
const stats = {
|
||||
"sensor.pv": [{ start: day(1), mean: 500 }, { start: day(0), mean: 1000 }],
|
||||
"sensor.grid": [{ start: day(1), mean: 250 }, { start: day(0), mean: -400 }],
|
||||
};
|
||||
const week = weekFromStats(stats, { solar: ["sensor.pv"], grid: "sensor.grid", gridInvert: false, battery: [], batteryInvert: false, consumption: null }, now);
|
||||
assert.equal(week.days.length, 7);
|
||||
assert.equal(week.solar[5], 12, "500 W all day");
|
||||
assert.equal(week.solar[6], 12, "1000 W for the 12 hours so far");
|
||||
assert.equal(week.use[5], 18, "500 + 250 W");
|
||||
assert.equal(week.use[6], 7.2, "1000 − 400 W for 12 h");
|
||||
assert.equal(week.solar[0], null, "no statistics that day");
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
// The last seven days for the house's energy card: solar and consumption per day in kWh, from Home Assistant's long-term statistics
|
||||
// of the power sensors (their daily mean × 24 h). One small request a day instead of a week of history.
|
||||
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
|
||||
/** The sensors the week is read from, and their signs (grid: + import, battery: + discharging). */
|
||||
export interface WeekSources {
|
||||
solar: string[];
|
||||
grid: string | null;
|
||||
gridInvert: boolean;
|
||||
battery: string[];
|
||||
batteryInvert: boolean;
|
||||
/** A house consumption sensor; without one the use is solar + grid + battery. */
|
||||
consumption: string | null;
|
||||
}
|
||||
|
||||
export interface WeekBars {
|
||||
/** Start of each day (ms), oldest first. */
|
||||
days: number[];
|
||||
solar: (number | null)[];
|
||||
use: (number | null)[];
|
||||
}
|
||||
|
||||
type Stats = Record<string, { start: number | string; mean?: number | null }[]>;
|
||||
|
||||
const DAY = 86_400_000;
|
||||
|
||||
/** Midnight of the day `t` falls on, `back` days earlier. */
|
||||
export function dayStart(t: number, back = 0): number {
|
||||
const d = new Date(t);
|
||||
d.setHours(0, 0, 0, 0);
|
||||
d.setDate(d.getDate() - back);
|
||||
return d.getTime();
|
||||
}
|
||||
|
||||
/** kWh per day from the daily mean power (W) of the sensors; today counts the hours gone so far. */
|
||||
export function weekFromStats(stats: Stats, src: WeekSources, now: number): WeekBars {
|
||||
const days = Array.from({ length: 7 }, (_, i) => dayStart(now, 6 - i));
|
||||
const hours = (day: number) => Math.min(24, Math.max(0, (Math.min(now, day + DAY) - day) / 3_600_000));
|
||||
const meanOn = (id: string | null, day: number): number | null => {
|
||||
if (!id) return null;
|
||||
const row = (stats[id] ?? []).find((r) => Math.abs(new Date(r.start).getTime() - day) < 3 * 3_600_000);
|
||||
return typeof row?.mean === "number" ? row.mean : null;
|
||||
};
|
||||
const sum = (ids: string[], day: number, sign = 1): number | null => {
|
||||
const values = ids.map((id) => meanOn(id, day)).filter((v): v is number => v !== null);
|
||||
return values.length ? values.reduce((a, b) => a + b, 0) * sign : null;
|
||||
};
|
||||
const kwh = (w: number | null, day: number) => (w === null ? null : Math.round(((w * hours(day)) / 1000) * 10) / 10);
|
||||
const solar = days.map((day) => kwh(sum(src.solar, day), day));
|
||||
const use = days.map((day) => {
|
||||
if (src.consumption) return kwh(meanOn(src.consumption, day), day);
|
||||
const parts = [sum(src.solar, day), sum(src.grid ? [src.grid] : [], day, src.gridInvert ? -1 : 1), sum(src.battery, day, src.batteryInvert ? -1 : 1)];
|
||||
if (parts.every((p) => p === null)) return null;
|
||||
return kwh(Math.max(0, parts.reduce<number>((a, b) => a + (b ?? 0), 0)), day);
|
||||
});
|
||||
return { days, solar, use };
|
||||
}
|
||||
|
||||
/** Loads the week from the recorder's statistics; null when there are no sensors or the recorder has nothing. */
|
||||
export async function loadWeek(hass: HomeAssistant, src: WeekSources, now = Date.now()): Promise<WeekBars | null> {
|
||||
const ids = [...new Set([...src.solar, ...src.battery, src.grid, src.consumption].filter((id): id is string => !!id))];
|
||||
if (!ids.length) return null;
|
||||
const stats = await hass.callWS<Stats>({
|
||||
type: "recorder/statistics_during_period",
|
||||
start_time: new Date(dayStart(now, 6)).toISOString(),
|
||||
end_time: new Date(now).toISOString(),
|
||||
statistic_ids: ids,
|
||||
period: "day",
|
||||
types: ["mean"],
|
||||
units: { power: "W" },
|
||||
});
|
||||
const week = weekFromStats(stats, src, now);
|
||||
return week.solar.some((v) => v !== null) || week.use.some((v) => v !== null) ? week : null;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity, hassOf } from "../entities/fixtures.ts";
|
||||
import { coverageColor, isAccessPoint, networkHealth, readAccessPoint } from "./wifi.ts";
|
||||
|
||||
test("an access point's clients and state from its device", () => {
|
||||
const d = { device_id: "ap" };
|
||||
const hass = hassOf([entity("sensor.ap_flur_clients", "14"), entity("binary_sensor.ap_flur_online", "on", { device_class: "connectivity" })], { "sensor.ap_flur_clients": d, "binary_sensor.ap_flur_online": d });
|
||||
const ap = readAccessPoint(hass, "sensor.ap_flur_clients")!;
|
||||
assert.deepEqual(ap, { clients: 14, online: true });
|
||||
assert.deepEqual(coverageColor(ap), [0.3, 0.7, 1]);
|
||||
assert.deepEqual(coverageColor({ clients: 2, online: false }), [1, 0.3, 0.3]);
|
||||
assert.equal(isAccessPoint("pack:nextfloor.a_smart2:access_point"), true);
|
||||
});
|
||||
|
||||
test("the network's health: connectivity sensors and router trackers", () => {
|
||||
const h = networkHealth([
|
||||
entity("binary_sensor.nas_online", "on", { device_class: "connectivity" }),
|
||||
entity("binary_sensor.printer_online", "off", { device_class: "connectivity", friendly_name: "Drucker" }),
|
||||
entity("device_tracker.phone", "home", { source_type: "router" }),
|
||||
entity("device_tracker.gps", "home", { source_type: "gps" }),
|
||||
]);
|
||||
assert.deepEqual(h, { online: 2, offline: ["Drucker"] });
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
// The Wi-Fi map: access points and mesh nodes of the plan with how many devices they carry, and how the house's network devices are
|
||||
// doing. Read from the entities of each access point's device (UniFi, Omada, FRITZ!Box, OpenWrt, Deco …).
|
||||
|
||||
import type { HassEntity, HomeAssistant } from "../types.ts";
|
||||
|
||||
/** Whether a piece of furniture is an access point, router or mesh node (by its pack item's id). */
|
||||
export const isAccessPoint = (type: string): boolean => /access_point|router|mesh|wifi|repeater/.test(type);
|
||||
|
||||
const has = (id: string, ...words: string[]) => words.some((w) => id.includes(w));
|
||||
|
||||
function siblings(hass: HomeAssistant, entity: string): string[] {
|
||||
const device = hass.entities?.[entity]?.device_id;
|
||||
if (!device) return hass.states[entity] ? [entity] : [];
|
||||
return Object.values(hass.entities ?? {})
|
||||
.filter((e) => e.device_id === device && !e.hidden)
|
||||
.map((e) => e.entity_id)
|
||||
.filter((id) => hass.states[id]);
|
||||
}
|
||||
|
||||
export interface AccessPointInfo {
|
||||
/** Devices connected now (null: it does not tell). */
|
||||
clients: number | null;
|
||||
online: boolean;
|
||||
}
|
||||
|
||||
/** What an access point reports: its clients (a "clients"/"stations"/"connected" sensor) and whether it is up. */
|
||||
export function readAccessPoint(hass: HomeAssistant, anchor: string | null): AccessPointInfo | null {
|
||||
if (!anchor || !hass.states[anchor]) return null;
|
||||
const all = siblings(hass, anchor);
|
||||
const count = all.find((id) => id.startsWith("sensor.") && has(id, "clients", "stations", "connected_devices", "users", "geräte", "wlan_clients") && Number.isFinite(Number(hass.states[id].state)));
|
||||
const status = all.map((id) => hass.states[id]).find((s) => s.entity_id.startsWith("binary_sensor.") && (s.attributes.device_class === "connectivity" || has(s.entity_id, "online", "connected", "status")));
|
||||
const st = hass.states[anchor];
|
||||
const down = ["unavailable", "off", "disconnected", "offline"].includes(String(status?.state ?? st.state).toLowerCase()) && (!!status || st.entity_id.startsWith("binary_sensor."));
|
||||
return { clients: count ? Number(hass.states[count].state) : null, online: !down && st.state !== "unavailable" };
|
||||
}
|
||||
|
||||
/** The coverage colour of an access point: blue while it has room, amber when busy, red when it is down. */
|
||||
export function coverageColor(ap: AccessPointInfo): [number, number, number] {
|
||||
if (!ap.online) return [1, 0.3, 0.3];
|
||||
if ((ap.clients ?? 0) >= 30) return [1, 0.72, 0.25];
|
||||
return [0.3, 0.7, 1];
|
||||
}
|
||||
|
||||
/** Network devices of the house (connectivity sensors and router trackers among the given entities): how many are online. */
|
||||
export function networkHealth(states: (HassEntity | undefined)[]): { online: number; offline: string[] } {
|
||||
let online = 0;
|
||||
const offline: string[] = [];
|
||||
for (const s of states) {
|
||||
if (!s) continue;
|
||||
const connectivity = s.entity_id.startsWith("binary_sensor.") && s.attributes.device_class === "connectivity";
|
||||
const tracker = s.entity_id.startsWith("device_tracker.") && s.attributes.source_type === "router";
|
||||
if (!connectivity && !tracker) continue;
|
||||
if (s.state === "on" || s.state === "home") online++;
|
||||
else offline.push(String(s.attributes.friendly_name ?? s.entity_id));
|
||||
}
|
||||
return { online, offline };
|
||||
}
|
||||
Reference in new issue
Block a user