kiosko-plugin-homeassistant 0.2.1 → 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, drawEmpty, listLayout, listOptions, t } 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) {
@@ -31,8 +78,34 @@ function compact(s) {
31
78
  if (action) e.action = action;
32
79
  const battery = num(a.battery_level) ?? num(a.battery);
33
80
  if (battery !== void 0) e.battery = battery;
81
+ const picture = str(a.entity_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
+ }
34
102
  return e;
35
103
  }
104
+ function httpBase(address) {
105
+ let a = address.trim().replace(/\/+$/, "").replace(/\/api\/websocket$/, "");
106
+ if (!/^[a-z]+:\/\//i.test(a)) a = `http://${a}`;
107
+ return a.replace(/^ws(s?):\/\//i, (_, s) => `http${s}://`);
108
+ }
36
109
  function websocketUrl(address) {
37
110
  let a = address.trim().replace(/\/+$/, "");
38
111
  if (!/^[a-z]+:\/\//i.test(a)) a = `http://${a}`;
@@ -154,8 +227,8 @@ var DANGER = /* @__PURE__ */ new Set(["smoke", "gas", "carbon_monoxide", "moistu
154
227
  var TROUBLE = /* @__PURE__ */ new Set(["problem", "tamper", "battery", "cold", "heat"]);
155
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"]);
156
229
  function stateText(e, ctx, decimals = -1) {
157
- const { t: t2 } = ctx;
158
- if (e.state === "unavailable" || e.state === "unknown") return t2(WORDS[e.state]);
230
+ const { t: t6 } = ctx;
231
+ if (e.state === "unavailable" || e.state === "unknown") return t6(WORDS[e.state]);
159
232
  if (e.deviceClass === "timestamp") {
160
233
  const at = Date.parse(e.state);
161
234
  if (Number.isFinite(at)) return at <= ctx.now ? ctx.fmt.ago(at) : ctx.fmt.time(at);
@@ -164,16 +237,16 @@ function stateText(e, ctx, decimals = -1) {
164
237
  if (n !== void 0 && e.domain !== "binary_sensor") return withUnit(formatNumber(n, ctx.locale, decimals), e.unit);
165
238
  if (e.domain === "binary_sensor") {
166
239
  const words = BINARY[e.deviceClass ?? ""] ?? on_off(WORDS.on, WORDS.off);
167
- if (e.state === "on" || e.state === "off") return t2(words[e.state]);
240
+ if (e.state === "on" || e.state === "off") return t6(words[e.state]);
168
241
  }
169
242
  if (e.domain === "climate" && e.current !== void 0) {
170
243
  const temp = withUnit(formatNumber(e.current, ctx.locale, decimals), e.unit ?? "\xB0");
171
- return e.action && e.action !== "idle" && e.action !== "off" ? `${temp} \xB7 ${t2(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;
172
245
  }
173
- if (e.domain === "update") return t2(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);
174
247
  if ((e.domain === "person" || e.domain === "device_tracker") && !WORDS[e.state]) return e.state;
175
248
  const w = WORDS[e.state];
176
- if (w) return t2(w);
249
+ if (w) return t6(w);
177
250
  const plain = e.state.replace(/_/g, " ");
178
251
  return plain.charAt(0).toUpperCase() + plain.slice(1);
179
252
  }
@@ -361,8 +434,8 @@ function parseHistory(rows) {
361
434
  const out = [];
362
435
  for (const r of rows) {
363
436
  const s = r?.s ?? r?.state;
364
- const t2 = num(r?.lu) ?? num(r?.lc);
365
- const at = t2 !== void 0 ? t2 * 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 ?? ""));
366
439
  const value = numericState({ state: String(s) });
367
440
  if (value !== void 0 && Number.isFinite(at)) out.push({ at, value });
368
441
  }
@@ -381,12 +454,17 @@ function demoHome(now, locale = "en") {
381
454
  { id: "sensor.outdoor_temperature", name: n("Outdoor temperature", "Temperatura exterior"), state: "11.2", unit: "\xB0C", deviceClass: "temperature", stateClass: "measurement", changedAt: ago(6 * min) },
382
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) },
383
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) },
384
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) },
385
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) },
386
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) },
387
463
  { id: "binary_sensor.balcony_door", name: n("Balcony door", "Puerta del balc\xF3n"), state: "on", deviceClass: "door", changedAt: ago(42 * min) },
388
464
  { id: "binary_sensor.front_door", name: n("Front door", "Puerta de entrada"), state: "off", deviceClass: "door", changedAt: ago(95 * min) },
389
465
  { id: "binary_sensor.kitchen_window", name: n("Kitchen window", "Ventana cocina"), state: "off", deviceClass: "window", changedAt: ago(5 * 36e5) },
466
+ { id: "camera.porch", name: n("Porch", "Porche"), state: "idle", picture: "/api/camera_proxy/camera.porch?token=demo", changedAt: ago(3 * 36e5) },
467
+ { id: "binary_sensor.porch_motion", name: n("Porch motion", "Movimiento porche"), state: "off", deviceClass: "motion", changedAt: ago(12 * min) },
390
468
  { id: "binary_sensor.hallway_motion", name: n("Hallway motion", "Movimiento pasillo"), state: "on", deviceClass: "motion", changedAt: ago(1 * min) },
391
469
  { id: "binary_sensor.washing_machine_leak", name: n("Washing machine leak", "Fuga lavadora"), state: "off", deviceClass: "moisture", changedAt: ago(26 * 36e5) },
392
470
  { id: "lock.front_door", name: n("Front door lock", "Cerradura entrada"), state: "locked", changedAt: ago(95 * min) },
@@ -396,6 +474,8 @@ function demoHome(now, locale = "en") {
396
474
  { id: "climate.living_room", name: n("Thermostat", "Termostato"), state: "heat", current: 21.4, target: 22, action: "heating", unit: "\xB0C", changedAt: ago(3 * 36e5) },
397
475
  { id: "person.alex", name: "Alex", state: "home", changedAt: ago(4 * 36e5) },
398
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) },
399
479
  { id: "media_player.living_room_tv", name: n("Living room TV", "Tele del sal\xF3n"), state: "playing", changedAt: ago(25 * min) },
400
480
  { id: "sensor.garage_temperature", name: n("Garage temperature", "Temperatura garaje"), state: "unavailable", unit: "\xB0C", deviceClass: "temperature", stateClass: "measurement", changedAt: ago(14 * 36e5) },
401
481
  { id: "update.home_assistant_core_update", name: "Home Assistant Core", state: "on", changedAt: ago(20 * 36e5) }
@@ -420,7 +500,10 @@ function demoHome(now, locale = "en") {
420
500
  const e = entities2[id];
421
501
  e.state = String(Math.round(last * (e.unit === "W" ? 1 : 10)) / (e.unit === "W" ? 1 : 10));
422
502
  }
423
- return { state: "ok", version: "2026.11.1", 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 };
424
507
  }
425
508
 
426
509
  // src/connection.ts
@@ -443,6 +526,7 @@ var PING_MS = 3e4;
443
526
  var FLUSH_MS = 1e3;
444
527
  var RETRY_MS = [2e3, 5e3, 1e4, 3e4, 6e4];
445
528
  var AUTH_RETRY_MS = 5 * 6e4;
529
+ var ENERGY_MS = 5 * 6e4;
446
530
  function connect(o, emit, deps = {}) {
447
531
  const timers = deps.timers ?? realTimers;
448
532
  const log = deps.log ?? (() => {
@@ -462,7 +546,10 @@ function connect(o, emit, deps = {}) {
462
546
  let ws = null;
463
547
  let attempt = 0;
464
548
  let nextId = 1;
465
- 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;
466
553
  let awaitingPong = false;
467
554
  let retryTimer = null;
468
555
  let pingTimer = null;
@@ -472,6 +559,8 @@ function connect(o, emit, deps = {}) {
472
559
  ...error ? { error } : {},
473
560
  ...since !== void 0 ? { since } : {},
474
561
  ...version ? { version } : {},
562
+ base: httpBase(o.url),
563
+ ...energy2 ? { energy: energy2 } : {},
475
564
  entities: Object.fromEntries(entities2),
476
565
  history
477
566
  });
@@ -565,7 +654,7 @@ function connect(o, emit, deps = {}) {
565
654
  const n = Number(e.state);
566
655
  if (Number.isFinite(n) && e.state.trim() !== "") history.add(id, Date.parse(data.new_state.last_updated ?? "") || timers.now(), n, timers.now());
567
656
  }
568
- 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;
569
658
  changed();
570
659
  };
571
660
  const onMessage = (raw) => {
@@ -590,6 +679,7 @@ function connect(o, emit, deps = {}) {
590
679
  request({ type: "supported_features", features: { coalesce_messages: 1 } });
591
680
  request({ type: "get_states" }, "states");
592
681
  request({ type: "subscribe_events", event_type: "state_changed" }, "subscribe");
682
+ request({ type: "energy/get_prefs" }, "prefs");
593
683
  pingTimer = timers.setTimeout(ping, PING_MS);
594
684
  return;
595
685
  case "auth_invalid":
@@ -623,16 +713,41 @@ function connect(o, emit, deps = {}) {
623
713
  onHistory(m.result);
624
714
  changed();
625
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"}`);
626
725
  } else if (m.id === ids.subscribe && !m.success) {
627
726
  log(`subscribe failed: ${m.error?.message ?? "refused"}`);
628
727
  }
629
728
  return;
630
729
  }
631
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
+ };
632
746
  const clearTimers = () => {
633
747
  if (pingTimer) timers.clearTimeout(pingTimer);
634
748
  if (retryTimer) timers.clearTimeout(retryTimer);
635
- pingTimer = retryTimer = null;
749
+ if (energyTimer) timers.clearTimeout(energyTimer);
750
+ pingTimer = retryTimer = energyTimer = null;
636
751
  };
637
752
  const close = (ms) => {
638
753
  clearTimers();
@@ -644,12 +759,12 @@ function connect(o, emit, deps = {}) {
644
759
  }
645
760
  if (!stopped) retryTimer = timers.setTimeout(open, ms);
646
761
  };
647
- const drop = (why) => {
762
+ const drop = (why2) => {
648
763
  if (stopped) return;
649
764
  const wasUp = status === "ok";
650
765
  if (status !== "error") {
651
766
  status = entities2.size ? "offline" : "error";
652
- error = why;
767
+ error = why2;
653
768
  since ??= timers.now();
654
769
  }
655
770
  if (wasUp || status === "error") changed(true);
@@ -661,7 +776,7 @@ function connect(o, emit, deps = {}) {
661
776
  retryTimer = null;
662
777
  if (stopped) return;
663
778
  awaitingPong = false;
664
- ids = { states: 0, subscribe: 0, history: 0, ping: 0 };
779
+ ids = { states: 0, subscribe: 0, history: 0, ping: 0, prefs: 0, energy: 0 };
665
780
  nextId = 1;
666
781
  let w;
667
782
  try {
@@ -753,7 +868,13 @@ var ICON_PATHS = {
753
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",
754
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",
755
870
  "clock": "M2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0ZM12 6v6l4 2",
756
- "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"
757
878
  };
758
879
 
759
880
  // src/icons.ts
@@ -1505,8 +1626,759 @@ function renderClimate(g, ctx, e, box) {
1505
1626
  }
1506
1627
  }
1507
1628
 
1508
- // src/index.ts
1629
+ // src/camera.ts
1630
+ import { createHash } from "node:crypto";
1631
+ import { defineWidget, t } from "@kiosko/sdk";
1509
1632
  var SOURCE = "homeassistant/states";
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
+ }
1643
+ var seen = /* @__PURE__ */ new Map();
1644
+ function pictureChangedAt(camera2, bytes, now) {
1645
+ const hash = createHash("sha1").update(bytes).digest("hex");
1646
+ const last = seen.get(camera2);
1647
+ if (last?.hash === hash) return last.at;
1648
+ seen.set(camera2, { hash, at: now });
1649
+ return now;
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
+ }
1657
+ function motionOf(entities2, camera2, chosen) {
1658
+ if (chosen) return entities2[chosen];
1659
+ const auto = `binary_sensor.${camera2.split(".")[1] ?? ""}_motion`;
1660
+ return entities2[auto];
1661
+ }
1662
+ function placePicture(box, w, h, fit2, fy) {
1663
+ const s = fit2 === "cover" ? Math.max(box.w / w, box.h / h) : Math.min(box.w / w, box.h / h);
1664
+ const dw = w * s, dh = h * s;
1665
+ return { x: box.x + (box.w - dw) / 2, y: box.y + (box.h - dh) * fy, w: dw, h: dh };
1666
+ }
1667
+ var KEEP = { top: 0, center: 0.5, bottom: 1 };
1668
+ var camera = defineWidget({
1669
+ id: "camera",
1670
+ name: { en: "Camera", es: "C\xE1mara" },
1671
+ description: {
1672
+ en: "The latest picture of a Home Assistant camera (Blink, Reolink, ONVIF\u2026), refreshed every minute, with how old it is; with a motion sensor, a red mark while it sees someone, and it can take over its tile. A still, not live video.",
1673
+ es: "La \xFAltima imagen de una c\xE1mara de Home Assistant (Blink, Reolink, ONVIF\u2026), refrescada cada minuto, con su antig\xFCedad; con un sensor de movimiento, una marca roja mientras ve a alguien, y puede quedarse con su tesela. Una foto, no v\xEDdeo en directo."
1674
+ },
1675
+ icon: "cctv",
1676
+ category: "media",
1677
+ tags: ["home assistant", "camera", "blink", "security"],
1678
+ chrome: "bare",
1679
+ size: { min: { w: 120, h: 80 }, preferred: { w: 400, h: 260 } },
1680
+ sources: [SOURCE],
1681
+ options: t.object({
1682
+ entity: t.string({
1683
+ choices: { source: SOURCE, list: "cameras" },
1684
+ placeholder: "camera.porch",
1685
+ label: { en: "Camera", es: "C\xE1mara" },
1686
+ help: { en: "Its id in Home Assistant: camera.something.", es: "Su id en Home Assistant: camera.algo." }
1687
+ }),
1688
+ name: t.string({ label: { en: "Name", es: "Nombre" }, help: { en: "Empty = the name in Home Assistant.", es: "Vac\xEDo = el nombre en Home Assistant." } }),
1689
+ showName: t.boolean({ default: true, label: { en: "Show the name", es: "Mostrar el nombre" } }),
1690
+ showAge: t.boolean({ default: true, label: { en: "Show how old the picture is", es: "Mostrar la antig\xFCedad de la imagen" }, help: { en: "Since the picture last changed. A battery camera (Blink) only takes a new one on motion or when asked.", es: "Desde que cambi\xF3 la imagen por \xFAltima vez. Una c\xE1mara de bater\xEDa (Blink) solo hace otra con movimiento o cuando se le pide." } }),
1691
+ motion: t.string({
1692
+ choices: { source: SOURCE, list: "motion" },
1693
+ placeholder: "binary_sensor.porch_motion",
1694
+ label: { en: "Motion sensor", es: "Sensor de movimiento" },
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)." }
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
+ }),
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" } } }),
1704
+ keep: t.enum(["center", "top", "bottom"], {
1705
+ advanced: true,
1706
+ label: { en: "Keep in view", es: "Mantener a la vista" },
1707
+ labels: { center: { en: "The centre", es: "El centro" }, top: { en: "The top", es: "La parte de arriba" }, bottom: { en: "The bottom", es: "La parte de abajo" } },
1708
+ help: { en: "What filling crops last: the sky or the ground.", es: "Lo \xFAltimo que recorta al llenar: el cielo o el suelo." }
1709
+ }),
1710
+ dim: t.integer({ default: 0, min: 0, max: 90, step: 5, unit: "%", slider: true, advanced: true, label: { en: "Darken", es: "Oscurecer" }, help: { en: "Keeps a bright picture from outshining everything else.", es: "Para que una imagen clara no deslumbre al resto." } })
1711
+ }),
1712
+ intervalMs: 6e4,
1713
+ // Until the connection has the camera, look again soon: the first picture shouldn't wait a minute.
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,
1716
+ timeoutMs: 3e4,
1717
+ async fetch({ options, sources, canvas, signal }) {
1718
+ if (!options.entity) return { state: "pick" };
1719
+ const d = dataOf(sources);
1720
+ if (!d || !d.base || !Object.keys(d.entities).length) return { state: "waiting" };
1721
+ const e = d.entities[options.entity];
1722
+ if (!e) return { state: "missing" };
1723
+ if (!e.picture) return { state: "nopicture" };
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 } : {} };
1728
+ },
1729
+ redraw: "minute",
1730
+ urgent: ({ options, sources, now }) => {
1731
+ const d = dataOf(sources);
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);
1734
+ },
1735
+ // Off by default: a camera's tile is for looking, not for interrupting. The user turns it on.
1736
+ takeOver: false,
1737
+ render(g, ctx) {
1738
+ const { options, sources, data, theme, t: tr } = ctx;
1739
+ const { box } = ctx;
1740
+ const d = dataOf(sources);
1741
+ const e = d?.entities[options.entity];
1742
+ g.fillStyle = theme.colors.surface;
1743
+ g.fillRect(box.x, box.y, box.w, box.h);
1744
+ const pad = Math.round(Math.min(16, box.h * 0.08));
1745
+ const inner = { x: box.x + pad, y: box.y + pad, w: box.w - pad * 2, h: box.h - pad * 2 };
1746
+ if (!data?.img && !data?.demo) {
1747
+ const [text, hint] = why(d, data, options.entity, tr);
1748
+ return drawMessage(g, inner, ctx, text, hint);
1749
+ }
1750
+ g.save();
1751
+ g.beginPath();
1752
+ g.rect(box.x, box.y, box.w, box.h);
1753
+ g.clip();
1754
+ if (data.demo) drawScene(g, box);
1755
+ else {
1756
+ const at = placePicture(box, data.img.width, data.img.height, options.fit, KEEP[options.keep]);
1757
+ g.drawImage(data.img, at.x, at.y, at.w, at.h);
1758
+ }
1759
+ if (options.dim > 0) {
1760
+ g.fillStyle = `rgba(0,0,0,${options.dim / 100})`;
1761
+ g.fillRect(box.x, box.y, box.w, box.h);
1762
+ }
1763
+ const stale = !d || d.state !== "ok" || e?.state === "unavailable";
1764
+ if (stale) {
1765
+ g.fillStyle = "rgba(0,0,0,0.45)";
1766
+ g.fillRect(box.x, box.y, box.w, box.h);
1767
+ }
1768
+ g.restore();
1769
+ const motion = d && e ? motionOf(d.entities, e.id, options.motion) : void 0;
1770
+ overlay(g, ctx, {
1771
+ name: options.showName ? options.name || e?.name || options.entity : "",
1772
+ age: options.showAge && data.changedAt ? ctx.fmt.ago(data.changedAt) : "",
1773
+ motion: motion?.state === "on",
1774
+ ring: !!d && ringing(options.doorbell ? d.entities[options.doorbell] : void 0, ctx.now),
1775
+ stale: stale ? e?.state === "unavailable" ? tr({ en: "camera unavailable", es: "c\xE1mara no disponible" }) : tr({ en: "offline", es: "sin conexi\xF3n" }) : ""
1776
+ });
1777
+ },
1778
+ demo: ({ now, locale }) => ({
1779
+ sources: { [SOURCE]: demoHome(now, locale) },
1780
+ data: { state: "ok", demo: true, changedAt: now - 4 * 6e4 },
1781
+ options: { entity: "camera.porch" }
1782
+ })
1783
+ });
1784
+ function why(d, data, entity2, tr) {
1785
+ if (d?.state === "unconfigured") return [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" })];
1786
+ if (!entity2 || data?.state === "pick") return [tr({ en: "Choose a camera", es: "Elige una c\xE1mara" }), tr({ en: "In the inspector: one of your Home Assistant cameras, e.g. camera.porch", es: "En el inspector: una de las c\xE1maras de tu Home Assistant, p. ej. camera.porch" })];
1787
+ if (d?.state === "error" && !Object.keys(d.entities).length) return [tr({ en: "Home Assistant unreachable", es: "Home Assistant no responde" }), d.error];
1788
+ if (data?.state === "missing") return [tr({ en: "Camera not found", es: "C\xE1mara no encontrada" }), entity2];
1789
+ if (data?.state === "nopicture") return [tr({ en: "This camera has no picture", es: "Esta c\xE1mara no tiene imagen" }), tr({ en: "It may be off, or not a camera", es: "Puede que est\xE9 apagada, o que no sea una c\xE1mara" })];
1790
+ return [tr({ en: "Waiting for the camera\u2026", es: "Esperando a la c\xE1mara\u2026" })];
1791
+ }
1792
+ function overlay(g, ctx, o) {
1793
+ const { box, theme, kit } = ctx;
1794
+ const { fonts, colors } = theme;
1795
+ const s = Math.max(11, Math.round(Math.min(22, box.h * 0.085, box.w * 0.05)));
1796
+ const pad = Math.round(s * 0.7);
1797
+ if (o.name || o.age) {
1798
+ const h = s * 2.6;
1799
+ const shade = g.createLinearGradient(0, box.y + box.h - h, 0, box.y + box.h);
1800
+ shade.addColorStop(0, "rgba(0,0,0,0)");
1801
+ shade.addColorStop(1, "rgba(0,0,0,0.72)");
1802
+ g.fillStyle = shade;
1803
+ g.fillRect(box.x, box.y + box.h - h, box.w, h);
1804
+ const base = box.y + box.h - pad;
1805
+ const ageO = { size: Math.round(s * 0.8), family: fonts.sans, color: "rgba(255,255,255,0.75)", align: "right" };
1806
+ const ageW = o.age ? kit.measureTracked(g, o.age, ageO) + pad : 0;
1807
+ if (o.age) kit.drawTracked(g, o.age, box.x + box.w - pad, base, ageO);
1808
+ if (o.name) {
1809
+ const nameO = { size: s, family: fonts.sansBold, color: "#fff" };
1810
+ kit.drawTracked(g, kit.truncate(g, o.name, box.w - pad * 2 - ageW, nameO), box.x + pad, base, nameO);
1811
+ }
1812
+ }
1813
+ let x = box.x + pad;
1814
+ const pill = (text, color, dot) => {
1815
+ const ps = Math.round(s * 0.8);
1816
+ const tw = kit.measureTracked(g, text, { size: ps, family: fonts.sansBold });
1817
+ const h = ps * 1.7, w = tw + ps * (dot ? 2.4 : 1.4);
1818
+ const y = box.y + pad;
1819
+ g.fillStyle = "rgba(0,0,0,0.6)";
1820
+ g.beginPath();
1821
+ g.roundRect(x, y, w, h, h / 2);
1822
+ g.fill();
1823
+ if (dot) {
1824
+ g.fillStyle = color;
1825
+ g.beginPath();
1826
+ g.arc(x + ps * 0.85, y + h / 2, ps * 0.32, 0, Math.PI * 2);
1827
+ g.fill();
1828
+ }
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 });
1830
+ x += w + ps * 0.5;
1831
+ };
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;
1836
+ g.lineWidth = Math.max(2, Math.round(s * 0.18));
1837
+ g.strokeRect(box.x + g.lineWidth / 2, box.y + g.lineWidth / 2, box.w - g.lineWidth, box.h - g.lineWidth);
1838
+ }
1839
+ if (o.stale) pill(o.stale, colors.warn, false);
1840
+ }
1841
+ function drawScene(g, b) {
1842
+ const sky = g.createLinearGradient(0, b.y, 0, b.y + b.h);
1843
+ sky.addColorStop(0, "#1d2a44");
1844
+ sky.addColorStop(0.55, "#3b4a63");
1845
+ sky.addColorStop(1, "#2a2622");
1846
+ g.fillStyle = sky;
1847
+ g.fillRect(b.x, b.y, b.w, b.h);
1848
+ const floor = b.y + b.h * 0.78;
1849
+ g.fillStyle = "#5b5148";
1850
+ g.fillRect(b.x, b.y + b.h * 0.18, b.w, floor - b.y - b.h * 0.18);
1851
+ g.fillStyle = "#3a332d";
1852
+ g.fillRect(b.x, floor, b.w, b.y + b.h - floor);
1853
+ const dw = b.w * 0.2, dh = b.h * 0.5, dx = b.x + b.w * 0.42, dy = floor - dh;
1854
+ const glow = g.createRadialGradient(dx + dw / 2, dy - b.h * 0.04, 2, dx + dw / 2, dy - b.h * 0.04, b.w * 0.35);
1855
+ glow.addColorStop(0, "rgba(255,214,150,0.55)");
1856
+ glow.addColorStop(1, "rgba(255,214,150,0)");
1857
+ g.fillStyle = glow;
1858
+ g.fillRect(b.x, b.y, b.w, b.h);
1859
+ g.fillStyle = "#2b2018";
1860
+ g.fillRect(dx, dy, dw, dh);
1861
+ g.fillStyle = "#6e4a2f";
1862
+ g.fillRect(dx + dw * 0.08, dy + dh * 0.05, dw * 0.84, dh * 0.95);
1863
+ g.fillStyle = "#d9b26a";
1864
+ g.beginPath();
1865
+ g.arc(dx + dw * 0.78, dy + dh * 0.55, Math.max(1.5, dw * 0.04), 0, Math.PI * 2);
1866
+ g.fill();
1867
+ g.fillStyle = "#ffe2a8";
1868
+ g.fillRect(dx + dw / 2 - dw * 0.08, dy - b.h * 0.07, dw * 0.16, b.h * 0.04);
1869
+ g.fillStyle = "#2f4a33";
1870
+ g.beginPath();
1871
+ g.ellipse(b.x + b.w * 0.24, floor - b.h * 0.12, b.w * 0.05, b.h * 0.11, 0, 0, Math.PI * 2);
1872
+ g.fill();
1873
+ g.fillStyle = "#4a3b30";
1874
+ g.fillRect(b.x + b.w * 0.205, floor - b.h * 0.05, b.w * 0.07, b.h * 0.06);
1875
+ g.fillStyle = "#2a2420";
1876
+ g.fillRect(dx - dw * 0.05, floor + b.h * 0.02, dw * 1.1, b.h * 0.05);
1877
+ const v = g.createRadialGradient(b.x + b.w / 2, b.y + b.h / 2, Math.min(b.w, b.h) * 0.3, b.x + b.w / 2, b.y + b.h / 2, Math.max(b.w, b.h) * 0.75);
1878
+ v.addColorStop(0, "rgba(0,0,0,0)");
1879
+ v.addColorStop(1, "rgba(0,0,0,0.5)");
1880
+ g.fillStyle = v;
1881
+ g.fillRect(b.x, b.y, b.w, b.h);
1882
+ }
1883
+
1884
+ // src/energy.ts
1885
+ import { defineWidget as defineWidget2, t as t2 } from "@kiosko/sdk";
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";
1510
2382
  var states = defineSource({
1511
2383
  id: "states",
1512
2384
  name: { en: "Home Assistant", es: "Home Assistant" },
@@ -1514,15 +2386,15 @@ var states = defineSource({
1514
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.",
1515
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."
1516
2388
  },
1517
- options: t.object({
1518
- url: t.string({
2389
+ options: t5.object({
2390
+ url: t5.string({
1519
2391
  format: "url",
1520
2392
  risk: "network",
1521
2393
  placeholder: "http://homeassistant.local:8123",
1522
2394
  label: { en: "Home Assistant address", es: "Direcci\xF3n de Home Assistant" },
1523
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." }
1524
2396
  }),
1525
- token: t.string({
2397
+ token: t5.string({
1526
2398
  secret: true,
1527
2399
  label: { en: "Long-lived access token", es: "Token de acceso de larga duraci\xF3n" },
1528
2400
  help: {
@@ -1530,16 +2402,16 @@ var states = defineSource({
1530
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."
1531
2403
  }
1532
2404
  }),
1533
- entities: t.filter({
2405
+ entities: t5.filter({
1534
2406
  label: { en: "Entities to read", es: "Entidades que leer" },
1535
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." }
1536
2408
  }),
1537
- history: t.filter({
2409
+ history: t5.filter({
1538
2410
  advanced: true,
1539
2411
  label: { en: "Entities with history", es: "Entidades con hist\xF3rico" },
1540
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." }
1541
2413
  }),
1542
- maxHistory: t.integer({
2414
+ maxHistory: t5.integer({
1543
2415
  default: 100,
1544
2416
  min: 0,
1545
2417
  max: 1e3,
@@ -1552,11 +2424,20 @@ var states = defineSource({
1552
2424
  demo: ({ now, locale }) => demoHome(now, locale),
1553
2425
  // Every entity it reads, by name, grouped by domain: for the entity field and the filters.
1554
2426
  choices: {
1555
- 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 }))
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 })),
2428
+ // The cameras, for the camera widget; and the motion sensors to go with them.
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 })),
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 }))
1556
2437
  }
1557
2438
  });
1558
- var dataOf = (sources) => sources[SOURCE];
1559
- var demo = ({ now, locale }) => ({ sources: { [SOURCE]: demoHome(now, locale) } });
2439
+ var dataOf5 = (sources) => sources[SOURCE5];
2440
+ var demo = ({ now, locale }) => ({ sources: { [SOURCE5]: demoHome(now, locale) } });
1560
2441
  function frame(g, box, ctx, data) {
1561
2442
  if (!data) return null;
1562
2443
  const tr = ctx.t;
@@ -1581,10 +2462,10 @@ function frame(g, box, ctx, data) {
1581
2462
  }
1582
2463
  var live = (d) => !!d && (d.state === "ok" || d.state === "offline" || d.state === "error" && Object.keys(d.entities).length > 0);
1583
2464
  var batteryFields = () => ({
1584
- batteryWarn: t.integer({ default: 20, min: 0, max: 100, unit: "%", advanced: true, label: { en: "Battery warning at", es: "Bater\xEDa en aviso desde" } }),
1585
- batteryAlert: t.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" } })
1586
2467
  });
1587
- var entity = defineWidget({
2468
+ var entity = defineWidget5({
1588
2469
  id: "entity",
1589
2470
  name: { en: "Entity", es: "Entidad" },
1590
2471
  description: {
@@ -1595,35 +2476,35 @@ var entity = defineWidget({
1595
2476
  category: "info",
1596
2477
  tags: ["home assistant", "smart home", "sensor"],
1597
2478
  size: { min: { w: 140, h: 80 }, preferred: { w: 320, h: 200 } },
1598
- sources: [SOURCE],
1599
- options: t.object({
1600
- entity: t.string({
1601
- choices: { source: SOURCE, list: "entities" },
2479
+ sources: [SOURCE5],
2480
+ options: t5.object({
2481
+ entity: t5.string({
2482
+ choices: { source: SOURCE5, list: "entities" },
1602
2483
  placeholder: "sensor.living_room_temperature",
1603
2484
  label: { en: "Entity", es: "Entidad" },
1604
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." }
1605
2486
  }),
1606
- name: t.string({ label: { en: "Name", es: "Nombre" }, help: { en: "Empty = the name in Home Assistant.", es: "Vac\xEDo = el nombre en Home Assistant." } }),
1607
- showName: t.boolean({ default: true, label: { en: "Show the name", es: "Mostrar el nombre" } }),
1608
- showHistory: t.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." } }),
1609
- historyMs: t.duration({ default: 24 * 36e5, min: 36e5, max: 24 * 36e5, label: { en: "History span", es: "Periodo del hist\xF3rico" } }),
1610
- decimals: t.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." } }),
1611
- thresholds: t.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"], {
1612
2493
  default: "off",
1613
2494
  label: { en: "Thresholds", es: "Umbrales" },
1614
2495
  labels: { off: { en: "Off", es: "No" }, above: { en: "Warn above", es: "Avisar por encima" }, below: { en: "Warn below", es: "Avisar por debajo" } }
1615
2496
  }),
1616
- warn: t.number({ default: 0, min: -1e6, max: 1e6, label: { en: "Warning (amber) at", es: "Aviso (\xE1mbar) en" } }),
1617
- alert: t.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." } })
1618
2499
  }),
1619
2500
  redraw: "minute",
1620
2501
  urgent: ({ options, sources }) => {
1621
- const e = dataOf(sources)?.entities[options.entity];
1622
- return !!e && dataOf(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";
1623
2504
  },
1624
2505
  render(g, ctx) {
1625
2506
  const { options, sources, t: tr } = ctx;
1626
- const data = dataOf(sources);
2507
+ const data = dataOf5(sources);
1627
2508
  const box = frame(g, ctx.box, ctx, data);
1628
2509
  if (!box || !data) return;
1629
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" }));
@@ -1632,7 +2513,7 @@ var entity = defineWidget({
1632
2513
  },
1633
2514
  demo: ({ now, locale }) => ({ ...demo({ now, locale }), options: { entity: "sensor.living_room_temperature" } })
1634
2515
  });
1635
- var entities = defineWidget({
2516
+ var entities = defineWidget5({
1636
2517
  id: "entities",
1637
2518
  name: { en: "Entities", es: "Entidades" },
1638
2519
  description: {
@@ -1643,27 +2524,27 @@ var entities = defineWidget({
1643
2524
  category: "info",
1644
2525
  tags: ["home assistant", "smart home"],
1645
2526
  size: { min: { w: 220, h: 90 }, preferred: { w: 480, h: 260 } },
1646
- sources: [SOURCE],
1647
- options: t.object({
2527
+ sources: [SOURCE5],
2528
+ options: t5.object({
1648
2529
  ...listOptions({ layouts: ["one-line", "detailed"] }),
1649
- entities: t.filter({
1650
- choices: { source: SOURCE, list: "entities" },
2530
+ entities: t5.filter({
2531
+ choices: { source: SOURCE5, list: "entities" },
1651
2532
  label: { en: "Entities", es: "Entidades" },
1652
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." }
1653
2534
  }),
1654
- hideOff: t.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." } }),
1655
- hideUnavailable: t.boolean({ label: { en: "Hide unavailable entities", es: "Ocultar las entidades no disponibles" } }),
1656
- decimals: t.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." } }),
1657
2538
  ...batteryFields()
1658
2539
  }),
1659
2540
  redraw: "minute",
1660
2541
  empty: ({ options, sources }) => {
1661
- const d = dataOf(sources);
2542
+ const d = dataOf5(sources);
1662
2543
  return live(d) && !listed(d, options).length;
1663
2544
  },
1664
2545
  render(g, ctx) {
1665
2546
  const { options, sources, theme, fmt, t: tr } = ctx;
1666
- const data = dataOf(sources);
2547
+ const data = dataOf5(sources);
1667
2548
  const box = frame(g, ctx.box, ctx, data);
1668
2549
  if (!box || !data) return;
1669
2550
  const list = listed(data, options);
@@ -1702,7 +2583,7 @@ function entityRow(e, level, ctx, decimals) {
1702
2583
  function listed(data, o) {
1703
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));
1704
2585
  }
1705
- var attention = defineWidget({
2586
+ var attention = defineWidget5({
1706
2587
  id: "attention",
1707
2588
  name: { en: "Home: needs you", es: "Casa: te necesita" },
1708
2589
  description: {
@@ -1713,35 +2594,35 @@ var attention = defineWidget({
1713
2594
  category: "info",
1714
2595
  tags: ["home assistant", "smart home", "alerts"],
1715
2596
  size: { min: { w: 220, h: 90 }, preferred: { w: 480, h: 220 } },
1716
- sources: [SOURCE],
1717
- options: t.object({
2597
+ sources: [SOURCE5],
2598
+ options: t5.object({
1718
2599
  ...listOptions({ layouts: ["one-line", "detailed"] }),
1719
- entities: t.filter({ choices: { source: SOURCE, 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." } }),
1720
- includeOpenings: t.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." } }),
1721
- openMs: t.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." } }),
1722
- includeBatteries: t.boolean({ default: true, label: { en: "Low batteries", es: "Bater\xEDas bajas" } }),
1723
- includeProblems: t.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." } }),
1724
- includeUnavailable: t.boolean({ label: { en: "Unavailable devices", es: "Dispositivos no disponibles" } }),
1725
- includeUpdates: t.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" } }),
1726
2607
  ...batteryFields()
1727
2608
  }),
1728
2609
  hideWhenEmpty: true,
1729
2610
  redraw: "minute",
1730
2611
  urgent: ({ options, sources, now }) => {
1731
- const d = dataOf(sources);
2612
+ const d = dataOf5(sources);
1732
2613
  return d?.state === "ok" && notices(d.entities, options, now).some((n) => n.kind === "danger");
1733
2614
  },
1734
2615
  idle: ({ options, sources, now }) => {
1735
- const d = dataOf(sources);
2616
+ const d = dataOf5(sources);
1736
2617
  return !live(d) || !notices(d.entities, options, now).length;
1737
2618
  },
1738
2619
  empty: ({ options, sources, now }) => {
1739
- const d = dataOf(sources);
2620
+ const d = dataOf5(sources);
1740
2621
  return live(d) && !notices(d.entities, options, now).length;
1741
2622
  },
1742
2623
  render(g, ctx) {
1743
2624
  const { options, sources, theme, fmt, now, t: tr } = ctx;
1744
- const data = dataOf(sources);
2625
+ const data = dataOf5(sources);
1745
2626
  const box = frame(g, ctx.box, ctx, data);
1746
2627
  if (!box || !data) return;
1747
2628
  const list = notices(data.entities, options, now);
@@ -1773,31 +2654,35 @@ var attention = defineWidget({
1773
2654
  var index_default = definePlugin({
1774
2655
  id: "homeassistant",
1775
2656
  name: { en: "Home Assistant", es: "Home Assistant" },
1776
- version: "0.2.1",
2657
+ version: "0.2.3",
1777
2658
  sdk: "^0.2.0",
1778
2659
  permissions: { network: ["user"] },
1779
2660
  description: {
1780
- en: "Home Assistant on the panel, live over its WebSocket API: any entity in big with its history, lists of entities, and what needs you at home (doors left open, low batteries, leaks, the alarm).",
1781
- es: "Home Assistant en el panel, en directo por su API WebSocket: cualquier entidad en grande con su hist\xF3rico, listas de entidades y lo que te necesita en casa (puertas abiertas, bater\xEDas bajas, fugas, la alarma)."
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."
1782
2663
  },
1783
2664
  icon: "house",
1784
- widgets: [entity, entities, attention],
2665
+ widgets: [entity, entities, attention, camera, energy, media, people],
1785
2666
  sources: [states]
1786
2667
  });
1787
2668
  export {
1788
2669
  AUTH_RETRY_MS,
1789
2670
  DEFAULT_LEVELS,
1790
2671
  DEVICE_DOMAINS,
2672
+ ENERGY_MS,
1791
2673
  FLUSH_MS,
1792
2674
  HISTORY_BUCKET_MS,
1793
2675
  HISTORY_SPAN_MS,
1794
2676
  History,
1795
2677
  PING_MS,
1796
2678
  RETRY_MS,
2679
+ RING_MS,
1797
2680
  alpha,
1798
2681
  attention,
1799
2682
  autoDecimals,
1800
2683
  batteryLevel,
2684
+ camera,
2685
+ clock,
1801
2686
  compact,
1802
2687
  connect,
1803
2688
  curveScale,
@@ -1813,28 +2698,49 @@ export {
1813
2698
  drawMessage,
1814
2699
  drawRows,
1815
2700
  drawTrend,
2701
+ energy,
2702
+ energyStats,
2703
+ energyToday,
1816
2704
  entities,
1817
2705
  entity,
2706
+ flows,
2707
+ formatEnergy,
1818
2708
  formatNumber,
2709
+ formatPower,
2710
+ homeToday,
2711
+ httpBase,
1819
2712
  iconFor,
2713
+ initials,
1820
2714
  isNumber,
1821
2715
  isTemperature,
1822
2716
  levelColor,
1823
2717
  levelOf,
1824
2718
  matchEntity,
2719
+ media,
2720
+ motionOf,
1825
2721
  noticeOf,
1826
2722
  notices,
1827
2723
  numericState,
1828
2724
  parseHistory,
1829
2725
  parsePath,
2726
+ people,
2727
+ peopleOf,
1830
2728
  pick,
2729
+ pickPlayer,
2730
+ pictureChangedAt,
2731
+ placePicture,
2732
+ positionNow,
2733
+ readPicture,
1831
2734
  renderEntity,
2735
+ ringing,
1832
2736
  stateColor,
1833
2737
  stateText,
1834
2738
  states,
1835
2739
  thresholdLevel,
1836
2740
  tracePath,
1837
2741
  wantsHistory,
2742
+ watts,
1838
2743
  websocketUrl,
2744
+ whereText,
1839
2745
  withUnit
1840
2746
  };