diff --git a/docs/changelog.md b/docs/changelog.md index ead2bf78..23b8cf69 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -19,6 +19,21 @@ docstring gives: it is a record, not a claim about now. ## 2026-11-18 +- **The wall gets a week, a countdown and a context card.** The first of + five steps that take the useful ideas from a denser mockup of the office + wall without shrinking its text below what reads from the chair. + `wall_calendar.yaml` now asks for seven days: today and tomorrow stay in + full, the rest of the week shows below them in grey while the box has + room, and the header counts down to the next timed event on a ring that + turns amber inside fifteen minutes. A new `wall_weather.yaml` gives the + header today's high and low, the next rain within six hours and the next + sunrise or sunset, at `/api/ha/forecast`. The Power card's cell becomes a + context card that shows one thing at a time by precedence, a Hebrew word + of the day until its other sources arrive; the UPS's mains or battery, + charge and runtime moved into `mjolnir`'s tile, which turns red on + battery. Previewed at 1920x1080 in a browser against stubbed answers, + including on battery with an alert firing. Not yet run against the real + Home Assistant. - **`fenrir` sheds the last of its audit's leftovers.** The audit of 2026-11-13 listed, as its finding 10, `atreus` in `lxd` with no LXD installed, an idle `docker0` and the `hwctl` snap, and called them diff --git a/docs/security.md b/docs/security.md index f33f7f6e..d981a909 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1145,11 +1145,11 @@ from Home Assistant with *not enough permissions*. firing alerts, per-host CPU, SNMP reachability, WAN traffic and latency, the UPS and `heimdall`'s temperature. That is less than the Homelab page already shows, and the page and the Pi hold no credential. - **Its household half reads ten Home Assistant entities the same way.** + **Its household half reads eleven Home Assistant entities the same way.** Each `/api/ha/NAME` is one `GET /api/states/` written in the - Caddyfile: the weather, the alarm's mode, four door contacts, two window - contacts, the office lights, and `sensor.wall_today`, which holds today's - and tomorrow's calendar events. Caddy adds the token of HA's non-admin + Caddyfile: the weather, today's forecast, the alarm's mode, four door + contacts, two window contacts, the office lights, and `sensor.wall_today`, + which holds the next seven days' calendar events. Caddy adds the token of HA's non-admin `wall` user. Home Assistant has no read-only role, so that token could call services, the alarm's included. It is read-only only because it lives in Caddy's environment alone and Caddy forwards nothing but those GETs. The diff --git a/stacks/sensitive/Caddyfile b/stacks/sensitive/Caddyfile index 20d7b28a..ebf523d2 100644 --- a/stacks/sensitive/Caddyfile +++ b/stacks/sensitive/Caddyfile @@ -441,7 +441,16 @@ wall.matrix.elysium { import wall_ha } - # Today's and tomorrow's events, gathered from the calendars by + # Today's high and low, the next rain and the next sunrise or sunset, + # asked of weather.get_forecasts by + # home-assistant/packages/wall_weather.yaml: since HA 2024.4 a forecast + # is an action's answer, not an attribute a fixed handle can read. + handle /api/ha/forecast { + rewrite * /api/states/sensor.wall_weather? + import wall_ha + } + + # The next seven days' events, gathered from the calendars by # home-assistant/packages/wall_calendar.yaml. A calendar's own API needs # a moving start and end, which a fixed handle cannot give. handle /api/ha/today { diff --git a/stacks/sensitive/README.md b/stacks/sensitive/README.md index 65abc004..7a33075b 100644 --- a/stacks/sensitive/README.md +++ b/stacks/sensitive/README.md @@ -784,12 +784,22 @@ container of its own: Caddy serves `wall/` as static files. any light whose id contains `office` is on). The page shows them as the header's weather and a one-line Home row: the alarm's mode, any open door or window in amber, and the office lights. + The header's high and low, the next rain and the next sunrise or sunset + are `sensor.wall_weather` at `/api/ha/forecast`, from + `home-assistant/packages/wall_weather.yaml`, which asks + `weather.get_forecasts` every fifteen minutes. The calendar is `sensor.wall_today` at `/api/ha/today`: the package `home-assistant/packages/wall_calendar.yaml` asks `calendar.get_events` - every five minutes for today and tomorrow, from the calendars labelled + every five minutes for the next seven days, from the calendars labelled `wall_calendar` in HA's UI, or from every calendar when none is labelled. It keeps each event's title, start, end, location and a calendar number for - its colour, and shows them in the Today panel under the alerts. Booted on + its colour. The page shows today and tomorrow in the Today panel under the + alerts, the rest of the week below them while there is room, and a + countdown to the next timed event in the header. The cell beside Internet + is a context card that shows one thing at a time, whichever matters now + (`CONTEXT` in `wall.js`); until other sources arrive that is a Hebrew word + of the day from a static list in the page. The UPS's mains or battery, + charge and runtime are in its node tile, `mjolnir`. Booted on Home Assistant 2026.11.1 against its demo calendars on 2026-11-18: the sensor held both events, and with no calendar it read unavailable, which the page shows as `calendar · unavailable`. The real ids of the alarm and the diff --git a/stacks/sensitive/home-assistant/packages/README.md b/stacks/sensitive/home-assistant/packages/README.md index e6e4af84..c846ee9f 100644 --- a/stacks/sensitive/home-assistant/packages/README.md +++ b/stacks/sensitive/home-assistant/packages/README.md @@ -28,8 +28,9 @@ and nothing else. This README is not YAML and Home Assistant ignores it. | `roomba.yaml` | *Roomba: start / stop / dock* scripts that ask the living-room Echo, through `alexa_devices.send_text_command`, to drive the Roomba 105 linked in Alexa. The core `roomba` integration does not support x05 models. One-way, cloud, with phrases editable in the UI | | `thermostat.yaml` | Thermostat alerts, no control: the hallway too cold or hot, humidity out of range, emergency heat switched on, the thermostat gone from Honeywell's cloud, or its gateway gone from the network (from its DHCP renewals in Loki). Each condition is a template binary sensor, so a restart does not lose it. Alerts go to phones labelled `household_phones` and to Home Assistant's notifications. The thermostat keeps its own schedule | | `tv_room_evening.yaml` | At 19:00 the TV comes on with Prime Video open and the TV room at its Mood scene; at 21:00 a bedtime nudge on the living-room Echo and the TV. A pause switch skips both | -| `wall_calendar.yaml` | `sensor.wall_today`: today's and tomorrow's events, asked of `calendar.get_events` every five minutes, for the office wall's Today panel (ADR-0119). The calendars are those labelled `wall_calendar` in the UI, or all of them when none is labelled, so no calendar is named here. Unavailable, not empty, when a calendar cannot be read | +| `wall_calendar.yaml` | `sensor.wall_today`: the next seven days' events, asked of `calendar.get_events` every five minutes, for the office wall's Today panel, its week below tomorrow and the header's *Up next* (ADR-0119). The calendars are those labelled `wall_calendar` in the UI, or all of them when none is labelled, so no calendar is named here. Unavailable, not empty, when a calendar cannot be read | | `wall_house.yaml` | `sensor.wall_alarm` and `binary_sensor.wall_office_lights` for the office wall (ADR-0119): the house's one alarm panel's mode, and whether any light whose id contains `office` is on. Their own ids name the city and a person, so the wall reads these instead. Unavailable when nothing matches | +| `wall_weather.yaml` | `sensor.wall_weather` for the office wall's header (ADR-0119): today's high and low, the first of the next six hours with rain or snow, and `sun.sun`'s next sunrise and sunset. Asked of `weather.get_forecasts` on `weather.forecast_home` every fifteen minutes, because a forecast is an action's answer, not an attribute. Unavailable only when neither the daily nor the hourly forecast answers; with no daily entry for today, the state is `none` and the rain and sun still come through | Home Assistant reads these files only when it starts, and the directory is mounted as a whole, so a changed package is visible inside the container at diff --git a/stacks/sensitive/home-assistant/packages/wall_calendar.yaml b/stacks/sensitive/home-assistant/packages/wall_calendar.yaml index 9b547ccd..a8aa2511 100644 --- a/stacks/sensitive/home-assistant/packages/wall_calendar.yaml +++ b/stacks/sensitive/home-assistant/packages/wall_calendar.yaml @@ -1,12 +1,14 @@ --- -# Today's and tomorrow's events, as one sensor the office wall can read -# (ADR-0119). +# The next seven days' events, today's first, as one sensor the office wall +# can read (ADR-0119). The wall shows today and tomorrow in full, the rest of +# the week below them when there is room, and counts down to the next one. # # The wall reads Home Assistant through fixed `GET /api/states/` # handles in the Caddyfile. A calendar's own state is only its next event, and # HA's calendar API needs a moving start and end that a fixed handle cannot # give. So this asks `calendar.get_events` every five minutes and keeps the -# answer in `sensor.wall_today`, which the wall reads at `/api/ha/today`. +# answer in `sensor.wall_today`, which the wall reads at `/api/ha/today`. The +# id predates the week; it keeps its name so its history does not split. # # Which calendars: the ones labelled `wall_calendar` in the UI, or every # calendar when no calendar carries that label. No calendar is named here. @@ -45,7 +47,7 @@ template: entity_id: "{{ wall_calendars }}" data: start_date_time: "{{ today_at() }}" - end_date_time: "{{ today_at() + timedelta(days=2) }}" + end_date_time: "{{ today_at() + timedelta(days=7) }}" response_variable: agenda continue_on_error: true - variables: @@ -82,7 +84,9 @@ template: {% endfor %} {% endfor %} {% endif %} - {{ (ns.items | sort(attribute='key'))[:16] }} + {# 40 events of at most ~250 bytes stay under the recorder's 16 KB + attribute limit, so the sensor's history keeps its attributes. #} + {{ (ns.items | sort(attribute='key'))[:40] }} sensor: - name: Wall today unique_id: wall_today diff --git a/stacks/sensitive/home-assistant/packages/wall_weather.yaml b/stacks/sensitive/home-assistant/packages/wall_weather.yaml new file mode 100644 index 00000000..7ebe2156 --- /dev/null +++ b/stacks/sensitive/home-assistant/packages/wall_weather.yaml @@ -0,0 +1,86 @@ +--- +# Today's high and low, the next rain, and the next sunrise or sunset, as one +# sensor the office wall can read (ADR-0119). +# +# The weather entity's own state is the present only: since HA 2024.4 its +# forecast is not an attribute but the answer to `weather.get_forecasts`, which +# a fixed `GET /api/states/` handle cannot ask. So this asks every +# fifteen minutes and keeps the answer in `sensor.wall_weather`, which the wall +# reads at `/api/ha/forecast`. The header's temperature and condition still +# come from the weather entity itself, at `/api/ha/weather`. +# +# Which weather entity: `weather.forecast_home`, the home zone's forecast +# (the Met.no default), the same one the Caddyfile already reads. It names no +# place. Sunrise and sunset come from `sun.sun`, also at the home zone. + +template: + - triggers: + - trigger: time_pattern + minutes: /15 + - trigger: homeassistant + event: start + - trigger: event + event_type: event_template_reloaded + actions: + - action: weather.get_forecasts + target: + entity_id: weather.forecast_home + data: + type: daily + response_variable: daily + continue_on_error: true + - action: weather.get_forecasts + target: + entity_id: weather.forecast_home + data: + type: hourly + response_variable: hourly + continue_on_error: true + - variables: + wall_days: >- + {{ daily['weather.forecast_home'].forecast + if daily is defined and daily is mapping + and 'weather.forecast_home' in daily else [] }} + wall_hours: >- + {{ hourly['weather.forecast_home'].forecast + if hourly is defined and hourly is mapping + and 'weather.forecast_home' in hourly else [] }} + # Today's entry, by local date. Late in the evening Met.no's first + # daily entry can already be tomorrow, and that is not today's high. + wall_day: >- + {% set today = now().date() %} + {% set ns = namespace(day=none) %} + {% for d in wall_days %} + {% if ns.day is none and as_local(as_datetime(d.datetime)).date() == today %} + {% set ns.day = d %} + {% endif %} + {% endfor %} + {{ ns.day if ns.day is not none else {} }} + # The first of the next six hours with rain or snow in it. + wall_rain: >- + {% set wet = ['rainy', 'pouring', 'snowy', 'snowy-rainy', 'lightning-rainy', 'hail'] %} + {% set ns = namespace(at='') %} + {% for h in wall_hours[:6] %} + {% if not ns.at and (h.condition in wet or (h.precipitation or 0) >= 0.2) %} + {% set ns.at = as_local(as_datetime(h.datetime)).isoformat() %} + {% endif %} + {% endfor %} + {{ ns.at }} + sensor: + - name: Wall weather + unique_id: wall_weather + icon: mdi:weather-partly-cloudy + # Available while either forecast answered, so a missing daily entry + # for today (late in the evening) costs only the high and low, not the + # rain and the sun. The state is today's high, or `none` when there is + # none: a word rather than HA's `unknown`, which the wall reads as no + # answer at all. So no unit, since the state is not always a number. + availability: "{{ wall_days | count > 0 or wall_hours | count > 0 }}" + state: "{{ wall_day.temperature if wall_day.temperature is defined else 'none' }}" + attributes: + high: "{{ wall_day.temperature | default(none) }}" + low: "{{ wall_day.templow | default(none) }}" + # An ISO time when rain or snow is expected within six hours, or ''. + rain_at: "{{ wall_rain }}" + next_rising: "{{ state_attr('sun.sun', 'next_rising') }}" + next_setting: "{{ state_attr('sun.sun', 'next_setting') }}" diff --git a/stacks/sensitive/wall/index.html b/stacks/sensitive/wall/index.html index 80fba41e..782cf0c1 100644 --- a/stacks/sensitive/wall/index.html +++ b/stacks/sensitive/wall/index.html @@ -32,9 +32,20 @@
--:--
+
—
-
—
+
—
Waiting for Prometheus @@ -68,14 +79,12 @@

Internet

-
-

Power

-
—
-
-
Charge—
-
Runtime—
-
Load—
-
+ +
+

—

+
+
diff --git a/stacks/sensitive/wall/wall.css b/stacks/sensitive/wall/wall.css index 7f963964..0b217e80 100644 --- a/stacks/sensitive/wall/wall.css +++ b/stacks/sensitive/wall/wall.css @@ -58,7 +58,7 @@ html, body { grid-template-areas: "top top top" "left nodes nodes" - "left wan power" + "left wan context" "house house house" "status status status"; gap: 22px; @@ -90,6 +90,7 @@ html, body { background: var(--panel); border: 1px solid var(--line); } +.verdict { white-space: nowrap; flex: none; } .verdict .dot { width: 22px; height: 22px; border-radius: 50%; background: var(--mute); flex: none; } .verdict[data-state="ok"] .dot { background: var(--green); } .verdict[data-state="warning"] { color: var(--yellow); } @@ -125,7 +126,7 @@ html, body { .today { flex: 1 1 0; min-height: 300px; } .nodes { grid-area: nodes; } .wan { grid-area: wan; } -.power { grid-area: power; } +.context { grid-area: context; } .household { grid-area: house; flex-direction: row; align-items: center; gap: 30px; } .household h2 { margin: 0; } @@ -187,8 +188,10 @@ html, body { .spark path.line { fill: none; stroke: var(--green); stroke-width: 2.5; vector-effect: non-scaling-stroke; } .spark path.fill { fill: var(--green); fill-opacity: 0.12; stroke: none; } -.power .hero { font-size: 64px; color: var(--fg-dim); } -.power[data-state="battery"] .hero { color: var(--red); } +/* The UPS, in its node tile: red and pulsing on battery. */ +.node.battery .dot { background: var(--red); color: var(--red); } +.node.battery .role, .node.battery .val { color: var(--red); } + .kv { display: flex; flex-direction: column; gap: 10px; margin-top: 18px; } .kv div { display: flex; font: 400 28px/1.2 var(--sans); color: var(--fg-dim); } .kv b { margin-left: auto; font: 500 30px/1 var(--mono); color: var(--fg); font-variant-numeric: tabular-nums; } @@ -216,9 +219,34 @@ html, body { .ev.c5 .bar { background: var(--mute); } .day { font: 500 20px/1 var(--mono); letter-spacing: 0.14em; text-transform: uppercase; color: var(--mute); margin-top: 6px; } .agenda .none { font: 400 28px/1.3 var(--sans); color: var(--fg-dim); } +/* Past tomorrow, the week is one line per event and dimmer: it is there to + be glanced at, not read. */ +.ev.later .t, .ev.later .what { color: var(--mute); font-weight: 400; } +.ev.later .where { display: none; } + +/* ---------- up next, in the header ---------- */ +.next { display: flex; align-items: center; gap: 20px; max-width: 470px; min-width: 0; margin-left: 40px; } +.next .ring { width: 76px; height: 76px; flex: none; } +.next .ring circle { fill: none; stroke-width: 7; } +.next .ring .track { stroke: var(--line); } +.next .ring .arc { stroke: var(--blue); stroke-linecap: round; stroke-dasharray: 188.5; } +.next[data-state="soon"] .ring .arc { stroke: var(--yellow); } +.next[data-state="soon"] .next-when { color: var(--yellow); } +.next-text { min-width: 0; } +.lbl { font: 500 20px/1 var(--mono); letter-spacing: 0.14em; text-transform: uppercase; color: var(--mute); } +.next-what { font: 600 32px/1.2 var(--sans); margin-top: 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.next-when { font: 400 24px/1.3 var(--mono); color: var(--fg-dim); white-space: nowrap; font-variant-numeric: tabular-nums; } +.next[data-state="none"] .next-what { color: var(--mute); font-weight: 400; } + +/* ---------- context: one card, whichever matters now ---------- */ +.context-body { flex: 1; display: flex; flex-direction: column; justify-content: center; min-height: 0; overflow: hidden; } +.context-also { font: 400 22px/1.3 var(--mono); color: var(--mute); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.word { font: 600 72px/1.15 var(--sans); color: var(--purple); align-self: flex-start; } +.word-sub { font: 400 28px/1.4 var(--sans); color: var(--fg-dim); margin-top: 10px; } +.word-sub b { font-weight: 600; color: var(--fg); } /* ---------- weather, in the header ---------- */ -.wx { display: flex; align-items: center; gap: 22px; margin-left: auto; margin-right: 40px; } +.wx { display: flex; align-items: center; gap: 22px; margin-left: auto; margin-right: 36px; } .wx-temp { font: 500 84px/1 var(--mono); color: var(--cyan); letter-spacing: -0.04em; font-variant-numeric: tabular-nums; } .wx-desc { font: 600 32px/1.2 var(--sans); } .wx-sub { font: 400 22px/1.3 var(--mono); color: var(--mute); margin-top: 4px; } @@ -251,7 +279,7 @@ html, body { /* The only motion: a pulse on what needs looking at. */ @media (prefers-reduced-motion: no-preference) { - .node.warning .dot, .node.down .dot, .verdict[data-state="critical"] .dot, + .node.warning .dot, .node.down .dot, .node.battery .dot, .verdict[data-state="critical"] .dot, .verdict[data-state="broken"] .dot { animation: pulse 1.6s ease-out infinite; } } @keyframes pulse { diff --git a/stacks/sensitive/wall/wall.js b/stacks/sensitive/wall/wall.js index 8e729387..d60e430f 100644 --- a/stacks/sensitive/wall/wall.js +++ b/stacks/sensitive/wall/wall.js @@ -29,6 +29,8 @@ { name: "oracle", src: "cpu", role: "wiki, off-host jobs" }, { name: "smaug", src: "cpu", role: "NAS" }, { name: "neo", src: "snmp", role: "core switch" }, + // The UPS's tile carries what the Power card used to: mains or battery, + // charge and runtime (renderNodes). { name: "mjolnir", src: "snmp", role: "UPS" }, ]; @@ -39,9 +41,11 @@ ["garden_door", "Garden"], ["patio_door", "Patio"], ]; const WINDOWS = [["window_left", "Left"], ["window_right", "Right"]]; - const HOUSE = ["weather", "alarm", "office_light", ...DOORS.map((d) => d[0]), ...WINDOWS.map((w) => w[0])]; - // "today" is sensor.wall_today: the calendars' events for today and - // tomorrow, gathered by home-assistant/packages/wall_calendar.yaml. + // "forecast" is sensor.wall_weather: today's high and low, the next rain and + // the next sunrise or sunset (home-assistant/packages/wall_weather.yaml). + const HOUSE = ["weather", "forecast", "alarm", "office_light", ...DOORS.map((d) => d[0]), ...WINDOWS.map((w) => w[0])]; + // "today" is sensor.wall_today: the calendars' events for the next seven + // days, gathered by home-assistant/packages/wall_calendar.yaml. const HA = [...HOUSE, "today"]; const states = {}; // HA name -> the entity's state object const answers = {}; // name -> data.result of the last good answer @@ -220,7 +224,7 @@ grid.replaceChildren(); const cpu = new Map((answers.cpu || []).map((r) => [r.metric.instance, num(r)])); const snmp = new Map((answers.snmp || []).map((r) => [r.metric.device, num(r)])); - const charge = (answers.ups || []).find((r) => r.metric.__name__ === "upsEstimatedChargeRemaining"); + const ups = new Map(fresh("ups") ? (answers.ups || []).map((r) => [r.metric.__name__, num(r)]) : []); for (const h of HOSTS) { const tile = el("div", "node"); @@ -244,9 +248,21 @@ } else { if (!fresh("snmp")) state = "unknown"; else if (snmp.get(h.name) !== 1) state = "down"; - if (state === "ok" && h.name === "mjolnir" && charge) { - val.textContent = `${Math.round(num(charge))}%`; - val.append(el("small", null, "charge")); + if (state === "ok" && h.name === "mjolnir" && ups.size) { + // On battery outranks everything else the tile could say, and does + // not wait on the charge: a missing charge is only a "—". + const onBattery = (ups.get("upsSecondsOnBattery") || 0) > 0; + const runtime = ups.has("upsEstimatedMinutesRemaining") + ? `${Math.round(ups.get("upsEstimatedMinutesRemaining"))} min` : ""; + if (onBattery) state = "battery"; + // Short enough to stay on one line in the tile. + role.textContent = [onBattery ? "BATTERY" : "mains", runtime].filter(Boolean).join(" · "); + if (ups.has("upsEstimatedChargeRemaining")) { + val.textContent = `${Math.round(ups.get("upsEstimatedChargeRemaining"))}%`; + val.append(el("small", null, "charge")); + } else { + val.textContent = "—"; + } } else { val.textContent = state === "ok" ? "up" : state === "down" ? "down" : "—"; } @@ -288,25 +304,6 @@ svg.append(fill, line); } - // ---------- power ---------- - function renderPower() { - const ups = new Map((answers.ups || []).map((r) => [r.metric.__name__, num(r)])); - const card = document.querySelector(".power"); - if (!fresh("ups") || ups.size === 0) { - card.dataset.state = "unknown"; - $("ups-state").textContent = "—"; - for (const id of ["ups-charge", "ups-runtime", "ups-load"]) $(id).textContent = "—"; - return; - } - const onBattery = (ups.get("upsSecondsOnBattery") || 0) > 0; - card.dataset.state = onBattery ? "battery" : "mains"; - $("ups-state").textContent = onBattery ? "On battery" : "On mains"; - const v = (k, unit) => (ups.has(k) ? `${Math.round(ups.get(k))}${unit}` : "—"); - $("ups-charge").textContent = v("upsEstimatedChargeRemaining", "%"); - $("ups-runtime").textContent = v("upsEstimatedMinutesRemaining", " min"); - $("ups-load").textContent = v("upsOutputPercentLoad", "%"); - } - // ---------- status bar: how old each answer is ---------- function age(ms) { const s = Math.round(ms / 1000); @@ -361,16 +358,42 @@ $("wx-temp").textContent = "—"; $("wx-cond").textContent = "—"; $("wx-sub").textContent = ""; + $("wx-sub2").textContent = ""; return; } const a = w.attributes || {}; const unit = a.temperature_unit || "°"; $("wx-temp").textContent = a.temperature !== undefined ? `${Math.round(a.temperature)}${unit.startsWith("°") ? "°" : unit}` : "—"; $("wx-cond").textContent = CONDITIONS[w.state] || w.state; - const bits = []; - if (a.humidity !== undefined) bits.push(`${Math.round(a.humidity)}% humidity`); - if (a.wind_speed !== undefined) bits.push(`wind ${Math.round(a.wind_speed)} ${a.wind_speed_unit || ""}`.trim()); - $("wx-sub").textContent = bits.join(" · "); + + // Line one: the day ahead, from sensor.wall_weather when it answers, the + // present's humidity when it does not. Line two: the next sun event and + // the wind. + const f = haFresh("forecast") ? states.forecast.attributes || {} : null; + const line1 = []; + const line2 = []; + const deg = (v) => `${Math.round(Number(v))}°`; + if (f && f.high != null && f.low != null) line1.push(`H ${deg(f.high)} · L ${deg(f.low)}`); + else if (a.humidity !== undefined) line1.push(`${Math.round(a.humidity)}% humidity`); + if (f && f.rain_at) { + const at = new Date(f.rain_at); + line1.push(at <= new Date() ? "rain now" : `rain by ${hm(at)}`); + } + if (f) { + // Whichever comes first, so the line always says what is next. The + // sensor is up to fifteen minutes old, so a time already past is + // dropped rather than shown as next. + const now = new Date(); + const sun = [["sunrise", f.next_rising], ["sunset", f.next_setting]] + .filter(([, t]) => t) + .map(([k, t]) => [k, new Date(t)]) + .filter(([, t]) => t > now) + .sort((x, y) => x[1] - y[1]); + if (sun.length) line2.push(`${sun[0][0]} ${hm(sun[0][1])}`); + } + if (a.wind_speed !== undefined) line2.push(`wind ${Math.round(a.wind_speed)} ${a.wind_speed_unit || ""}`.trim()); + $("wx-sub").textContent = line1.join(" · "); + $("wx-sub2").textContent = line2.join(" · "); } // ---------- home row ---------- @@ -432,41 +455,159 @@ const h = d.getHours(); return `${h % 12 || 12}:${String(d.getMinutes()).padStart(2, "0")} ${h < 12 ? "AM" : "PM"}`; }; - function eventRow(e, now) { + const shortDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + const midnight = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()); + // Whole days from today's midnight to the event's start: 0 today (or + // earlier, for something still going), 1 tomorrow, and so on. + const dayOf = (e, now) => Math.max(0, Math.round((midnight(evStart(e)) - midnight(now)) / 86_400_000)); + + function eventRow(e, now, later) { const start = evStart(e); const going = start <= now; - const row = el("div", `ev c${Number(e.cal) % 6}${going && !e.all_day ? " now" : ""}`); + const cls = `ev c${Number(e.cal) % 6}${going && !e.all_day ? " now" : ""}${later ? " later" : ""}`; + const row = el("div", cls); const t = e.all_day ? "All day" : going ? "Now" : hm(start); row.append(el("span", "bar"), el("span", "t", t), el("span", "what", String(e.title || "Busy"))); if (e.location) row.append(el("span", "where", String(e.location))); return row; } + + // The sensor is up to five minutes old, so drop what has ended since. + function upcoming(now) { + if (!haFresh("today")) return null; + return ((states.today.attributes || {}).events || []) + .filter((e) => evEnd(e) > now) + .sort((a, b) => evStart(a) - evStart(b)); + } + + // Today and tomorrow in full; then the rest of the week, one dim line per + // event under its day, for as long as the box has room. fitList takes the + // overflow from the far end, so the week shortens before today does. function renderToday() { const box = $("today"); box.replaceChildren(); - if (!haFresh("today")) { + const now = new Date(); + const evs = upcoming(now); + if (!evs) { box.append(el("div", "none", "—")); return; } - const now = new Date(); - const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1); - // The sensor is up to five minutes old, so drop what has ended since. - const evs = ((states.today.attributes || {}).events || []) - .filter((e) => evEnd(e) > now) - .sort((a, b) => evStart(a) - evStart(b)); - const todays = evs.filter((e) => evStart(e) < tomorrow); - const later = evs.filter((e) => evStart(e) >= tomorrow); + const byDay = new Map(); + for (const e of evs) { + const d = dayOf(e, now); + if (!byDay.has(d)) byDay.set(d, []); + byDay.get(d).push(e); + } - if (todays.length) for (const e of todays) box.append(eventRow(e, now)); + const todays = byDay.get(0) || []; + if (todays.length) for (const e of todays) box.append(eventRow(e, now, false)); else box.append(el("div", "none", "Nothing else today")); - if (later.length) { - box.append(el("div", "day", "Tomorrow")); - for (const e of later) box.append(eventRow(e, now)); + for (const d of [...byDay.keys()].filter((k) => k > 0).sort((a, b) => a - b)) { + const date = new Date(now.getFullYear(), now.getMonth(), now.getDate() + d); + box.append(el("div", "day", d === 1 ? "Tomorrow" : `${shortDays[date.getDay()]} ${date.getDate()}`)); + for (const e of byDay.get(d)) box.append(eventRow(e, now, d > 1)); } fitList(box, "ev"); } + // ---------- up next: the header's countdown ---------- + // The next timed event that has not started. The ring is the last hour: + // full an hour out, empty at the start, amber inside fifteen minutes. + const RING = 188.5; // 2πr, r = 30, as in index.html + function renderNext() { + const card = $("next"); + const arc = $("next-arc"); + const now = new Date(); + const evs = upcoming(now); + const next = evs && evs.find((e) => !e.all_day && evStart(e) > now); + if (!next) { + card.dataset.state = "none"; + $("next-what").textContent = evs ? "Nothing this week" : "—"; + $("next-when").textContent = ""; + arc.setAttribute("stroke-dashoffset", String(RING)); + return; + } + const start = evStart(next); + const mins = Math.max(0, Math.round((start - now) / 60_000)); + const d = dayOf(next, now); + let when; + if (d === 0 && mins < 60) when = `in ${mins} min · ${hm(start)}`; + else if (d === 0) when = `in ${Math.floor(mins / 60)} h ${mins % 60} min · ${hm(start)}`; + else if (d === 1) when = `tomorrow · ${hm(start)}`; + else when = `${shortDays[start.getDay()]} · ${hm(start)}`; + card.dataset.state = mins <= 15 ? "soon" : "later"; + $("next-what").textContent = String(next.title || "Busy"); + $("next-when").textContent = when; + arc.setAttribute("stroke-dashoffset", String(RING * (1 - Math.min(mins, 60) / 60))); + } + + // ---------- context: one card, whichever matters now ---------- + // In order of precedence. The first whose `when` is true gets the card; the + // others that are also true are named on its last line, so nothing that + // matters is hidden without a word. The last entry always applies, so the + // card is never empty. Later cards (commute, Shabbat, trash, deliveries, + // now playing) slot in above it as their sources arrive. + const CONTEXT = [ + { title: "Word of the day", short: "word", when: () => true, render: renderWord }, + ]; + + // A static list, so nothing is fetched: one word a day, by day of the year. + // Hebrew without niqqud, the transliteration, the meaning. + const WORDS = [ + ["סבלנות", "savlanut", "patience"], ["שלום", "shalom", "peace; hello"], + ["תודה", "todah", "thank you"], ["בוקר", "boker", "morning"], + ["ערב", "erev", "evening"], ["לילה", "laylah", "night"], + ["משפחה", "mishpachah", "family"], ["חבר", "chaver", "friend"], + ["בית", "bayit", "home, house"], ["אהבה", "ahavah", "love"], + ["שמחה", "simchah", "joy"], ["תקווה", "tikvah", "hope"], + ["אמונה", "emunah", "faith"], ["חכמה", "chochmah", "wisdom"], + ["אומץ", "ometz", "courage"], ["כבוד", "kavod", "respect, honour"], + ["צדקה", "tzedakah", "charity, justice"], ["חסד", "chesed", "kindness"], + ["אמת", "emet", "truth"], ["ברכה", "brachah", "blessing"], + ["שבת", "Shabbat", "Sabbath, rest"], ["מנוחה", "menuchah", "rest"], + ["עבודה", "avodah", "work"], ["מחשב", "machshev", "computer"], + ["רשת", "reshet", "network"], ["שרת", "sharat", "server"], + ["סיסמה", "sisma", "password"], ["מפתח", "mafteach", "key"], + ["ענן", "anan", "cloud"], ["גשם", "geshem", "rain"], + ["שמש", "shemesh", "sun"], ["ירח", "yareach", "moon"], + ["כוכב", "kochav", "star"], ["ים", "yam", "sea"], + ["הר", "har", "mountain"], ["עץ", "etz", "tree"], + ["כלב", "kelev", "dog"], ["חתול", "chatul", "cat"], + ["ספר", "sefer", "book"], ["מים", "mayim", "water"], + ["לחם", "lechem", "bread"], ["קפה", "kafeh", "coffee"], + ["זמן", "zman", "time"], ["שעה", "sha'ah", "hour"], + ["יום", "yom", "day"], ["שבוע", "shavua", "week"], + ["חודש", "chodesh", "month"], ["שנה", "shanah", "year"], + ["לאט", "le'at", "slowly"], ["בסדר", "beseder", "okay, in order"], + ["סבבה", "sababa", "great, cool"], ["תיקון", "tikkun", "repair"], + ["דרך", "derech", "way, path"], ["שאלה", "she'elah", "question"], + ["תשובה", "teshuvah", "answer; return"], ["התחלה", "hatchalah", "beginning"], + ["כוח", "koach", "strength"], ["ביחד", "beyachad", "together"], + ]; + function renderWord(box) { + const now = new Date(); + const dayOfYear = Math.round((midnight(now) - new Date(now.getFullYear(), 0, 1)) / 86_400_000); + const [he, tr, en] = WORDS[dayOfYear % WORDS.length]; + const w = el("div", "word", he); + w.lang = "he"; + w.dir = "rtl"; + const sub = el("div", "word-sub"); + sub.append(el("b", null, tr), document.createTextNode(` · ${en}`)); + box.append(w, sub); + } + + function renderContext() { + const box = $("context"); + box.replaceChildren(); + const live = CONTEXT.filter((c) => c.when()); + const top = live[0]; + $("h-context").textContent = top.title; + top.render(box); + const rest = live.slice(1, -1).map((c) => c.short); + $("context-also").textContent = rest.length ? `also: ${rest.join(" · ")}` : ""; + } + function render() { renderWeather(); renderHome(); @@ -474,9 +615,10 @@ // After the alerts: they take the height they need, and the calendar // fits itself into what is left. renderToday(); + renderNext(); renderNodes(); renderWan(); - renderPower(); + renderContext(); renderStatus(); }