kiosko-plugin-homeassistant 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,57 @@
1
1
  import { createRequire as __pluginRequire } from 'node:module'; const require = __pluginRequire(import.meta.url);
2
2
 
3
3
  // src/index.ts
4
- import { defineSource, definePlugin, defineWidget as defineWidget2, drawEmpty, listLayout, listOptions, t as t2 } from "@kiosko/sdk";
4
+ import { defineSource, definePlugin, defineWidget as defineWidget5, drawEmpty, listLayout, listOptions, t as t5 } from "@kiosko/sdk";
5
5
 
6
6
  // src/ha.ts
7
7
  import { matchFilter, filterPatterns } from "@kiosko/sdk";
8
+ function energyStats(prefs) {
9
+ const out = { gridIn: [], gridOut: [], solar: [], batteryIn: [], batteryOut: [], power: {} };
10
+ const sources = prefs?.energy_sources;
11
+ if (!Array.isArray(sources)) return out;
12
+ const id = (v) => typeof v === "string" && v ? v : void 0;
13
+ const rate = (s) => id(s.stat_rate) ?? id(s.power?.[0]?.stat_rate) ?? id(s.power_config?.stat_rate);
14
+ for (const s of sources) {
15
+ if (s?.type === "grid") {
16
+ for (const f of Array.isArray(s.flow_from) ? s.flow_from : []) if (id(f?.stat_energy_from)) out.gridIn.push(f.stat_energy_from);
17
+ for (const f of Array.isArray(s.flow_to) ? s.flow_to : []) if (id(f?.stat_energy_to)) out.gridOut.push(f.stat_energy_to);
18
+ const r = rate(s);
19
+ if (r) out.power.grid ??= r;
20
+ } else if (s?.type === "solar") {
21
+ if (id(s.stat_energy_from)) out.solar.push(s.stat_energy_from);
22
+ const r = rate(s);
23
+ if (r) out.power.solar ??= r;
24
+ } else if (s?.type === "battery") {
25
+ if (id(s.stat_energy_from)) out.batteryOut.push(s.stat_energy_from);
26
+ if (id(s.stat_energy_to)) out.batteryIn.push(s.stat_energy_to);
27
+ const r = rate(s);
28
+ if (r) out.power.battery ??= r;
29
+ }
30
+ }
31
+ return out;
32
+ }
33
+ function energyToday(stats, result, at) {
34
+ const rows = result ?? {};
35
+ const sum = (ids) => {
36
+ if (!ids.length) return void 0;
37
+ let total = 0;
38
+ for (const id of ids) for (const r of rows[id] ?? []) if (typeof r?.change === "number" && Number.isFinite(r.change)) total += r.change;
39
+ return total;
40
+ };
41
+ const e = { at };
42
+ const put = (k) => {
43
+ const v = sum(stats[k]);
44
+ if (v !== void 0) e[k] = v;
45
+ };
46
+ put("gridIn");
47
+ put("gridOut");
48
+ put("solar");
49
+ put("batteryIn");
50
+ put("batteryOut");
51
+ const power = Object.fromEntries(Object.entries(stats.power).filter(([, v]) => v));
52
+ if (Object.keys(power).length) e.power = power;
53
+ return e;
54
+ }
8
55
  var num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
9
56
  var str = (v) => typeof v === "string" && v ? v : void 0;
10
57
  function compact(s) {
@@ -32,7 +79,26 @@ function compact(s) {
32
79
  const battery = num(a.battery_level) ?? num(a.battery);
33
80
  if (battery !== void 0) e.battery = battery;
34
81
  const picture = str(a.entity_picture);
35
- if (picture && (e.domain === "camera" || e.domain === "image")) e.picture = picture;
82
+ if (picture && (e.domain === "camera" || e.domain === "image" || e.domain === "media_player")) e.picture = picture;
83
+ if (picture && (e.domain === "person" || e.domain === "device_tracker")) e.photo = picture;
84
+ if (e.domain === "media_player") {
85
+ const m = {};
86
+ const title = str(a.media_title);
87
+ if (title) m.title = title;
88
+ const artist = str(a.media_artist) ?? str(a.media_series_title);
89
+ if (artist) m.artist = artist;
90
+ const album = str(a.media_album_name);
91
+ if (album) m.album = album;
92
+ const app = str(a.app_name) ?? str(a.source);
93
+ if (app) m.app = app;
94
+ const duration = num(a.media_duration);
95
+ if (duration !== void 0 && duration > 0) m.duration = duration;
96
+ const position = num(a.media_position);
97
+ if (position !== void 0) m.position = position;
98
+ const at = Date.parse(str(a.media_position_updated_at) ?? "");
99
+ if (Number.isFinite(at)) m.positionAt = at;
100
+ if (Object.keys(m).length) e.media = m;
101
+ }
36
102
  return e;
37
103
  }
38
104
  function httpBase(address) {
@@ -161,8 +227,8 @@ var DANGER = /* @__PURE__ */ new Set(["smoke", "gas", "carbon_monoxide", "moistu
161
227
  var TROUBLE = /* @__PURE__ */ new Set(["problem", "tamper", "battery", "cold", "heat"]);
162
228
  var DEVICE_DOMAINS = /* @__PURE__ */ new Set(["sensor", "binary_sensor", "light", "switch", "lock", "cover", "climate", "fan", "media_player", "vacuum", "camera", "alarm_control_panel", "water_heater", "humidifier", "valve", "siren", "device_tracker"]);
163
229
  function stateText(e, ctx, decimals = -1) {
164
- const { t: t3 } = ctx;
165
- if (e.state === "unavailable" || e.state === "unknown") return t3(WORDS[e.state]);
230
+ const { t: t6 } = ctx;
231
+ if (e.state === "unavailable" || e.state === "unknown") return t6(WORDS[e.state]);
166
232
  if (e.deviceClass === "timestamp") {
167
233
  const at = Date.parse(e.state);
168
234
  if (Number.isFinite(at)) return at <= ctx.now ? ctx.fmt.ago(at) : ctx.fmt.time(at);
@@ -171,16 +237,16 @@ function stateText(e, ctx, decimals = -1) {
171
237
  if (n !== void 0 && e.domain !== "binary_sensor") return withUnit(formatNumber(n, ctx.locale, decimals), e.unit);
172
238
  if (e.domain === "binary_sensor") {
173
239
  const words = BINARY[e.deviceClass ?? ""] ?? on_off(WORDS.on, WORDS.off);
174
- if (e.state === "on" || e.state === "off") return t3(words[e.state]);
240
+ if (e.state === "on" || e.state === "off") return t6(words[e.state]);
175
241
  }
176
242
  if (e.domain === "climate" && e.current !== void 0) {
177
243
  const temp = withUnit(formatNumber(e.current, ctx.locale, decimals), e.unit ?? "\xB0");
178
- return e.action && e.action !== "idle" && e.action !== "off" ? `${temp} \xB7 ${t3(WORDS[e.action] ?? { en: e.action })}` : temp;
244
+ return e.action && e.action !== "idle" && e.action !== "off" ? `${temp} \xB7 ${t6(WORDS[e.action] ?? { en: e.action })}` : temp;
179
245
  }
180
- if (e.domain === "update") return t3(e.state === "on" ? BINARY.update.on : BINARY.update.off);
246
+ if (e.domain === "update") return t6(e.state === "on" ? BINARY.update.on : BINARY.update.off);
181
247
  if ((e.domain === "person" || e.domain === "device_tracker") && !WORDS[e.state]) return e.state;
182
248
  const w = WORDS[e.state];
183
- if (w) return t3(w);
249
+ if (w) return t6(w);
184
250
  const plain = e.state.replace(/_/g, " ");
185
251
  return plain.charAt(0).toUpperCase() + plain.slice(1);
186
252
  }
@@ -368,8 +434,8 @@ function parseHistory(rows) {
368
434
  const out = [];
369
435
  for (const r of rows) {
370
436
  const s = r?.s ?? r?.state;
371
- const t3 = num(r?.lu) ?? num(r?.lc);
372
- const at = t3 !== void 0 ? t3 * 1e3 : Date.parse(String(r?.last_changed ?? r?.last_updated ?? ""));
437
+ const t6 = num(r?.lu) ?? num(r?.lc);
438
+ const at = t6 !== void 0 ? t6 * 1e3 : Date.parse(String(r?.last_changed ?? r?.last_updated ?? ""));
373
439
  const value = numericState({ state: String(s) });
374
440
  if (value !== void 0 && Number.isFinite(at)) out.push({ at, value });
375
441
  }
@@ -388,6 +454,9 @@ function demoHome(now, locale = "en") {
388
454
  { id: "sensor.outdoor_temperature", name: n("Outdoor temperature", "Temperatura exterior"), state: "11.2", unit: "\xB0C", deviceClass: "temperature", stateClass: "measurement", changedAt: ago(6 * min) },
389
455
  { id: "sensor.house_power", name: n("House power", "Consumo de la casa"), state: "1534", unit: "W", deviceClass: "power", stateClass: "measurement", changedAt: ago(0.2 * min) },
390
456
  { id: "sensor.solar_power", name: n("Solar production", "Producci\xF3n solar"), state: "2210", unit: "W", deviceClass: "power", stateClass: "measurement", changedAt: ago(0.4 * min) },
457
+ { id: "sensor.grid_power", name: n("Grid power", "Potencia de la red"), state: "0", unit: "W", deviceClass: "power", stateClass: "measurement", changedAt: ago(0.1 * min) },
458
+ { id: "sensor.battery_power", name: n("Battery power", "Potencia de la bater\xEDa"), state: "-420", unit: "W", deviceClass: "power", stateClass: "measurement", changedAt: ago(0.1 * min) },
459
+ { id: "sensor.battery_level", name: n("Battery level", "Nivel de la bater\xEDa"), state: "64", unit: "%", deviceClass: "battery", stateClass: "measurement", changedAt: ago(3 * min) },
391
460
  { id: "sensor.energy_today", name: n("Energy today", "Energ\xEDa hoy"), state: "7.84", unit: "kWh", deviceClass: "energy", stateClass: "total_increasing", changedAt: ago(1 * min) },
392
461
  { id: "sensor.hallway_motion_battery", name: n("Hallway sensor battery", "Bater\xEDa sensor pasillo"), state: "8", unit: "%", deviceClass: "battery", stateClass: "measurement", changedAt: ago(30 * 36e5) },
393
462
  { id: "sensor.front_door_lock_battery", name: n("Front door lock battery", "Bater\xEDa cerradura"), state: "64", unit: "%", deviceClass: "battery", stateClass: "measurement", changedAt: ago(3 * 36e5) },
@@ -405,6 +474,8 @@ function demoHome(now, locale = "en") {
405
474
  { id: "climate.living_room", name: n("Thermostat", "Termostato"), state: "heat", current: 21.4, target: 22, action: "heating", unit: "\xB0C", changedAt: ago(3 * 36e5) },
406
475
  { id: "person.alex", name: "Alex", state: "home", changedAt: ago(4 * 36e5) },
407
476
  { id: "person.sam", name: "Sam", state: n("Work", "Trabajo"), changedAt: ago(6 * 36e5) },
477
+ { id: "person.robin", name: "Robin", state: "not_home", changedAt: ago(35 * min) },
478
+ { id: "media_player.living_room_speaker", name: n("Living room speaker", "Altavoz del sal\xF3n"), state: "playing", picture: "/api/media_player_proxy/media_player.living_room_speaker?token=demo", media: { title: n("Blue in Green", "Blue in Green"), artist: "Miles Davis", album: "Kind of Blue", app: "Spotify", duration: 337, position: 128, positionAt: ago(0) }, changedAt: ago(3 * min) },
408
479
  { id: "media_player.living_room_tv", name: n("Living room TV", "Tele del sal\xF3n"), state: "playing", changedAt: ago(25 * min) },
409
480
  { id: "sensor.garage_temperature", name: n("Garage temperature", "Temperatura garaje"), state: "unavailable", unit: "\xB0C", deviceClass: "temperature", stateClass: "measurement", changedAt: ago(14 * 36e5) },
410
481
  { id: "update.home_assistant_core_update", name: "Home Assistant Core", state: "on", changedAt: ago(20 * 36e5) }
@@ -429,7 +500,10 @@ function demoHome(now, locale = "en") {
429
500
  const e = entities2[id];
430
501
  e.state = String(Math.round(last * (e.unit === "W" ? 1 : 10)) / (e.unit === "W" ? 1 : 10));
431
502
  }
432
- return { state: "ok", version: "2026.11.1", base: "http://homeassistant.local:8123", entities: entities2, history };
503
+ const w = (id) => Number(entities2[id].state);
504
+ entities2["sensor.grid_power"].state = String(Math.round(w("sensor.house_power") - w("sensor.solar_power") - w("sensor.battery_power")));
505
+ const energy2 = { gridIn: 3.1, gridOut: 4.6, solar: 14.2, batteryIn: 3.4, batteryOut: 2.1, at: now };
506
+ return { state: "ok", version: "2026.11.1", base: "http://homeassistant.local:8123", energy: energy2, entities: entities2, history };
433
507
  }
434
508
 
435
509
  // src/connection.ts
@@ -452,6 +526,7 @@ var PING_MS = 3e4;
452
526
  var FLUSH_MS = 1e3;
453
527
  var RETRY_MS = [2e3, 5e3, 1e4, 3e4, 6e4];
454
528
  var AUTH_RETRY_MS = 5 * 6e4;
529
+ var ENERGY_MS = 5 * 6e4;
455
530
  function connect(o, emit, deps = {}) {
456
531
  const timers = deps.timers ?? realTimers;
457
532
  const log = deps.log ?? (() => {
@@ -471,7 +546,10 @@ function connect(o, emit, deps = {}) {
471
546
  let ws = null;
472
547
  let attempt = 0;
473
548
  let nextId = 1;
474
- let ids = { states: 0, subscribe: 0, history: 0, ping: 0 };
549
+ let ids = { states: 0, subscribe: 0, history: 0, ping: 0, prefs: 0, energy: 0 };
550
+ let stats = null;
551
+ let energy2;
552
+ let energyTimer = null;
475
553
  let awaitingPong = false;
476
554
  let retryTimer = null;
477
555
  let pingTimer = null;
@@ -482,6 +560,7 @@ function connect(o, emit, deps = {}) {
482
560
  ...since !== void 0 ? { since } : {},
483
561
  ...version ? { version } : {},
484
562
  base: httpBase(o.url),
563
+ ...energy2 ? { energy: energy2 } : {},
485
564
  entities: Object.fromEntries(entities2),
486
565
  history
487
566
  });
@@ -575,7 +654,7 @@ function connect(o, emit, deps = {}) {
575
654
  const n = Number(e.state);
576
655
  if (Number.isFinite(n) && e.state.trim() !== "") history.add(id, Date.parse(data.new_state.last_updated ?? "") || timers.now(), n, timers.now());
577
656
  }
578
- if (prev && prev.state === e.state && prev.name === e.name && prev.current === e.current && prev.target === e.target && prev.action === e.action && prev.battery === e.battery) return;
657
+ if (prev && prev.state === e.state && prev.name === e.name && prev.current === e.current && prev.target === e.target && prev.action === e.action && prev.battery === e.battery && prev.picture === e.picture && prev.photo === e.photo && JSON.stringify(prev.media) === JSON.stringify(e.media)) return;
579
658
  changed();
580
659
  };
581
660
  const onMessage = (raw) => {
@@ -600,6 +679,7 @@ function connect(o, emit, deps = {}) {
600
679
  request({ type: "supported_features", features: { coalesce_messages: 1 } });
601
680
  request({ type: "get_states" }, "states");
602
681
  request({ type: "subscribe_events", event_type: "state_changed" }, "subscribe");
682
+ request({ type: "energy/get_prefs" }, "prefs");
603
683
  pingTimer = timers.setTimeout(ping, PING_MS);
604
684
  return;
605
685
  case "auth_invalid":
@@ -633,16 +713,41 @@ function connect(o, emit, deps = {}) {
633
713
  onHistory(m.result);
634
714
  changed();
635
715
  } else log(`no history: ${m.error?.message ?? "refused"}`);
716
+ } else if (m.id === ids.prefs) {
717
+ stats = m.success ? energyStats(m.result) : null;
718
+ if (stats && [stats.gridIn, stats.gridOut, stats.solar, stats.batteryIn, stats.batteryOut].some((l) => l.length)) readEnergy();
719
+ else stats = null;
720
+ } else if (m.id === ids.energy) {
721
+ if (m.success && stats) {
722
+ energy2 = energyToday(stats, m.result, timers.now());
723
+ changed();
724
+ } else if (!m.success) log(`no energy statistics: ${m.error?.message ?? "refused"}`);
636
725
  } else if (m.id === ids.subscribe && !m.success) {
637
726
  log(`subscribe failed: ${m.error?.message ?? "refused"}`);
638
727
  }
639
728
  return;
640
729
  }
641
730
  };
731
+ const readEnergy = () => {
732
+ energyTimer = null;
733
+ if (stopped || !ws || !stats) return;
734
+ const midnight = new Date(timers.now());
735
+ midnight.setHours(0, 0, 0, 0);
736
+ request({
737
+ type: "recorder/statistics_during_period",
738
+ start_time: midnight.toISOString(),
739
+ statistic_ids: [.../* @__PURE__ */ new Set([...stats.gridIn, ...stats.gridOut, ...stats.solar, ...stats.batteryIn, ...stats.batteryOut])],
740
+ period: "day",
741
+ types: ["change"],
742
+ units: { energy: "kWh" }
743
+ }, "energy");
744
+ energyTimer = timers.setTimeout(readEnergy, ENERGY_MS);
745
+ };
642
746
  const clearTimers = () => {
643
747
  if (pingTimer) timers.clearTimeout(pingTimer);
644
748
  if (retryTimer) timers.clearTimeout(retryTimer);
645
- pingTimer = retryTimer = null;
749
+ if (energyTimer) timers.clearTimeout(energyTimer);
750
+ pingTimer = retryTimer = energyTimer = null;
646
751
  };
647
752
  const close = (ms) => {
648
753
  clearTimers();
@@ -671,7 +776,7 @@ function connect(o, emit, deps = {}) {
671
776
  retryTimer = null;
672
777
  if (stopped) return;
673
778
  awaitingPong = false;
674
- ids = { states: 0, subscribe: 0, history: 0, ping: 0 };
779
+ ids = { states: 0, subscribe: 0, history: 0, ping: 0, prefs: 0, energy: 0 };
675
780
  nextId = 1;
676
781
  let w;
677
782
  try {
@@ -763,7 +868,13 @@ var ICON_PATHS = {
763
868
  "speaker": "M6 2H18A2 2 0 0 1 20 4V20A2 2 0 0 1 18 22H6A2 2 0 0 1 4 20V4A2 2 0 0 1 6 2ZM12 6h.01M8 14a4 4 0 1 0 8 0a4 4 0 1 0 -8 0ZM12 14h.01",
764
869
  "cpu": "M12 20v2M12 2v2M17 20v2M17 2v2M2 12h2M2 17h2M2 7h2M20 12h2M20 17h2M20 7h2M7 20v2M7 2v2M6 4H18A2 2 0 0 1 20 6V18A2 2 0 0 1 18 20H6A2 2 0 0 1 4 18V6A2 2 0 0 1 6 4ZM9 8H15A1 1 0 0 1 16 9V15A1 1 0 0 1 15 16H9A1 1 0 0 1 8 15V9A1 1 0 0 1 9 8Z",
765
870
  "clock": "M2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0ZM12 6v6l4 2",
766
- "circle-dot": "M11 12a1 1 0 1 0 2 0a1 1 0 1 0 -2 0ZM2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0Z"
871
+ "circle-dot": "M11 12a1 1 0 1 0 2 0a1 1 0 1 0 -2 0ZM2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0Z",
872
+ "utility-pole": "M12 2v20M2 5h20M3 3v2M7 3v2M17 3v2M21 3v2M19 5l-7 7-7-7",
873
+ "music": "M21 16V3a1 1 0 0 0-1.28-.96l-10 2.917a1 1 0 0 0-.72.96V19M15 16a3 3 0 1 0 6 0a3 3 0 1 0 -6 0M3 19a3 3 0 1 0 6 0a3 3 0 1 0 -6 0",
874
+ "map-pin": "M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0M9 10a3 3 0 1 0 6 0a3 3 0 1 0 -6 0",
875
+ "users": "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M16 3.128a4 4 0 0 1 0 7.744M22 21v-2a4 4 0 0 0-3-3.87M5 7a4 4 0 1 0 8 0a4 4 0 1 0 -8 0",
876
+ "cast": "M2 8V6a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-6M2 12a9 9 0 0 1 8 8M2 16a5 5 0 0 1 4 4M2 20L2.01 20",
877
+ "house-plug": "M10 12V8.964M14 12V8.964M15 12a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2v-2a1 1 0 0 1 1-1zM8.5 21H5a2 2 0 0 1-2-2v-9a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2h-5a2 2 0 0 1-2-2v-2"
767
878
  };
768
879
 
769
880
  // src/icons.ts
@@ -1520,6 +1631,15 @@ import { createHash } from "node:crypto";
1520
1631
  import { defineWidget, t } from "@kiosko/sdk";
1521
1632
  var SOURCE = "homeassistant/states";
1522
1633
  var dataOf = (sources) => sources[SOURCE];
1634
+ var RING_MS = 6e4;
1635
+ function ringing(e, now) {
1636
+ if (!e) return false;
1637
+ if (e.domain === "event") {
1638
+ const at = Date.parse(e.state);
1639
+ return Number.isFinite(at) && now - at >= -5e3 && now - at < RING_MS;
1640
+ }
1641
+ return e.state === "on";
1642
+ }
1523
1643
  var seen = /* @__PURE__ */ new Map();
1524
1644
  function pictureChangedAt(camera2, bytes, now) {
1525
1645
  const hash = createHash("sha1").update(bytes).digest("hex");
@@ -1528,6 +1648,12 @@ function pictureChangedAt(camera2, bytes, now) {
1528
1648
  seen.set(camera2, { hash, at: now });
1529
1649
  return now;
1530
1650
  }
1651
+ async function readPicture(base, path, signal) {
1652
+ const url = /^https?:\/\//i.test(path) ? path : base + (path.startsWith("/") ? path : `/${path}`);
1653
+ const res = await fetch(url, signal ? { signal } : {});
1654
+ if (!res.ok) throw new Error(`Home Assistant answered HTTP ${res.status} for ${path.split("?")[0]}`);
1655
+ return new Uint8Array(await res.arrayBuffer());
1656
+ }
1531
1657
  function motionOf(entities2, camera2, chosen) {
1532
1658
  if (chosen) return entities2[chosen];
1533
1659
  const auto = `binary_sensor.${camera2.split(".")[1] ?? ""}_motion`;
@@ -1568,6 +1694,12 @@ var camera = defineWidget({
1568
1694
  label: { en: "Motion sensor", es: "Sensor de movimiento" },
1569
1695
  help: { en: "Empty = binary_sensor.<camera>_motion if there is one (Blink names them so).", es: "Vac\xEDo = binary_sensor.<c\xE1mara>_motion si existe (Blink los llama as\xED)." }
1570
1696
  }),
1697
+ doorbell: t.string({
1698
+ choices: { source: SOURCE, list: "doorbells" },
1699
+ placeholder: "event.front_door_ding",
1700
+ label: { en: "Doorbell", es: "Timbre" },
1701
+ help: { en: "An event entity (event.*) or a binary sensor: for a minute after it rings, a mark on the picture, and the camera takes the tile if allowed.", es: "Una entidad de evento (event.*) o un sensor binario: durante un minuto tras sonar, una marca en la imagen, y la c\xE1mara se queda con la tesela si se le deja." }
1702
+ }),
1571
1703
  fit: t.enum(["cover", "contain"], { label: { en: "Fit", es: "Ajuste" }, labels: { cover: { en: "Fill (crop)", es: "Llenar (recorta)" }, contain: { en: "Whole picture", es: "Imagen entera" } } }),
1572
1704
  keep: t.enum(["center", "top", "bottom"], {
1573
1705
  advanced: true,
@@ -1579,7 +1711,8 @@ var camera = defineWidget({
1579
1711
  }),
1580
1712
  intervalMs: 6e4,
1581
1713
  // Until the connection has the camera, look again soon: the first picture shouldn't wait a minute.
1582
- intervalOf: ({ data }) => !data || data.state === "waiting" ? 5e3 : void 0,
1714
+ // While someone moves or rings, every 10 s: the picture to look at is the one of now.
1715
+ intervalOf: ({ data }) => !data || data.state === "waiting" ? 5e3 : data.lively ? 1e4 : void 0,
1583
1716
  timeoutMs: 3e4,
1584
1717
  async fetch({ options, sources, canvas, signal }) {
1585
1718
  if (!options.entity) return { state: "pick" };
@@ -1588,15 +1721,16 @@ var camera = defineWidget({
1588
1721
  const e = d.entities[options.entity];
1589
1722
  if (!e) return { state: "missing" };
1590
1723
  if (!e.picture) return { state: "nopicture" };
1591
- const res = await fetch(d.base + e.picture, { signal });
1592
- if (!res.ok) throw new Error(`Home Assistant answered HTTP ${res.status} for ${options.entity}`);
1593
- const bytes = new Uint8Array(await res.arrayBuffer());
1594
- return { state: "ok", img: await canvas.loadImage(Buffer.from(bytes)), changedAt: pictureChangedAt(options.entity, bytes, Date.now()) };
1724
+ const bytes = await readPicture(d.base, e.picture, signal);
1725
+ const now = Date.now();
1726
+ const lively = motionOf(d.entities, e.id, options.motion)?.state === "on" || ringing(options.doorbell ? d.entities[options.doorbell] : void 0, now);
1727
+ return { state: "ok", img: await canvas.loadImage(Buffer.from(bytes)), changedAt: pictureChangedAt(options.entity, bytes, now), ...lively ? { lively } : {} };
1595
1728
  },
1596
1729
  redraw: "minute",
1597
- urgent: ({ options, sources }) => {
1730
+ urgent: ({ options, sources, now }) => {
1598
1731
  const d = dataOf(sources);
1599
- return d?.state === "ok" && !!options.entity && motionOf(d.entities, options.entity, options.motion)?.state === "on";
1732
+ if (d?.state !== "ok" || !options.entity) return false;
1733
+ return motionOf(d.entities, options.entity, options.motion)?.state === "on" || ringing(options.doorbell ? d.entities[options.doorbell] : void 0, now);
1600
1734
  },
1601
1735
  // Off by default: a camera's tile is for looking, not for interrupting. The user turns it on.
1602
1736
  takeOver: false,
@@ -1637,6 +1771,7 @@ var camera = defineWidget({
1637
1771
  name: options.showName ? options.name || e?.name || options.entity : "",
1638
1772
  age: options.showAge && data.changedAt ? ctx.fmt.ago(data.changedAt) : "",
1639
1773
  motion: motion?.state === "on",
1774
+ ring: !!d && ringing(options.doorbell ? d.entities[options.doorbell] : void 0, ctx.now),
1640
1775
  stale: stale ? e?.state === "unavailable" ? tr({ en: "camera unavailable", es: "c\xE1mara no disponible" }) : tr({ en: "offline", es: "sin conexi\xF3n" }) : ""
1641
1776
  });
1642
1777
  },
@@ -1694,9 +1829,10 @@ function overlay(g, ctx, o) {
1694
1829
  kit.drawTracked(g, text, x + ps * (dot ? 1.55 : 0.7), y + h / 2 + ps * 0.36, { size: ps, family: fonts.sansBold, color: dot ? "#fff" : color });
1695
1830
  x += w + ps * 0.5;
1696
1831
  };
1697
- if (o.motion) {
1698
- pill(ctx.t({ en: "Motion", es: "Movimiento" }), colors.alert, true);
1699
- g.strokeStyle = colors.alert;
1832
+ if (o.ring) pill(ctx.t({ en: "Doorbell", es: "Llaman" }), colors.warn, true);
1833
+ if (o.motion) pill(ctx.t({ en: "Motion", es: "Movimiento" }), colors.alert, true);
1834
+ if (o.motion || o.ring) {
1835
+ g.strokeStyle = o.motion ? colors.alert : colors.warn;
1700
1836
  g.lineWidth = Math.max(2, Math.round(s * 0.18));
1701
1837
  g.strokeRect(box.x + g.lineWidth / 2, box.y + g.lineWidth / 2, box.w - g.lineWidth, box.h - g.lineWidth);
1702
1838
  }
@@ -1745,8 +1881,504 @@ function drawScene(g, b) {
1745
1881
  g.fillRect(b.x, b.y, b.w, b.h);
1746
1882
  }
1747
1883
 
1748
- // src/index.ts
1884
+ // src/energy.ts
1885
+ import { defineWidget as defineWidget2, t as t2 } from "@kiosko/sdk";
1749
1886
  var SOURCE2 = "homeassistant/states";
1887
+ var dataOf2 = (sources) => sources[SOURCE2];
1888
+ function flows(p) {
1889
+ const solar = Math.max(0, p.solar ?? 0);
1890
+ const gridIn = Math.max(0, p.grid ?? 0);
1891
+ const gridOut = Math.max(0, -(p.grid ?? 0));
1892
+ const batOut = Math.max(0, p.battery ?? 0);
1893
+ const batIn = Math.max(0, -(p.battery ?? 0));
1894
+ const solarBattery = Math.min(solar, batIn);
1895
+ const gridBattery = Math.min(gridIn, batIn - solarBattery);
1896
+ const solarGrid = Math.min(solar - solarBattery, gridOut);
1897
+ const batteryGrid = Math.min(batOut, gridOut - solarGrid);
1898
+ const solarHome = Math.max(0, solar - solarBattery - solarGrid);
1899
+ const gridHome = Math.max(0, gridIn - gridBattery);
1900
+ const batteryHome = Math.max(0, batOut - batteryGrid);
1901
+ return { solarHome, solarGrid, solarBattery, gridHome, gridBattery, batteryHome, batteryGrid, home: solarHome + gridHome + batteryHome };
1902
+ }
1903
+ function watts(e) {
1904
+ if (!e) return void 0;
1905
+ const n = numericState(e);
1906
+ if (n === void 0) return void 0;
1907
+ const u = (e.unit ?? "W").trim();
1908
+ return u === "kW" ? n * 1e3 : u === "MW" ? n * 1e6 : n;
1909
+ }
1910
+ function formatPower(w, locale) {
1911
+ const a = Math.abs(w);
1912
+ return a < 1e3 ? `${formatNumber(Math.round(a), locale, 0)} W` : `${formatNumber(a / 1e3, locale, a < 1e4 ? 2 : 1)} kW`;
1913
+ }
1914
+ var formatEnergy = (kwh, locale) => `${formatNumber(kwh, locale, kwh < 10 ? 1 : 0)} kWh`;
1915
+ function homeToday(e) {
1916
+ if (e.gridIn === void 0 && e.solar === void 0 && e.batteryOut === void 0) return void 0;
1917
+ return Math.max(0, (e.gridIn ?? 0) + (e.solar ?? 0) + (e.batteryOut ?? 0) - (e.gridOut ?? 0) - (e.batteryIn ?? 0));
1918
+ }
1919
+ var IDLE_W = 10;
1920
+ var energy = defineWidget2({
1921
+ id: "energy",
1922
+ name: { en: "Energy flow", es: "Flujo de energ\xEDa" },
1923
+ description: {
1924
+ en: "Where the power comes from and goes, now: the grid, the solar panels and the battery around the house, a line for every flow (thicker the more it carries) and today's kWh from the Energy dashboard. A grid sensor is enough to start.",
1925
+ es: "De d\xF3nde viene la energ\xEDa y ad\xF3nde va, ahora: la red, las placas y la bater\xEDa alrededor de la casa, una l\xEDnea por cada flujo (m\xE1s gruesa cuanto m\xE1s lleva) y los kWh de hoy del panel de Energ\xEDa. Basta un sensor de la red para empezar."
1926
+ },
1927
+ icon: "zap",
1928
+ category: "info",
1929
+ tags: ["home assistant", "energy", "solar", "battery"],
1930
+ size: { min: { w: 220, h: 140 }, preferred: { w: 420, h: 300 } },
1931
+ sources: [SOURCE2],
1932
+ options: t2.object({
1933
+ grid: t2.string({
1934
+ choices: { source: SOURCE2, list: "power" },
1935
+ placeholder: "sensor.grid_power",
1936
+ label: { en: "Grid power", es: "Potencia de la red" },
1937
+ help: { en: "W or kW, positive while buying. Empty = the one in the Energy dashboard.", es: "W o kW, positiva al comprar. Vac\xEDo = la del panel de Energ\xEDa." }
1938
+ }),
1939
+ gridExportPositive: t2.boolean({ label: { en: "The grid sensor is positive while selling", es: "El sensor de la red es positivo al vender" } }),
1940
+ solar: t2.string({ choices: { source: SOURCE2, list: "power" }, placeholder: "sensor.solar_power", label: { en: "Solar power", es: "Potencia solar" }, help: { en: "Empty = the one in the Energy dashboard, or none.", es: "Vac\xEDo = la del panel de Energ\xEDa, o ninguna." } }),
1941
+ battery: t2.string({ choices: { source: SOURCE2, list: "power" }, placeholder: "sensor.battery_power", label: { en: "Battery power", es: "Potencia de la bater\xEDa" }, help: { en: "Positive while discharging. Empty = the one in the Energy dashboard, or none.", es: "Positiva al descargar. Vac\xEDo = la del panel de Energ\xEDa, o ninguna." } }),
1942
+ batteryChargePositive: t2.boolean({ label: { en: "The battery sensor is positive while charging", es: "El sensor de la bater\xEDa es positivo al cargar" } }),
1943
+ batteryLevel: t2.string({ choices: { source: SOURCE2, list: "entities" }, placeholder: "sensor.battery_state_of_charge", label: { en: "Battery level", es: "Nivel de la bater\xEDa" }, help: { en: "Its %, shown in the battery.", es: "Su %, que se ve en la bater\xEDa." } }),
1944
+ showToday: t2.boolean({ default: true, label: { en: "Today's energy", es: "La energ\xEDa de hoy" }, help: { en: "From the Energy dashboard, under each part.", es: "Del panel de Energ\xEDa, bajo cada parte." } }),
1945
+ moving: t2.boolean({ default: true, label: { en: "Moving dots", es: "Puntos en movimiento" }, help: { en: "Repaints the tile every second.", es: "Vuelve a pintar la tesela cada segundo." } })
1946
+ }),
1947
+ redraw: ({ options }) => options.moving ? "second" : "minute",
1948
+ render(g, ctx) {
1949
+ const { options, sources, t: tr, theme, locale } = ctx;
1950
+ const d = dataOf2(sources);
1951
+ const box = ctx.box;
1952
+ if (!d || d.state === "unconfigured") return drawMessage(g, box, ctx, tr({ en: "Home Assistant not set up", es: "Home Assistant sin configurar" }), tr({ en: "Set its address and a token in Settings \u2192 Data sources", es: "Pon su direcci\xF3n y un token en Ajustes \u2192 Fuentes de datos" }));
1953
+ if (d.state === "connecting") return drawMessage(g, box, ctx, tr({ en: "Connecting to Home Assistant\u2026", es: "Conectando con Home Assistant\u2026" }));
1954
+ const ids = { grid: options.grid || d.energy?.power?.grid, solar: options.solar || d.energy?.power?.solar, battery: options.battery || d.energy?.power?.battery };
1955
+ const raw = { grid: watts(ids.grid ? d.entities[ids.grid] : void 0), solar: watts(ids.solar ? d.entities[ids.solar] : void 0), battery: watts(ids.battery ? d.entities[ids.battery] : void 0) };
1956
+ if (raw.grid === void 0 && raw.solar === void 0 && raw.battery === void 0) {
1957
+ return drawMessage(g, box, ctx, tr({ en: "Choose the power sensors", es: "Elige los sensores de potencia" }), tr({ en: "At least the grid one, in the inspector (or set them in the Energy dashboard of Home Assistant).", es: "Al menos el de la red, en el inspector (o ponlos en el panel de Energ\xEDa de Home Assistant)." }));
1958
+ }
1959
+ const p = {
1960
+ ...raw.grid !== void 0 ? { grid: options.gridExportPositive ? -raw.grid : raw.grid } : {},
1961
+ ...raw.solar !== void 0 ? { solar: raw.solar } : {},
1962
+ ...raw.battery !== void 0 ? { battery: options.batteryChargePositive ? -raw.battery : raw.battery } : {}
1963
+ };
1964
+ const f = flows(p);
1965
+ const level = options.batteryLevel ? numericState(d.entities[options.batteryLevel] ?? { state: "" }) : void 0;
1966
+ const today = options.showToday ? d.energy : void 0;
1967
+ const { colors } = theme;
1968
+ const C = { grid: colors.info, solar: colors.warn, battery: colors.ok, home: colors.ink };
1969
+ const has = { solar: p.solar !== void 0, battery: p.battery !== void 0, grid: p.grid !== void 0 };
1970
+ const rowH = Math.max(11, Math.min(20, box.h * 0.07));
1971
+ const textH = rowH * (today ? 2.5 : 1.4);
1972
+ const r = Math.max(10, Math.min(box.w * 0.085, box.h / (has.solar && has.battery ? 5.4 : has.solar || has.battery ? 3.6 : 2.6)));
1973
+ const midY = has.solar && has.battery ? box.y + box.h / 2 - textH * 0.3 : has.solar ? box.y + box.h - textH - r - 4 : has.battery ? box.y + r + 4 : box.y + (box.h - textH) / 2;
1974
+ const span = Math.min(box.w, Math.max(box.h * 2.1, 280));
1975
+ const left = box.x + (box.w - span) / 2;
1976
+ const m = r + Math.max(2, r * 0.12) / 2 + 1;
1977
+ const at = {
1978
+ grid: { x: left + m, y: midY },
1979
+ home: { x: left + span - m, y: midY },
1980
+ solar: { x: left + span / 2, y: box.y + m },
1981
+ battery: { x: left + span / 2, y: box.y + box.h - m }
1982
+ };
1983
+ const maxW = Math.max(1e3, ...Object.values(f));
1984
+ const line = (from, to, w, color, bend) => {
1985
+ const on = w >= IDLE_W;
1986
+ const mx = (from.x + to.x) / 2 + (to.y - from.y) * bend;
1987
+ const my = (from.y + to.y) / 2 - (to.x - from.x) * bend;
1988
+ g.strokeStyle = on ? alpha(color, 0.75) : alpha(colors.inkFaint, 0.5);
1989
+ g.lineWidth = on ? Math.max(1.5, Math.min(r * 0.22, 1.5 + w / maxW * r * 0.2)) : 1;
1990
+ g.lineCap = "round";
1991
+ g.beginPath();
1992
+ g.moveTo(from.x, from.y);
1993
+ g.quadraticCurveTo(mx, my, to.x, to.y);
1994
+ g.stroke();
1995
+ if (!on) return;
1996
+ const len = Math.hypot(to.x - from.x, to.y - from.y);
1997
+ const n = Math.max(2, Math.round(len / (r * 1.4)));
1998
+ const speed = 0.12 + 0.35 * Math.min(1, w / maxW);
1999
+ const phase = options.moving ? ctx.now / 1e3 * speed % 1 : 0.5 / n;
2000
+ g.fillStyle = color;
2001
+ for (let i = 0; i < n; i++) {
2002
+ const tt = (i / n + phase) % 1;
2003
+ const x = (1 - tt) ** 2 * from.x + 2 * (1 - tt) * tt * mx + tt ** 2 * to.x;
2004
+ const y = (1 - tt) ** 2 * from.y + 2 * (1 - tt) * tt * my + tt ** 2 * to.y;
2005
+ g.beginPath();
2006
+ g.arc(x, y, Math.max(1.5, g.lineWidth * 0.9), 0, Math.PI * 2);
2007
+ g.fill();
2008
+ }
2009
+ };
2010
+ if (has.grid) line(at.grid, at.home, f.gridHome, C.grid, 0);
2011
+ if (has.solar) {
2012
+ line(at.solar, at.home, f.solarHome, C.solar, -0.12);
2013
+ if (has.grid) line(at.solar, at.grid, f.solarGrid, C.solar, 0.12);
2014
+ if (has.battery) line(at.solar, at.battery, f.solarBattery, C.solar, 0);
2015
+ }
2016
+ if (has.battery) {
2017
+ line(at.battery, at.home, f.batteryHome, C.battery, 0.12);
2018
+ if (has.grid) {
2019
+ if (f.gridBattery >= IDLE_W) line(at.grid, at.battery, f.gridBattery, C.grid, 0.12);
2020
+ else line(at.battery, at.grid, f.batteryGrid, C.battery, -0.12);
2021
+ }
2022
+ }
2023
+ const node = (pos, icon, color, value, sub, active, place, fill) => {
2024
+ g.fillStyle = theme.colors.surface;
2025
+ g.beginPath();
2026
+ g.arc(pos.x, pos.y, r, 0, Math.PI * 2);
2027
+ g.fill();
2028
+ if (fill !== void 0) {
2029
+ g.strokeStyle = alpha(color, 0.25);
2030
+ g.lineWidth = Math.max(2, r * 0.12);
2031
+ g.beginPath();
2032
+ g.arc(pos.x, pos.y, r, 0, Math.PI * 2);
2033
+ g.stroke();
2034
+ g.strokeStyle = color;
2035
+ g.beginPath();
2036
+ g.arc(pos.x, pos.y, r, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * Math.max(0, Math.min(100, fill)) / 100);
2037
+ g.stroke();
2038
+ } else {
2039
+ g.strokeStyle = active ? color : alpha(color, 0.35);
2040
+ g.lineWidth = Math.max(1.5, r * 0.08);
2041
+ g.beginPath();
2042
+ g.arc(pos.x, pos.y, r, 0, Math.PI * 2);
2043
+ g.stroke();
2044
+ }
2045
+ const s = r * 0.95;
2046
+ drawIcon(g, icon, pos.x - s / 2, pos.y - s / 2, s, active ? color : alpha(color, 0.6));
2047
+ const vs = Math.round(rowH);
2048
+ const so = { size: Math.round(vs * 0.78), family: theme.fonts.sans, color: theme.colors.inkDim };
2049
+ const vo = { size: vs, family: theme.fonts.sansBold, color: active ? theme.colors.ink : theme.colors.inkDim };
2050
+ let tx, ty, align, maxTw;
2051
+ if (place === "right") [tx, ty, align, maxTw] = [pos.x + r * 1.25, pos.y - vs * 0.1, "left", box.x + box.w - pos.x - r * 1.3];
2052
+ else if (place === "below-left") [tx, ty, align, maxTw] = [pos.x - r, pos.y + r + vs * 1.15, "left", span / 2 - r];
2053
+ else if (place === "below-right") [tx, ty, align, maxTw] = [pos.x + r, pos.y + r + vs * 1.15, "right", span / 2 - r];
2054
+ else [tx, ty, align, maxTw] = [pos.x, pos.y + r + vs * 1.15, "center", span * 0.4];
2055
+ ctx.kit.drawTracked(g, ctx.kit.truncate(g, value, maxTw, vo), tx, ty, { ...vo, align });
2056
+ sub.forEach((line2, i) => ctx.kit.drawTracked(g, ctx.kit.truncate(g, line2, maxTw, so), tx, ty + vs * 1.1 * (i + 1), { ...so, align }));
2057
+ };
2058
+ const kwh = (n) => n === void 0 ? void 0 : formatEnergy(n, locale);
2059
+ const both = (a, b) => [a, b].filter(Boolean).join(" ");
2060
+ if (has.grid) {
2061
+ const v = p.grid >= 0 ? formatPower(p.grid, locale) : `${formatPower(p.grid, locale)} \u2191`;
2062
+ node(at.grid, "utility-pole", C.grid, v, today ? [both(today.gridIn !== void 0 ? `\u2193 ${kwh(today.gridIn)}` : "", today.gridOut ? `\u2191 ${kwh(today.gridOut)}` : "")].filter(Boolean) : [], Math.abs(p.grid) >= IDLE_W, "below-left");
2063
+ }
2064
+ if (has.solar) node(at.solar, "sun", C.solar, formatPower(p.solar, locale), today?.solar !== void 0 ? [kwh(today.solar)] : [], p.solar >= IDLE_W, "right");
2065
+ if (has.battery) {
2066
+ const b = p.battery;
2067
+ const v = `${formatPower(b, locale)}${b >= IDLE_W ? " \u2193" : b <= -IDLE_W ? " \u2191" : ""}`;
2068
+ const sub = level !== void 0 ? [`${formatNumber(level, locale, 0)} %`] : today ? [both(today.batteryOut !== void 0 ? `\u2193 ${kwh(today.batteryOut)}` : "", today.batteryIn !== void 0 ? `\u2191 ${kwh(today.batteryIn)}` : "")].filter(Boolean) : [];
2069
+ node(at.battery, "battery", C.battery, v, sub, Math.abs(b) >= IDLE_W, "right", level);
2070
+ }
2071
+ const home = today ? homeToday(today) : void 0;
2072
+ node(at.home, "house", C.home, formatPower(f.home, locale), home !== void 0 ? [kwh(home)] : [], f.home >= IDLE_W, "below-right");
2073
+ if (d.state !== "ok") {
2074
+ const s = Math.max(10, Math.round(rowH * 0.8));
2075
+ ctx.kit.drawTracked(g, tr({ en: "offline", es: "sin conexi\xF3n" }), box.x + box.w, box.y + s, { size: s, family: theme.fonts.sans, color: theme.colors.warn, align: "right" });
2076
+ }
2077
+ },
2078
+ demo: ({ now, locale }) => ({ sources: { [SOURCE2]: demoHome(now, locale) }, options: { grid: "sensor.grid_power", solar: "sensor.solar_power", battery: "sensor.battery_power", batteryLevel: "sensor.battery_level" } })
2079
+ });
2080
+
2081
+ // src/media.ts
2082
+ import { defineWidget as defineWidget3, t as t3 } from "@kiosko/sdk";
2083
+ var SOURCE3 = "homeassistant/states";
2084
+ var dataOf3 = (sources) => sources[SOURCE3];
2085
+ var ACTIVE = /* @__PURE__ */ new Set(["playing", "paused", "buffering", "on"]);
2086
+ function pickPlayer(entities2, chosen) {
2087
+ if (chosen && !/[*!,]/.test(chosen)) return entities2[chosen];
2088
+ const all = pick(entities2, chosen || "media_player.*").filter((e) => e.domain === "media_player");
2089
+ const rank = (e) => e.state === "playing" ? 2 : e.state === "paused" || e.state === "buffering" ? 1 : 0;
2090
+ return all.sort((a, b) => rank(b) - rank(a) || b.changedAt - a.changedAt)[0];
2091
+ }
2092
+ function positionNow(e, now) {
2093
+ const m = e.media;
2094
+ if (m?.position === void 0) return void 0;
2095
+ const moved = e.state === "playing" && m.positionAt ? (now - m.positionAt) / 1e3 : 0;
2096
+ const p = m.position + Math.max(0, moved);
2097
+ return m.duration ? Math.min(m.duration, p) : p;
2098
+ }
2099
+ function clock(s) {
2100
+ const v = Math.max(0, Math.floor(s));
2101
+ const h = Math.floor(v / 3600), m = Math.floor(v % 3600 / 60), sec = v % 60;
2102
+ return h ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` : `${m}:${String(sec).padStart(2, "0")}`;
2103
+ }
2104
+ var media = defineWidget3({
2105
+ id: "media",
2106
+ name: { en: "Now playing", es: "Lo que suena" },
2107
+ description: {
2108
+ en: "What a Home Assistant media player is playing (the TV, Spotify on a speaker, a Chromecast, Sonos\u2026): cover, title, artist, the app and how far it has got. Of several, the one playing. Hides itself while nothing plays.",
2109
+ es: "Lo que reproduce un media player de Home Assistant (la tele, Spotify en un altavoz, un Chromecast, Sonos\u2026): car\xE1tula, t\xEDtulo, artista, la app y por d\xF3nde va. De varios, el que suena. Se oculta mientras no suena nada."
2110
+ },
2111
+ icon: "music",
2112
+ category: "media",
2113
+ tags: ["home assistant", "music", "tv", "spotify"],
2114
+ size: { min: { w: 200, h: 70 }, preferred: { w: 460, h: 160 } },
2115
+ sources: [SOURCE3],
2116
+ options: t3.object({
2117
+ entity: t3.string({
2118
+ choices: { source: SOURCE3, list: "players" },
2119
+ placeholder: "media_player.living_room",
2120
+ label: { en: "Player", es: "Reproductor" },
2121
+ help: { en: "One, or several with patterns (media_player.*, !media_player.kitchen): the one playing is shown. Empty = all.", es: "Uno, o varios con patrones (media_player.*, !media_player.cocina): se ve el que suena. Vac\xEDo = todos." }
2122
+ }),
2123
+ showCover: t3.boolean({ default: true, label: { en: "Show the cover", es: "Mostrar la car\xE1tula" } }),
2124
+ showProgress: t3.boolean({ default: true, label: { en: "Show how far it has got", es: "Mostrar por d\xF3nde va" } })
2125
+ }),
2126
+ intervalMs: 1e4,
2127
+ timeoutMs: 2e4,
2128
+ // The cover is read again only when the player's picture changes (a new track, a new token).
2129
+ async fetch({ options, sources, signal, canvas }) {
2130
+ const d = dataOf3(sources);
2131
+ const e = d ? pickPlayer(d.entities, options.entity) : void 0;
2132
+ if (!d?.base || !e?.picture || !options.showCover) return {};
2133
+ const key = e.picture.split("?")[0] + "|" + e.media?.title + "|" + e.media?.album;
2134
+ const hit = covers.get(e.id);
2135
+ if (hit?.key === key) return { cover: hit.img, coverOf: key };
2136
+ const img = await canvas.loadImage(Buffer.from(await readPicture(d.base, e.picture, signal)));
2137
+ covers.set(e.id, { key, img });
2138
+ return { cover: img, coverOf: key };
2139
+ },
2140
+ redraw: ({ options, sources }) => {
2141
+ const d = dataOf3(sources);
2142
+ const e = d ? pickPlayer(d.entities, options.entity) : void 0;
2143
+ return e?.state === "playing" && options.showProgress ? "second" : "minute";
2144
+ },
2145
+ empty: ({ options, sources }) => {
2146
+ const d = dataOf3(sources);
2147
+ const e = d ? pickPlayer(d.entities, options.entity) : void 0;
2148
+ return d?.state === "ok" && (!e || !ACTIVE.has(e.state));
2149
+ },
2150
+ hideWhenEmpty: true,
2151
+ idle: ({ options, sources }) => {
2152
+ const d = dataOf3(sources);
2153
+ const e = d ? pickPlayer(d.entities, options.entity) : void 0;
2154
+ return !e || e.state !== "playing";
2155
+ },
2156
+ render(g, ctx) {
2157
+ const { options, sources, data, t: tr } = ctx;
2158
+ const d = dataOf3(sources);
2159
+ const box = ctx.box;
2160
+ if (!d || d.state === "unconfigured") return drawMessage(g, box, ctx, tr({ en: "Home Assistant not set up", es: "Home Assistant sin configurar" }), tr({ en: "Set its address and a token in Settings \u2192 Data sources", es: "Pon su direcci\xF3n y un token en Ajustes \u2192 Fuentes de datos" }));
2161
+ if (d.state === "connecting") return drawMessage(g, box, ctx, tr({ en: "Connecting to Home Assistant\u2026", es: "Conectando con Home Assistant\u2026" }));
2162
+ const e = pickPlayer(d.entities, options.entity);
2163
+ if (!e) return drawMessage(g, box, ctx, tr({ en: "No media player", es: "Ning\xFAn reproductor" }), options.entity || tr({ en: "Home Assistant has none", es: "Home Assistant no tiene ninguno" }));
2164
+ if (!ACTIVE.has(e.state)) return drawMessage(g, box, ctx, tr({ en: "Nothing playing", es: "No suena nada" }), e.name);
2165
+ paintPlayer(g, ctx, e, data);
2166
+ },
2167
+ demo: ({ now, locale }) => ({ sources: { [SOURCE3]: demoHome(now, locale) }, data: { demo: true }, options: { entity: "media_player.living_room_speaker" } })
2168
+ });
2169
+ var covers = /* @__PURE__ */ new Map();
2170
+ function paintPlayer(g, ctx, e, data) {
2171
+ const { box, theme, kit, options, now, t: tr } = ctx;
2172
+ const { colors, fonts } = theme;
2173
+ const m = e.media ?? {};
2174
+ const paused = e.state !== "playing";
2175
+ const side = options.showCover ? Math.min(box.h, box.w * 0.42) : 0;
2176
+ if (side) {
2177
+ const r = Math.max(4, side * 0.06);
2178
+ g.save();
2179
+ g.beginPath();
2180
+ g.roundRect(box.x, box.y + (box.h - side) / 2, side, side, r);
2181
+ g.clip();
2182
+ const cy = box.y + (box.h - side) / 2;
2183
+ if (data?.cover) {
2184
+ const img = data.cover;
2185
+ const s = Math.max(side / img.width, side / img.height);
2186
+ g.drawImage(img, box.x + (side - img.width * s) / 2, cy + (side - img.height * s) / 2, img.width * s, img.height * s);
2187
+ } else if (data?.demo) drawDemoCover(g, box.x, cy, side, colors.accent);
2188
+ else {
2189
+ g.fillStyle = colors.surfaceEdge;
2190
+ g.fillRect(box.x, cy, side, side);
2191
+ drawIcon(g, "music", box.x + side * 0.3, cy + side * 0.3, side * 0.4, colors.inkDim);
2192
+ }
2193
+ if (paused) {
2194
+ g.fillStyle = "rgba(0,0,0,0.45)";
2195
+ g.fillRect(box.x, cy, side, side);
2196
+ const p = side * 0.12;
2197
+ g.fillStyle = "#fff";
2198
+ g.fillRect(box.x + side / 2 - p * 1.1, cy + side / 2 - p * 1.4, p * 0.75, p * 2.8);
2199
+ g.fillRect(box.x + side / 2 + p * 0.35, cy + side / 2 - p * 1.4, p * 0.75, p * 2.8);
2200
+ }
2201
+ g.restore();
2202
+ }
2203
+ const x = box.x + side + (side ? Math.max(10, box.w * 0.035) : 0);
2204
+ const w = box.x + box.w - x;
2205
+ const showBar = options.showProgress && !!m.duration;
2206
+ const ts = Math.max(13, Math.min(34, box.h * 0.2, w * 0.09));
2207
+ const ss = Math.round(ts * 0.68);
2208
+ const title = m.title || e.name;
2209
+ const lines = [
2210
+ { text: title, o: { size: ts, family: fonts.sansBold, color: colors.ink } },
2211
+ ...m.artist ? [{ text: m.artist, o: { size: ss, family: fonts.sans, color: colors.inkDim } }] : [],
2212
+ { text: [m.album && m.album !== m.title ? m.album : "", m.app ?? (m.title ? e.name : "")].filter(Boolean).join(" \xB7 "), o: { size: Math.round(ss * 0.85), family: fonts.sans, color: colors.inkFaint } }
2213
+ ].filter((l) => l.text);
2214
+ const barH = showBar ? ss * 1.9 : 0;
2215
+ const textH = lines.reduce((a, l) => a + l.o.size * 1.25, 0);
2216
+ let y = box.y + Math.max(0, (box.h - textH - barH) / 2);
2217
+ for (const l of lines) {
2218
+ y += l.o.size * 1.05;
2219
+ kit.drawTracked(g, kit.truncate(g, l.text, w, l.o), x, y, l.o);
2220
+ y += l.o.size * 0.2;
2221
+ }
2222
+ if (showBar) {
2223
+ const pos = positionNow(e, now) ?? 0;
2224
+ const by = y + ss * 0.7;
2225
+ const bh = Math.max(3, ss * 0.22);
2226
+ g.fillStyle = alpha(colors.ink, 0.15);
2227
+ g.beginPath();
2228
+ g.roundRect(x, by, w, bh, bh / 2);
2229
+ g.fill();
2230
+ g.fillStyle = paused ? colors.inkDim : colors.accent;
2231
+ g.beginPath();
2232
+ g.roundRect(x, by, Math.max(bh, w * Math.min(1, pos / m.duration)), bh, bh / 2);
2233
+ g.fill();
2234
+ const to = { size: Math.round(ss * 0.8), family: fonts.mono, color: colors.inkDim };
2235
+ kit.drawTracked(g, clock(pos), x, by + bh + to.size * 1.25, to);
2236
+ kit.drawTracked(g, clock(m.duration), x + w, by + bh + to.size * 1.25, { ...to, align: "right" });
2237
+ } else if (paused) {
2238
+ const po = { size: Math.round(ss * 0.8), family: fonts.sans, color: colors.inkDim };
2239
+ kit.drawTracked(g, tr({ en: "Paused", es: "En pausa" }), x, y + po.size * 1.4, po);
2240
+ }
2241
+ }
2242
+ function drawDemoCover(g, x, y, s, color) {
2243
+ const bg = g.createLinearGradient(x, y, x + s, y + s);
2244
+ bg.addColorStop(0, "#2b1d4f");
2245
+ bg.addColorStop(1, "#0f3b4a");
2246
+ g.fillStyle = bg;
2247
+ g.fillRect(x, y, s, s);
2248
+ for (let i = 6; i > 0; i--) {
2249
+ g.strokeStyle = alpha(color, 0.12 + i * 0.05);
2250
+ g.lineWidth = Math.max(1, s * 0.012);
2251
+ g.beginPath();
2252
+ g.arc(x + s * 0.62, y + s * 0.58, s * 0.07 * i, 0, Math.PI * 2);
2253
+ g.stroke();
2254
+ }
2255
+ g.fillStyle = color;
2256
+ g.beginPath();
2257
+ g.arc(x + s * 0.62, y + s * 0.58, s * 0.05, 0, Math.PI * 2);
2258
+ g.fill();
2259
+ }
2260
+
2261
+ // src/people.ts
2262
+ import { defineWidget as defineWidget4, t as t4 } from "@kiosko/sdk";
2263
+ var SOURCE4 = "homeassistant/states";
2264
+ var dataOf4 = (sources) => sources[SOURCE4];
2265
+ var photos = /* @__PURE__ */ new Map();
2266
+ function peopleOf(d, filter) {
2267
+ return pick(d.entities, filter).filter((e) => e.domain === "person");
2268
+ }
2269
+ function initials(name) {
2270
+ const words = name.trim().split(/\s+/).filter(Boolean);
2271
+ if (!words.length) return "?";
2272
+ return (words.length > 1 ? words[0][0] + words[words.length - 1][0] : words[0][0]).toUpperCase();
2273
+ }
2274
+ var people = defineWidget4({
2275
+ id: "people",
2276
+ name: { en: "Who is home", es: "Qui\xE9n est\xE1 en casa" },
2277
+ description: {
2278
+ en: "The people Home Assistant knows, with their photo: at home, away or in a zone of yours (Work, School), and since when.",
2279
+ es: "Las personas que conoce Home Assistant, con su foto: en casa, fuera o en una de tus zonas (Trabajo, Colegio), y desde cu\xE1ndo."
2280
+ },
2281
+ icon: "users",
2282
+ category: "info",
2283
+ tags: ["home assistant", "presence", "family"],
2284
+ size: { min: { w: 140, h: 80 }, preferred: { w: 420, h: 160 } },
2285
+ sources: [SOURCE4],
2286
+ options: t4.object({
2287
+ people: t4.filter({ choices: { source: SOURCE4, list: "people" }, label: { en: "People", es: "Personas" }, help: { en: "In this order. Empty = everyone.", es: "En este orden. Vac\xEDo = todas." } }),
2288
+ showSince: t4.boolean({ default: true, label: { en: "Since when", es: "Desde cu\xE1ndo" } }),
2289
+ homeFirst: t4.boolean({ label: { en: "Who is home first", es: "Primero quien est\xE1 en casa" } })
2290
+ }),
2291
+ intervalMs: 30 * 6e4,
2292
+ async fetch({ options, sources, canvas, signal }) {
2293
+ const d = dataOf4(sources);
2294
+ const out = { photos: {} };
2295
+ if (!d?.base) return out;
2296
+ for (const e of peopleOf(d, options.people)) {
2297
+ if (!e.photo) continue;
2298
+ const key = e.photo.split("?")[0];
2299
+ try {
2300
+ let img = photos.get(key);
2301
+ if (!img) {
2302
+ img = await canvas.loadImage(Buffer.from(await readPicture(d.base, e.photo, signal)));
2303
+ photos.set(key, img);
2304
+ }
2305
+ out.photos[e.id] = img;
2306
+ } catch {
2307
+ }
2308
+ }
2309
+ return out;
2310
+ },
2311
+ redraw: "minute",
2312
+ render(g, ctx) {
2313
+ const { options, sources, data, t: tr } = ctx;
2314
+ const d = dataOf4(sources);
2315
+ const box = ctx.box;
2316
+ if (!d || d.state === "unconfigured") return drawMessage(g, box, ctx, tr({ en: "Home Assistant not set up", es: "Home Assistant sin configurar" }), tr({ en: "Set its address and a token in Settings \u2192 Data sources", es: "Pon su direcci\xF3n y un token en Ajustes \u2192 Fuentes de datos" }));
2317
+ if (d.state === "connecting") return drawMessage(g, box, ctx, tr({ en: "Connecting to Home Assistant\u2026", es: "Conectando con Home Assistant\u2026" }));
2318
+ let list = peopleOf(d, options.people);
2319
+ if (!list.length) return drawMessage(g, box, ctx, tr({ en: "Nobody", es: "Nadie" }), tr({ en: "Home Assistant has no people (Settings \u2192 People)", es: "Home Assistant no tiene personas (Ajustes \u2192 Personas)" }));
2320
+ if (options.homeFirst) list = [...list].sort((a, b) => Number(b.state === "home") - Number(a.state === "home"));
2321
+ paintPeople(g, ctx, list, data?.photos ?? {});
2322
+ },
2323
+ demo: ({ now, locale }) => ({ sources: { [SOURCE4]: demoHome(now, locale) } })
2324
+ });
2325
+ function whereText(e, tr) {
2326
+ if (e.state === "home") return tr({ en: "Home", es: "En casa" });
2327
+ if (e.state === "not_home") return tr({ en: "Away", es: "Fuera" });
2328
+ if (e.state === "unknown" || e.state === "unavailable") return tr({ en: "Unknown", es: "Sin datos" });
2329
+ return e.state;
2330
+ }
2331
+ function paintPeople(g, ctx, list, faces) {
2332
+ const { box, theme, kit, fmt, options, t: tr } = ctx;
2333
+ const { colors, fonts } = theme;
2334
+ const n = list.length;
2335
+ const gap = Math.max(8, box.w * 0.03);
2336
+ const cell = (box.w - gap * (n - 1)) / n;
2337
+ const face = Math.max(18, Math.min(cell * 0.78, box.h / 1.75));
2338
+ const ns = Math.max(10, Math.min(20, face * 0.26, cell * 0.14));
2339
+ const totalW = n * Math.min(cell, face * 2.2) + gap * (n - 1);
2340
+ let x = box.x + (box.w - totalW) / 2;
2341
+ const w = Math.min(cell, face * 2.2);
2342
+ const top = box.y + Math.max(0, (box.h - face - ns * 2.6) / 2);
2343
+ for (const e of list) {
2344
+ const cx = x + w / 2, cy = top + face / 2;
2345
+ const home = e.state === "home";
2346
+ const ring = home ? colors.ok : e.state === "not_home" || e.state === "unknown" || e.state === "unavailable" ? colors.inkFaint : colors.info;
2347
+ g.save();
2348
+ g.beginPath();
2349
+ g.arc(cx, cy, face / 2, 0, Math.PI * 2);
2350
+ g.clip();
2351
+ const img = faces[e.id];
2352
+ if (img) {
2353
+ const s = Math.max(face / img.width, face / img.height);
2354
+ g.drawImage(img, cx - img.width * s / 2, cy - img.height * s / 2, img.width * s, img.height * s);
2355
+ if (!home) {
2356
+ g.fillStyle = "rgba(0,0,0,0.45)";
2357
+ g.fillRect(cx - face / 2, cy - face / 2, face, face);
2358
+ }
2359
+ } else {
2360
+ g.fillStyle = alpha(ring, home ? 0.25 : 0.12);
2361
+ g.fillRect(cx - face / 2, cy - face / 2, face, face);
2362
+ const io = { size: Math.round(face * 0.36), family: fonts.sansBold, color: home ? colors.ink : colors.inkDim, align: "center" };
2363
+ kit.drawTracked(g, initials(e.name), cx, cy + io.size * 0.36, io);
2364
+ }
2365
+ g.restore();
2366
+ g.strokeStyle = ring;
2367
+ g.lineWidth = Math.max(2, face * 0.05);
2368
+ g.beginPath();
2369
+ g.arc(cx, cy, face / 2, 0, Math.PI * 2);
2370
+ g.stroke();
2371
+ const no = { size: Math.round(ns), family: fonts.sansBold, color: home ? colors.ink : colors.inkDim, align: "center" };
2372
+ kit.drawTracked(g, kit.truncate(g, e.name, w, no), cx, top + face + ns * 1.25, no);
2373
+ const where = whereText(e, tr) + (options.showSince && e.changedAt ? ` \xB7 ${fmt.ago(e.changedAt, { suffix: false })}` : "");
2374
+ const wo = { size: Math.round(ns * 0.8), family: fonts.sans, color: home ? colors.ok : colors.inkDim, align: "center" };
2375
+ kit.drawTracked(g, kit.truncate(g, where, w, wo), cx, top + face + ns * 2.35, wo);
2376
+ x += w + gap;
2377
+ }
2378
+ }
2379
+
2380
+ // src/index.ts
2381
+ var SOURCE5 = "homeassistant/states";
1750
2382
  var states = defineSource({
1751
2383
  id: "states",
1752
2384
  name: { en: "Home Assistant", es: "Home Assistant" },
@@ -1754,15 +2386,15 @@ var states = defineSource({
1754
2386
  en: "The states of your Home Assistant entities, live over its WebSocket API (a change shows at once), and the last day of the numeric sensors for the history bars.",
1755
2387
  es: "Los estados de las entidades de tu Home Assistant, en directo por su API WebSocket (un cambio se ve al momento), y el \xFAltimo d\xEDa de los sensores num\xE9ricos para las barras de hist\xF3rico."
1756
2388
  },
1757
- options: t2.object({
1758
- url: t2.string({
2389
+ options: t5.object({
2390
+ url: t5.string({
1759
2391
  format: "url",
1760
2392
  risk: "network",
1761
2393
  placeholder: "http://homeassistant.local:8123",
1762
2394
  label: { en: "Home Assistant address", es: "Direcci\xF3n de Home Assistant" },
1763
2395
  help: { en: "The one you open in the browser, e.g. http://homeassistant.local:8123 or https://home.example.com.", es: "La que abres en el navegador, p. ej. http://homeassistant.local:8123 o https://casa.example.com." }
1764
2396
  }),
1765
- token: t2.string({
2397
+ token: t5.string({
1766
2398
  secret: true,
1767
2399
  label: { en: "Long-lived access token", es: "Token de acceso de larga duraci\xF3n" },
1768
2400
  help: {
@@ -1770,16 +2402,16 @@ var states = defineSource({
1770
2402
  es: "En Home Assistant: tu perfil \u2192 Seguridad \u2192 Tokens de acceso de larga duraci\xF3n \u2192 Crear token. Basta un usuario que no sea administrador."
1771
2403
  }
1772
2404
  }),
1773
- entities: t2.filter({
2405
+ entities: t5.filter({
1774
2406
  label: { en: "Entities to read", es: "Entidades que leer" },
1775
2407
  help: { en: "Empty = all. Ids or names, with * and !: sensor.*, binary_sensor.*, lock.*, !sensor.*_linkquality.", es: "Vac\xEDo = todas. Ids o nombres, con * y !: sensor.*, binary_sensor.*, lock.*, !sensor.*_linkquality." }
1776
2408
  }),
1777
- history: t2.filter({
2409
+ history: t5.filter({
1778
2410
  advanced: true,
1779
2411
  label: { en: "Entities with history", es: "Entidades con hist\xF3rico" },
1780
2412
  help: { en: "Numeric sensors whose last day is kept for the history bars. Empty = every one with a unit.", es: "Sensores num\xE9ricos de los que se guarda el \xFAltimo d\xEDa para las barras de hist\xF3rico. Vac\xEDo = todos los que tienen unidad." }
1781
2413
  }),
1782
- maxHistory: t2.integer({
2414
+ maxHistory: t5.integer({
1783
2415
  default: 100,
1784
2416
  min: 0,
1785
2417
  max: 1e3,
@@ -1795,11 +2427,17 @@ var states = defineSource({
1795
2427
  entities: (d) => Object.values(d?.entities ?? {}).sort((a, b) => a.domain.localeCompare(b.domain) || a.name.localeCompare(b.name)).map((e) => ({ value: e.id, label: e.name, group: e.domain })),
1796
2428
  // The cameras, for the camera widget; and the motion sensors to go with them.
1797
2429
  cameras: (d) => Object.values(d?.entities ?? {}).filter((e) => e.picture).sort((a, b) => a.name.localeCompare(b.name)).map((e) => ({ value: e.id, label: e.name, group: e.domain })),
2430
+ // Doorbells: event entities (their state is when they last rang) and binary sensors.
2431
+ doorbells: (d) => Object.values(d?.entities ?? {}).filter((e) => e.domain === "event" && (e.deviceClass === "doorbell" || /ding|ring|doorbell|timbre/i.test(e.id)) || e.domain === "binary_sensor" && /ding|ring|doorbell|timbre/i.test(e.id)).sort((a, b) => a.name.localeCompare(b.name)).map((e) => ({ value: e.id, label: e.name, group: e.domain })),
2432
+ people: (d) => Object.values(d?.entities ?? {}).filter((e) => e.domain === "person").sort((a, b) => a.name.localeCompare(b.name)).map((e) => ({ value: e.id, label: e.name })),
2433
+ players: (d) => Object.values(d?.entities ?? {}).filter((e) => e.domain === "media_player").sort((a, b) => a.name.localeCompare(b.name)).map((e) => ({ value: e.id, label: e.name })),
2434
+ // Power sensors, for the energy flow.
2435
+ power: (d) => Object.values(d?.entities ?? {}).filter((e) => e.deviceClass === "power" || ["W", "kW", "MW"].includes(e.unit ?? "")).sort((a, b) => a.name.localeCompare(b.name)).map((e) => ({ value: e.id, label: e.name })),
1798
2436
  motion: (d) => Object.values(d?.entities ?? {}).filter((e) => e.domain === "binary_sensor" && ["motion", "occupancy", "presence"].includes(e.deviceClass ?? "")).sort((a, b) => a.name.localeCompare(b.name)).map((e) => ({ value: e.id, label: e.name }))
1799
2437
  }
1800
2438
  });
1801
- var dataOf2 = (sources) => sources[SOURCE2];
1802
- var demo = ({ now, locale }) => ({ sources: { [SOURCE2]: demoHome(now, locale) } });
2439
+ var dataOf5 = (sources) => sources[SOURCE5];
2440
+ var demo = ({ now, locale }) => ({ sources: { [SOURCE5]: demoHome(now, locale) } });
1803
2441
  function frame(g, box, ctx, data) {
1804
2442
  if (!data) return null;
1805
2443
  const tr = ctx.t;
@@ -1824,10 +2462,10 @@ function frame(g, box, ctx, data) {
1824
2462
  }
1825
2463
  var live = (d) => !!d && (d.state === "ok" || d.state === "offline" || d.state === "error" && Object.keys(d.entities).length > 0);
1826
2464
  var batteryFields = () => ({
1827
- batteryWarn: t2.integer({ default: 20, min: 0, max: 100, unit: "%", advanced: true, label: { en: "Battery warning at", es: "Bater\xEDa en aviso desde" } }),
1828
- batteryAlert: t2.integer({ default: 10, min: 0, max: 100, unit: "%", advanced: true, label: { en: "Battery alert at", es: "Bater\xEDa en alerta desde" } })
2465
+ batteryWarn: t5.integer({ default: 20, min: 0, max: 100, unit: "%", advanced: true, label: { en: "Battery warning at", es: "Bater\xEDa en aviso desde" } }),
2466
+ batteryAlert: t5.integer({ default: 10, min: 0, max: 100, unit: "%", advanced: true, label: { en: "Battery alert at", es: "Bater\xEDa en alerta desde" } })
1829
2467
  });
1830
- var entity = defineWidget2({
2468
+ var entity = defineWidget5({
1831
2469
  id: "entity",
1832
2470
  name: { en: "Entity", es: "Entidad" },
1833
2471
  description: {
@@ -1838,35 +2476,35 @@ var entity = defineWidget2({
1838
2476
  category: "info",
1839
2477
  tags: ["home assistant", "smart home", "sensor"],
1840
2478
  size: { min: { w: 140, h: 80 }, preferred: { w: 320, h: 200 } },
1841
- sources: [SOURCE2],
1842
- options: t2.object({
1843
- entity: t2.string({
1844
- choices: { source: SOURCE2, list: "entities" },
2479
+ sources: [SOURCE5],
2480
+ options: t5.object({
2481
+ entity: t5.string({
2482
+ choices: { source: SOURCE5, list: "entities" },
1845
2483
  placeholder: "sensor.living_room_temperature",
1846
2484
  label: { en: "Entity", es: "Entidad" },
1847
2485
  help: { en: "Its id, as in Home Assistant \u2192 Settings \u2192 Devices & services \u2192 Entities.", es: "Su id, como en Home Assistant \u2192 Ajustes \u2192 Dispositivos y servicios \u2192 Entidades." }
1848
2486
  }),
1849
- name: t2.string({ label: { en: "Name", es: "Nombre" }, help: { en: "Empty = the name in Home Assistant.", es: "Vac\xEDo = el nombre en Home Assistant." } }),
1850
- showName: t2.boolean({ default: true, label: { en: "Show the name", es: "Mostrar el nombre" } }),
1851
- showHistory: t2.boolean({ default: true, label: { en: "Show the history", es: "Mostrar el hist\xF3rico" }, help: { en: "Numeric sensors only, when the source keeps their history.", es: "Solo sensores num\xE9ricos cuyo hist\xF3rico guarda la fuente." } }),
1852
- historyMs: t2.duration({ default: 24 * 36e5, min: 36e5, max: 24 * 36e5, label: { en: "History span", es: "Periodo del hist\xF3rico" } }),
1853
- decimals: t2.integer({ default: -1, min: -1, max: 4, advanced: true, label: { en: "Decimals", es: "Decimales" }, help: { en: "-1 = automatic: fewer as the number grows.", es: "-1 = autom\xE1tico: menos cuanto mayor es el n\xFAmero." } }),
1854
- thresholds: t2.enum(["off", "above", "below"], {
2487
+ name: t5.string({ label: { en: "Name", es: "Nombre" }, help: { en: "Empty = the name in Home Assistant.", es: "Vac\xEDo = el nombre en Home Assistant." } }),
2488
+ showName: t5.boolean({ default: true, label: { en: "Show the name", es: "Mostrar el nombre" } }),
2489
+ showHistory: t5.boolean({ default: true, label: { en: "Show the history", es: "Mostrar el hist\xF3rico" }, help: { en: "Numeric sensors only, when the source keeps their history.", es: "Solo sensores num\xE9ricos cuyo hist\xF3rico guarda la fuente." } }),
2490
+ historyMs: t5.duration({ default: 24 * 36e5, min: 36e5, max: 24 * 36e5, label: { en: "History span", es: "Periodo del hist\xF3rico" } }),
2491
+ decimals: t5.integer({ default: -1, min: -1, max: 4, advanced: true, label: { en: "Decimals", es: "Decimales" }, help: { en: "-1 = automatic: fewer as the number grows.", es: "-1 = autom\xE1tico: menos cuanto mayor es el n\xFAmero." } }),
2492
+ thresholds: t5.enum(["off", "above", "below"], {
1855
2493
  default: "off",
1856
2494
  label: { en: "Thresholds", es: "Umbrales" },
1857
2495
  labels: { off: { en: "Off", es: "No" }, above: { en: "Warn above", es: "Avisar por encima" }, below: { en: "Warn below", es: "Avisar por debajo" } }
1858
2496
  }),
1859
- warn: t2.number({ default: 0, min: -1e6, max: 1e6, label: { en: "Warning (amber) at", es: "Aviso (\xE1mbar) en" } }),
1860
- alert: t2.number({ default: 0, min: -1e6, max: 1e6, label: { en: "Alert (red) at", es: "Alerta (rojo) en" }, help: { en: "Red, and the widget keeps its tile.", es: "Rojo, y el widget se queda con su tesela." } })
2497
+ warn: t5.number({ default: 0, min: -1e6, max: 1e6, label: { en: "Warning (amber) at", es: "Aviso (\xE1mbar) en" } }),
2498
+ alert: t5.number({ default: 0, min: -1e6, max: 1e6, label: { en: "Alert (red) at", es: "Alerta (rojo) en" }, help: { en: "Red, and the widget keeps its tile.", es: "Rojo, y el widget se queda con su tesela." } })
1861
2499
  }),
1862
2500
  redraw: "minute",
1863
2501
  urgent: ({ options, sources }) => {
1864
- const e = dataOf2(sources)?.entities[options.entity];
1865
- return !!e && dataOf2(sources)?.state === "ok" && thresholdLevel(e, options) === "alert";
2502
+ const e = dataOf5(sources)?.entities[options.entity];
2503
+ return !!e && dataOf5(sources)?.state === "ok" && thresholdLevel(e, options) === "alert";
1866
2504
  },
1867
2505
  render(g, ctx) {
1868
2506
  const { options, sources, t: tr } = ctx;
1869
- const data = dataOf2(sources);
2507
+ const data = dataOf5(sources);
1870
2508
  const box = frame(g, ctx.box, ctx, data);
1871
2509
  if (!box || !data) return;
1872
2510
  if (!options.entity) return drawMessage(g, box, ctx, tr({ en: "Choose an entity", es: "Elige una entidad" }), tr({ en: "Its id in the inspector, e.g. sensor.living_room_temperature", es: "Su id en el inspector, p. ej. sensor.living_room_temperature" }));
@@ -1875,7 +2513,7 @@ var entity = defineWidget2({
1875
2513
  },
1876
2514
  demo: ({ now, locale }) => ({ ...demo({ now, locale }), options: { entity: "sensor.living_room_temperature" } })
1877
2515
  });
1878
- var entities = defineWidget2({
2516
+ var entities = defineWidget5({
1879
2517
  id: "entities",
1880
2518
  name: { en: "Entities", es: "Entidades" },
1881
2519
  description: {
@@ -1886,27 +2524,27 @@ var entities = defineWidget2({
1886
2524
  category: "info",
1887
2525
  tags: ["home assistant", "smart home"],
1888
2526
  size: { min: { w: 220, h: 90 }, preferred: { w: 480, h: 260 } },
1889
- sources: [SOURCE2],
1890
- options: t2.object({
2527
+ sources: [SOURCE5],
2528
+ options: t5.object({
1891
2529
  ...listOptions({ layouts: ["one-line", "detailed"] }),
1892
- entities: t2.filter({
1893
- choices: { source: SOURCE2, list: "entities" },
2530
+ entities: t5.filter({
2531
+ choices: { source: SOURCE5, list: "entities" },
1894
2532
  label: { en: "Entities", es: "Entidades" },
1895
2533
  help: { en: "Ids or names, in the order to list them: sensor.*_temperature, light.*, *kitchen*, !light.porch. Empty = all.", es: "Ids o nombres, en el orden en que listarlas: sensor.*_temperature, light.*, *cocina*, !light.porch. Vac\xEDo = todas." }
1896
2534
  }),
1897
- hideOff: t2.boolean({ label: { en: "Only what is on, open or wrong", es: "Solo lo encendido, abierto o con problemas" }, help: { en: "Leaves out what is off or closed. Numbers always stay.", es: "Deja fuera lo apagado o cerrado. Los n\xFAmeros se quedan siempre." } }),
1898
- hideUnavailable: t2.boolean({ label: { en: "Hide unavailable entities", es: "Ocultar las entidades no disponibles" } }),
1899
- decimals: t2.integer({ default: -1, min: -1, max: 4, advanced: true, label: { en: "Decimals", es: "Decimales" }, help: { en: "-1 = automatic.", es: "-1 = autom\xE1tico." } }),
2535
+ hideOff: t5.boolean({ label: { en: "Only what is on, open or wrong", es: "Solo lo encendido, abierto o con problemas" }, help: { en: "Leaves out what is off or closed. Numbers always stay.", es: "Deja fuera lo apagado o cerrado. Los n\xFAmeros se quedan siempre." } }),
2536
+ hideUnavailable: t5.boolean({ label: { en: "Hide unavailable entities", es: "Ocultar las entidades no disponibles" } }),
2537
+ decimals: t5.integer({ default: -1, min: -1, max: 4, advanced: true, label: { en: "Decimals", es: "Decimales" }, help: { en: "-1 = automatic.", es: "-1 = autom\xE1tico." } }),
1900
2538
  ...batteryFields()
1901
2539
  }),
1902
2540
  redraw: "minute",
1903
2541
  empty: ({ options, sources }) => {
1904
- const d = dataOf2(sources);
2542
+ const d = dataOf5(sources);
1905
2543
  return live(d) && !listed(d, options).length;
1906
2544
  },
1907
2545
  render(g, ctx) {
1908
2546
  const { options, sources, theme, fmt, t: tr } = ctx;
1909
- const data = dataOf2(sources);
2547
+ const data = dataOf5(sources);
1910
2548
  const box = frame(g, ctx.box, ctx, data);
1911
2549
  if (!box || !data) return;
1912
2550
  const list = listed(data, options);
@@ -1945,7 +2583,7 @@ function entityRow(e, level, ctx, decimals) {
1945
2583
  function listed(data, o) {
1946
2584
  return pick(data.entities, o.entities).map((e) => ({ e, level: levelOf(e, o) })).filter(({ e, level }) => !(o.hideUnavailable && level === "na") && !(o.hideOff && level === "off" && numericState(e) === void 0));
1947
2585
  }
1948
- var attention = defineWidget2({
2586
+ var attention = defineWidget5({
1949
2587
  id: "attention",
1950
2588
  name: { en: "Home: needs you", es: "Casa: te necesita" },
1951
2589
  description: {
@@ -1956,35 +2594,35 @@ var attention = defineWidget2({
1956
2594
  category: "info",
1957
2595
  tags: ["home assistant", "smart home", "alerts"],
1958
2596
  size: { min: { w: 220, h: 90 }, preferred: { w: 480, h: 220 } },
1959
- sources: [SOURCE2],
1960
- options: t2.object({
2597
+ sources: [SOURCE5],
2598
+ options: t5.object({
1961
2599
  ...listOptions({ layouts: ["one-line", "detailed"] }),
1962
- entities: t2.filter({ choices: { source: SOURCE2, list: "entities" }, label: { en: "Entities", es: "Entidades" }, help: { en: "Empty = all. Leave out the ones that are fine open with !: !binary_sensor.patio_door.", es: "Vac\xEDo = todas. Deja fuera con ! las que pueden estar abiertas: !binary_sensor.patio_door." } }),
1963
- includeOpenings: t2.boolean({ default: true, label: { en: "Doors, windows and locks", es: "Puertas, ventanas y cerraduras" }, help: { en: "Open doors, windows, garage doors and gates; unlocked locks.", es: "Puertas, ventanas, garajes y cancelas abiertas; cerraduras sin cerrar." } }),
1964
- openMs: t2.duration({ default: 0, label: { en: "Open for at least", es: "Abierta al menos" }, help: { en: "A door counts once it has been open this long. 0 = at once.", es: "Una puerta cuenta cuando lleva abierta este tiempo. 0 = al momento." } }),
1965
- includeBatteries: t2.boolean({ default: true, label: { en: "Low batteries", es: "Bater\xEDas bajas" } }),
1966
- includeProblems: t2.boolean({ default: true, label: { en: "Problems", es: "Problemas" }, help: { en: "Problem and tamper sensors, lost connections, a vacuum in error.", es: "Sensores de problema y manipulaci\xF3n, conexiones perdidas, un robot aspirador en error." } }),
1967
- includeUnavailable: t2.boolean({ label: { en: "Unavailable devices", es: "Dispositivos no disponibles" } }),
1968
- includeUpdates: t2.boolean({ label: { en: "Updates available", es: "Actualizaciones disponibles" } }),
2600
+ entities: t5.filter({ choices: { source: SOURCE5, list: "entities" }, label: { en: "Entities", es: "Entidades" }, help: { en: "Empty = all. Leave out the ones that are fine open with !: !binary_sensor.patio_door.", es: "Vac\xEDo = todas. Deja fuera con ! las que pueden estar abiertas: !binary_sensor.patio_door." } }),
2601
+ includeOpenings: t5.boolean({ default: true, label: { en: "Doors, windows and locks", es: "Puertas, ventanas y cerraduras" }, help: { en: "Open doors, windows, garage doors and gates; unlocked locks.", es: "Puertas, ventanas, garajes y cancelas abiertas; cerraduras sin cerrar." } }),
2602
+ openMs: t5.duration({ default: 0, label: { en: "Open for at least", es: "Abierta al menos" }, help: { en: "A door counts once it has been open this long. 0 = at once.", es: "Una puerta cuenta cuando lleva abierta este tiempo. 0 = al momento." } }),
2603
+ includeBatteries: t5.boolean({ default: true, label: { en: "Low batteries", es: "Bater\xEDas bajas" } }),
2604
+ includeProblems: t5.boolean({ default: true, label: { en: "Problems", es: "Problemas" }, help: { en: "Problem and tamper sensors, lost connections, a vacuum in error.", es: "Sensores de problema y manipulaci\xF3n, conexiones perdidas, un robot aspirador en error." } }),
2605
+ includeUnavailable: t5.boolean({ label: { en: "Unavailable devices", es: "Dispositivos no disponibles" } }),
2606
+ includeUpdates: t5.boolean({ label: { en: "Updates available", es: "Actualizaciones disponibles" } }),
1969
2607
  ...batteryFields()
1970
2608
  }),
1971
2609
  hideWhenEmpty: true,
1972
2610
  redraw: "minute",
1973
2611
  urgent: ({ options, sources, now }) => {
1974
- const d = dataOf2(sources);
2612
+ const d = dataOf5(sources);
1975
2613
  return d?.state === "ok" && notices(d.entities, options, now).some((n) => n.kind === "danger");
1976
2614
  },
1977
2615
  idle: ({ options, sources, now }) => {
1978
- const d = dataOf2(sources);
2616
+ const d = dataOf5(sources);
1979
2617
  return !live(d) || !notices(d.entities, options, now).length;
1980
2618
  },
1981
2619
  empty: ({ options, sources, now }) => {
1982
- const d = dataOf2(sources);
2620
+ const d = dataOf5(sources);
1983
2621
  return live(d) && !notices(d.entities, options, now).length;
1984
2622
  },
1985
2623
  render(g, ctx) {
1986
2624
  const { options, sources, theme, fmt, now, t: tr } = ctx;
1987
- const data = dataOf2(sources);
2625
+ const data = dataOf5(sources);
1988
2626
  const box = frame(g, ctx.box, ctx, data);
1989
2627
  if (!box || !data) return;
1990
2628
  const list = notices(data.entities, options, now);
@@ -2016,32 +2654,35 @@ var attention = defineWidget2({
2016
2654
  var index_default = definePlugin({
2017
2655
  id: "homeassistant",
2018
2656
  name: { en: "Home Assistant", es: "Home Assistant" },
2019
- version: "0.2.2",
2657
+ version: "0.2.3",
2020
2658
  sdk: "^0.2.0",
2021
2659
  permissions: { network: ["user"] },
2022
2660
  description: {
2023
- en: "Home Assistant on the panel, live over its WebSocket API: any entity in big with its history, lists of entities, what needs you at home (doors left open, low batteries, leaks, the alarm) and your cameras' latest pictures.",
2024
- es: "Home Assistant en el panel, en directo por su API WebSocket: cualquier entidad en grande con su hist\xF3rico, listas de entidades, lo que te necesita en casa (puertas abiertas, bater\xEDas bajas, fugas, la alarma) y la \xFAltima imagen de tus c\xE1maras."
2661
+ en: "Home Assistant on the panel, live over its WebSocket API: any entity in big with its history, lists of entities, what needs you at home (doors left open, low batteries, leaks, the alarm), your cameras (with the doorbell), the energy flow, what's playing and who is home.",
2662
+ es: "Home Assistant en el panel, en directo por su API WebSocket: cualquier entidad en grande con su hist\xF3rico, listas de entidades, lo que te necesita en casa (puertas abiertas, bater\xEDas bajas, fugas, la alarma), tus c\xE1maras (con el timbre), el flujo de energ\xEDa, lo que suena y qui\xE9n est\xE1 en casa."
2025
2663
  },
2026
2664
  icon: "house",
2027
- widgets: [entity, entities, attention, camera],
2665
+ widgets: [entity, entities, attention, camera, energy, media, people],
2028
2666
  sources: [states]
2029
2667
  });
2030
2668
  export {
2031
2669
  AUTH_RETRY_MS,
2032
2670
  DEFAULT_LEVELS,
2033
2671
  DEVICE_DOMAINS,
2672
+ ENERGY_MS,
2034
2673
  FLUSH_MS,
2035
2674
  HISTORY_BUCKET_MS,
2036
2675
  HISTORY_SPAN_MS,
2037
2676
  History,
2038
2677
  PING_MS,
2039
2678
  RETRY_MS,
2679
+ RING_MS,
2040
2680
  alpha,
2041
2681
  attention,
2042
2682
  autoDecimals,
2043
2683
  batteryLevel,
2044
2684
  camera,
2685
+ clock,
2045
2686
  compact,
2046
2687
  connect,
2047
2688
  curveScale,
@@ -2057,32 +2698,49 @@ export {
2057
2698
  drawMessage,
2058
2699
  drawRows,
2059
2700
  drawTrend,
2701
+ energy,
2702
+ energyStats,
2703
+ energyToday,
2060
2704
  entities,
2061
2705
  entity,
2706
+ flows,
2707
+ formatEnergy,
2062
2708
  formatNumber,
2709
+ formatPower,
2710
+ homeToday,
2063
2711
  httpBase,
2064
2712
  iconFor,
2713
+ initials,
2065
2714
  isNumber,
2066
2715
  isTemperature,
2067
2716
  levelColor,
2068
2717
  levelOf,
2069
2718
  matchEntity,
2719
+ media,
2070
2720
  motionOf,
2071
2721
  noticeOf,
2072
2722
  notices,
2073
2723
  numericState,
2074
2724
  parseHistory,
2075
2725
  parsePath,
2726
+ people,
2727
+ peopleOf,
2076
2728
  pick,
2729
+ pickPlayer,
2077
2730
  pictureChangedAt,
2078
2731
  placePicture,
2732
+ positionNow,
2733
+ readPicture,
2079
2734
  renderEntity,
2735
+ ringing,
2080
2736
  stateColor,
2081
2737
  stateText,
2082
2738
  states,
2083
2739
  thresholdLevel,
2084
2740
  tracePath,
2085
2741
  wantsHistory,
2742
+ watts,
2086
2743
  websocketUrl,
2744
+ whereText,
2087
2745
  withUnit
2088
2746
  };