diff --git a/apps/ha-remote/ANDROID_COMPANION.md b/apps/ha-remote/ANDROID_COMPANION.md index 4bdb243..05f264d 100644 --- a/apps/ha-remote/ANDROID_COMPANION.md +++ b/apps/ha-remote/ANDROID_COMPANION.md @@ -1,4 +1,4 @@ -# Home Assistant Remote Android companion +# Home Assistant remote Android companion This is the implementation contract for the Android companion paired with `apps/ha-remote`. The phone is the only Home Assistant client: the watch sends an intent, and the phone reports the entity state after Home Assistant @@ -10,15 +10,16 @@ The configured short button labels are sent over BLE to be shown on the watch; k 1. The user pairs the watch once in Nothing X. The companion does not run a second pairing flow and must not perform the App Loader's `0x8047` / `0x8049` bind handshake. 2. Resolve the already bonded WP2 and use `connectGatt` to its existing GATT identity while Nothing X is active. - Android coexistence with Nothing X is a required hardware validation: SDK documentation calls this expected but - untested. If Android cannot maintain the second GATT client on a phone model, report that combination as - unsupported instead of rebinding or disconnecting Nothing X. -3. Subscribe to notify UUIDs `0000FFF1-0000-1000-8000-00805F9B34FB` and - `77D4FF02-2FE2-2334-0D35-9CCD078F529C`; write to `FFF2` and shell `77D4FF01-2FE2-2334-0D35-9CCD078F529C`. - Accumulate shell notifications until the complete `GETSECRET:<32 hex>,OK` response arrives. + Android coexistence with Nothing X is a required hardware validation. If Android cannot maintain the second GATT + client on a phone model, report that combination as unsupported instead of rebinding or disconnecting Nothing X. +3. Subscribe to notify UUIDs `0000FFF1-0000-1000-8000-00805F9B34FB`, + `77D4FF02-2FE2-2334-0D35-9CCD078F529C`, and + `02F00000-0000-0000-0000-00000000FFE2`; write to `FFF2` and shell + `77D4FF01-2FE2-2334-0D35-9CCD078F529C`. The data-notify subscription is the stock firmware's + phone-ready signal, so wait briefly after the third subscription before reading K. Accumulate shell + notifications until the complete `GETSECRET:<32 hex>,OK` response arrives and retry that read after a reconnect. 4. Treat K as a password. This companion keeps K in memory only and clears it when the GATT session closes; never - log, export, sync, or put it in a project file. The SDK threat model notes that the watch pairing secret is - readable over BLE by a nearby client, so this channel must not carry secrets or personal data. + log, export, sync, or put it in a project file. Nothing personal goes over this channel. 5. Send one encrypted channel `PING` (`0x90A7`) under K to register. Encode/decode channel frames as specified in `.sdk/wp2-apps/docs/abi-1.4.md`. Do not send Nothing X authentication or pairing frames. 6. Decode `0xB0A6` EVENT notifications, verify sequence and running app slot, and pass only `H1` app messages to @@ -26,66 +27,78 @@ The configured short button labels are sent over BLE to be shown on the watch; k 7. On process restart, reconnect and try K directly. On no response, show a compatibility diagnostic for stock or old patched firmware; never silently start a fresh bind. -## Watch protocol (`H1`) +## Watch protocol v3 (`H1`) -All integers are unsigned bytes. App messages have a 128 byte maximum. UTF-8 names are capped at 15 bytes. There -are at most five button records, indexed 0–4. Entity IDs remain phone-local. +All integers are unsigned bytes. App messages have a 128-byte maximum. UTF-8 names are capped at 15 bytes and +section titles at 10. There are **ten slots** (0-9), each with a kind: `0` toggle, `1` dimmer (brightness slider). +Up to **five favorites** are slot indexes sent as five bytes with `0xFF` for an empty slot. Entity IDs remain +phone-local. | Direction | Frame | Meaning | |---|---|---| | Watch → phone | `H1?` | App started or resumed; send config and all states | -| Phone → watch | `H1C count (enabled name_len name)*` | Replace the configured buttons in order; count 0–5 | -| Watch → phone | `H1T seq index requested_on` | Request toggle to requested state; seq is diagnostic/deduplication only | -| Phone → watch | `H1A seq` | Command accepted by companion for processing; pending remains until `H1S` | -| Phone → watch | `H1P` | Companion heartbeat; refreshes the watch's phone-connected indicator | -| Watch → phone | `H1W result` | Runtime result from `Api::widget`; 0 means the current loader accepts widget updates | -| Phone → watch | `H1S index actual_on result` | Authoritative state; result 0 means confirmed, nonzero is generic failure | +| Phone → watch | `H1V n (enabled kind len name)*` | Slots 5-9; `n <= 5` | +| Phone → watch | `H1J n (len section)*` | Sections for slots 0-4 | +| Phone → watch | `H1K n (len section)*` | Sections for slots 5-9 | +| Phone → watch | `H1U n (enabled kind len name)* fav[5]` | Slots 0-4 + favorites; **the commit frame the watch persists** | +| Phone → watch | `H1I icon[10]` | Per-control icon id: `0` auto, `1` bulb, `2` ceiling light, `3` fan, `4` device | +| Watch → phone | `H1T seq slot on` | Toggle request (`slot 0..9`) | +| Watch → phone | `H1B seq slot value` | Brightness request, `value 0..=100`, dimmer slots only | +| Phone → watch | `H1A seq` | Command accepted; pending remains until `H1S` | +| Phone → watch | `H1P` | Companion heartbeat (10 s) | +| Phone → watch | `H1S slot on value result available` | Authoritative state; `value` is brightness percent, result `0` confirmed, nonzero generic failure, `available 0` means HA has no data for the entity (device lost power): the watch greys the row and shows **Inactive** | | Phone → watch | `H1E seq error_code` | Generic failure; never include HA response text or entity data | +| Watch → phone | `H1W result` | Runtime result from `Api::widget` | -`H1C` body encoding is `count:u8`, then `count` records of `enabled:u8, name_len:u8, name[name_len]`. `H1S` is -exactly `index:u8, actual_on:u8, result:u8`; result 0 confirms the command and clears pending/error state, nonzero -reports failure while still updating the last known actual state. `H1E` is `seq:u8, error_code:u8`. On `H1T`, -send `H1A` promptly, then await HA confirmation and send `H1S`. The phone deduplicates repeated toggle sequences -and permits only one outstanding watch command at a time. A failed or timed-out Home Assistant call sends `H1S` -with nonzero result and a fresh state; it must not optimistically leave the watch showing the requested value. -`H1P` is sent every 10 seconds while the watch app is active. It refreshes liveness without changing a control or -rewriting watch storage. +The phone sends `V, J, K, U, I` in that order on every HELLO; `U` commits the control configuration and `I` +updates its icon choices. A half-delivered +configuration never replaces the stored one. The legacy `H1C` (five slots, optional single favorite) and `H1G` +frames from older companions are still accepted. For `H1B`, send `H1A` promptly, set the brightness through Home +Assistant, wait for the reported value to settle, then send `H1S`. The phone serializes commands: one outstanding +watch command at a time, duplicate sequences are idempotent, and a failed or timed-out Home Assistant call sends +`H1S` with a nonzero result and the cached state so the watch never keeps an optimistic value. -Watch config persistence uses a versioned `D1` blob containing exactly five fixed records of -`enabled:u8, name_len:u8, actual_on:u8, name[15]`; this is a startup display fallback only. Android remains -authoritative and resends config and fresh states after every HELLO. +On the watch a dimmer row is a plain element: a short press sends `H1B` with 0 or 100 (on/off), and a long press +opens the device's own slider page — drag it or turn the crown; both send normal `H1B` frames. No slider lives in +the list rows. + +Watch config persistence uses a versioned `D4` blob: count, the five favorites, then ten fixed records of +`enabled, kind, icon, on, value, len, name[15], sec_len, section[10]`. The old `D3` and `D2` blobs are migrated on load +(icons default to auto; `D2` controls migrate as toggles). Android remains authoritative and resends config, icons and fresh states after every +HELLO. + +State frames may be 6 bytes (legacy), 7 bytes (no availability byte) or 8 bytes (current); a missing availability +byte means available. An unavailable push is a device state, not an app error: the watch clears any pending command, +keeps the last on/value, and shows the row as Inactive until HA reports the entity again. ## Android app behavior - Home Assistant setup: user enters instance URL and long-lived access token in app UI; token stays in Keystore- protected app storage and is used only by the phone's HTTPS REST client. -- Five slots: enable/disable, short display name, and a Home Assistant light or light group. The entity picker - loads `light.*` entities and legacy `group.*` entities containing lights. Individual lights use - `light.turn_on` / `light.turn_off`; legacy groups use `homeassistant.turn_on` / `homeassistant.turn_off`. -- Startup: load stored slot settings, connect HA, resolve current states, connect to the bonded watch, open K channel, - then publish config and state. Send a full config and state snapshots on `H1?` and after any watch reconnect. Keep - the app channel registered with `PING` on entry; the 2026-11-13+ loader delivers app messages unsolicited. While the - app runs, send `H1P` at least every 10 seconds so the watch does not mark a healthy companion as disconnected. -- Toggle handling: validate slot and requested state; serialize watch commands; call `light.turn_on` or - `light.turn_off`; await HA state confirmation; publish `H1S`. Duplicate seq is idempotent. +- **All entities** in Home Assistant are selectable (the picker loads `/api/states`); for each of the ten slots the + user chooses the kind: toggle switch or brightness slider (sliders require `light.*`). +- Watch labels are short names (15 UTF-8 bytes), section titles are 10 bytes, each control can choose a Material + icon, and up to five slots can be marked favorite: favorites are what the watch page and widget show. +- Startup: load stored slot settings, connect HA, resolve current states, connect to the bonded watch, open K + channel, then publish `V, J, K, U` and state snapshots. Send a full config and states on `H1?` and after every + reconnect. Keep the channel registered with `P` at least every 10 seconds. +- Toggle handling: validate slot and requested state; serialize watch commands; call `homeassistant.turn_on/off`, + await the state, publish `H1S` with the read-back value. Brightness uses `light.turn_on` with `brightness_pct` + (0 turns off) and confirms against the reported brightness. Duplicate seq is idempotent. - HA state changes from another controller are detected by five-second polling and sent to the watch as `H1S`, so - its indicators stay current. -- The Android connected-device foreground service owns the GATT session independently of the setup screen. It keeps + the rows and widget stay current. +- The Android connected-device foreground service owns the GATT session independently of the setup screen; it keeps an ongoing notification and reconnects with exponential backoff up to 60 seconds after BLE errors. Home Assistant - outages keep the watch channel alive and retain the last confirmed states until polling recovers. Android - force-stop and denied Bluetooth permission require the user to reopen the app. Request deduplication is held in - memory for 15 seconds; Home Assistant on/off commands are idempotent, so an app process restart cannot turn a - retried request into the opposite state. + outages keep the watch channel alive and retain the last confirmed states until polling recovers. - UI exposes BLE/channel/HA connection status and a **Test connection** action. Never expose K or raw protocol payloads in logs or diagnostics. ## Compatibility and release gates - Firmware: K channel requires patched stub and loader from 2026-11-13 or later. The app widget requires stub v4+ - and a loader release from 2026-11-15 or later. Latest SDK upstream is `b81cb772` (2026-11-17); it adds a - background phone wake-probe example and does not change the loader, K channel, or widget support used here. + and a loader release from 2026-11-15 or later. - Android release gate: exercise Nothing X + companion simultaneously on each supported Android vendor/version; verify no new pairing popup, both BLE clients retain notifications, K channel works after screen off, service - restart and watch reboot, and Home Assistant state changes propagate both ways. -- Watch release gate: host protocol tests, target build, FMC store check, then emulator/hardware validation. Emulator - does not model LVGL widgets, cards, pages, or BLE coexistence. + restart and watch reboot, and Home Assistant state changes and brightness propagate both ways. +- Watch release gate: host protocol tests, target build, FMC store check, then emulator/hardware validation. The + emulator does not model LVGL widgets, cards, pages, or BLE coexistence. diff --git a/apps/ha-remote/README.md b/apps/ha-remote/README.md index 560656f..1d35a6c 100644 --- a/apps/ha-remote/README.md +++ b/apps/ha-remote/README.md @@ -1,14 +1,15 @@ # Home Assistant (ha-remote) -Five Home Assistant light or group toggles on the watch. Each control's name and section are set from the phone, -and a tap on a row asks the phone to toggle the light; the phone confirms the resulting state back. +Up to ten Home Assistant controls on the watch: toggle switches for on/off entities and brightness +sliders for lights, with names and sections set from the phone. The Apps row lists every control; +the page next to the face and the widget card show up to five favorites. -The Android companion (setup UI, Home Assistant connection, the watch's BLE link, and the APK) lives in its own -repository: . That repository also carries this watch app under the same -`apps/ha-remote/` layout, plus PC install instructions. +The Android companion (setup UI, entity picker, Home Assistant connection, the watch's BLE link, +and the APK) lives in its own repository: . That repository +also carries this watch app under the same `apps/ha-remote/` layout, plus PC install instructions. -`store.toml` and `store.md` are the FMC store listing; `ANDROID_COMPANION.md` documents the watch-phone protocol -contract. +`store.toml` and `store.md` are the FMC store listing; `ANDROID_COMPANION.md` documents the +watch-phone protocol contract. ## Build and install diff --git a/apps/ha-remote/icons/ceiling-light.svg b/apps/ha-remote/icons/ceiling-light.svg new file mode 100644 index 0000000..a7c4c5d --- /dev/null +++ b/apps/ha-remote/icons/ceiling-light.svg @@ -0,0 +1 @@ + diff --git a/apps/ha-remote/icons/device.svg b/apps/ha-remote/icons/device.svg new file mode 100644 index 0000000..587bada --- /dev/null +++ b/apps/ha-remote/icons/device.svg @@ -0,0 +1 @@ + diff --git a/apps/ha-remote/icons/fan.svg b/apps/ha-remote/icons/fan.svg new file mode 100644 index 0000000..7346742 --- /dev/null +++ b/apps/ha-remote/icons/fan.svg @@ -0,0 +1 @@ + diff --git a/apps/ha-remote/icons/light-bulb.svg b/apps/ha-remote/icons/light-bulb.svg new file mode 100644 index 0000000..4732e72 --- /dev/null +++ b/apps/ha-remote/icons/light-bulb.svg @@ -0,0 +1 @@ + diff --git a/apps/ha-remote/src/main.rs b/apps/ha-remote/src/main.rs index fedafd0..6393226 100644 --- a/apps/ha-remote/src/main.rs +++ b/apps/ha-remote/src/main.rs @@ -14,46 +14,72 @@ fn main() {} #[cfg(any(target_os = "none", wp2_sim))] mod device { use crate::proto::{self, Effect, MAX_BUTTONS, Model}; - use crate::screen::Screen; + use crate::screen::{Mode, Screen, View}; use cmf_wp2_app::lv::{Batch, Lv}; - use cmf_wp2_app::{Api, BUTTON, LV, MSG_MAX, PAUSE, RESUME, stock}; + use cmf_wp2_app::{Api, BUTTON, CROWN, LV, MSG_MAX, PAUSE, RESUME, stock}; cmf_wp2_app::entry!(main); cmf_wp2_app::app_icon!(); cmf_wp2_app::app_features!(cmf_wp2_app::WIDGET | cmf_wp2_app::PAGE); + /// LVGL event codes: row tap, row long press, slider drag. + const CLICKED: i16 = 7; + const LONG_PRESSED: i16 = 5; + const RELEASED: i16 = 8; + const VALUE_CHANGED: i16 = 28; + /// A long press opens the slider page; a CLICKED landing right after it belongs to the + /// same press and must not flip the brightness. + const LONG_GRACE_MS: u32 = 900; + /// Percent per crown detent on the slider page. + const CROWN_STEP: i16 = 5; + static mut MODEL: Model = Model::new(); - static mut STORE: [u8; 192] = [0; 192]; + static mut STORE: [u8; 384] = [0; 384]; - /// The widget card: a grey title line, white value lines (the control's name, then its - /// state). The card is text-only and a tap starts the app; the interactive toggles live - /// on the page next to the face. + /// The widget card: the first favorite's name and state (or the first enabled control). fn update_widget(api: &Api, m: &Model) -> i32 { - let chosen = (m.fav != proto::NO_FAVORITE) - .then(|| m.buttons[m.fav as usize]) - .filter(|b| b.enabled) - .or_else(|| m.buttons.iter().find(|b| b.enabled).copied()); + let chosen = m.primary().and_then(|i| m.buttons.get(i)).copied(); let mut val = [0u8; 40]; let value = if !m.connected { "Phone offline" } else { match chosen { - Some(b) => { + Some(b) if b.enabled => { let label = b.label(); let n = label.len().min(proto::NAME_MAX); val[..n].copy_from_slice(&label.as_bytes()[..n]); let mut k = n; val[k] = b'\n'; k += 1; - let state: &[u8] = if b.on { b"ON" } else { b"OFF" }; - val[k..k + 2].copy_from_slice(state); - k += 2; - let tail: &[u8] = b" \xc2\xb7 tap to toggle"; - val[k..k + tail.len()].copy_from_slice(tail); - k += tail.len(); + if !b.available { + val[k..k + 8].copy_from_slice(b"INACTIVE"); + k += 8; + } else { + let state: &[u8] = if b.on { b"ON" } else { b"OFF" }; + val[k..k + 2].copy_from_slice(state); + k += 2; + if b.is_dimmer() { + val[k] = b' '; + k += 1; + let v = b.value.min(100); + if v >= 100 { + val[k..k + 3].copy_from_slice(b"100"); + k += 3; + } else if v >= 10 { + val[k] = b'0' + v / 10; + val[k + 1] = b'0' + v % 10; + k += 2; + } else { + val[k] = b'0' + v; + k += 1; + } + val[k] = b'%'; + k += 1; + } + } core::str::from_utf8(&val[..k]).unwrap_or("") } - None => "Set up in the phone app", + _ => "Set up in the phone app", } }; api.widget("Home Assistant", value) @@ -61,9 +87,10 @@ mod device { fn main(api: &'static Api) -> i32 { let Some(lv) = api.lv() else { return -95 }; - let Some(mut batch) = Batch::new() else { - return -1; - }; + // The crown press / right swipe is ours: while the slider page is open it goes + // back to the list; only a plain list press exits. + api.own_back(true); + let Some(mut batch) = Batch::new() else { return 6 }; if stock::font(&mut batch) .and_then(|_| batch.submit(&lv)) .is_err() @@ -77,14 +104,10 @@ mod device { if n > 0 { m.load(&stored[..n as usize]); } - // The same screen runs as the menu app and as the page next to the face; the loader - // tells the surfaces apart, the app does not have to. - list_main(api, m, stored, lv, batch) + let mode = if api.on_page() { Mode::Page } else { Mode::Menu }; + list_main(api, m, stored, lv, batch, mode) } - /// The connection tail both loops share: phone messages into the model, the - /// pending/disconnect timeouts, the connection flag and the widget card. Returns true - /// when the caller's screen should redraw. struct Link { last_rx: u32, last_connection: bool, @@ -107,7 +130,7 @@ mod device { } } - fn sync(api: &Api, m: &mut Model, stored: &mut [u8; 192], link: &mut Link) -> bool { + fn sync(api: &Api, m: &mut Model, stored: &mut [u8; 384], link: &mut Link) -> bool { let mut dirty = false; if m.connected != link.last_connection { link.last_connection = m.connected; @@ -115,39 +138,42 @@ mod device { link.widget_dirty = true; } for i in 0..MAX_BUTTONS { - let state = (m.buttons[i].enabled as u8) << 1 | m.buttons[i].on as u8; + let b = match m.buttons.get(i) { Some(b) => b, None => continue }; + let state = ((b.enabled as u8) << 2) | ((b.on as u8) << 1) | (b.value >= 100) as u8; if link.last_state[i] != state { link.last_state[i] = state; link.widget_dirty = true; + dirty = true; } } let mut rx = [0u8; MSG_MAX]; while let Some(msg) = api.recv(&mut rx) { link.last_rx = api.now(); match m.apply(msg) { - Effect::Ignored => {} + Effect::Ignored | Effect::Heartbeat | Effect::Ack(_) => {} + Effect::Linked => { + dirty = true; + link.widget_dirty = true; + } Effect::Configured => { let n = m.save(stored); - if n > 0 { - let _ = api.save(&stored[..n]); - } + if n > 0 { let _ = api.save(&stored[..n]); } dirty = true; link.widget_dirty = true; } - Effect::Heartbeat => {} Effect::Changed => { dirty = true; link.widget_dirty = true; } - Effect::Ack(_) | Effect::Error(_) => dirty = true, + Effect::Error(_) => dirty = true, } } let now = api.now(); if m.pending.is_some() && now.wrapping_sub(link.last_rx) > 12_000 { - m.pending = None; - m.error = Some(2); + m.cancel_pending(2); link.last_rx = now; dirty = true; + link.widget_dirty = true; } if m.connected && now.wrapping_sub(link.last_rx) > 30_000 { m.mark_disconnected(); @@ -165,55 +191,139 @@ mod device { dirty } - /// The full control list, as the Apps-menu entry and as the page next to the face. - /// BUTTON exits from the menu; on the page the crown stays with the watch, so the app - /// keeps running behind the face until a swipe away pauses it. + /// Maps a negative `send` result to a diagnostic code shown on the phone row. + fn send_code(r: i32) -> u8 { + match r { + -11 => 11, + -107 => 107, + _ => 255, + } + } + + /// Sends one already-built command and consumes its sequence number. + fn send_cmd(api: &Api, m: &mut Model, frame: [u8; 6], seq: &mut u8) { + *seq = seq.wrapping_add(1); + let sent = api.send(&frame); + if sent < 0 { m.cancel_pending(send_code(sent)); } + } + fn list_main( api: &'static Api, m: &mut Model, - stored: &mut [u8; 192], + stored: &mut [u8; 384], lv: Lv, mut batch: Batch, + mode: Mode, ) -> i32 { let mut flush = |b: &mut Batch| b.submit(&lv); - let mut screen = match Screen::build(&mut batch, m, &mut flush) { + let mut screen = match Screen::build(&mut batch, m, mode, &mut flush) { Ok(screen) => screen, Err(_) => return 2, }; - if flush(&mut batch).is_err() { - return 3; - } + if flush(&mut batch).is_err() { return 3; } let mut seq = 0u8; let mut dirty = true; let mut redraw_retry = false; let mut last_redraw_retry = api.now(); let mut link = Link::new(api, m); + let mut long_at = 0u32; + let mut long_slot = usize::MAX; let _ = api.send(&proto::HELLO); loop { let mut timeout = 250; - if m.pending.is_some() { - timeout = 20; - } + if m.pending.is_some() { timeout = 20; } match api.event(timeout) { - Some(e) if e.kind == BUTTON => return 0, - Some(e) if e.kind == LV && e.y == 7 => { - let i = screen.rows.iter().position(|row| row.0 == e.x as u16); - if let Some(i) = i { - if let Some(frame) = m.toggle_frame(i, seq) { - seq = seq.wrapping_add(1); - let sent = api.send(&frame); - if sent < 0 { - m.pending = None; - m.pending_target = None; - m.pending_seq = None; - // Keep the transport failure distinguishable from the - // companion's protocol error 1 (busy/invalid slot). - m.error = Some(match sent { - -11 => 11, - -107 => 107, - _ => 255, - }); + Some(e) if e.kind == BUTTON => { + if screen.view == View::Slider { + // Own back: close the slider page instead of leaving the app. + if screen.leave(&mut batch).is_err() { return 7; } + screen = match Screen::build(&mut batch, m, mode, &mut flush) { + Ok(s) => s, + Err(_) => return 7, + }; + dirty = true; + } else if mode == Mode::Menu { + return 0; + } + } + Some(e) if e.kind == CROWN && screen.view == View::Slider => { + let slot = screen.slider_slot as usize; + if slot < MAX_BUTTONS { + let cur = m.buttons[slot].value.min(100) as i16; + let v = (cur + e.delta * CROWN_STEP).clamp(0, 100) as u8; + if let Some(frame) = m.brightness_frame(slot, v, seq) { + send_cmd(api, m, frame, &mut seq); + } else if !m.connected { + m.cancel_pending(107); + } + dirty = true; + } + } + Some(e) if e.kind == LV && e.y == CLICKED => { + let now = api.now(); + let slot = screen.row_slot(e.x as u16); + if let Some(slot) = slot { + if slot == long_slot && now.wrapping_sub(long_at) < LONG_GRACE_MS { + long_slot = usize::MAX; + } else if let Some((enabled, dimmer, on, value)) = + m.buttons.get(slot).map(|b| (b.enabled, b.is_dimmer(), b.on, b.value)) + { + if enabled && dimmer { + // Short press on a device: jump between 0 and 100. + let target = if on && value > 0 { 0 } else { 100 }; + if let Some(frame) = m.brightness_frame(slot, target, seq) { + send_cmd(api, m, frame, &mut seq); + } else if !m.connected { + m.cancel_pending(107); + } + dirty = true; + } else if enabled { + if let Some(frame) = m.toggle_frame(slot, seq) { + send_cmd(api, m, frame, &mut seq); + dirty = true; + } else if !m.connected { + m.cancel_pending(107); + dirty = true; + } + } + } + } + } + Some(e) if e.kind == LV && e.y == LONG_PRESSED => { + if screen.view == View::List { + if let Some(slot) = screen.row_slot(e.x as u16) { + if m.buttons.get(slot).is_some_and(|b| b.enabled && b.is_dimmer()) { + long_at = api.now(); + long_slot = slot; + if screen.leave(&mut batch).is_err() { return 7; } + screen = match Screen::build_slider(&mut batch, m, mode, &mut flush, slot) { + Ok(s) => s, + Err(_) => return 7, + }; + dirty = true; + } + } + } + } + Some(e) if e.kind == LV && e.y == VALUE_CHANGED => { + if screen.is_slider(e.x as u16) { + let slot = screen.slider_slot as usize; + if slot < MAX_BUTTONS { + let v = e.delta.clamp(0, 100) as u8; + screen.preview_slider(v); + dirty = true; + } + } + } + Some(e) if e.kind == LV && e.y == RELEASED => { + if screen.is_slider(e.x as u16) { + let slot = screen.slider_slot as usize; + if let (Some(v), true) = (screen.finish_slider(), slot < MAX_BUTTONS) { + if let Some(frame) = m.brightness_frame(slot, v, seq) { + send_cmd(api, m, frame, &mut seq); + } else if !m.connected { + m.cancel_pending(107); } dirty = true; } @@ -222,32 +332,40 @@ mod device { Some(e) if e.kind == PAUSE => { loop { match api.event(u32::MAX).map(|e| e.kind) { - Some(BUTTON) => return 0, + Some(BUTTON) if mode == Mode::Menu && screen.view == View::List => return 0, Some(RESUME) => break, _ => {} } } + if screen.view == View::Slider { + // Returning from a popup lands back on the main list. + if screen.leave(&mut batch).is_err() { return 7; } + screen = match Screen::build(&mut batch, m, mode, &mut flush) { + Ok(s) => s, + Err(_) => return 7, + }; + } let _ = api.send(&proto::HELLO); dirty = true; } _ => {} } - if redraw_retry && api.now().wrapping_sub(last_redraw_retry) >= 1000 { + // Flush a brightness queued behind an in-flight command. + if let Some(frame) = m.take_later(seq) { + send_cmd(api, m, frame, &mut seq); dirty = true; - last_redraw_retry = api.now(); } - if sync(api, m, stored, &mut link) { + if redraw_retry && api.now().wrapping_sub(last_redraw_retry) >= 1000 { dirty = true; + last_redraw_retry = api.now(); } + if sync(api, m, stored, &mut link) { dirty = true; } if dirty { let redraw = screen - .update(&mut batch, m) - .and_then(|_| batch.submit(&lv)); + .update(&mut batch, m, &mut flush) + .and_then(|_| flush(&mut batch)); if redraw.is_err() { - // LVGL batches can fail transiently when the loader is changing - // surfaces. Returning here closes the app and loses the live BLE - // session, so leave it running and retry on the next event/update. - m.error = Some(3); + // Keep the live BLE session: retry instead of exiting the app. redraw_retry = true; last_redraw_retry = api.now(); } else { @@ -257,5 +375,5 @@ mod device { } } } - } + diff --git a/apps/ha-remote/src/proto.rs b/apps/ha-remote/src/proto.rs index e42e038..5d269ae 100644 --- a/apps/ha-remote/src/proto.rs +++ b/apps/ha-remote/src/proto.rs @@ -1,13 +1,31 @@ //! Compact, bounded protocol shared with the Android companion. //! -//! Frames are ASCII `H1`, a type byte and fixed binary fields. Names are UTF-8 and capped at -//! 15 bytes, section titles at 10 bytes. The phone sends the controls (CONFIG) and then their -//! sections and favorite (GROUPS) as two messages, because one message cannot carry both -//! within MSG_MAX. The favorite is a slot index, or 0xFF for none. +//! Frames are ASCII `H1`, a type byte and fixed binary fields. v3 carries ten slots, a +//! control kind per slot (toggle or dimmer) and up to five favorites. Ten 15-byte names do +//! not fit one 128-byte message, so configuration is split: `V`/`K` configure slots 5..10 +//! (config, sections), `J` their sections and `U` slots 0..5 plus the favorites; the phone +//! sends V, J, K, U in that order and `U` commits the state to NAND. The legacy `C`/`G` +//! frames from an older companion stay accepted, so an old phone still works. -pub const MAX_BUTTONS: usize = 5; +pub const MAX_BUTTONS: usize = 10; +pub const MAX_FAVORITES: usize = 5; +pub const HALF: usize = 5; pub const NAME_MAX: usize = 15; pub const SECTION_MAX: usize = 10; + +pub const KIND_TOGGLE: u8 = 0; +pub const KIND_DIMMER: u8 = 1; +pub const ICON_AUTO: u8 = 0; +pub const ICON_LIGHT_BULB: u8 = 1; +pub const ICON_CEILING_LIGHT: u8 = 2; +pub const ICON_FAN: u8 = 3; +pub const ICON_DEVICE: u8 = 4; + +pub const CONFIG_A: u8 = b'U'; +pub const CONFIG_B: u8 = b'V'; +pub const SECTIONS_A: u8 = b'J'; +pub const SECTIONS_B: u8 = b'K'; +pub const ICONS: u8 = b'I'; pub const CONFIG: u8 = b'C'; pub const GROUPS: u8 = b'G'; pub const STATE: u8 = b'S'; @@ -15,19 +33,27 @@ pub const HEARTBEAT: u8 = b'P'; pub const ACK: u8 = b'A'; pub const ERROR: u8 = b'E'; pub const TOGGLE: u8 = b'T'; +pub const BRIGHTNESS: u8 = b'B'; pub const RESULT_OK: u8 = 0; pub const HELLO: [u8; 3] = *b"H1?"; -/// One persisted controls blob. -pub const SAVE_LEN: usize = 4 + MAX_BUTTONS * (3 + NAME_MAX + 1 + SECTION_MAX); +/// One persisted controls blob: `D4`, count, favorites, then ten fixed records including an icon id. +pub const SAVE_LEN: usize = 3 + MAX_FAVORITES + MAX_BUTTONS * (6 + NAME_MAX + 1 + SECTION_MAX); +const SAVE_LEN_V3: usize = 3 + MAX_FAVORITES + MAX_BUTTONS * (4 + NAME_MAX + 1 + SECTION_MAX); -/// No favorite control. +/// No favorite in a favorites slot. pub const NO_FAVORITE: u8 = 0xFF; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Button { pub enabled: bool, pub on: bool, + /// Last HA availability; runtime-only (not persisted): true until the phone says otherwise. + pub available: bool, + /// Brightness percent 0..=100 for a dimmer; 0 or 100 mirrors `on` for a toggle. + pub value: u8, + pub kind: u8, + pub icon: u8, pub name: [u8; NAME_MAX], pub len: u8, pub section: [u8; SECTION_MAX], @@ -38,6 +64,10 @@ impl Button { pub const EMPTY: Self = Self { enabled: false, on: false, + available: true, + value: 0, + kind: KIND_TOGGLE, + icon: ICON_AUTO, name: [0; NAME_MAX], len: 0, section: [0; SECTION_MAX], @@ -51,12 +81,17 @@ impl Button { pub fn section_label(&self) -> &str { core::str::from_utf8(&self.section[..self.sec_len as usize]).unwrap_or("") } + + pub fn is_dimmer(&self) -> bool { self.kind == KIND_DIMMER } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Effect { Ignored, Changed, + /// A half config or sections frame: redraw, mark linked, no NAND write yet. + Linked, + /// The commit frame: redraw and persist. Configured, Heartbeat, Ack(u8), @@ -65,11 +100,14 @@ pub enum Effect { pub struct Model { pub buttons: [Button; MAX_BUTTONS], - pub fav: u8, + pub favorites: [u8; MAX_FAVORITES], pub connected: bool, pub pending: Option, pub pending_target: Option, + pub pending_value: Option, pub pending_seq: Option, + /// Latest brightness the user dragged to while another command was in flight. + pub later: Option<(u8, u8)>, pub error: Option, } @@ -77,227 +115,457 @@ impl Model { pub const fn new() -> Self { Self { buttons: [Button::EMPTY; MAX_BUTTONS], - fav: NO_FAVORITE, + favorites: [NO_FAVORITE; MAX_FAVORITES], connected: false, pending: None, pending_target: None, + pending_value: None, pending_seq: None, + later: None, error: None, } } - pub fn load(&mut self, bytes: &[u8]) { - if bytes.len() != SAVE_LEN || &bytes[..2] != b"D2" { - return; + /// The widget's control: the first favorite, else the first enabled slot. + pub fn primary(&self) -> Option { + self.favorites + .iter() + .filter(|&&f| f != NO_FAVORITE) + .map(|&f| f as usize) + .find(|&i| i < MAX_BUTTONS && self.buttons[i].enabled) + .or_else(|| self.buttons.iter().position(|b| b.enabled)) + } + + pub fn is_favorite(&self, slot: usize) -> bool { + self.favorites.iter().any(|&f| f as usize == slot) + } + + fn parse_record(msg: &[u8], p: usize, three_byte: bool) -> Option<(usize, bool, u8, usize, [u8; NAME_MAX])> { + // three_byte: v3 records carry `enabled, kind, len`; legacy carries `enabled, len`. + let head = if three_byte { 3 } else { 2 }; + if p + head > msg.len() { return None; } + let enabled = msg[p]; + let (kind, len_at) = if three_byte { (msg[p + 1], p + 2) } else { (KIND_TOGGLE, p + 1) }; + let len = msg[len_at] as usize; + if enabled > 1 || len > NAME_MAX { return None; } + if three_byte && kind != KIND_TOGGLE && kind != KIND_DIMMER { return None; } + let name_at = p + head; + if name_at + len > msg.len() { return None; } + if core::str::from_utf8(&msg[name_at..name_at + len]).is_err() { return None; } + let mut name = [0u8; NAME_MAX]; + name[..len].copy_from_slice(&msg[name_at..name_at + len]); + Some((name_at + len, enabled == 1, kind, len, name)) + } + + fn config_half(&mut self, msg: &[u8], base: usize, with_favs: bool) -> Effect { + if base >= MAX_BUTTONS || msg[3] as usize > HALF { return Effect::Ignored; } + let n = msg[3] as usize; + let mut p = 4; + let mut parsed = [(false, KIND_TOGGLE, 0usize, [0u8; NAME_MAX]); HALF]; + for slot in parsed.iter_mut().take(n) { + match Self::parse_record(msg, p, true) { + Some((next, enabled, kind, len, name)) => { + p = next; + *slot = (enabled, kind, len, name); + } + None => return Effect::Ignored, + } } - if bytes[2] as usize != MAX_BUTTONS { - return; + let fav_len = if with_favs { MAX_FAVORITES } else { 0 }; + if p + fav_len != msg.len() { return Effect::Ignored; } + let mut favs = self.favorites; + if with_favs { + favs = [NO_FAVORITE; MAX_FAVORITES]; + for (f, &b) in favs.iter_mut().zip(&msg[p..p + MAX_FAVORITES]) { + if b != NO_FAVORITE && b as usize >= MAX_BUTTONS { return Effect::Ignored; } + *f = b; + } } - let fav = bytes[3]; - if fav != NO_FAVORITE && fav as usize >= MAX_BUTTONS { - return; + for (i, &(enabled, kind, len, ref name)) in parsed.iter().enumerate().take(n) { + let b = &mut self.buttons[base + i]; + b.enabled = enabled; + b.kind = kind; + b.icon = ICON_AUTO; + b.len = len as u8; + b.name = *name; } - for i in 0..MAX_BUTTONS { - let p = 4 + i * (3 + NAME_MAX + 1 + SECTION_MAX); - let len = bytes[p + 1] as usize; - let sec_len = bytes[p + 3 + NAME_MAX] as usize; - if bytes[p] > 1 - || bytes[p + 2] > 1 - || len > NAME_MAX - || sec_len > SECTION_MAX - || core::str::from_utf8(&bytes[p + 3..p + 3 + len]).is_err() - || core::str::from_utf8(&bytes[p + 4 + NAME_MAX..p + 4 + NAME_MAX + sec_len]).is_err() - { - return; + for i in n..HALF { + let b = &mut self.buttons[base + i]; + b.enabled = false; + b.icon = ICON_AUTO; + b.len = 0; + } + if with_favs { self.favorites = favs; } + self.connected = true; + if with_favs { Effect::Configured } else { Effect::Linked } + } + + fn sections_half(&mut self, msg: &[u8], base: usize) -> Effect { + if base >= MAX_BUTTONS || msg[3] as usize > HALF { return Effect::Ignored; } + let n = msg[3] as usize; + let mut p = 4; + let mut sections = [[0u8; SECTION_MAX]; HALF]; + let mut lens = [0usize; HALF]; + for i in 0..n { + if p >= msg.len() { return Effect::Ignored; } + let len = msg[p] as usize; + p += 1; + if len > SECTION_MAX || p + len > msg.len() { return Effect::Ignored; } + if core::str::from_utf8(&msg[p..p + len]).is_err() { return Effect::Ignored; } + sections[i][..len].copy_from_slice(&msg[p..p + len]); + lens[i] = len; + p += len; + } + if p != msg.len() { return Effect::Ignored; } + for i in 0..HALF { + let b = &mut self.buttons[base + i]; + if i < n { + b.sec_len = lens[i] as u8; + b.section = sections[i]; + } else { + b.sec_len = 0; } - self.buttons[i].enabled = bytes[p] == 1; - self.buttons[i].on = bytes[p + 2] == 1; - self.buttons[i].len = len as u8; - self.buttons[i].name[..len].copy_from_slice(&bytes[p + 3..p + 3 + len]); - self.buttons[i].sec_len = sec_len as u8; - self.buttons[i].section[..sec_len] - .copy_from_slice(&bytes[p + 4 + NAME_MAX..p + 4 + NAME_MAX + sec_len]); } - self.fav = fav; + self.connected = true; + Effect::Linked } - pub fn save(&self, bytes: &mut [u8]) -> usize { - if bytes.len() < SAVE_LEN { - return 0; + fn icons(&mut self, msg: &[u8]) -> Effect { + if msg.len() != 3 + MAX_BUTTONS || msg[3..].iter().any(|&icon| icon > ICON_DEVICE) { + return Effect::Ignored; } - bytes[..SAVE_LEN].fill(0); - bytes[..2].copy_from_slice(b"D2"); - bytes[2] = MAX_BUTTONS as u8; - bytes[3] = self.fav; - for i in 0..MAX_BUTTONS { - let p = 4 + i * (3 + NAME_MAX + 1 + SECTION_MAX); - let b = &self.buttons[i]; - bytes[p] = b.enabled as u8; - bytes[p + 1] = b.len; - bytes[p + 2] = b.on as u8; - bytes[p + 3..p + 3 + b.len as usize].copy_from_slice(&b.name[..b.len as usize]); - bytes[p + 3 + NAME_MAX] = b.sec_len; - bytes[p + 4 + NAME_MAX..p + 4 + NAME_MAX + b.sec_len as usize] - .copy_from_slice(&b.section[..b.sec_len as usize]); + for (button, &icon) in self.buttons.iter_mut().zip(&msg[3..]) { + button.icon = icon; } - SAVE_LEN + self.connected = true; + Effect::Configured } - pub fn apply(&mut self, msg: &[u8]) -> Effect { - if msg.len() < 3 || &msg[..2] != b"H1" { + fn legacy_config(&mut self, msg: &[u8]) -> Effect { + let n = msg[3] as usize; + if n > HALF { return Effect::Ignored; } + let mut p = 4; + let mut parsed = [(false, 0usize, [0u8; NAME_MAX]); HALF]; + for slot in parsed.iter_mut().take(n) { + match Self::parse_record(msg, p, false) { + Some((next, enabled, _, len, name)) => { p = next; *slot = (enabled, len, name); } + None => return Effect::Ignored, + } + } + let mut favs = self.favorites; + if p == msg.len() { + // older phone, no favorite byte: keep what we have + } else if p + 1 == msg.len() { + let fav = msg[p]; + if fav != NO_FAVORITE && fav as usize >= MAX_BUTTONS { return Effect::Ignored; } + favs = [NO_FAVORITE; MAX_FAVORITES]; + favs[0] = fav; + } else { + return Effect::Ignored; + } + for (i, &(enabled, len, ref name)) in parsed.iter().enumerate().take(n) { + let b = &mut self.buttons[i]; + b.enabled = enabled; + b.icon = ICON_AUTO; + b.len = len as u8; + b.name = *name; + } + for i in n..HALF { + self.buttons[i].enabled = false; + self.buttons[i].icon = ICON_AUTO; + self.buttons[i].len = 0; + } + self.favorites = favs; + self.connected = true; + Effect::Configured + } + + fn legacy_groups(&mut self, msg: &[u8]) -> Effect { + if msg[3] as usize != HALF { return Effect::Ignored; } + let mut p = 4; + let mut sections = [[0u8; SECTION_MAX]; HALF]; + let mut lens = [0usize; HALF]; + for i in 0..HALF { + if p >= msg.len() { return Effect::Ignored; } + let len = msg[p] as usize; + p += 1; + if len > SECTION_MAX || p + len > msg.len() { return Effect::Ignored; } + if core::str::from_utf8(&msg[p..p + len]).is_err() { return Effect::Ignored; } + sections[i][..len].copy_from_slice(&msg[p..p + len]); + lens[i] = len; + p += len; + } + let mut favs = self.favorites; + if p + 1 == msg.len() { + let fav = msg[p]; + if fav != NO_FAVORITE && fav as usize >= MAX_BUTTONS { return Effect::Ignored; } + favs = [NO_FAVORITE; MAX_FAVORITES]; + favs[0] = fav; + } else if p != msg.len() { return Effect::Ignored; } + for i in 0..HALF { + self.buttons[i].sec_len = lens[i] as u8; + self.buttons[i].section = sections[i]; + } + self.favorites = favs; + self.connected = true; + Effect::Configured + } + + pub fn apply(&mut self, msg: &[u8]) -> Effect { + if msg.len() < 3 || &msg[..2] != b"H1" { return Effect::Ignored; } match msg[2] { - CONFIG if msg.len() >= 4 => { - let count = (msg[3] as usize).min(MAX_BUTTONS); - if msg[3] as usize > MAX_BUTTONS { - return Effect::Ignored; - } - let mut next = [Button::EMPTY; MAX_BUTTONS]; - let mut p = 4; - for b in next.iter_mut().take(count) { - if p + 2 > msg.len() { - return Effect::Ignored; - } - let enabled = msg[p] == 1; - let len = msg[p + 1] as usize; - p += 2; - if msg[p - 2] > 1 - || len > NAME_MAX - || p + len > msg.len() - || core::str::from_utf8(&msg[p..p + len]).is_err() - { - return Effect::Ignored; + CONFIG_A if msg.len() >= 4 => self.config_half(msg, 0, true), + CONFIG_B if msg.len() >= 4 => self.config_half(msg, HALF, false), + SECTIONS_A if msg.len() >= 4 => self.sections_half(msg, 0), + SECTIONS_B if msg.len() >= 4 => self.sections_half(msg, HALF), + ICONS => self.icons(msg), + CONFIG if msg.len() >= 4 => self.legacy_config(msg), + GROUPS if msg.len() >= 4 => self.legacy_groups(msg), + HEARTBEAT if msg.len() == 3 => { self.connected = true; Effect::Heartbeat } + STATE if matches!(msg.len(), 6 | 7 | 8) => { + let i = msg[3] as usize; + if i >= MAX_BUTTONS || msg[4] > 1 { return Effect::Ignored; } + let (value, result, available) = match msg.len() { + 8 => { + if msg[5] > 100 || msg[7] > 1 { return Effect::Ignored; } + (msg[5], msg[6], msg[7] == 1) } - b.enabled = enabled; - b.len = len as u8; - b.name[..len].copy_from_slice(&msg[p..p + len]); - p += len; - } - // The favorite byte is optional in CONFIG: an older phone sends none and - // keeps the current favorite. GROUPS always carries it. - let fav = if p == msg.len() { - self.fav - } else if p + 1 == msg.len() { - let fav = msg[p]; - if fav != NO_FAVORITE && fav as usize >= MAX_BUTTONS { - return Effect::Ignored; + 7 => { + if msg[5] > 100 { return Effect::Ignored; } + (msg[5], msg[6], true) } - p += 1; - fav - } else { - return Effect::Ignored; + _ => (if msg[4] == 1 { 100 } else { 0 }, msg[5], true), }; - if p != msg.len() { - return Effect::Ignored; - } - for i in 0..MAX_BUTTONS { - next[i].on = self.buttons[i].on; - next[i].section = self.buttons[i].section; - next[i].sec_len = self.buttons[i].sec_len; - } - self.buttons = next; - self.fav = fav; - self.connected = true; - Effect::Configured - } - GROUPS if msg.len() >= 4 => { - if msg[3] as usize != MAX_BUTTONS { - return Effect::Ignored; - } - let mut p = 4; - for b in self.buttons.iter_mut() { - if p + 1 > msg.len() { - return Effect::Ignored; - } - let len = msg[p] as usize; - p += 1; - if len > SECTION_MAX || p + len > msg.len() { - return Effect::Ignored; - } - if core::str::from_utf8(&msg[p..p + len]).is_err() { - return Effect::Ignored; - } - b.sec_len = len as u8; - b.section[..len].copy_from_slice(&msg[p..p + len]); - p += len; - } - if p != msg.len() { - // GROUPS always carries the favorite: a slot index, or 0xFF for none. - if p + 1 != msg.len() { - return Effect::Ignored; - } - let fav = msg[p]; - if fav != NO_FAVORITE && fav as usize >= MAX_BUTTONS { - return Effect::Ignored; - } - p += 1; - self.fav = fav; - } - if p != msg.len() { - return Effect::Ignored; - } - self.connected = true; - Effect::Configured - } - HEARTBEAT if msg.len() == 3 => { + let b = &mut self.buttons[i]; + b.on = msg[4] == 1; + b.value = value; + b.available = available; self.connected = true; - Effect::Heartbeat - } - STATE if msg.len() == 6 && (msg[3] as usize) < MAX_BUTTONS && msg[4] <= 1 => { - let i = msg[3] as usize; - self.buttons[i].on = msg[4] == 1; - self.connected = true; - if self.pending == Some(i as u8) - && (msg[5] != RESULT_OK || self.pending_target == Some(self.buttons[i].on)) - { + let was_pending = self.pending == Some(i as u8); + if self.pending == Some(i as u8) { self.pending = None; self.pending_target = None; + self.pending_value = None; self.pending_seq = None; } - if msg[5] != RESULT_OK { - self.error = Some(msg[5]); - } else if self.pending.is_none() { + if available { + if result != RESULT_OK { self.error = Some(result); } else { self.error = None; } + } else if was_pending { + // The device itself is offline; the command is resolved and that is a + // device state, not an app/link failure. self.error = None; } Effect::Changed } - ACK if msg.len() == 4 => { - if self.pending_seq == Some(msg[3]) { - self.error = None; - Effect::Ack(msg[3]) - } else { - Effect::Ignored - } + ACK if msg.len() == 4 && self.pending_seq == Some(msg[3]) => { + self.error = None; + Effect::Ack(msg[3]) } ERROR if msg.len() == 5 && self.pending_seq == Some(msg[3]) => { - self.pending = None; - self.pending_target = None; - self.pending_seq = None; - self.error = Some(msg[4]); - Effect::Error(msg[4]) + let code = msg[4]; + self.cancel_pending(code); + Effect::Error(code) } _ => Effect::Ignored, } } pub fn toggle_frame(&mut self, i: usize, seq: u8) -> Option<[u8; 6]> { - if i >= MAX_BUTTONS || !self.connected || !self.buttons[i].enabled || self.pending.is_some() - { + if i >= MAX_BUTTONS || !self.connected || !self.buttons[i].enabled || self.pending.is_some() { return None; } - self.pending = Some(i as u8); let target = !self.buttons[i].on; + self.pending = Some(i as u8); self.pending_target = Some(target); + self.pending_value = None; self.pending_seq = Some(seq); Some([b'H', b'1', TOGGLE, seq, i as u8, target as u8]) } + /// Starts (or queues) a brightness change. Returns the frame to send now, or None when + /// another command is in flight (the value is remembered and flushed by [`take_later`]). + pub fn brightness_frame(&mut self, i: usize, value: u8, seq: u8) -> Option<[u8; 6]> { + if i >= MAX_BUTTONS || !self.connected || !self.buttons[i].enabled || !self.buttons[i].is_dimmer() { + return None; + } + let value = value.min(100); + // Show the dragged/pressed value immediately; the phone's state confirms it. + self.buttons[i].value = value; + if self.pending.is_some() { + self.later = Some((i as u8, value)); + return None; + } + self.pending = Some(i as u8); + self.pending_value = Some(value); + self.pending_target = None; + self.pending_seq = Some(seq); + Some([b'H', b'1', BRIGHTNESS, seq, i as u8, value]) + } + + /// Sends the queued drag value once the line is free again. + pub fn take_later(&mut self, seq: u8) -> Option<[u8; 6]> { + if self.pending.is_some() { return None; } + let (i, v) = self.later?; + self.later = None; + self.brightness_frame(i as usize, v, seq) + } + + /// A send failed or a command was rejected: drop every trace of it and show the code. + pub fn cancel_pending(&mut self, code: u8) { + self.pending = None; + self.pending_target = None; + self.pending_value = None; + self.pending_seq = None; + self.later = None; + self.error = Some(code); + } + pub fn mark_disconnected(&mut self) { self.connected = false; self.pending = None; self.pending_target = None; + self.pending_value = None; self.pending_seq = None; + self.later = None; + self.error = None; + } + + pub fn load(&mut self, bytes: &[u8]) { + if bytes.len() == SAVE_LEN && &bytes[..2] == b"D4" && bytes[2] as usize == MAX_BUTTONS { + let base = 3 + MAX_FAVORITES; + let stride = 6 + NAME_MAX + 1 + SECTION_MAX; + let mut buttons = [Button::EMPTY; MAX_BUTTONS]; + let mut favs = [NO_FAVORITE; MAX_FAVORITES]; + for (f, &b) in favs.iter_mut().zip(&bytes[3..3 + MAX_FAVORITES]) { + if b != NO_FAVORITE && b as usize >= MAX_BUTTONS { return; } + *f = b; + } + for i in 0..MAX_BUTTONS { + let p = base + i * stride; + let len = bytes[p + 5] as usize; + let sec_len = bytes[p + 6 + NAME_MAX] as usize; + if bytes[p] > 1 + || (bytes[p + 1] != KIND_TOGGLE && bytes[p + 1] != KIND_DIMMER) + || bytes[p + 2] > ICON_DEVICE + || bytes[p + 3] > 1 + || bytes[p + 4] > 100 + || len > NAME_MAX + || sec_len > SECTION_MAX + || core::str::from_utf8(&bytes[p + 6..p + 6 + len]).is_err() + || core::str::from_utf8(&bytes[p + 7 + NAME_MAX..p + 7 + NAME_MAX + sec_len]).is_err() + { + return; + } + let b = &mut buttons[i]; + b.enabled = bytes[p] == 1; + b.kind = bytes[p + 1]; + b.icon = bytes[p + 2]; + b.on = bytes[p + 3] == 1; + b.value = bytes[p + 4]; + b.len = len as u8; + b.name[..len].copy_from_slice(&bytes[p + 6..p + 6 + len]); + b.sec_len = sec_len as u8; + b.section[..sec_len].copy_from_slice(&bytes[p + 7 + NAME_MAX..p + 7 + NAME_MAX + sec_len]); + } + self.buttons = buttons; + self.favorites = favs; + return; + } + // D3: the previous ten-slot format had no per-control icon. + if bytes.len() == SAVE_LEN_V3 && &bytes[..2] == b"D3" && bytes[2] as usize == MAX_BUTTONS { + let base = 3 + MAX_FAVORITES; + let stride = 4 + NAME_MAX + 1 + SECTION_MAX; + let mut migrated = [0u8; SAVE_LEN]; + migrated[..2].copy_from_slice(b"D4"); + migrated[2] = MAX_BUTTONS as u8; + migrated[3..3 + MAX_FAVORITES].copy_from_slice(&bytes[3..3 + MAX_FAVORITES]); + for i in 0..MAX_BUTTONS { + let old = base + i * stride; + let new = base + i * (6 + NAME_MAX + 1 + SECTION_MAX); + let len = bytes[old + 4] as usize; + let old_section_len = bytes[old + 5 + NAME_MAX] as usize; + // D3's stride overlapped the prior row's final section byte with this row's + // enabled flag, so retain only the bytes that were independently stored. + let section_len = old_section_len.min(SECTION_MAX - 1); + if bytes[old] > 1 + || (bytes[old + 1] != KIND_TOGGLE && bytes[old + 1] != KIND_DIMMER) + || bytes[old + 2] > 1 || bytes[old + 3] > 100 || len > NAME_MAX + || old_section_len > SECTION_MAX + || core::str::from_utf8(&bytes[old + 5..old + 5 + len]).is_err() + || core::str::from_utf8(&bytes[old + 6 + NAME_MAX..old + 6 + NAME_MAX + section_len]).is_err() + { + return; + } + migrated[new] = bytes[old]; + migrated[new + 1] = bytes[old + 1]; + migrated[new + 2] = ICON_AUTO; + migrated[new + 3] = bytes[old + 2]; + migrated[new + 4] = bytes[old + 3]; + migrated[new + 5] = len as u8; + migrated[new + 6..new + 6 + len].copy_from_slice(&bytes[old + 5..old + 5 + len]); + migrated[new + 6 + NAME_MAX] = section_len as u8; + migrated[new + 7 + NAME_MAX..new + 7 + NAME_MAX + section_len] + .copy_from_slice(&bytes[old + 6 + NAME_MAX..old + 6 + NAME_MAX + section_len]); + } + self.load(&migrated); + return; + } + // D2: the old five-slot blob (enabled, len, on, name[15], sec_len, section[10]). + if bytes.len() == 4 + HALF * (3 + NAME_MAX + 1 + SECTION_MAX) && &bytes[..2] == b"D2" && bytes[2] as usize == HALF { + let stride = 3 + NAME_MAX + 1 + SECTION_MAX; + let mut buttons = [Button::EMPTY; MAX_BUTTONS]; + let fav = bytes[3]; + if fav != NO_FAVORITE && fav as usize >= HALF { return; } + for i in 0..HALF { + let p = 4 + i * stride; + let len = bytes[p + 1] as usize; + let sec_len = bytes[p + 3 + NAME_MAX] as usize; + if bytes[p] > 1 || bytes[p + 2] > 1 || len > NAME_MAX || sec_len > SECTION_MAX + || core::str::from_utf8(&bytes[p + 3..p + 3 + len]).is_err() + || core::str::from_utf8(&bytes[p + 4 + NAME_MAX..p + 4 + NAME_MAX + sec_len]).is_err() + { + return; + } + let b = &mut buttons[i]; + b.enabled = bytes[p] == 1; + b.on = bytes[p + 2] == 1; + b.value = if b.on { 100 } else { 0 }; + b.len = len as u8; + b.name[..len].copy_from_slice(&bytes[p + 3..p + 3 + len]); + b.sec_len = sec_len as u8; + b.section[..sec_len].copy_from_slice(&bytes[p + 4 + NAME_MAX..p + 4 + NAME_MAX + sec_len]); + } + self.buttons = buttons; + self.favorites = [NO_FAVORITE; MAX_FAVORITES]; + self.favorites[0] = fav; + } + } + + pub fn save(&self, bytes: &mut [u8]) -> usize { + if bytes.len() < SAVE_LEN { return 0; } + bytes[..SAVE_LEN].fill(0); + bytes[..2].copy_from_slice(b"D4"); + bytes[2] = MAX_BUTTONS as u8; + bytes[3..3 + MAX_FAVORITES].copy_from_slice(&self.favorites); + let base = 3 + MAX_FAVORITES; + let stride = 6 + NAME_MAX + 1 + SECTION_MAX; + for i in 0..MAX_BUTTONS { + let p = base + i * stride; + let b = &self.buttons[i]; + bytes[p] = b.enabled as u8; + bytes[p + 1] = b.kind; + bytes[p + 2] = b.icon; + bytes[p + 3] = b.on as u8; + bytes[p + 4] = b.value; + bytes[p + 5] = b.len; + bytes[p + 6..p + 6 + b.len as usize].copy_from_slice(&b.name[..b.len as usize]); + bytes[p + 6 + NAME_MAX] = b.sec_len; + bytes[p + 7 + NAME_MAX..p + 7 + NAME_MAX + b.sec_len as usize] + .copy_from_slice(&b.section[..b.sec_len as usize]); + } + SAVE_LEN } } @@ -305,83 +573,182 @@ impl Model { mod tests { use super::*; - #[test] - fn config_state_toggle_and_bad_packets() { + fn config_frame(t: u8, base: usize, specs: &[(&str, bool, u8)], favs: Option<&[u8]>) -> Vec { + let mut f = vec![b'H', b'1', t, specs.len() as u8]; + for (name, enabled, kind) in specs { + let raw = name.as_bytes(); + f.push(*enabled as u8); + f.push(*kind); + f.push(raw.len() as u8); + f.extend_from_slice(raw); + } + if let Some(favs) = favs { f.extend_from_slice(favs); } + let _ = base; + f + } + + fn sections_frame(t: u8, sections: &[&str]) -> Vec { + let mut f = vec![b'H', b'1', t, sections.len() as u8]; + for s in sections { + f.push(s.len() as u8); + f.extend_from_slice(s.as_bytes()); + } + f + } + + fn ten_slots() -> Model { let mut m = Model::new(); - assert_eq!(m.apply(b"H1C\x01\x01\x04Lamp"), Effect::Configured); - assert!(m.buttons[0].enabled); - assert_eq!(m.buttons[0].label(), "Lamp"); - assert_eq!(m.toggle_frame(0, 7), Some(*b"H1T\x07\x00\x01")); - assert!(m.toggle_frame(0, 8).is_none()); - assert_eq!(m.apply(b"H1S\x00\x01\x00"), Effect::Changed); - assert!(m.buttons[0].on); - assert!(m.pending.is_none()); - assert_eq!(m.apply(b"H1C\x06"), Effect::Ignored); + let half_a = [("Lamp", true, KIND_DIMMER), ("Fan", true, KIND_TOGGLE), ("Desk", true, KIND_TOGGLE), ("Hall", false, KIND_TOGGLE), ("Plug", true, KIND_TOGGLE)]; + let half_b = [("Strip", true, KIND_DIMMER), ("Porch", false, KIND_TOGGLE), ("Bed", true, KIND_DIMMER), ("TV", true, KIND_TOGGLE), ("Heater", true, KIND_TOGGLE)]; + let favs = [0u8, 5, 7, 9, NO_FAVORITE]; + assert_eq!(m.apply(&config_frame(CONFIG_B, HALF, &half_b, None)), Effect::Linked); + assert_eq!(m.apply(§ions_frame(SECTIONS_A, &["Room", "Room", "", "", ""])), Effect::Linked); + assert_eq!(m.apply(§ions_frame(SECTIONS_B, &["", "", "Room", "", ""])), Effect::Linked); + assert_eq!(m.apply(&config_frame(CONFIG_A, 0, &half_a, Some(&favs))), Effect::Configured); + m } #[test] - fn persisted_config_round_trips_names_sections_and_states() { - let mut m = Model::new(); - m.apply(b"H1C\x02\x01\x04Desk\x01\x05Hall1"); - assert_eq!(m.apply(b"H1G\x05\x04Room\x00\x00\x00\x00\x01"), Effect::Configured); - m.toggle_frame(0, 3).unwrap(); - m.apply(b"H1S\x00\x01\x00"); - let mut data = [0u8; SAVE_LEN]; - let n = m.save(&mut data); - let mut loaded = Model::new(); - loaded.load(&data[..n]); - assert_eq!(loaded.buttons[0].label(), "Desk"); - assert_eq!(loaded.buttons[0].section_label(), "Room"); - assert_eq!(loaded.buttons[1].label(), "Hall1"); - assert_eq!(loaded.buttons[1].section_label(), ""); - assert!(loaded.buttons[0].on); - assert_eq!(loaded.fav, 1); + fn ten_slots_kinds_sections_and_favorites() { + let m = ten_slots(); + assert_eq!(m.buttons[0].label(), "Lamp"); + assert!(m.buttons[0].is_dimmer()); + assert_eq!(m.buttons[5].label(), "Strip"); + assert!(m.buttons[5].is_dimmer()); + assert!(!m.buttons[1].is_dimmer()); + assert!(!m.buttons[6].enabled); + assert_eq!(m.buttons[0].section_label(), "Room"); + assert_eq!(m.buttons[7].section_label(), "Room"); + assert_eq!(m.favorites, [0, 5, 7, 9, NO_FAVORITE]); + assert!(m.is_favorite(9)); + assert!(!m.is_favorite(1)); + assert_eq!(m.primary(), Some(0)); } #[test] - fn groups_must_carry_every_slot_and_valid_utf8() { + fn legacy_five_slot_companion_still_configures() { let mut m = Model::new(); - assert_eq!(m.apply(b"H1G\x04\x00\x00\x00\x00"), Effect::Ignored); - assert_eq!(m.apply(b"H1G\x05\xFF\x00\x00\x00\x00\xFF"), Effect::Ignored); - assert_eq!(m.apply(b"H1G\x05\x01\xC3\x00\x00\x00\x00\xFF"), Effect::Ignored); - assert_eq!(m.apply(b"H1G\x05\x01z\x00\x00\x00\x00\xFF"), Effect::Configured); - assert_eq!(m.apply(b"H1G\x05\x01z\x00\x00\x00\x00\x05"), Effect::Ignored); + assert_eq!(m.apply(b"H1C\x02\x01\x04Desk\x01\x05Hall1"), Effect::Configured); + assert_eq!(m.apply(b"H1G\x05\x04Room\x00\x00\x00\x00\x00"), Effect::Configured); + assert!(m.buttons[0].enabled); + assert_eq!(m.buttons[0].label(), "Desk"); + assert_eq!(m.buttons[0].section_label(), "Room"); + assert!(!m.buttons[0].is_dimmer()); + assert_eq!(m.favorites[0], 0); + for i in HALF..MAX_BUTTONS { assert!(!m.buttons[i].enabled); } + assert_eq!(m.apply(b"H1C\x06"), Effect::Ignored); } #[test] - fn config_keeps_sections_and_state_updates_only_resolve_matching_toggle() { - let mut m = Model::new(); - m.apply(b"H1C\x01\x01\x04Desk"); - m.apply(b"H1G\x05\x04Down\x00\x00\x00\x00\xFF"); - m.apply(b"H1C\x01\x01\x04Desk"); - assert_eq!(m.buttons[0].section_label(), "Down"); - m.toggle_frame(0, 3).unwrap(); - assert_eq!(m.apply(b"H1S\x01\x01\x00"), Effect::Changed); - assert_eq!(m.pending, Some(0)); + fn toggle_state_old_and_new_brightness_flow() { + let mut m = ten_slots(); + assert_eq!(m.toggle_frame(0, 7), Some(*b"H1T\x07\x00\x01")); + assert!(m.toggle_frame(0, 8).is_none()); + // old 6-byte state from an older companion: value mirrors on/off assert_eq!(m.apply(b"H1S\x00\x01\x00"), Effect::Changed); - assert_eq!(m.pending, None); + assert!(m.buttons[0].on); + assert_eq!(m.buttons[0].value, 100); + assert!(m.pending.is_none()); + // new 7-byte state: authoritative brightness + assert_eq!(m.apply(b"H1S\x05\x01\x19\x00"), Effect::Changed); + assert_eq!(m.buttons[5].value, 25); + // drag while busy is queued, then flushed when the line frees + assert_eq!(m.apply(b"H1S\x05\x01\x19\x00"), Effect::Changed); + let f = m.brightness_frame(7, 40, 1).unwrap(); + assert_eq!(f, [b'H', b'1', b'B', 1, 7, 40]); + assert_eq!(m.buttons[7].value, 40); + assert!(m.brightness_frame(7, 80, 2).is_none()); + assert_eq!(m.later, Some((7, 80))); + assert_eq!(m.apply(b"H1S\x07\x01\x19\x00"), Effect::Changed); + let f2 = m.take_later(3).unwrap(); + assert_eq!(f2, [b'H', b'1', b'B', 3, 7, 80]); + assert_eq!(m.buttons[7].value, 80); } #[test] - fn errors_and_acks_must_match_the_pending_sequence() { - let mut m = Model::new(); - m.apply(b"H1C\x01\x01\x04Lamp"); + fn errors_timeouts_and_disconnect_clear_pending_state() { + let mut m = ten_slots(); m.toggle_frame(0, 19).unwrap(); assert_eq!(m.apply(b"H1A\x12"), Effect::Ignored); - assert_eq!(m.apply(b"H1E\x12\x01"), Effect::Ignored); - assert_eq!(m.pending, Some(0)); assert_eq!(m.apply(b"H1E\x13\x02"), Effect::Error(2)); assert_eq!(m.pending, None); assert_eq!(m.error, Some(2)); - } - - #[test] - fn heartbeat_restores_connection_without_changing_controls() { - let mut m = Model::new(); - m.apply(b"H1C\x01\x01\x04Lamp"); + m.brightness_frame(5, 60, 1).unwrap(); + m.brightness_frame(5, 75, 2); // queued + assert_eq!(m.later, Some((5, 75))); + m.cancel_pending(107); + assert_eq!(m.pending, None); + assert_eq!(m.later, None); + assert_eq!(m.error, Some(107)); m.mark_disconnected(); + assert!(!m.connected); + assert_eq!(m.error, None); + assert!(m.toggle_frame(0, 1).is_none()); + assert!(m.brightness_frame(0, 10, 1).is_none()); assert_eq!(m.apply(b"H1P"), Effect::Heartbeat); assert!(m.connected); - assert_eq!(m.buttons[0].label(), "Lamp"); + } + + #[test] + fn availability_marks_a_device_inactive_without_an_app_error() { + let mut m = ten_slots(); + m.toggle_frame(0, 9).unwrap(); + // 8-byte state: slot, on, value, result, available + assert_eq!(m.apply(b"H1S\x00\x00\x00\x00\x00"), Effect::Changed); + assert!(!m.buttons[0].available); + assert!(m.pending.is_none()); + assert_eq!(m.error, None); + // HA reports the entity again + assert_eq!(m.apply(b"H1S\x00\x01\x64\x00\x01"), Effect::Changed); + assert!(m.buttons[0].available); + // an availability byte other than 0/1 is rejected + assert_eq!(m.apply(b"H1S\x01\x00\x00\x00\x02"), Effect::Ignored); + assert!(m.buttons[1].available); + } + + #[test] + fn malformed_v3_frames_are_ignored_without_mutation() { + let mut m = ten_slots(); + let before = m.buttons[0].label().to_string(); + assert_eq!(m.apply(&config_frame(CONFIG_A, 0, &[("X", true, KIND_DIMMER)], Some(&[0, 1, 2, 3, 10]))), Effect::Ignored); // favorite 10 is not a slot + let mut bad_kind = config_frame(CONFIG_A, 0, &[("X", true, 9)], Some(&[0, 1, 2, 3, 4])); + bad_kind[3] = 1; + assert_eq!(m.apply(&bad_kind), Effect::Ignored); + assert_eq!(m.apply(§ions_frame(SECTIONS_A, &["Room", "Room", "", "", "", "Extra"])), Effect::Ignored); + assert_eq!(m.apply(b"H1S\x0A\x01\x32\x00"), Effect::Ignored); // slot 10 + assert_eq!(m.apply(b"H1S\x00\x01\x65\x00"), Effect::Ignored); // 101 percent + assert_eq!(m.buttons[0].label(), before); + } + + #[test] + fn d3_round_trip_and_d2_migration() { + let mut m = ten_slots(); + m.buttons[0].on = true; + m.buttons[0].value = 65; + m.buttons[7].on = true; + m.buttons[7].value = 100; + let mut data = [0u8; SAVE_LEN]; + let n = m.save(&mut data); + let mut loaded = Model::new(); + loaded.load(&data[..n]); + assert_eq!(loaded.buttons[0].label(), "Lamp"); + assert_eq!(loaded.buttons[0].value, 65); + assert!(loaded.buttons[7].is_dimmer()); + assert_eq!(loaded.favorites, m.favorites); + // the old five-slot blob migrates: toggles, one favorite, slots 5.. empty + let mut old = [0u8; 4 + HALF * (3 + NAME_MAX + 1 + SECTION_MAX)]; + old[..2].copy_from_slice(b"D2"); + old[2] = HALF as u8; + old[3] = 1; + let p = 4; + old[p] = 1; old[p + 1] = 4; old[p + 2] = 1; + old[p + 3..p + 7].copy_from_slice(b"Desk"); + let mut mig = Model::new(); + mig.load(&old); + assert!(mig.buttons[0].enabled && mig.buttons[0].on); + assert_eq!(mig.buttons[0].value, 100); + assert!(!mig.buttons[0].is_dimmer()); + assert_eq!(mig.favorites[0], 1); + for i in HALF..MAX_BUTTONS { assert!(!mig.buttons[i].enabled); } } } diff --git a/apps/ha-remote/src/screen.rs b/apps/ha-remote/src/screen.rs index bff3067..84098f3 100644 --- a/apps/ha-remote/src/screen.rs +++ b/apps/ha-remote/src/screen.rs @@ -1,83 +1,112 @@ -use crate::proto::{MAX_BUTTONS, Model, NO_FAVORITE}; +use crate::proto::{ + Button, ICON_CEILING_LIGHT, ICON_DEVICE, ICON_FAN, ICON_LIGHT_BULB, MAX_BUTTONS, Model, NAME_MAX, +}; use cmf_wp2_app::lv::{ - Align, BUF, Batch, Class, CONTENT, Flag, LongMode, LvError, Obj, Prop, + Align, BUF, Batch, Class, CONTENT, CHECKED, Ev, Flag, LongMode, LvError, Obj, Prop, ROOT, }; use cmf_wp2_app::stock; -const ROW_BYTES: usize = 700; - -/// Row height: the same full-size row as before; the compact look comes from the gaps. +const ROW_BYTES: usize = 1200; +const UPDATE_BYTES: usize = 400; const ROW_H: i32 = 110; -/// The flex gap between two rows of one section; the section header between groups adds the -/// separation, and an empty header is Hidden so it adds no gap at all. const ROW_GAP: i32 = 2; -/// The control icon at a row's left edge, and where the name starts, right of it. const ICON_SLOT: i32 = 80; const ICON_X: i16 = 8; const NAME_X: i16 = 104; -/// The name stops before the switch: the row's right pad (20), the pill (56) and a gap. const NAME_W: i32 = stock::ROW_W - NAME_X as i32 - 84; - -/// The toggle switch at a row's right edge: stock pill and knob colours. const SWITCH_W: i32 = 56; const SWITCH_H: i32 = 28; const KNOB: i32 = 24; +const PCT_W: i32 = 84; +/// The dimmer page's capsule: like the firmware's volume slider, no knob nub. +const TRACK_W: i32 = 168; +/// Tall like the firmware volume capsule; no text on the page, so it sits centered. +const TRACK_H: i32 = 300; + +/// Which surface is showing: the Apps row / face page list, or a device's slider page. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Mode { Menu, Page } +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum View { List, Slider } pub(crate) struct Screen { + pub(crate) mode: Mode, + pub(crate) view: View, + page: Obj, + // list surface (ROOT handles while the slider page is showing) phone_detail: Obj, headers: [Obj; MAX_BUTTONS], names: [Obj; MAX_BUTTONS], pills: [Obj; MAX_BUTTONS], knobs: [Obj; MAX_BUTTONS], - /// The icon slot of each row, and the glyph it currently shows (a rename swaps it). + details: [Obj; MAX_BUTTONS], + inactive: [Obj; MAX_BUTTONS], icons: [Obj; MAX_BUTTONS], icon_kinds: [u8; MAX_BUTTONS], pub(crate) rows: [Obj; MAX_BUTTONS], + // slider surface + slider: Obj, + /// Local touch preview; the phone receives it only after release. + slider_preview: Option, + /// The slot whose slider page is open (0xFF on the list). + pub(crate) slider_slot: u8, } -/// The text of the section header above row [i]: the slot's section when it differs from the -/// previous slot's, otherwise empty (the row continues the section above it). -fn header_text(m: &Model, i: usize) -> &str { +/// A row shows when its slot is enabled; the page next to the face also requires a favorite. +fn visible(m: &Model, i: usize, mode: Mode) -> bool { + m.buttons.get(i).is_some_and(|b| b.enabled) + && (mode == Mode::Menu || m.is_favorite(i)) +} + +fn header_for<'a>(m: &'a Model, i: usize, mode: Mode) -> &'a str { + if !visible(m, i, mode) { return ""; } let section = m.buttons[i].section_label(); - if !m.buttons[i].enabled - || section.is_empty() - || (i > 0 && m.buttons[i - 1].section_label() == section) - { - "" - } else { - section + if section.is_empty() { return ""; } + match (0..i).rev().find(|&j| visible(m, j, mode)) { + Some(prev) if m.buttons[prev].section_label() == section => "", + _ => section, } } -/// The glyph shown beside a row's name, picked from the name's words. +/// "65%" / "100%" for a dimmer row or the slider page. +pub(crate) fn pct_text<'a>(value: u8, buf: &'a mut [u8; 5]) -> &'a str { + let v = value.min(100); + let n = if v >= 100 { + buf[..3].copy_from_slice(b"100"); + 3 + } else if v >= 10 { + buf[0] = b'0' + v / 10; + buf[1] = b'0' + v % 10; + 2 + } else { + buf[0] = b'0' + v; + 1 + }; + buf[n] = b'%'; + core::str::from_utf8(&buf[..n + 1]).unwrap_or("") +} + #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum Glyph { Bulb, + CeilingLight, Switch, Fan, + Device, Phone, } -/// Words that make a control a light: the bulb glyph. Whole words only, so "Clamp" stays a -/// switch, with a tolerant trailing "s" (lights, lamps). const LIGHT_WORDS: &[&str] = &["light", "lamp", "bulb", "chandelier", "sconce", "lantern"]; fn word_matches(word: &str, needles: &[&str]) -> bool { - let bare = word - .strip_suffix('s') - .or_else(|| word.strip_suffix('S')) - .unwrap_or(word); - needles - .iter() - .any(|n| word.eq_ignore_ascii_case(n) || bare.eq_ignore_ascii_case(n)) + let bare = word.strip_suffix('s').or_else(|| word.strip_suffix('S')).unwrap_or(word); + needles.iter().any(|n| word.eq_ignore_ascii_case(n) || bare.eq_ignore_ascii_case(n)) } fn words_of(name: &str) -> impl Iterator { name.split(|c: char| !c.is_ascii_alphanumeric()) } -/// A light word -> bulb, "switch" -> switch, "fan" -> fan; anything else is a plain switch, -/// the generic toggle. A light word wins, so "Fan with Light" gets the bulb. fn glyph_kind(name: &str) -> Glyph { if words_of(name).any(|w| word_matches(w, LIGHT_WORDS)) { Glyph::Bulb @@ -90,13 +119,18 @@ fn glyph_kind(name: &str) -> Glyph { } } -/// The row name with a "…" prefix while its toggle is in flight, "!" after an error. -fn write_label<'a>( - m: &'a Model, - i: usize, - buf: &'a mut [u8; crate::proto::NAME_MAX + 2], -) -> &'a str { - let label = m.buttons[i].label(); +fn glyph_for(button: &Button) -> Glyph { + match button.icon { + ICON_LIGHT_BULB => Glyph::Bulb, + ICON_CEILING_LIGHT => Glyph::CeilingLight, + ICON_FAN => Glyph::Fan, + ICON_DEVICE => Glyph::Device, + _ => glyph_kind(button.label()), + } +} + +fn write_label<'a>(m: &'a Model, i: usize, buf: &'a mut [u8; NAME_MAX + 2]) -> &'a str { + let label = match m.buttons.get(i) { Some(b) => b.label(), None => return "Control" }; let prefix: &[u8] = if m.pending == Some(i as u8) { b"\xe2\x80\xa6 " } else if m.error.is_some() { @@ -104,13 +138,13 @@ fn write_label<'a>( } else { b"" }; + let copy = prefix.len().min(buf.len()); + buf[..copy].copy_from_slice(&prefix[..copy]); let n = (prefix.len() + label.len()).min(buf.len()); - buf[..prefix.len()].copy_from_slice(prefix); - buf[prefix.len()..n].copy_from_slice(&label.as_bytes()[..n - prefix.len()]); + buf[prefix.len().min(n)..n].copy_from_slice(&label.as_bytes()[..n - prefix.len().min(n)]); core::str::from_utf8(&buf[..n]).unwrap_or(label) } -/// One solid shape of a glyph; it cannot be pressed, so a press goes to the row. fn glyph_piece( b: &mut Batch, parent: Obj, @@ -132,7 +166,6 @@ fn glyph_piece( Ok(piece) } -/// One curved blade of the fan: a white arc stroke, `rotation` degrees around the hub. fn glyph_blade(b: &mut Batch, parent: Obj, rotation: u16) -> Result { let blade = b.create(Class::Arc, parent)?; b.size(blade, 56, 56)?; @@ -149,38 +182,41 @@ fn glyph_blade(b: &mut Batch, parent: Obj, rotation: u16) -> Result Result<(), LvError> { match kind { Glyph::Bulb => { - // Material Symbols "lightbulb" (rounded): a round glass over two base bars. - glyph_piece(b, slot, 46, 46, 0, -11, stock::CIRCLE, stock::WHITE)?; // the glass - glyph_piece(b, slot, 20, 9, 0, 14, 4, stock::WHITE)?; // the base - glyph_piece(b, slot, 12, 8, 0, 25, 3, stock::WHITE)?; // the base tip + glyph_piece(b, slot, 42, 42, 0, -8, stock::CIRCLE, stock::WHITE)?; + glyph_piece(b, slot, 30, 30, 0, -8, stock::CIRCLE, stock::ROW_BG)?; + glyph_piece(b, slot, 22, 8, 0, 14, 3, stock::WHITE)?; + glyph_piece(b, slot, 14, 5, 0, 22, 2, stock::WHITE)?; + } + Glyph::CeilingLight => { + glyph_piece(b, slot, 30, 5, 0, -24, 2, stock::WHITE)?; + glyph_piece(b, slot, 4, 11, 0, -16, 2, stock::WHITE)?; + glyph_piece(b, slot, 42, 19, 0, -4, 12, stock::WHITE)?; + glyph_piece(b, slot, 32, 11, 0, -4, 8, stock::ROW_BG)?; + glyph_piece(b, slot, 4, 14, 0, 11, 2, stock::WHITE)?; + glyph_piece(b, slot, 20, 5, 0, 20, 2, stock::WHITE)?; } Glyph::Switch => { - // Material Symbols "toggle_on" (rounded): a track with the knob at its end. - glyph_piece(b, slot, 48, 28, 0, 0, 14, stock::WHITE)?; // the track - glyph_piece(b, slot, 20, 20, 10, 0, stock::CIRCLE, stock::BLACK)?; // the knob + glyph_piece(b, slot, 48, 28, 0, 0, 14, stock::WHITE)?; + glyph_piece(b, slot, 20, 20, 10, 0, stock::CIRCLE, stock::BLACK)?; } Glyph::Fan => { - // Material Symbols "mode_fan" (rounded): a hub with four curved blades. - glyph_piece(b, slot, 18, 18, 0, 0, stock::CIRCLE, stock::WHITE)?; // the hub + glyph_piece(b, slot, 18, 18, 0, 0, stock::CIRCLE, stock::WHITE)?; glyph_blade(b, slot, 0)?; - glyph_blade(b, slot, 90)?; - glyph_blade(b, slot, 180)?; - glyph_blade(b, slot, 270)?; + glyph_blade(b, slot, 120)?; + glyph_blade(b, slot, 240)?; } - Glyph::Phone => { - glyph_piece(b, slot, 30, 48, 0, 0, 9, stock::WHITE)?; // the body - glyph_piece(b, slot, 22, 34, 0, -3, 5, stock::BLACK)?; // the screen - glyph_piece(b, slot, 6, 6, 0, 16, stock::CIRCLE, stock::WHITE)?; // the home dot + Glyph::Device | Glyph::Phone => { + glyph_piece(b, slot, 30, 48, 0, 0, 9, stock::WHITE)?; + glyph_piece(b, slot, 22, 34, 0, -3, 5, stock::BLACK)?; + glyph_piece(b, slot, 6, 6, 0, 16, stock::CIRCLE, stock::WHITE)?; } } Ok(()) } -/// The transparent icon slot at a row's left edge, with its glyph inside. fn draw_icon(b: &mut Batch, row: Obj, kind: Glyph) -> Result { let slot = b.create(Class::Obj, row)?; b.size(slot, ICON_SLOT, ICON_SLOT)?; @@ -193,88 +229,80 @@ fn draw_icon(b: &mut Batch, row: Obj, kind: Glyph) -> Result { } impl Screen { + fn empty(mode: Mode, view: View, page: Obj) -> Self { + Self { + mode, + view, + page, + phone_detail: ROOT, + headers: [ROOT; MAX_BUTTONS], + names: [ROOT; MAX_BUTTONS], + pills: [ROOT; MAX_BUTTONS], + knobs: [ROOT; MAX_BUTTONS], + details: [ROOT; MAX_BUTTONS], + inactive: [ROOT; MAX_BUTTONS], + icons: [ROOT; MAX_BUTTONS], + icon_kinds: [0; MAX_BUTTONS], + rows: [ROOT; MAX_BUTTONS], + slider: ROOT, + slider_preview: None, + slider_slot: 0xFF, + } + } + + /// The control list, as the Apps row or the page next to the face. pub(crate) fn build( b: &mut Batch, m: &Model, + mode: Mode, flush: &mut impl FnMut(&mut Batch) -> Result<(), LvError>, ) -> Result { stock::theme(b)?; - // The stock app list's fisheye: the loader slides every child right with its distance - // from the centre line and fades its text, so rows travel along the screen's arc - // while the list scrolls. (The Exercise-list mode narrows the cards instead, which - // reads as a teardrop rather than an arc.) The fixed left pad keeps the column - // itself centred. let (page, _bar) = stock::focus_page(b, 0)?; + let mut s = Self::empty(mode, View::List, page); b.style(page, Prop::PadRow, 0, ROW_GAP)?; - // The title scrolls with the list as its first row, so nothing is ever clipped - // behind a fixed band: the fisheye slides and fades it out at the top edge. The - // small top pad keeps it near the top at rest, like the stock Settings list. b.style(page, Prop::PadTop, 0, 40)?; let title = b.create(Class::Label, page)?; b.size(title, stock::ROW_W, 72)?; - // White: the watch has a single system font, so there is no bold face to switch to. b.style(title, Prop::TextColor, 0, stock::WHITE)?; b.style(title, Prop::TextAlign, 0, 2)?; b.text(title, "Home Assistant")?; - Self::room(b, flush)?; + Self::room(b, flush, ROW_BYTES)?; let phone = Self::row_base(b, page)?; draw_icon(b, phone, Glyph::Phone)?; let phone_name = b.create(Class::Label, phone)?; b.text(phone_name, "Phone")?; b.align(phone_name, Align::LeftMid, NAME_X, 0)?; - let phone_detail = b.create(Class::Label, phone)?; - b.text(phone_detail, Self::phone_status(m))?; - b.style(phone_detail, Prop::TextColor, 0, stock::GREY)?; - b.align(phone_detail, Align::RightMid, -20, 0)?; - let mut headers = [Obj(0); MAX_BUTTONS]; - let mut names = [Obj(0); MAX_BUTTONS]; - let mut pills = [Obj(0); MAX_BUTTONS]; - let mut knobs = [Obj(0); MAX_BUTTONS]; - let mut rows = [Obj(0); MAX_BUTTONS]; - let mut icons = [Obj(0); MAX_BUTTONS]; - let mut icon_kinds = [0u8; MAX_BUTTONS]; + s.phone_detail = b.create(Class::Label, phone)?; + b.text(s.phone_detail, Self::phone_status(m))?; + b.style(s.phone_detail, Prop::TextColor, 0, stock::GREY)?; + b.align(s.phone_detail, Align::RightMid, -20, 0)?; + for i in 0..MAX_BUTTONS { - Self::room(b, flush)?; + Self::room(b, flush, ROW_BYTES)?; let header = b.create(Class::Label, page)?; - let text = header_text(m, i); + let text = header_for(m, i, mode); b.size(header, stock::ROW_W, CONTENT)?; b.style(header, Prop::TextAlign, 0, 2)?; b.style(header, Prop::TextColor, 0, stock::GREY)?; b.text(header, text)?; - if text.is_empty() { - // A hidden child is skipped by the flex layout, so it adds no gap either: - // rows of one section sit exactly ROW_GAP apart. - b.flags(header, &[Flag::Hidden], &[])?; - } - headers[i] = header; + if text.is_empty() { b.flags(header, &[Flag::Hidden], &[])?; } + s.headers[i] = header; let row = Self::row_base(b, page)?; - rows[i] = row; + s.rows[i] = row; + if !visible(m, i, mode) { b.flags(row, &[Flag::Hidden], &[])?; } let button = &m.buttons[i]; - // Unconfigured controls do not appear in the list at all. - if !button.enabled { - b.flags(row, &[Flag::Hidden], &[])?; - } - let name = if button.enabled { - button.label() - } else { - "Not configured" - }; - // The icon comes from the name's words and travels with it: left-aligned text - // beside a fixed icon stays balanced while the fisheye slides the row. - let kind = glyph_kind(button.label()); - icons[i] = draw_icon(b, row, kind)?; - icon_kinds[i] = kind as u8; + let kind = glyph_for(button); + s.icons[i] = draw_icon(b, row, kind)?; + s.icon_kinds[i] = kind as u8; let name_label = b.create(Class::Label, row)?; b.size(name_label, NAME_W, CONTENT)?; b.long_mode(name_label, LongMode::Dot)?; - b.align(name_label, Align::LeftMid, NAME_X, 0)?; - b.text(name_label, name)?; - names[i] = name_label; + b.text(name_label, if button.enabled { button.label() } else { "Not configured" })?; + s.names[i] = name_label; - // A switch built from stock pill and knob colours; the loader has no switch class, - // so the row stays the tap target and the switch animates with state. let pill = b.create(Class::Obj, row)?; b.size(pill, SWITCH_W, SWITCH_H)?; b.align(pill, Align::RightMid, -20, 0)?; @@ -289,44 +317,159 @@ impl Screen { b.style(knob, Prop::BgOpa, 0, 255)?; b.flags(knob, &[], &[Flag::Clickable, Flag::Scrollable])?; b.align(knob, Align::LeftMid, 2, 0)?; - pills[i] = pill; - knobs[i] = knob; + s.pills[i] = pill; + s.knobs[i] = knob; + + // A dimmer's row shows its brightness; a switch row shows the pill. + let pct = b.create(Class::Label, row)?; + b.size(pct, PCT_W, CONTENT)?; + b.style(pct, Prop::TextAlign, 0, 2)?; + b.style(pct, Prop::TextColor, 0, stock::GREY)?; + s.details[i] = pct; + let inactive = b.create(Class::Label, row)?; + b.text(inactive, "Inactive")?; + b.size(inactive, 120, CONTENT)?; + b.style(inactive, Prop::TextColor, 0, stock::GREY)?; + b.style(inactive, Prop::TextAlign, 0, 2)?; + s.inactive[i] = inactive; + Self::row_state_layout( + b, name_label, pill, pct, inactive, button.is_dimmer(), button.available, + )?; } - Ok(Self { - phone_detail: Obj(phone_detail.0), - headers, - names, - pills, - knobs, - icons, - icon_kinds, - rows, - }) + Ok(s) + } + + /// A device's brightness page: the stock-looking thick vertical slider, a big percent + /// number, and the crown (the page is non-scrollable, so knob() routes CROWN to us). + pub(crate) fn build_slider( + b: &mut Batch, + m: &Model, + mode: Mode, + flush: &mut impl FnMut(&mut Batch) -> Result<(), LvError>, + slot: usize, + ) -> Result { + if slot >= MAX_BUTTONS || !m.buttons[slot].is_dimmer() { return Err(LvError::Code(-22)); } + stock::theme(b)?; + Self::room(b, flush, ROW_BYTES)?; + let page = b.create(Class::Obj, ROOT)?; + b.size(page, stock::SCREEN, stock::SCREEN)?; + for p in [ + Prop::PadTop, Prop::PadBottom, Prop::PadLeft, Prop::PadRight, + Prop::BorderWidth, Prop::Radius, Prop::BgOpa, + ] { + b.style(page, p, 0, 0)?; + } + b.flags(page, &[], &[Flag::Scrollable])?; + b.knob(page)?; + + let mut s = Self::empty(mode, View::Slider, page); + s.slider_slot = slot as u8; + s.slider = b.create(Class::Slider, page)?; + b.size(s.slider, TRACK_W, TRACK_H)?; + b.align(s.slider, Align::Center, 0, 0)?; + b.range(s.slider, 0, 100)?; + b.value(s.slider, m.buttons[slot].value.min(100) as i32, false)?; + // Use LVGL's own clipped indicator so the fill follows the capsule exactly at every value. + b.style(s.slider, Prop::BgColor, 0, stock::LETTER_BG)?; + b.style(s.slider, Prop::BgOpa, 0, 255)?; + b.style(s.slider, Prop::Radius, 0, stock::CIRCLE)?; + b.style(s.slider, Prop::BgColor, stock::INDICATOR, stock::WHITE)?; + b.style(s.slider, Prop::BgOpa, stock::INDICATOR, 255)?; + b.style(s.slider, Prop::Radius, stock::INDICATOR, stock::CIRCLE)?; + b.style(s.slider, Prop::BgOpa, stock::KNOB, 0)?; + b.style(s.slider, Prop::BorderWidth, stock::KNOB, 0)?; + b.events(s.slider, &[Ev::ValueChanged, Ev::Released])?; + + // Plus (top) and minus (bottom), both inset within the capsule ends. + Self::plus_minus(b, s.slider, 0, -((TRACK_H / 2 - 48) as i16), true, stock::GREY)?; + Self::plus_minus(b, s.slider, 0, (TRACK_H / 2 - 48) as i16, false, stock::BLACK)?; + Ok(s) + } + + /// Plus/Minus icon: a circle (26x26) with a plus (vertical+horizontal) or minus (horizontal only) cross. + /// Plus (is_plus=true): grey on dark track. Minus (is_plus=false): black on white fill. + fn plus_minus( + b: &mut Batch, + parent: Obj, + x: i16, + y: i16, + is_plus: bool, + colour: i32, + ) -> Result<(), LvError> { + // Circle background + glyph_piece(b, parent, 26, 26, x, y, stock::CIRCLE, colour)?; + // Horizontal bar (both plus and minus) + let mark = if colour == stock::GREY { stock::BLACK } else { stock::WHITE }; + glyph_piece(b, parent, 18, 4, x, y, 2, mark)?; + // Vertical bar (plus only) + if is_plus { + glyph_piece(b, parent, 4, 18, x, y, 2, mark)?; + } + Ok(()) + } + + /// Deletes the current screen (its page, with every object and its scroll bar), like + /// ui-gallery's screen switch; the next build starts from a clean handle table. + pub(crate) fn leave(&mut self, b: &mut Batch) -> Result<(), LvError> { + if self.page != ROOT { b.del(self.page)?; } + Ok(()) } - /// A tappable list row: transparent like the stock app list's, so the icon and the name - /// ride the fisheye arc with no card behind any of them. fn row_base(b: &mut Batch, parent: Obj) -> Result { let row = stock::focus_row(b, parent)?; b.size(row, stock::ROW_W, ROW_H)?; + b.style(row, Prop::BgOpa, CHECKED, 0)?; + // Long press opens the device's slider page. + b.events(row, &[Ev::LongPressed])?; Ok(row) } + /// Switch/percent/inactive visibility for the row's kind and availability. + fn row_state_layout( + b: &mut Batch, + name: Obj, + pill: Obj, + pct: Obj, + inactive: Obj, + dimmer: bool, + available: bool, + ) -> Result<(), LvError> { + b.align(name, Align::LeftMid, NAME_X, 0)?; + b.align(pct, Align::RightMid, -20, 0)?; + b.align(inactive, Align::RightMid, -20, 0)?; + b.style(name, Prop::TextColor, 0, if available { stock::WHITE } else { stock::GREY })?; + if !available { + b.flags(pct, &[Flag::Hidden], &[])?; + b.flags(inactive, &[], &[Flag::Hidden])?; + b.flags(pill, &[Flag::Hidden], &[])?; + } else if dimmer { + b.flags(pill, &[Flag::Hidden], &[])?; + b.flags(inactive, &[Flag::Hidden], &[])?; + b.flags(pct, &[], &[Flag::Hidden])?; + } else { + b.flags(pct, &[Flag::Hidden], &[])?; + b.flags(inactive, &[Flag::Hidden], &[])?; + b.flags(pill, &[], &[Flag::Hidden])?; + } + Ok(()) + } + fn room( b: &mut Batch, flush: &mut impl FnMut(&mut Batch) -> Result<(), LvError>, + need: usize, ) -> Result<(), LvError> { - if b.bytes().len() + ROW_BYTES > BUF { - flush(b)?; - } + if b.bytes().len() + need > BUF { flush(b)?; } Ok(()) } fn phone_status(m: &Model) -> &'static str { if !m.connected { "Offline" + } else if m.error == Some(2) { + "Timeout" } else if m.error.is_some() { - "Error" + "Failed" } else if m.pending.is_some() { "Busy" } else { @@ -334,62 +477,108 @@ impl Screen { } } - pub(crate) fn update(&mut self, b: &mut Batch, m: &Model) -> Result<(), LvError> { - b.text(self.phone_detail, Self::phone_status(m))?; - for i in 0..MAX_BUTTONS { - let text = header_text(m, i); - b.text(self.headers[i], text)?; - if text.is_empty() { - b.flags(self.headers[i], &[Flag::Hidden], &[])?; - } else { - b.flags(self.headers[i], &[], &[Flag::Hidden])?; - } - let button = &m.buttons[i]; - if button.enabled { - b.flags(self.rows[i], &[], &[Flag::Hidden])?; - } else { - b.flags(self.rows[i], &[Flag::Hidden], &[])?; + pub(crate) fn row_slot(&self, handle: u16) -> Option { + if self.view != View::List { return None; } + self.rows.iter().position(|r| r.0 == handle && handle != ROOT.0) + } + + /// True when [handle] is the slider page's slider. + pub(crate) fn is_slider(&self, handle: u16) -> bool { + self.view == View::Slider && self.slider.0 == handle + } + + pub(crate) fn preview_slider(&mut self, value: u8) { + self.slider_preview = Some(value.min(100)); + } + + pub(crate) fn finish_slider(&mut self) -> Option { + self.slider_preview.take() + } + + pub(crate) fn update( + &mut self, + b: &mut Batch, + m: &Model, + flush: &mut impl FnMut(&mut Batch) -> Result<(), LvError>, + ) -> Result<(), LvError> { + match self.view { + View::Slider => { + let i = self.slider_slot as usize; + if i >= MAX_BUTTONS { return Ok(()); } + let value = self.slider_preview.unwrap_or(m.buttons[i].value).min(100); + b.value(self.slider, value as i32, false)?; + Ok(()) } - // A renamed control swaps its glyph; the name itself updates below either way. - let kind = glyph_kind(button.label()); - if kind as u8 != self.icon_kinds[i] { - b.del(self.icons[i])?; - self.icons[i] = draw_icon(b, self.rows[i], kind)?; - self.icon_kinds[i] = kind as u8; + View::List => { + b.text(self.phone_detail, Self::phone_status(m))?; + for i in 0..MAX_BUTTONS { + Self::room(b, flush, UPDATE_BYTES)?; + let text = header_for(m, i, self.mode); + b.text(self.headers[i], text)?; + if text.is_empty() { b.flags(self.headers[i], &[Flag::Hidden], &[])?; } + else { b.flags(self.headers[i], &[], &[Flag::Hidden])?; } + let button = &m.buttons[i]; + if visible(m, i, self.mode) { b.flags(self.rows[i], &[], &[Flag::Hidden])?; } + else { b.flags(self.rows[i], &[Flag::Hidden], &[])?; } + let kind = glyph_for(button); + if kind as u8 != self.icon_kinds[i] { + Self::room(b, flush, UPDATE_BYTES)?; + let _ = b.del(self.icons[i]); + match draw_icon(b, self.rows[i], kind) { + Ok(icon) => { + self.icons[i] = icon; + self.icon_kinds[i] = kind as u8; + } + Err(e) => return Err(e), + } + } + let mut buf = [0u8; NAME_MAX + 2]; + b.text(self.names[i], write_label(m, i, &mut buf))?; + let dimmer = button.is_dimmer(); + if dimmer && button.available { + let mut pbuf = [0u8; 5]; + b.text(self.details[i], pct_text(button.value, &mut pbuf))?; + } + if !dimmer && button.available { + b.style(self.pills[i], Prop::BgColor, 0, if button.on { stock::WHITE } else { stock::GREY })?; + b.style(self.knobs[i], Prop::BgColor, 0, if button.on { stock::BLACK } else { stock::WHITE })?; + b.align( + self.knobs[i], + if button.on { Align::RightMid } else { Align::LeftMid }, + if button.on { -2 } else { 2 }, + 0, + )?; + } + Self::row_state_layout( + b, + self.names[i], + self.pills[i], + self.details[i], + self.inactive[i], + dimmer, + button.available, + )?; + } + Ok(()) } - let mut buf = [0u8; crate::proto::NAME_MAX + 2]; - // Status lives in the name itself: "…" while the toggle is in flight, "!" after - // an error. - b.text(self.names[i], write_label(m, i, &mut buf))?; - // Switch reflects state; the row itself is the tap target. White and grey only: - // the watch's accent is orange and reads as a warning here. - b.style(self.pills[i], Prop::BgColor, 0, if button.on { stock::WHITE } else { stock::GREY })?; - b.style(self.knobs[i], Prop::BgColor, 0, if button.on { stock::BLACK } else { stock::WHITE })?; - b.align( - self.knobs[i], - if button.on { Align::RightMid } else { Align::LeftMid }, - if button.on { -2 } else { 2 }, - 0, - )?; } - Ok(()) } } -/// Unused today but keeps the favorite rule visible next to the widget code. -#[allow(dead_code)] -fn favorite_is(m: &Model, i: usize) -> bool { - m.fav != NO_FAVORITE && m.fav as usize == i -} - #[cfg(test)] mod tests { use super::*; - use crate::proto::Effect; + use crate::proto::{Effect, KIND_DIMMER, NO_FAVORITE}; use wp2_core::lvcmd::{self, Table}; + const FONTS: u8 = 1 << stock::FONT; + + fn open_fonts(b: &mut Batch) { + stock::font(b).unwrap(); + } + fn validate_and_apply(b: &mut Batch, table: &mut Table) -> Result<(), LvError> { - assert_eq!(lvcmd::validate(b.bytes(), table, 1 << stock::FONT), Ok(())); + assert_eq!(lvcmd::validate(b.bytes(), table, FONTS), Ok(())); for record in lvcmd::records(b.bytes()) { lvcmd::apply(table, &record.unwrap()); } @@ -397,34 +586,123 @@ mod tests { Ok(()) } + fn menu_model() -> Model { + let mut m = Model::new(); + let mut v = vec![b'H', b'1', b'V', 5]; + for (name, kind, en) in [("Strip", KIND_DIMMER, 1u8), ("Porch", 0, 1), ("Bed", KIND_DIMMER, 1), ("TV", 0, 1), ("Heater", 0, 0)] { + v.extend([en, kind, name.len() as u8]); + v.extend_from_slice(name.as_bytes()); + } + assert_eq!(m.apply(&v), Effect::Linked); + let mut u = vec![b'H', b'1', b'U', 3]; + for (name, kind, en) in [("Lamp", KIND_DIMMER, 1u8), ("Fan", 0, 1), ("Desk", 0, 1)] { + u.extend([en, kind, name.len() as u8]); + u.extend_from_slice(name.as_bytes()); + } + u.extend([0, 5, 7, 9, 0xFF]); + assert_eq!(m.apply(&u), Effect::Configured); + m + } + #[test] - fn compact_rows_batches_and_live_updates_validate() { + fn menu_build_updates_and_lifecycle_validate() { let mut b = Batch::with_buf(Box::leak(Box::new([0; BUF]))); - stock::font(&mut b).unwrap(); - assert_eq!(lvcmd::validate(b.bytes(), &Table::new(), 0), Ok(())); + open_fonts(&mut b); + assert_eq!(lvcmd::validate(b.bytes(), &Table::new(), FONTS), Ok(())); b.clear(); - let mut model = Model::new(); - assert_eq!(model.apply(b"H1C\x02\x01\x04Desk\x01\x05Hall1"), Effect::Configured); - assert_eq!(model.apply(b"H1G\x05\x04Room\x00\x00\x00\x00\xFF"), Effect::Configured); + let mut model = menu_model(); let mut table = Table::new(); - let mut flush = |batch: &mut Batch| validate_and_apply(batch, &mut table); - let mut screen = Screen::build(&mut b, &model, &mut flush).unwrap(); - flush(&mut b).unwrap(); - drop(flush); + let mut screen = Screen::build(&mut b, &model, Mode::Menu, &mut |batch| { + validate_and_apply(batch, &mut table) + }) + .unwrap(); + validate_and_apply(&mut b, &mut table).unwrap(); assert!(table.has(wp2_core::lvcmd::Class::ScrollBar)); for i in 0..MAX_BUTTONS { - let row = screen.rows[i]; - assert_eq!(table.class(row.0), Some(wp2_core::lvcmd::Class::Obj)); - assert_eq!(table.class(screen.names[i].0), Some(wp2_core::lvcmd::Class::Label)); + assert_eq!(table.class(screen.rows[i].0), Some(wp2_core::lvcmd::Class::Obj)); + assert_eq!(table.class(screen.details[i].0), Some(wp2_core::lvcmd::Class::Label)); assert_eq!(table.class(screen.pills[i].0), Some(wp2_core::lvcmd::Class::Obj)); - assert_eq!(table.class(screen.headers[i].0), Some(wp2_core::lvcmd::Class::Label)); + assert_eq!(table.class(screen.inactive[i].0), Some(wp2_core::lvcmd::Class::Label)); } + // state, failure, disconnect and the inactive state all redraw cleanly + assert_eq!(model.apply(b"H1S\x00\x01\x19\x00\x01"), Effect::Changed); + screen.update(&mut b, &model, &mut |batch| validate_and_apply(batch, &mut table)).unwrap(); + validate_and_apply(&mut b, &mut table).unwrap(); + model.apply(b"H1S\x02\x00\x00\x01\x01"); + screen.update(&mut b, &model, &mut |batch| validate_and_apply(batch, &mut table)).unwrap(); + validate_and_apply(&mut b, &mut table).unwrap(); + model.mark_disconnected(); + screen.update(&mut b, &model, &mut |batch| validate_and_apply(batch, &mut table)).unwrap(); + validate_and_apply(&mut b, &mut table).unwrap(); + model.apply(b"H1S\x00\x00\x00\x00\x00"); + screen.update(&mut b, &model, &mut |batch| validate_and_apply(batch, &mut table)).unwrap(); + validate_and_apply(&mut b, &mut table).unwrap(); + // a rename swaps the glyph + model.apply(b"H1C\x01\x01\x04Desk"); + screen.update(&mut b, &model, &mut |batch| validate_and_apply(batch, &mut table)).unwrap(); + validate_and_apply(&mut b, &mut table).unwrap(); - model.apply(b"H1S\x00\x01\x00"); - screen.update(&mut b, &model).unwrap(); + // switch to a dimmer's slider page and back: delete + rebuild, ui-gallery style + screen.leave(&mut b).unwrap(); + validate_and_apply(&mut b, &mut table).unwrap(); + let mut slider = Screen::build_slider(&mut b, &model, Mode::Menu, &mut |batch| { + validate_and_apply(batch, &mut table) + }, 0) + .unwrap(); + validate_and_apply(&mut b, &mut table).unwrap(); + assert!(slider.is_slider(slider.slider.0)); + model.buttons[0].value = 65; + slider.update(&mut b, &model, &mut |batch| validate_and_apply(batch, &mut table)).unwrap(); validate_and_apply(&mut b, &mut table).unwrap(); + slider.leave(&mut b).unwrap(); + validate_and_apply(&mut b, &mut table).unwrap(); + let back = Screen::build(&mut b, &model, Mode::Menu, &mut |batch| { + validate_and_apply(batch, &mut table) + }) + .unwrap(); + validate_and_apply(&mut b, &mut table).unwrap(); + assert_eq!(back.view, View::List); + } + + #[test] + fn page_shows_only_favorites_and_headers_follow_visible_rows() { + let mut m = menu_model(); + m.apply(b"H1J\x05\x04East\x04East\x04West\x00\x00"); + m.apply(b"H1K\x05\x04East\x00\x04West\x00\x00"); + assert!(visible(&m, 0, Mode::Page)); + assert!(!visible(&m, 1, Mode::Page)); + assert!(!visible(&m, 3, Mode::Page)); + assert!(visible(&m, 5, Mode::Page)); + assert!(visible(&m, 7, Mode::Page)); + assert_eq!(header_for(&m, 0, Mode::Page), "East"); + assert_eq!(header_for(&m, 7, Mode::Page), "West"); + assert!(visible(&m, 1, Mode::Menu)); + assert_eq!(header_for(&m, 1, Mode::Menu), ""); + assert_eq!(header_for(&m, 5, Mode::Menu), "East"); + assert_eq!(header_for(&m, 7, Mode::Menu), "West"); + } + + #[test] + fn rows_map_back_to_slots_and_pct_formats() { + let m = menu_model(); + let mut b = Batch::with_buf(Box::leak(Box::new([0; BUF]))); + let mut flush = |batch: &mut Batch| { + batch.clear(); + Ok(()) + }; + let s = Screen::build(&mut b, &m, Mode::Menu, &mut flush).unwrap(); + assert_eq!(s.row_slot(s.rows[3].0), Some(3)); + assert_eq!(s.row_slot(ROOT.0), None); + assert!(!s.is_slider(s.rows[3].0)); + let mut buf = [0u8; 5]; + assert_eq!(pct_text(0, &mut buf), "0%"); + assert_eq!(pct_text(7, &mut buf), "7%"); + assert_eq!(pct_text(65, &mut buf), "65%"); + assert_eq!(pct_text(100, &mut buf), "100%"); + let _ = m.primary(); + assert_eq!(m.favorites.iter().filter(|&&f| f != NO_FAVORITE).count(), 4); } #[test] @@ -432,26 +710,18 @@ mod tests { let mut m = Model::new(); m.apply(b"H1C\x03\x01\x02A1\x01\x02A2\x01\x02B1"); m.apply(b"H1G\x05\x04East\x04East\x04West\x00\x00\xFF"); - assert_eq!(header_text(&m, 0), "East"); - assert_eq!(header_text(&m, 1), ""); - assert_eq!(header_text(&m, 2), "West"); + assert_eq!(header_for(&m, 0, Mode::Menu), "East"); + assert_eq!(header_for(&m, 1, Mode::Menu), ""); + assert_eq!(header_for(&m, 2, Mode::Menu), "West"); } #[test] fn control_names_pick_their_icon() { assert!(word_matches("LIGHTS", LIGHT_WORDS)); assert!(word_matches("Lamps", LIGHT_WORDS)); - assert!(words_of("Living Room Light").any(|w| word_matches(w, LIGHT_WORDS))); assert_eq!(glyph_kind("Living Room Light"), Glyph::Bulb); - assert_eq!(glyph_kind("LIGHTS"), Glyph::Bulb); - assert_eq!(glyph_kind("Bedroom Lamp"), Glyph::Bulb); - assert_eq!(glyph_kind("Chandelier"), Glyph::Bulb); assert_eq!(glyph_kind("Fan with Light"), Glyph::Bulb); assert_eq!(glyph_kind("Ceiling Fan"), Glyph::Fan); assert_eq!(glyph_kind("Main Switch"), Glyph::Switch); - assert_eq!(glyph_kind("Clamp"), Glyph::Switch); - assert_eq!(glyph_kind("TV Plug"), Glyph::Switch); } - } - diff --git a/apps/ha-remote/store.md b/apps/ha-remote/store.md index 1c6940c..08bbadb 100644 --- a/apps/ha-remote/store.md +++ b/apps/ha-remote/store.md @@ -1,18 +1,17 @@ -Control up to five Home Assistant lights or groups. Configure each button in the Android companion app, give it a name, and tap its row on the watch to request a toggle. The phone sends Home Assistant commands and confirms the resulting state back to the watch. +Control up to ten Home Assistant entities from the wrist: lights, switches, fans, plugs, anything that turns on and off. The Android companion lists every entity in your Home Assistant; you pick each control's kind, short watch name and section, and the watch shows them grouped and centered. -Next to the watch face it offers two optional surfaces, both added by long-pressing the app in Apps: +- **Toggle rows** show a stock switch for on/off controls. +- **Lights are one tap for 0/100 and a long press for the dimmer page**: a knob-free, text-free vertical capsule — dark track, white fill, drag or crown — the same shape as the settings volume slider. A finger drag sends its brightness after release; the phone confirms the real state back. +- **Choose a Material icon for each control** in the Android app, or leave it on Auto to match the control name. +- **Up to five favorites** live on the page next to the watch face and the widget card; everything else stays in the Apps row. +- **Inactive** appears when Home Assistant has no data for a device (it lost power): the row greys out instead of failing, and comes back when the device does. -- **Add page**: the same screen as the app, living next to the face — same rows, icons and - arc scrolling, and touching a row toggles it right there. -- **Add widget**: a text card showing the favorite's name and state. A card is drawn by - the stock firmware and a tap starts the app; the toggling happens on the page. +The phone is the only Home Assistant client: it sends commands over the encrypted app channel and reports the confirmed state, including changes made from other apps. ## Requirements -- FMC patched firmware/App Loader with channel key K support (2026-11-13 or later). The optional page and widget need - firmware stub v4+ and a loader from 2026-11-15 or later. -- The HA Watch Remote Android companion app on the same phone as Nothing X. The companion connects to the watch's existing bonded BLE identity without rebinding, obtains the channel key K through the shell service, and sends commands through the encrypted app channel. Android's second-GATT-client coexistence with Nothing X must be validated on the target phone/watch combination. - Companion source and builds: . -- A Home Assistant instance configured in the Android companion app. +- FMC patched firmware/App Loader with channel key K support (2026-11-13 or later). The optional page and widget need firmware stub v4+ and a loader from 2026-11-15 or later. +- The Home Assistant companion app v0.3.0 or later on the same phone as Nothing X: . It connects to the watch's existing bonded BLE identity without rebinding and sends commands through the encrypted app channel. +- A Home Assistant instance configured in the companion app. -The BLE app channel is readable by any nearby BLE client that can obtain the pairing secret. Do not send credentials or personal data over it. The app protocol carries button indexes, states, and generic error codes only. +The BLE app channel is readable by any nearby BLE client that can obtain the pairing secret. Do not send credentials or personal data over it. The app protocol carries slot indexes, short labels, states and generic error codes only. diff --git a/apps/ha-remote/store.toml b/apps/ha-remote/store.toml index 79525d5..89b4051 100644 --- a/apps/ha-remote/store.toml +++ b/apps/ha-remote/store.toml @@ -1,6 +1,6 @@ name = "Home Assistant" -summary = "Control up to five Home Assistant lights and groups from your watch" -version = "0.1.25" +summary = "Control up to ten Home Assistant entities from your watch, with brightness sliders" +version = "0.2.6" author = "CMF Tech Community" screenshots = ["shots/watch.jpg"]