diff --git a/README.md b/README.md index a42b020..3fe30b5 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ An app runs on a watch with the patched firmware and the App Loader, both on the | [`vela-nav`](apps/vela-nav) | Turn-by-turn directions from the Vela maps app on an Android phone | | [`calendar`](apps/calendar) | A month with the phone's events as dots, a page next to the face and a widget card (needs FMC Companion) | | [`reminders`](apps/reminders) | The iPhone's open reminders: overdue, today, later; tick one off with a tap, and a widget card (needs FMC Companion on an iPhone) | +| [`ha-remote`](apps/ha-remote) | Up to five Home Assistant light and group toggles with an Android companion | ## Make your own app diff --git a/apps/Cargo.lock b/apps/Cargo.lock index 706ba3d..1a3121c 100644 --- a/apps/Cargo.lock +++ b/apps/Cargo.lock @@ -36,6 +36,14 @@ dependencies = [ "wp2-core", ] +[[package]] +name = "ha-remote" +version = "0.1.0" +dependencies = [ + "cmf-wp2-app", + "wp2-core", +] + [[package]] name = "metronome" version = "0.1.0" diff --git a/apps/ha-remote/ANDROID_COMPANION.md b/apps/ha-remote/ANDROID_COMPANION.md new file mode 100644 index 0000000..4bdb243 --- /dev/null +++ b/apps/ha-remote/ANDROID_COMPANION.md @@ -0,0 +1,91 @@ +# 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 +confirms it. The watch never stores a Home Assistant URL, token, entity ID, room name, or credential. +The configured short button labels are sent over BLE to be shown on the watch; keep them generic and non-sensitive. + +## Connection model + +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. +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. +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 + the protocol handler. Respond to watch HELLO with a full button configuration and current state snapshots. +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`) + +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. + +| 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 | `H1E seq error_code` | Generic failure; never include HA response text or entity data | + +`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. + +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. + +## 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. +- 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 + 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. +- 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. +- 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. diff --git a/apps/ha-remote/Cargo.toml b/apps/ha-remote/Cargo.toml new file mode 100644 index 0000000..5952558 --- /dev/null +++ b/apps/ha-remote/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "ha-remote" +edition.workspace = true +license.workspace = true +version.workspace = true + +[dependencies] +cmf-wp2-app.workspace = true + +[dev-dependencies] +wp2-core.workspace = true + +[[bin]] +name = "ha-remote" +bench = false diff --git a/apps/ha-remote/README.md b/apps/ha-remote/README.md new file mode 100644 index 0000000..560656f --- /dev/null +++ b/apps/ha-remote/README.md @@ -0,0 +1,24 @@ +# 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. + +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. + +`store.toml` and `store.md` are the FMC store listing; `ANDROID_COMPANION.md` documents the watch-phone protocol +contract. + +## Build and install + +From the repository root (the same commands work in both repositories): + +```bash +make test APP=ha-remote # host protocol and screen-batch tests +make build APP=ha-remote # target/ha-remote.wp2app +make run APP=ha-remote ADDRESS=AA:BB:CC:DD:EE:FF # install on the watch over BLE +``` + +The watch needs the FMC patched firmware and App Loader with channel key K (2026-11-13 or newer); the page and +widget surfaces need a loader from 2026-11-15 or newer. diff --git a/apps/ha-remote/icon.svg b/apps/ha-remote/icon.svg new file mode 100644 index 0000000..9454f64 --- /dev/null +++ b/apps/ha-remote/icon.svg @@ -0,0 +1,4 @@ + + + + diff --git a/apps/ha-remote/shots/watch.jpg b/apps/ha-remote/shots/watch.jpg new file mode 100644 index 0000000..3ae5757 Binary files /dev/null and b/apps/ha-remote/shots/watch.jpg differ diff --git a/apps/ha-remote/src/main.rs b/apps/ha-remote/src/main.rs new file mode 100644 index 0000000..fedafd0 --- /dev/null +++ b/apps/ha-remote/src/main.rs @@ -0,0 +1,261 @@ +#![cfg_attr( + any(target_os = "none", wp2_sim), + no_main, + cfg_attr(target_os = "none", no_std) +)] + +#[cfg_attr(not(any(target_os = "none", wp2_sim)), allow(dead_code))] +mod proto; +mod screen; + +#[cfg(not(any(target_os = "none", wp2_sim)))] +fn main() {} + +#[cfg(any(target_os = "none", wp2_sim))] +mod device { + use crate::proto::{self, Effect, MAX_BUTTONS, Model}; + use crate::screen::Screen; + use cmf_wp2_app::lv::{Batch, Lv}; + use cmf_wp2_app::{Api, BUTTON, 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); + + static mut MODEL: Model = Model::new(); + static mut STORE: [u8; 192] = [0; 192]; + + /// 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. + 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 mut val = [0u8; 40]; + let value = if !m.connected { + "Phone offline" + } else { + match chosen { + Some(b) => { + 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(); + core::str::from_utf8(&val[..k]).unwrap_or("") + } + None => "Set up in the phone app", + } + }; + api.widget("Home Assistant", value) + } + + fn main(api: &'static Api) -> i32 { + let Some(lv) = api.lv() else { return -95 }; + let Some(mut batch) = Batch::new() else { + return -1; + }; + if stock::font(&mut batch) + .and_then(|_| batch.submit(&lv)) + .is_err() + { + return 1; + } + // SAFETY: a single app thread owns these static buffers. + let m = unsafe { &mut *core::ptr::addr_of_mut!(MODEL) }; + let stored = unsafe { &mut *core::ptr::addr_of_mut!(STORE) }; + let n = api.load(stored); + 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) + } + + /// 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, + widget_last: u32, + widget_reported: bool, + widget_dirty: bool, + last_state: [u8; MAX_BUTTONS], + } + + impl Link { + fn new(api: &Api, m: &Model) -> Self { + Self { + last_rx: api.now(), + last_connection: m.connected, + widget_last: 0, + widget_reported: false, + widget_dirty: true, + last_state: [0xFF; MAX_BUTTONS], + } + } + } + + fn sync(api: &Api, m: &mut Model, stored: &mut [u8; 192], link: &mut Link) -> bool { + let mut dirty = false; + if m.connected != link.last_connection { + link.last_connection = m.connected; + dirty = true; + 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; + if link.last_state[i] != state { + link.last_state[i] = state; + link.widget_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::Configured => { + let n = m.save(stored); + 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, + } + } + let now = api.now(); + if m.pending.is_some() && now.wrapping_sub(link.last_rx) > 12_000 { + m.pending = None; + m.error = Some(2); + link.last_rx = now; + dirty = true; + } + if m.connected && now.wrapping_sub(link.last_rx) > 30_000 { + m.mark_disconnected(); + dirty = true; + link.widget_dirty = true; + } + if link.widget_dirty && now.wrapping_sub(link.widget_last) >= 1000 { + let result = update_widget(api, m); + link.widget_dirty = false; + link.widget_last = now; + if !link.widget_reported && api.send(&[b'H', b'1', b'W', result as i8 as u8]) >= 0 { + link.widget_reported = true; + } + } + 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. + fn list_main( + api: &'static Api, + m: &mut Model, + stored: &mut [u8; 192], + lv: Lv, + mut batch: Batch, + ) -> i32 { + let mut flush = |b: &mut Batch| b.submit(&lv); + let mut screen = match Screen::build(&mut batch, m, &mut flush) { + Ok(screen) => screen, + Err(_) => return 2, + }; + 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 _ = api.send(&proto::HELLO); + loop { + let mut timeout = 250; + 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, + }); + } + dirty = true; + } + } + } + Some(e) if e.kind == PAUSE => { + loop { + match api.event(u32::MAX).map(|e| e.kind) { + Some(BUTTON) => return 0, + Some(RESUME) => break, + _ => {} + } + } + let _ = api.send(&proto::HELLO); + dirty = true; + } + _ => {} + } + 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)); + 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); + redraw_retry = true; + last_redraw_retry = api.now(); + } else { + redraw_retry = false; + } + dirty = false; + } + } + } + +} diff --git a/apps/ha-remote/src/proto.rs b/apps/ha-remote/src/proto.rs new file mode 100644 index 0000000..e42e038 --- /dev/null +++ b/apps/ha-remote/src/proto.rs @@ -0,0 +1,387 @@ +//! 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. + +pub const MAX_BUTTONS: usize = 5; +pub const NAME_MAX: usize = 15; +pub const SECTION_MAX: usize = 10; +pub const CONFIG: u8 = b'C'; +pub const GROUPS: u8 = b'G'; +pub const STATE: u8 = b'S'; +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 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); + +/// No favorite control. +pub const NO_FAVORITE: u8 = 0xFF; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Button { + pub enabled: bool, + pub on: bool, + pub name: [u8; NAME_MAX], + pub len: u8, + pub section: [u8; SECTION_MAX], + pub sec_len: u8, +} + +impl Button { + pub const EMPTY: Self = Self { + enabled: false, + on: false, + name: [0; NAME_MAX], + len: 0, + section: [0; SECTION_MAX], + sec_len: 0, + }; + + pub fn label(&self) -> &str { + core::str::from_utf8(&self.name[..self.len as usize]).unwrap_or("Control") + } + + pub fn section_label(&self) -> &str { + core::str::from_utf8(&self.section[..self.sec_len as usize]).unwrap_or("") + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Effect { + Ignored, + Changed, + Configured, + Heartbeat, + Ack(u8), + Error(u8), +} + +pub struct Model { + pub buttons: [Button; MAX_BUTTONS], + pub fav: u8, + pub connected: bool, + pub pending: Option, + pub pending_target: Option, + pub pending_seq: Option, + pub error: Option, +} + +impl Model { + pub const fn new() -> Self { + Self { + buttons: [Button::EMPTY; MAX_BUTTONS], + fav: NO_FAVORITE, + connected: false, + pending: None, + pending_target: None, + pending_seq: None, + error: None, + } + } + + pub fn load(&mut self, bytes: &[u8]) { + if bytes.len() != SAVE_LEN || &bytes[..2] != b"D2" { + return; + } + if bytes[2] as usize != MAX_BUTTONS { + return; + } + let fav = bytes[3]; + if fav != NO_FAVORITE && fav as usize >= MAX_BUTTONS { + return; + } + 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; + } + 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; + } + + 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"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]); + } + SAVE_LEN + } + + 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; + } + 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; + } + p += 1; + fav + } else { + return Effect::Ignored; + }; + 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 => { + 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)) + { + self.pending = None; + self.pending_target = None; + self.pending_seq = None; + } + if msg[5] != RESULT_OK { + self.error = Some(msg[5]); + } else if self.pending.is_none() { + 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 + } + } + 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]) + } + _ => 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() + { + return None; + } + self.pending = Some(i as u8); + let target = !self.buttons[i].on; + self.pending_target = Some(target); + self.pending_seq = Some(seq); + Some([b'H', b'1', TOGGLE, seq, i as u8, target as u8]) + } + + pub fn mark_disconnected(&mut self) { + self.connected = false; + self.pending = None; + self.pending_target = None; + self.pending_seq = None; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn config_state_toggle_and_bad_packets() { + 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); + } + + #[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); + } + + #[test] + fn groups_must_carry_every_slot_and_valid_utf8() { + 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); + } + + #[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)); + assert_eq!(m.apply(b"H1S\x00\x01\x00"), Effect::Changed); + assert_eq!(m.pending, None); + } + + #[test] + fn errors_and_acks_must_match_the_pending_sequence() { + let mut m = Model::new(); + m.apply(b"H1C\x01\x01\x04Lamp"); + 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.mark_disconnected(); + assert_eq!(m.apply(b"H1P"), Effect::Heartbeat); + assert!(m.connected); + assert_eq!(m.buttons[0].label(), "Lamp"); + } +} diff --git a/apps/ha-remote/src/screen.rs b/apps/ha-remote/src/screen.rs new file mode 100644 index 0000000..bff3067 --- /dev/null +++ b/apps/ha-remote/src/screen.rs @@ -0,0 +1,457 @@ +use crate::proto::{MAX_BUTTONS, Model, NO_FAVORITE}; +use cmf_wp2_app::lv::{ + Align, BUF, Batch, Class, CONTENT, Flag, LongMode, LvError, Obj, Prop, +}; +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_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; + +pub(crate) struct Screen { + 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). + icons: [Obj; MAX_BUTTONS], + icon_kinds: [u8; MAX_BUTTONS], + pub(crate) rows: [Obj; MAX_BUTTONS], +} + +/// 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 { + 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 + } +} + +/// The glyph shown beside a row's name, picked from the name's words. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Glyph { + Bulb, + Switch, + Fan, + 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)) +} + +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 + } else if words_of(name).any(|w| word_matches(w, &["switch"])) { + Glyph::Switch + } else if words_of(name).any(|w| word_matches(w, &["fan"])) { + Glyph::Fan + } else { + Glyph::Switch + } +} + +/// 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(); + let prefix: &[u8] = if m.pending == Some(i as u8) { + b"\xe2\x80\xa6 " + } else if m.error.is_some() { + b"! " + } else { + b"" + }; + 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()]); + 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, + w: i32, + h: i32, + x: i16, + y: i16, + radius: i32, + color: i32, +) -> Result { + let piece = b.create(Class::Obj, parent)?; + b.size(piece, w, h)?; + b.align(piece, Align::Center, x, y)?; + b.style(piece, Prop::Radius, 0, radius)?; + b.style(piece, Prop::BgColor, 0, color)?; + b.style(piece, Prop::BgOpa, 0, 255)?; + b.style(piece, Prop::BorderWidth, 0, 0)?; + b.flags(piece, &[], &[Flag::Clickable, Flag::Scrollable])?; + 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)?; + b.align(blade, Align::Center, 0, 0)?; + b.angles(blade, 15, 80, rotation)?; + b.value(blade, 0, false)?; + b.style(blade, Prop::ArcWidth, 0, 12)?; + b.style(blade, Prop::ArcRounded, 0, 1)?; + b.style(blade, Prop::ArcColor, 0, stock::WHITE)?; + b.style(blade, Prop::ArcOpa, 0, 255)?; + b.style(blade, Prop::ArcOpa, stock::INDICATOR, 0)?; + b.style(blade, Prop::BgOpa, stock::KNOB, 0)?; + b.flags(blade, &[], &[Flag::Clickable, Flag::Scrollable])?; + Ok(blade) +} + +/// The glyph pieces inside an icon slot. +fn draw_glyph(b: &mut Batch, slot: Obj, kind: Glyph) -> 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::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::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_blade(b, slot, 0)?; + glyph_blade(b, slot, 90)?; + glyph_blade(b, slot, 180)?; + glyph_blade(b, slot, 270)?; + } + 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 + } + } + 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)?; + b.align(slot, Align::LeftMid, ICON_X, 0)?; + b.style(slot, Prop::BgOpa, 0, 0)?; + b.style(slot, Prop::BorderWidth, 0, 0)?; + b.flags(slot, &[], &[Flag::Clickable, Flag::Scrollable])?; + draw_glyph(b, slot, kind)?; + Ok(slot) +} + +impl Screen { + pub(crate) fn build( + b: &mut Batch, + m: &Model, + 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)?; + 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)?; + 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]; + for i in 0..MAX_BUTTONS { + Self::room(b, flush)?; + let header = b.create(Class::Label, page)?; + let text = header_text(m, i); + 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; + + let row = Self::row_base(b, page)?; + rows[i] = row; + 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 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; + + // 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)?; + b.style(pill, Prop::Radius, 0, stock::CIRCLE)?; + b.style(pill, Prop::BgColor, 0, stock::GREY)?; + b.style(pill, Prop::BgOpa, 0, 255)?; + b.flags(pill, &[], &[Flag::Clickable, Flag::Scrollable])?; + let knob = b.create(Class::Obj, pill)?; + b.size(knob, KNOB, KNOB)?; + b.style(knob, Prop::Radius, 0, stock::CIRCLE)?; + b.style(knob, Prop::BgColor, 0, stock::WHITE)?; + 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; + } + Ok(Self { + phone_detail: Obj(phone_detail.0), + headers, + names, + pills, + knobs, + icons, + icon_kinds, + rows, + }) + } + + /// 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)?; + Ok(row) + } + + fn room( + b: &mut Batch, + flush: &mut impl FnMut(&mut Batch) -> Result<(), LvError>, + ) -> Result<(), LvError> { + if b.bytes().len() + ROW_BYTES > BUF { + flush(b)?; + } + Ok(()) + } + + fn phone_status(m: &Model) -> &'static str { + if !m.connected { + "Offline" + } else if m.error.is_some() { + "Error" + } else if m.pending.is_some() { + "Busy" + } else { + "Online" + } + } + + 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], &[])?; + } + // 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; + } + 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 wp2_core::lvcmd::{self, Table}; + + fn validate_and_apply(b: &mut Batch, table: &mut Table) -> Result<(), LvError> { + assert_eq!(lvcmd::validate(b.bytes(), table, 1 << stock::FONT), Ok(())); + for record in lvcmd::records(b.bytes()) { + lvcmd::apply(table, &record.unwrap()); + } + b.clear(); + Ok(()) + } + + #[test] + fn compact_rows_batches_and_live_updates_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(())); + 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 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); + + 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.pills[i].0), Some(wp2_core::lvcmd::Class::Obj)); + assert_eq!(table.class(screen.headers[i].0), Some(wp2_core::lvcmd::Class::Label)); + } + + model.apply(b"H1S\x00\x01\x00"); + screen.update(&mut b, &model).unwrap(); + validate_and_apply(&mut b, &mut table).unwrap(); + } + + #[test] + fn section_headers_show_only_at_group_starts() { + 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"); + } + + #[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 new file mode 100644 index 0000000..1c6940c --- /dev/null +++ b/apps/ha-remote/store.md @@ -0,0 +1,18 @@ +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. + +Next to the watch face it offers two optional surfaces, both added by long-pressing the app in Apps: + +- **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. + +## 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. + +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. diff --git a/apps/ha-remote/store.toml b/apps/ha-remote/store.toml new file mode 100644 index 0000000..79525d5 --- /dev/null +++ b/apps/ha-remote/store.toml @@ -0,0 +1,6 @@ +name = "Home Assistant" +summary = "Control up to five Home Assistant lights and groups from your watch" +version = "0.1.25" +author = "CMF Tech Community" +screenshots = ["shots/watch.jpg"] + diff --git a/scripts/store b/scripts/store index 26e3984..d4852eb 100755 --- a/scripts/store +++ b/scripts/store @@ -171,7 +171,8 @@ def build(name): env["WP2_ICON"] = str(icons / f"{name}.wp2icon") # the SDK sits outside the workspace, so panic locations would carry this machine's absolute path to it; # remapped, a package is the same on every machine (appended to apps/.cargo/config.toml's rustflags) - remap = f'target.thumbv7em-none-eabi.rustflags=["--remap-path-prefix={SDK}=wp2-apps"]' + # Cargo parses --config as TOML; native Windows backslashes in a quoted value are escapes there. + remap = f'target.thumbv7em-none-eabi.rustflags=["--remap-path-prefix={SDK.as_posix()}=wp2-apps"]' subprocess.run(["cargo", "build", "--release", "-p", name, "--config", remap], cwd=APPS, env=env, check=True) elf = TARGET / "thumbv7em-none-eabi/release" / name subprocess.run(["llvm-objcopy", "-O", "binary", "--set-section-flags", ".data=alloc,load,contents",