sqs4NTQQUo_l%eqf#Pddx%koGNI%27eA{=l
z-zrmr?JS1~Z4y3*+B+|)Xt8znkTo%+B?lh*7$VE}=wW(T9oR%?$@Q}{cxcP)5B(CV
z_4vnPE;>8#<5M|E2)=`&s_W&-fvq3S* i32 {
+ api.time().map_or(0, |t| {
+ wall_min(
+ t.year as i32,
+ t.month as u32,
+ t.day as u32,
+ t.hour as u32,
+ t.minute as u32,
+ )
+ })
+ }
+
+ /// Persist metadata only when it changed and the NAND write succeeded.
+ fn save_cache(api: &Api, model: &mut Model, blob: &mut [u8; BLOB_MAX]) {
+ if !model.cache_dirty() {
+ return;
+ }
+ let len = model.save(blob);
+ if len > 0 && api.save(&blob[..len]) == 0 {
+ model.cache_saved();
+ }
+ }
+
+ // true on RESUME, false on BUTTON
+ fn paused(api: &Api) -> bool {
+ loop {
+ match api.event(u32::MAX).map(|e| e.kind) {
+ Some(RESUME) => return true,
+ Some(BUTTON) => return false,
+ _ => {}
+ }
+ }
+ }
+
+ fn main(api: &'static Api) -> i32 {
+ let m = unsafe { &mut *addr_of_mut!(MODEL) };
+ let blob = unsafe { &mut *addr_of_mut!(BLOB) };
+ let n = api.load(blob);
+ if n > 0 {
+ m.load(&blob[..n as usize]);
+ }
+ m.ask_now(api.now());
+
+ let mut screen = api;
+ let mut motor = Motor::new(api);
+ let mut drawn = None;
+ let mut msg = [0u8; MSG_MAX];
+ loop {
+ motor.update();
+ let now = api.now();
+ let wall = wall(api);
+ while let Some(data) = api.recv(&mut msg) {
+ if m.reply(data, now, wall) == Got::Save {
+ save_cache(api, m, blob); // on change: the app can end without notice
+ }
+ }
+ if let Some(request) = m.poll(now) {
+ if api.send(request.bytes()) != 0 {
+ // No host or a full outbox is not a 30-second silence; recover on the next backoff.
+ m.send_failed(now);
+ drawn = None;
+ }
+ }
+ if drawn != Some(m.rev) {
+ frame(&mut screen, m);
+ api.show();
+ drawn = Some(m.rev);
+ }
+
+ let wait = m.wait(api.now()).min(motor.wait().unwrap_or(u32::MAX));
+ let Some(event) = api.event(wait) else {
+ continue;
+ };
+ match event.kind {
+ BUTTON => return 0,
+ PAUSE => {
+ motor.off();
+ if !paused(api) {
+ return 0;
+ }
+ m.ask_now(api.now());
+ drawn = None;
+ }
+ RESUME => {
+ m.ask_now(api.now());
+ drawn = None;
+ }
+ TOUCH_DOWN => {
+ let action = action(event.x as i32, event.y as i32, m.max_volume());
+ let queued = match action {
+ Action::Previous => m.command(rpc::PREVIOUS, 0),
+ Action::Toggle => m.command(rpc::TOGGLE, 0),
+ Action::Next => m.command(rpc::NEXT, 0),
+ Action::VolumeUp => m.command(rpc::VOLUME_UP, 0),
+ Action::VolumeDown => m.command(rpc::VOLUME_DOWN, 0),
+ Action::SetVolume(value) => m.command(rpc::SET_VOLUME, value),
+ Action::None => false,
+ };
+ if queued {
+ motor.play(TICK);
+ save_cache(api, m, blob);
+ drawn = None;
+ }
+ }
+ CROWN => {
+ // The crown adjusts the visible music volume, while the button remains the back action.
+ if event.delta != 0 {
+ let command = if event.delta > 0 {
+ rpc::VOLUME_UP
+ } else {
+ rpc::VOLUME_DOWN
+ };
+ if m.command(command, 0) {
+ motor.play(TICK);
+ save_cache(api, m, blob);
+ drawn = None;
+ }
+ }
+ }
+ _ => {} // MESSAGE: drained at the top
+ }
+ }
+ }
+}
diff --git a/apps/music-controller/src/model.rs b/apps/music-controller/src/model.rs
new file mode 100644
index 0000000..9ef5cae
--- /dev/null
+++ b/apps/music-controller/src/model.rs
@@ -0,0 +1,810 @@
+//! The phone-music state machine: requests, optimistic commands and the local cache.
+//!
+//! One RPC request is in flight at a time. Commands tapped while a snapshot is in flight wait in a
+//! small local queue. Only playback flags and music volume cross the BLE channel; no track text or
+//! artwork is accepted or retained.
+
+use crate::rpc::{self, Metadata};
+
+pub const POLL_MS: u32 = 2_000;
+pub const RETRY_MS: u32 = 3_000;
+pub const ASK_AGAIN_MS: u32 = 10_000;
+pub const COMMAND_REFRESH_MS: u32 = 250;
+pub const SNAPSHOT_TIMEOUT_MS: u32 = 10_000;
+pub const COMMAND_TIMEOUT_MS: u32 = 8_000;
+pub const MAX_BACKOFF_MS: u32 = 30_000;
+
+const COMMAND_QUEUE_MAX: usize = 8;
+const MAGIC: &[u8; 2] = b"M2";
+/// Magic, fetched wall minute, then the four-byte metadata record.
+pub const BLOB_MAX: usize = 2 + 4 + 4;
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(test, derive(Debug))]
+pub enum Status {
+ Waiting,
+ Ok,
+ Ask,
+ Denied,
+ Unavailable,
+ /// The latest request got no answer.
+ Silent,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(test, derive(Debug))]
+pub enum Got {
+ Nothing,
+ /// The screen changed.
+ Changed,
+ /// Metadata changed and should be written to the watch's local storage.
+ Save,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(test, derive(Debug))]
+enum Active {
+ Snapshot {
+ id: u8,
+ started: u32,
+ },
+ Command {
+ id: u8,
+ command: u8,
+ value: u8,
+ before: Metadata,
+ started: u32,
+ },
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(test, derive(Debug))]
+struct Command {
+ code: u8,
+ value: u8,
+ before: Metadata,
+}
+
+pub struct Model {
+ pub metadata: Metadata,
+ pub has_snapshot: bool,
+ pub status: Status,
+ /// Wall minute of the last committed snapshot.
+ pub fetched: Option,
+ /// Bumped on every visible change.
+ pub rev: u32,
+
+ id: u8,
+ next_poll: u32,
+ next_command: u32,
+ backoff: u32,
+ active: Option,
+ commands: [Command; COMMAND_QUEUE_MAX],
+ command_head: usize,
+ command_len: usize,
+ cache_dirty: bool,
+}
+
+impl Model {
+ pub const fn new() -> Self {
+ Model {
+ metadata: Metadata::EMPTY,
+ has_snapshot: false,
+ status: Status::Waiting,
+ fetched: None,
+ rev: 0,
+ id: 0,
+ next_poll: 0,
+ next_command: 0,
+ backoff: RETRY_MS,
+ active: None,
+ commands: [Command {
+ code: 0,
+ value: 0,
+ before: Metadata::EMPTY,
+ }; COMMAND_QUEUE_MAX],
+ command_head: 0,
+ command_len: 0,
+ cache_dirty: false,
+ }
+ }
+
+ /// Ask at once (start or RESUME). A reply from the previous run has a different id and is ignored.
+ pub fn ask_now(&mut self, now: u32) {
+ self.active = None;
+ self.backoff = RETRY_MS;
+ self.next_poll = now;
+ if self.command_len > 0 {
+ self.next_command = now;
+ }
+ self.rev += 1;
+ }
+
+ /// Whether the current metadata represents an active media session.
+ pub fn active(&self) -> bool {
+ self.metadata.active()
+ }
+
+ /// The current music stream volume.
+ pub fn volume(&self) -> u8 {
+ self.metadata.volume
+ }
+
+ /// The maximum music stream volume.
+ pub fn max_volume(&self) -> u8 {
+ self.metadata.max_volume
+ }
+
+ /// Whether the current media session is playing.
+ pub fn playing(&self) -> bool {
+ self.metadata.playing()
+ }
+
+ /// The next request to send, if any.
+ pub fn poll(&mut self, now: u32) -> Option {
+ if let Some(active) = self.active {
+ if now.wrapping_sub(started_at(active)) >= timeout_for(active) {
+ if matches!(active, Active::Command { .. }) {
+ self.send_failed(now);
+ } else {
+ self.active = None;
+ self.status = Status::Silent;
+ self.backoff = (self.backoff * 2).min(MAX_BACKOFF_MS);
+ self.next_poll = now.wrapping_add(self.backoff);
+ self.rev += 1;
+ }
+ }
+ return None;
+ }
+
+ if self.command_len > 0 && due(now, self.next_command) {
+ let command = self.commands[self.command_head];
+ self.command_head = (self.command_head + 1) % COMMAND_QUEUE_MAX;
+ self.command_len -= 1;
+ self.id = self.id.wrapping_add(1);
+ self.active = Some(Active::Command {
+ id: self.id,
+ command: command.code,
+ value: command.value,
+ before: command.before,
+ started: now,
+ });
+ return Some(rpc::command_request(self.id, command.code, command.value));
+ }
+
+ if !due(now, self.next_poll) {
+ return None;
+ }
+ self.id = self.id.wrapping_add(1);
+ self.active = Some(Active::Snapshot {
+ id: self.id,
+ started: now,
+ });
+ Some(rpc::snapshot_request(self.id))
+ }
+
+ /// Queue a playback or volume command and update the visible state immediately.
+ pub fn command(&mut self, command: u8, value: u8) -> bool {
+ if self.command_len == COMMAND_QUEUE_MAX
+ || !matches!(
+ command,
+ rpc::PLAY
+ | rpc::PAUSE
+ | rpc::TOGGLE
+ | rpc::PREVIOUS
+ | rpc::NEXT
+ | rpc::VOLUME_UP
+ | rpc::VOLUME_DOWN
+ | rpc::SET_VOLUME
+ )
+ {
+ return false;
+ }
+
+ let old = self.metadata;
+ let before = old;
+ apply_command(&mut self.metadata, command, value);
+
+ let at = (self.command_head + self.command_len) % COMMAND_QUEUE_MAX;
+ self.commands[at] = Command {
+ code: command,
+ value,
+ before,
+ };
+ if self.command_len == 0 {
+ self.next_command = 0;
+ }
+ self.command_len += 1;
+
+ if !old.same_data(&self.metadata) {
+ self.cache_dirty = true;
+ self.rev += 1;
+ }
+ true
+ }
+
+ /// Recover immediately when the loader could not queue a request. A command is put back at the
+ /// front of the queue so a transient outbox or host failure does not silently drop it.
+ pub fn send_failed(&mut self, now: u32) {
+ let Some(active) = self.active.take() else {
+ return;
+ };
+ match active {
+ Active::Snapshot { .. } => {
+ self.next_poll = now.wrapping_add(self.backoff);
+ }
+ Active::Command {
+ command,
+ value,
+ before,
+ ..
+ } => {
+ if self.command_len < COMMAND_QUEUE_MAX {
+ self.command_head =
+ (self.command_head + COMMAND_QUEUE_MAX - 1) % COMMAND_QUEUE_MAX;
+ self.commands[self.command_head] = Command {
+ code: command,
+ value,
+ before,
+ };
+ self.command_len += 1;
+ }
+ self.next_command = now.wrapping_add(self.backoff);
+ self.next_poll = now.wrapping_add(self.backoff);
+ }
+ }
+ self.status = Status::Silent;
+ self.backoff = (self.backoff * 2).min(MAX_BACKOFF_MS);
+ self.rev += 1;
+ }
+
+ /// Handle one host message.
+ pub fn reply(&mut self, message: &[u8], now: u32, wall: i32) -> Got {
+ let Some(reply) = rpc::reply(message) else {
+ return Got::Nothing;
+ };
+ let Some(active) = self.active else {
+ return Got::Nothing;
+ };
+ match active {
+ Active::Command { id, before, .. } if id == reply.id => {
+ self.active = None;
+ self.next_poll = now.wrapping_add(COMMAND_REFRESH_MS);
+ self.next_command = now.wrapping_add(COMMAND_REFRESH_MS);
+ self.status = if reply.status == rpc::OK {
+ Status::Ok
+ } else {
+ status_of(reply.status)
+ };
+ let rolled_back = reply.status != rpc::OK && self.rollback_command(before);
+ self.rev += 1;
+ if rolled_back {
+ self.cache_dirty = true;
+ Got::Save
+ } else {
+ Got::Changed
+ }
+ }
+ Active::Snapshot { id, .. } if id == reply.id => self.snapshot(reply, now, wall),
+ _ => Got::Nothing,
+ }
+ }
+
+ /// Restore the state before a denied command, then reapply commands still queued behind it.
+ fn rollback_command(&mut self, before: Metadata) -> bool {
+ let old = self.metadata;
+ self.metadata = before;
+ self.reapply_queued_commands();
+ !old.same_data(&self.metadata)
+ }
+
+ /// Reapply queued optimistic commands and record each command's new rollback baseline.
+ fn reapply_queued_commands(&mut self) {
+ let mut state = self.metadata;
+ for offset in 0..self.command_len {
+ let index = (self.command_head + offset) % COMMAND_QUEUE_MAX;
+ let mut command = self.commands[index];
+ command.before = state;
+ apply_command(&mut state, command.code, command.value);
+ self.commands[index] = command;
+ }
+ self.metadata = state;
+ }
+
+ fn snapshot(&mut self, reply: rpc::Reply<'_>, now: u32, wall: i32) -> Got {
+ if reply.status != rpc::OK {
+ self.active = None;
+ self.status = status_of(reply.status);
+ self.next_poll = now.wrapping_add(if self.status == Status::Ask {
+ ASK_AGAIN_MS
+ } else {
+ RETRY_MS
+ });
+ self.rev += 1;
+ return Got::Changed;
+ }
+ if reply.total != 1 || reply.index != 0 {
+ return self.reject_snapshot(now);
+ }
+ let Some(metadata) = Metadata::decode(reply.record) else {
+ return self.reject_snapshot(now);
+ };
+ self.commit(metadata, now, wall)
+ }
+
+ fn reject_snapshot(&mut self, now: u32) -> Got {
+ self.active = None;
+ self.status = Status::Unavailable;
+ self.next_poll = now.wrapping_add(RETRY_MS);
+ self.rev += 1;
+ Got::Changed
+ }
+
+ fn commit(&mut self, metadata: Metadata, now: u32, wall: i32) -> Got {
+ let old = self.metadata;
+ self.metadata = metadata;
+ self.reapply_queued_commands();
+ self.has_snapshot = true;
+ self.fetched = Some(wall);
+ self.status = Status::Ok;
+ self.backoff = RETRY_MS;
+ self.next_poll = now.wrapping_add(POLL_MS);
+ self.active = None;
+
+ if !old.same_data(&metadata) {
+ self.rev += 1;
+ self.cache_dirty = true;
+ Got::Save
+ } else {
+ Got::Changed
+ }
+ }
+
+ /// The cache blob. It holds non-personal playback state and volume only.
+ pub fn save(&mut self, out: &mut [u8]) -> usize {
+ if !self.has_snapshot {
+ return 0;
+ }
+ let Some(wall) = self.fetched else { return 0 };
+ out[..2].copy_from_slice(MAGIC);
+ out[2..6].copy_from_slice(&wall.to_le_bytes());
+ let Some(len) = self.metadata.encode(&mut out[6..]) else {
+ return 0;
+ };
+ 6 + len
+ }
+
+ /// Whether metadata has changed since the last successful storage write.
+ pub fn cache_dirty(&self) -> bool {
+ self.cache_dirty
+ }
+
+ /// Mark the current metadata as durably stored.
+ pub fn cache_saved(&mut self) {
+ self.cache_dirty = false;
+ }
+
+ /// Restore cached non-personal playback state.
+ pub fn load(&mut self, blob: &[u8]) {
+ if blob.len() < 10 || &blob[..2] != MAGIC {
+ return;
+ }
+ let Some(metadata) = Metadata::decode(&blob[6..10]) else {
+ return;
+ };
+ self.metadata = metadata;
+ self.has_snapshot = true;
+ self.fetched = Some(i32::from_le_bytes([blob[2], blob[3], blob[4], blob[5]]));
+ self.cache_dirty = false;
+ self.status = Status::Waiting;
+ self.rev += 1;
+ }
+
+ /// Ms until the next request or timeout.
+ pub fn wait(&self, now: u32) -> u32 {
+ let next = if let Some(active) = self.active {
+ started_at(active).wrapping_add(timeout_for(active))
+ } else if self.command_len > 0 {
+ self.next_command.min(self.next_poll)
+ } else {
+ self.next_poll
+ };
+ next.wrapping_sub(now).min(SNAPSHOT_TIMEOUT_MS)
+ }
+}
+
+fn apply_command(metadata: &mut Metadata, command: u8, value: u8) {
+ match command {
+ rpc::PLAY => {
+ metadata.flags |= rpc::RESPONSE_PLAYING | rpc::RESPONSE_ACTIVE;
+ }
+ rpc::PAUSE => metadata.flags &= !rpc::RESPONSE_PLAYING,
+ rpc::TOGGLE => {
+ if metadata.active() && metadata.playing() {
+ metadata.flags &= !rpc::RESPONSE_PLAYING;
+ } else {
+ metadata.flags |= rpc::RESPONSE_PLAYING | rpc::RESPONSE_ACTIVE;
+ }
+ }
+ rpc::VOLUME_UP => {
+ let max = metadata.max_volume;
+ metadata.volume = metadata.volume.saturating_add(1).min(max);
+ }
+ rpc::VOLUME_DOWN => metadata.volume = metadata.volume.saturating_sub(1),
+ rpc::SET_VOLUME => metadata.volume = value.min(metadata.max_volume),
+ rpc::PREVIOUS | rpc::NEXT => {}
+ _ => {}
+ }
+}
+
+fn due(now: u32, at: u32) -> bool {
+ now.wrapping_sub(at) as i32 >= 0
+}
+
+fn started_at(active: Active) -> u32 {
+ match active {
+ Active::Snapshot { started, .. } | Active::Command { started, .. } => started,
+ }
+}
+
+fn timeout_for(active: Active) -> u32 {
+ match active {
+ Active::Snapshot { .. } => SNAPSHOT_TIMEOUT_MS,
+ Active::Command { .. } => COMMAND_TIMEOUT_MS,
+ }
+}
+
+fn status_of(status: u8) -> Status {
+ match status {
+ rpc::OK => Status::Ok,
+ rpc::ASK => Status::Ask,
+ rpc::DENIED => Status::Denied,
+ rpc::BAD_REQUEST | rpc::UNAVAILABLE => Status::Unavailable,
+ _ => Status::Unavailable,
+ }
+}
+
+/// A compact, fixed-size text buffer used by the view.
+pub struct Buf {
+ bytes: [u8; N],
+ len: usize,
+}
+
+impl Buf {
+ pub const fn new() -> Self {
+ Buf {
+ bytes: [0; N],
+ len: 0,
+ }
+ }
+
+ pub fn as_str(&self) -> &str {
+ core::str::from_utf8(&self.bytes[..self.len]).unwrap_or("")
+ }
+
+ fn push_byte(&mut self, byte: u8) {
+ if self.len < N {
+ self.bytes[self.len] = byte;
+ self.len += 1;
+ }
+ }
+
+ fn push_u8(&mut self, value: u8) {
+ if value >= 100 {
+ self.push_byte(b'0' + value / 100);
+ self.push_byte(b'0' + (value / 10) % 10);
+ } else if value >= 10 {
+ self.push_byte(b'0' + value / 10);
+ }
+ self.push_byte(b'0' + value % 10);
+ }
+}
+
+/// Writes a volume percentage without allocating or pulling in the formatting machinery.
+pub fn percent(out: &mut Buf<8>, volume: u8, max: u8) {
+ let value = if max == 0 {
+ 0
+ } else {
+ (volume as u32 * 100 / max as u32).min(100)
+ } as u8;
+ out.push_u8(value);
+ out.push_byte(b'%');
+}
+
+/// Days since 1970-01-01 of a civil date (H. Hinnant's `days_from_civil`).
+pub fn days(y: i32, m: u32, d: u32) -> i32 {
+ let y = if m <= 2 { y - 1 } else { y };
+ let era = y.div_euclid(400);
+ let yoe = y - era * 400;
+ let mp = (m as i32 + 9) % 12;
+ let doy = (153 * mp + 2) / 5 + d as i32 - 1;
+ era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468
+}
+
+/// Local wall-clock minutes since 1970-01-01.
+pub fn wall_min(y: i32, m: u32, d: u32, hour: u32, minute: u32) -> i32 {
+ days(y, m, d) * 1440 + (hour * 60 + minute) as i32
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::rpc;
+
+ fn reply(id: u8, status: u8, index: u8, total: u8, record: &[u8]) -> Vec {
+ let mut out = vec![b'M', b'1', b'A', id, status, index, total];
+ out.extend_from_slice(record);
+ out
+ }
+
+ fn metadata_record(flags: u8, volume: u8, max_volume: u8) -> Vec {
+ vec![0, flags, volume, max_volume]
+ }
+
+ #[test]
+ fn metadata_snapshot_commits() {
+ let mut model = Model::new();
+ let request = model.poll(0).unwrap();
+ let id = match request {
+ rpc::Request::Snapshot(bytes) => bytes[3],
+ _ => panic!("expected snapshot"),
+ };
+ let record = metadata_record(3, 7, 15);
+ assert_eq!(
+ model.reply(&reply(id, 0, 0, 1, &record), 10, 100),
+ Got::Save
+ );
+ assert!(model.has_snapshot);
+ assert!(model.active() && model.playing());
+ assert_eq!((model.volume(), model.max_volume()), (7, 15));
+ assert_eq!(model.status, Status::Ok);
+ }
+
+ #[test]
+ fn malformed_snapshot_is_rejected_without_committing() {
+ let mut model = Model::new();
+ let id = match model.poll(0).unwrap() {
+ rpc::Request::Snapshot(bytes) => bytes[3],
+ _ => panic!("expected snapshot"),
+ };
+ assert_eq!(
+ model.reply(&reply(id, 0, 0, 1, &[0, 3, 16, 15]), 10, 100),
+ Got::Changed
+ );
+ assert!(!model.has_snapshot);
+ assert_eq!(model.status, Status::Unavailable);
+ assert!(model.poll(10 + RETRY_MS).is_some());
+ }
+
+ #[test]
+ fn commands_are_queued_behind_a_snapshot() {
+ let mut model = Model::new();
+ model.poll(0);
+ assert!(model.command(rpc::TOGGLE, 0));
+ assert!(model.metadata.playing());
+ assert!(model.poll(10).is_none());
+ assert!(model.poll(SNAPSHOT_TIMEOUT_MS).is_none());
+ assert_eq!(model.status, Status::Silent);
+ let id = match model.poll(SNAPSHOT_TIMEOUT_MS + 1).unwrap() {
+ rpc::Request::Command(bytes) => bytes[3],
+ _ => panic!("expected queued command"),
+ };
+ model.reply(&reply(id, 0, 0, 0, &[]), SNAPSHOT_TIMEOUT_MS + 11, 100);
+ assert!(model.poll(SNAPSHOT_TIMEOUT_MS + 12).is_none());
+ assert!(matches!(
+ model.poll(SNAPSHOT_TIMEOUT_MS + 12 + COMMAND_REFRESH_MS + 1),
+ Some(rpc::Request::Snapshot(_))
+ ));
+ }
+
+ #[test]
+ fn optimistic_volume_is_clamped() {
+ let mut model = Model::new();
+ let id = match model.poll(0).unwrap() {
+ rpc::Request::Snapshot(bytes) => bytes[3],
+ _ => panic!("expected snapshot"),
+ };
+ model.reply(&reply(id, 0, 0, 1, &metadata_record(3, 7, 15)), 10, 100);
+ model.command(rpc::SET_VOLUME, 200);
+ assert_eq!(model.volume(), 15);
+ model.command(rpc::VOLUME_UP, 0);
+ assert_eq!(model.volume(), 15);
+ model.command(rpc::VOLUME_DOWN, 0);
+ assert_eq!(model.volume(), 14);
+ }
+
+ #[test]
+ fn queue_overflow_does_not_change_visible_state() {
+ let mut model = Model::new();
+ for _ in 0..COMMAND_QUEUE_MAX {
+ assert!(model.command(rpc::VOLUME_UP, 0));
+ }
+ let volume = model.volume();
+ assert!(!model.command(rpc::VOLUME_UP, 0));
+ assert_eq!(model.volume(), volume);
+ }
+
+ #[test]
+ fn unchanged_metadata_does_not_bump_the_visible_revision() {
+ let mut model = Model::new();
+ let id = match model.poll(0).unwrap() {
+ rpc::Request::Snapshot(bytes) => bytes[3],
+ _ => panic!("expected snapshot"),
+ };
+ model.reply(&reply(id, 0, 0, 1, &metadata_record(3, 7, 15)), 10, 100);
+ let rev = model.rev;
+ let id = match model.poll(POLL_MS + 10).unwrap() {
+ rpc::Request::Snapshot(bytes) => bytes[3],
+ _ => panic!("expected snapshot"),
+ };
+ model.reply(
+ &reply(id, 0, 0, 1, &metadata_record(3, 7, 15)),
+ POLL_MS + 11,
+ 100,
+ );
+ assert_eq!(model.rev, rev);
+ }
+
+ #[test]
+ fn cache_round_trip_keeps_non_personal_state() {
+ let mut model = Model::new();
+ let id = match model.poll(0).unwrap() {
+ rpc::Request::Snapshot(bytes) => bytes[3],
+ _ => panic!("expected snapshot"),
+ };
+ model.reply(&reply(id, 0, 0, 1, &metadata_record(3, 7, 15)), 10, 1234);
+ let mut blob = [0u8; BLOB_MAX];
+ let len = model.save(&mut blob);
+ assert_eq!(len, BLOB_MAX);
+ let mut restored = Model::new();
+ restored.load(&blob[..len]);
+ assert!(restored.has_snapshot);
+ assert!(restored.active() && restored.playing());
+ assert_eq!(restored.volume(), 7);
+ assert_eq!(restored.fetched, Some(1234));
+ }
+
+ #[test]
+ fn a_failed_command_is_queued_again() {
+ let mut model = Model::new();
+ assert!(model.command(rpc::TOGGLE, 0));
+ let request = model.poll(0).unwrap();
+ assert!(matches!(request, rpc::Request::Command(_)));
+ model.send_failed(1);
+ assert_eq!(model.status, Status::Silent);
+ let retry_at = 1 + RETRY_MS;
+ let request = model.poll(retry_at).unwrap();
+ assert!(matches!(request, rpc::Request::Command(_)));
+ }
+
+ #[test]
+ fn a_timed_out_command_is_queued_again() {
+ let mut model = Model::new();
+ assert!(model.command(rpc::TOGGLE, 0));
+ assert!(matches!(model.poll(0), Some(rpc::Request::Command(_))));
+ assert!(model.poll(COMMAND_TIMEOUT_MS).is_none());
+ assert_eq!(model.status, Status::Silent);
+ let retry_at = COMMAND_TIMEOUT_MS + RETRY_MS * 2;
+ assert!(matches!(
+ model.poll(retry_at),
+ Some(rpc::Request::Command(_))
+ ));
+ }
+
+ #[test]
+ fn an_optimistic_command_marks_the_cache_dirty() {
+ let mut model = Model::new();
+ let id = match model.poll(0).unwrap() {
+ rpc::Request::Snapshot(bytes) => bytes[3],
+ _ => panic!("expected snapshot"),
+ };
+ model.reply(&reply(id, 0, 0, 1, &metadata_record(3, 7, 15)), 10, 100);
+ model.cache_saved();
+ assert!(model.command(rpc::VOLUME_UP, 0));
+ assert!(model.cache_dirty());
+ let mut blob = [0u8; BLOB_MAX];
+ assert!(model.save(&mut blob) > 0);
+ model.cache_saved();
+ assert!(!model.cache_dirty());
+ }
+
+ #[test]
+ fn denied_command_rolls_back_and_reapplies_later_optimistic_commands() {
+ let mut model = Model::new();
+ let id = match model.poll(0).unwrap() {
+ rpc::Request::Snapshot(bytes) => bytes[3],
+ _ => panic!("expected snapshot"),
+ };
+ model.reply(&reply(id, 0, 0, 1, &metadata_record(3, 7, 15)), 10, 100);
+ model.cache_saved();
+ assert!(model.command(rpc::PAUSE, 0));
+ assert!(model.command(rpc::VOLUME_UP, 0));
+ assert!(!model.playing());
+ assert_eq!(model.volume(), 8);
+
+ let id = match model.poll(11).unwrap() {
+ rpc::Request::Command(bytes) => bytes[3],
+ _ => panic!("expected command"),
+ };
+ assert_eq!(
+ model.reply(&reply(id, rpc::DENIED, 0, 0, &[]), 12, 100),
+ Got::Save
+ );
+ assert!(model.playing());
+ assert_eq!(model.volume(), 8);
+ assert!(model.cache_dirty());
+ assert_eq!(model.status, Status::Denied);
+ }
+
+ #[test]
+ fn snapshot_while_a_command_is_queued_refreshes_its_rollback_baseline() {
+ let mut model = Model::new();
+ let id = match model.poll(0).unwrap() {
+ rpc::Request::Snapshot(bytes) => bytes[3],
+ _ => panic!("expected snapshot"),
+ };
+ model.reply(&reply(id, 0, 0, 1, &metadata_record(3, 7, 15)), 10, 100);
+
+ let id = match model.poll(POLL_MS + 10).unwrap() {
+ rpc::Request::Snapshot(bytes) => bytes[3],
+ _ => panic!("expected snapshot"),
+ };
+ assert!(model.command(rpc::VOLUME_UP, 0));
+ assert_eq!(model.volume(), 8);
+ model.reply(
+ &reply(id, 0, 0, 1, &metadata_record(3, 6, 15)),
+ POLL_MS + 11,
+ 100,
+ );
+ assert_eq!(model.volume(), 7);
+
+ let id = match model.poll(POLL_MS + 12).unwrap() {
+ rpc::Request::Command(bytes) => bytes[3],
+ _ => panic!("expected command"),
+ };
+ assert_eq!(
+ model.reply(&reply(id, rpc::DENIED, 0, 0, &[]), POLL_MS + 13, 100),
+ Got::Save
+ );
+ assert_eq!(model.volume(), 6);
+ }
+
+ #[test]
+ fn permission_and_unavailable_statuses_are_distinct() {
+ let mut model = Model::new();
+ let id = match model.poll(0).unwrap() {
+ rpc::Request::Snapshot(bytes) => bytes[3],
+ _ => panic!("expected snapshot"),
+ };
+ model.reply(&reply(id, rpc::ASK, 0, 0, &[]), 10, 100);
+ assert_eq!(model.status, Status::Ask);
+ assert!(model.poll(ASK_AGAIN_MS).is_none());
+ let id = match model.poll(ASK_AGAIN_MS + 11).unwrap() {
+ rpc::Request::Snapshot(bytes) => bytes[3],
+ _ => panic!("expected snapshot"),
+ };
+ model.reply(&reply(id, rpc::DENIED, 0, 0, &[]), ASK_AGAIN_MS + 12, 100);
+ assert_eq!(model.status, Status::Denied);
+ }
+
+ #[test]
+ fn stale_reply_ids_are_ignored() {
+ let mut model = Model::new();
+ model.poll(0);
+ assert_eq!(
+ model.reply(&reply(99, 0, 0, 1, &metadata_record(3, 7, 15)), 10, 100),
+ Got::Nothing
+ );
+ assert!(!model.has_snapshot);
+ }
+
+ #[test]
+ fn wall_clock_uses_local_calendar_time() {
+ assert_eq!(wall_min(1970, 1, 1, 0, 0), 0);
+ assert_eq!(wall_min(1970, 1, 2, 0, 0), 1440);
+ assert_eq!(
+ wall_min(2026, 11, 19, 12, 30),
+ days(2026, 11, 19) * 1440 + 750
+ );
+ }
+}
diff --git a/apps/music-controller/src/rpc.rs b/apps/music-controller/src/rpc.rs
new file mode 100644
index 0000000..671e502
--- /dev/null
+++ b/apps/music-controller/src/rpc.rs
@@ -0,0 +1,206 @@
+//! The dedicated Music Companion RPC, watch side.
+//!
+//! Requests are `M1Q id method args`; replies are `M1A id status index total record`.
+//! The `M1` namespace is intentionally separate from FMC Companion's generic `R1` namespace, so both phone
+//! apps can coexist without answering each other's requests.
+//!
+//! Only non-personal playback state and music volume cross the BLE channel. Track names, artists,
+//! notification text and artwork never do.
+
+pub const MUSIC_SNAPSHOT: u8 = 0x60;
+pub const MUSIC_COMMAND: u8 = 0x61;
+
+pub const OK: u8 = 0;
+pub const BAD_REQUEST: u8 = 1;
+pub const DENIED: u8 = 2;
+pub const UNAVAILABLE: u8 = 3;
+pub const ASK: u8 = 4;
+
+pub const RESPONSE_PLAYING: u8 = 1;
+pub const RESPONSE_ACTIVE: u8 = 2;
+
+pub const PLAY: u8 = 0;
+pub const PAUSE: u8 = 1;
+pub const TOGGLE: u8 = 2;
+pub const PREVIOUS: u8 = 3;
+pub const NEXT: u8 = 4;
+pub const VOLUME_UP: u8 = 5;
+pub const VOLUME_DOWN: u8 = 6;
+pub const SET_VOLUME: u8 = 7;
+
+/// A request that fits the app-message channel.
+#[derive(Clone, Copy, PartialEq)]
+#[cfg_attr(test, derive(Debug))]
+pub enum Request {
+ Snapshot([u8; 6]),
+ Command([u8; 7]),
+}
+
+impl Request {
+ pub fn bytes(&self) -> &[u8] {
+ match self {
+ Request::Snapshot(bytes) => bytes,
+ Request::Command(bytes) => bytes,
+ }
+ }
+}
+
+/// Requests the current non-personal playback state.
+pub fn snapshot_request(id: u8) -> Request {
+ Request::Snapshot([b'M', b'1', b'Q', id, MUSIC_SNAPSHOT, 0])
+}
+
+/// `music.command`; `value` is used only by `SET_VOLUME`.
+pub fn command_request(id: u8, command: u8, value: u8) -> Request {
+ Request::Command([b'M', b'1', b'Q', id, MUSIC_COMMAND, command, value])
+}
+
+#[derive(Clone, Copy, PartialEq)]
+#[cfg_attr(test, derive(Debug))]
+pub struct Reply<'a> {
+ pub id: u8,
+ pub status: u8,
+ pub index: u8,
+ pub total: u8,
+ pub record: &'a [u8],
+}
+
+/// A reply on this channel; anything else is ignored.
+pub fn reply(message: &[u8]) -> Option> {
+ match message {
+ [b'M', b'1', b'A', id, status, index, total, record @ ..]
+ if *status <= ASK && record.len() <= 121 =>
+ {
+ Some(Reply {
+ id: *id,
+ status: *status,
+ index: *index,
+ total: *total,
+ record,
+ })
+ }
+ _ => None,
+ }
+}
+
+/// Non-personal playback state from the snapshot record.
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(test, derive(Debug))]
+pub struct Metadata {
+ pub flags: u8,
+ pub volume: u8,
+ pub max_volume: u8,
+}
+
+impl Metadata {
+ pub const EMPTY: Metadata = Metadata {
+ flags: 0,
+ volume: 0,
+ max_volume: 0,
+ };
+
+ pub fn playing(&self) -> bool {
+ self.flags & RESPONSE_PLAYING != 0
+ }
+
+ pub fn active(&self) -> bool {
+ self.flags & RESPONSE_ACTIVE != 0
+ }
+
+ /// Whether two records contain exactly the same cache data.
+ pub fn same_data(&self, other: &Metadata) -> bool {
+ self.flags == other.flags
+ && self.volume == other.volume
+ && self.max_volume == other.max_volume
+ }
+
+ /// Encodes the metadata record for the watch's local cache.
+ pub fn encode(&self, out: &mut [u8]) -> Option {
+ if out.len() < 4 {
+ return None;
+ }
+ out[0] = 0;
+ out[1] = self.flags;
+ out[2] = self.volume;
+ out[3] = self.max_volume;
+ Some(4)
+ }
+
+ /// Decodes `0:u8 || flags || volume || max_volume`.
+ pub fn decode(record: &[u8]) -> Option {
+ if record.len() != 4 || record[0] != 0 {
+ return None;
+ }
+ let flags = record[1];
+ if flags & !(RESPONSE_PLAYING | RESPONSE_ACTIVE) != 0 || record[2] > record[3] {
+ return None;
+ }
+ Some(Metadata {
+ flags,
+ volume: record[2],
+ max_volume: record[3],
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn hex(s: &str) -> Vec {
+ (0..s.len())
+ .step_by(2)
+ .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
+ .collect()
+ }
+
+ #[test]
+ fn metadata_vector_decodes() {
+ let metadata = Metadata::decode(&hex("0003070f")).unwrap();
+ assert_eq!(metadata.flags, 3);
+ assert!(metadata.playing() && metadata.active());
+ assert_eq!((metadata.volume, metadata.max_volume), (7, 15));
+ }
+
+ #[test]
+ fn malformed_metadata_is_rejected() {
+ // Wrong type, wrong length, unknown flag, and volume above maximum are all rejected.
+ assert!(Metadata::decode(&hex("0103070f")).is_none());
+ assert!(Metadata::decode(&hex("000307")).is_none());
+ assert!(Metadata::decode(&hex("0008070f")).is_none());
+ assert!(Metadata::decode(&hex("00030f07")).is_none());
+ }
+
+ #[test]
+ fn requests_match_the_wire_layout() {
+ assert_eq!(snapshot_request(8).bytes(), &hex("4d3151086000"));
+ assert_eq!(command_request(10, NEXT, 0).bytes(), &hex("4d31510a610400"));
+ assert_eq!(
+ command_request(11, SET_VOLUME, 9).bytes(),
+ &hex("4d31510b610709")
+ );
+ }
+
+ #[test]
+ fn replies_are_parsed() {
+ let first_bytes = hex("4d314107000000");
+ let first = reply(&first_bytes).unwrap();
+ assert_eq!(
+ (
+ first.id,
+ first.status,
+ first.index,
+ first.total,
+ first.record
+ ),
+ (7, OK, 0, 0, &[][..])
+ );
+ let second_bytes = hex("4d3141080000010003070f");
+ let second = reply(&second_bytes).unwrap();
+ assert_eq!(second.total, 1);
+ assert_eq!(second.record, &hex("0003070f")[..]);
+ let invalid = hex("4d31510701");
+ assert!(reply(&invalid).is_none());
+ assert!(reply(&hex("52314105000000")).is_none());
+ }
+}
diff --git a/apps/music-controller/src/view.rs b/apps/music-controller/src/view.rs
new file mode 100644
index 0000000..e6f7881
--- /dev/null
+++ b/apps/music-controller/src/view.rs
@@ -0,0 +1,263 @@
+//! The watch screen: generic playback state, transport controls and a music-volume slider.
+//!
+//! Track names, artists and artwork deliberately stay on the phone. The watch receives only whether
+//! media is active/playing and the current music-stream volume.
+
+use crate::model::{Model, Status};
+use cmf_wp2_ui::color::{BLACK, Rgb};
+use cmf_wp2_ui::geom::text_box;
+use cmf_wp2_ui::text::{centre, fitted};
+use cmf_wp2_ui::{C, SIZE, Surface};
+
+const BLACK_U16: u16 = 0x0000;
+const WHITE: u16 = 0xFFFF;
+const GREY: u16 = 0x8C92;
+const DIM: u16 = 0x52AB;
+const ACCENT: u16 = 0xFA23;
+const RED: u16 = 0xF213;
+const STATUS_Y: i32 = 174;
+const DETAIL_Y: i32 = 202;
+const VOLUME_Y: i32 = 312;
+const FOOTER_Y: i32 = 378;
+
+const PREV_X: i32 = 91;
+const PLAY_X: i32 = 233;
+const NEXT_X: i32 = 375;
+const CONTROL_Y: i32 = 250;
+const CONTROL_R: i32 = 34;
+
+/// What a tap in the transport row should do.
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(test, derive(Debug))]
+pub enum Action {
+ Previous,
+ Toggle,
+ Next,
+ VolumeUp,
+ VolumeDown,
+ SetVolume(u8),
+ None,
+}
+
+/// Maps a touch to a playback or volume action.
+pub fn action(x: i32, y: i32, max_volume: u8) -> Action {
+ if (CONTROL_Y - CONTROL_R..CONTROL_Y + CONTROL_R).contains(&y) {
+ if (PREV_X - CONTROL_R..PREV_X + CONTROL_R).contains(&x) {
+ return Action::Previous;
+ }
+ if (PLAY_X - CONTROL_R..PLAY_X + CONTROL_R).contains(&x) {
+ return Action::Toggle;
+ }
+ if (NEXT_X - CONTROL_R..NEXT_X + CONTROL_R).contains(&x) {
+ return Action::Next;
+ }
+ }
+ if (VOLUME_Y - 16..VOLUME_Y + 34).contains(&y) {
+ if x < 112 {
+ return Action::VolumeDown;
+ }
+ if x > 354 {
+ return Action::VolumeUp;
+ }
+ if max_volume > 0 {
+ let value = ((x - 115).clamp(0, 236) * max_volume as i32 + 118) / 236;
+ return Action::SetVolume(value.clamp(0, max_volume as i32) as u8);
+ }
+ }
+ Action::None
+}
+
+pub fn frame(s: &mut impl Surface, m: &Model) {
+ s.rect(0, 0, SIZE, SIZE, BLACK_U16);
+
+ if !m.has_snapshot && matches!(m.status, Status::Ask | Status::Denied) {
+ let (title, detail) = match m.status {
+ Status::Ask => ("Allow on your phone", "Open Music Companion"),
+ _ => ("No music access", "Allow it in Music Companion"),
+ };
+ centre(s, C, 194, title, WHITE);
+ centre(s, C, 224, detail, GREY);
+ return;
+ }
+
+ let active = m.active();
+ draw_music_mark(s, active);
+
+ let (state, colour) = if !active {
+ ("NO MEDIA", GREY)
+ } else if m.playing() {
+ ("PLAYING", ACCENT)
+ } else {
+ ("PAUSED", WHITE)
+ };
+ centre(s, C, STATUS_Y, state, colour);
+ let detail = if active {
+ "Music session"
+ } else {
+ "Open a music app"
+ };
+ centre(s, C, DETAIL_Y, detail, DIM);
+
+ transport(s, m.playing(), active);
+ volume(s, m.volume(), m.max_volume(), active);
+
+ let (footer, colour) = match m.status {
+ Status::Ask => ("Allow music on your phone", ACCENT),
+ Status::Denied => ("Music access denied", RED),
+ Status::Unavailable => ("Phone can't answer", ACCENT),
+ Status::Silent if m.has_snapshot => ("No phone reply - showing cached", ACCENT),
+ Status::Silent => ("Phone not answering", ACCENT),
+ Status::Waiting => ("Waiting for phone", DIM),
+ Status::Ok => ("Connected to phone", DIM),
+ };
+ let (x, cells) = text_box(FOOTER_Y, 8);
+ fitted(s, x, FOOTER_Y, footer, cells, colour);
+}
+
+/// Draws a generic two-note mark; it contains no information about the current track.
+fn draw_music_mark(s: &mut impl Surface, active: bool) {
+ let colour = if active { ACCENT } else { DIM };
+ let fill = if active {
+ Rgb(250, 35, 0)
+ } else {
+ Rgb(82, 82, 82)
+ };
+ s.rect(174, 72, 6, 52, colour);
+ s.rect(228, 62, 6, 62, colour);
+ s.rect(180, 72, 48, 6, colour);
+ s.rect(234, 62, 48, 6, colour);
+ cmf_wp2_ui::draw::disc(s, 171, 124, 12, fill, BLACK);
+ cmf_wp2_ui::draw::disc(s, 225, 114, 12, fill, BLACK);
+}
+
+fn transport(s: &mut impl Surface, playing: bool, active: bool) {
+ let colour = if active { WHITE } else { DIM };
+ let icon_colour = if active { BLACK_U16 } else { DIM };
+ // The focused play/pause button has a stock accent disc behind it.
+ if active {
+ cmf_wp2_ui::draw::disc(s, PLAY_X, CONTROL_Y, 28, Rgb(250, 35, 0), BLACK);
+ }
+ // Previous: a vertical bar at the left and a triangle whose point faces left.
+ s.rect(PREV_X - 10, CONTROL_Y - 11, 4, 22, colour);
+ triangle_left(s, PREV_X + 11, CONTROL_Y, 12, 11, colour);
+ // Next: a triangle whose point faces right and a vertical bar at the right.
+ triangle_right(s, NEXT_X - 10, CONTROL_Y, 12, 11, colour);
+ s.rect(NEXT_X + 7, CONTROL_Y - 11, 4, 22, colour);
+
+ if playing {
+ s.rect(PLAY_X - 7, CONTROL_Y - 13, 5, 26, icon_colour);
+ s.rect(PLAY_X + 2, CONTROL_Y - 13, 5, 26, icon_colour);
+ } else {
+ triangle_right(s, PLAY_X - 7, CONTROL_Y, 14, 14, icon_colour);
+ }
+}
+
+/// Draws a solid left-pointing triangle with its point at `x - half_width`.
+fn triangle_left(
+ s: &mut impl Surface,
+ x: i32,
+ y: i32,
+ half_width: i32,
+ half_height: i32,
+ colour: u16,
+) {
+ for row in 0..=half_height {
+ let width = half_width - row;
+ if width > 0 {
+ s.rect(x - width, y - row, width, 1, colour);
+ s.rect(x - width, y + row, width, 1, colour);
+ }
+ }
+}
+
+/// Draws a solid right-pointing triangle with its point at `x + half_width - 1`.
+fn triangle_right(
+ s: &mut impl Surface,
+ x: i32,
+ y: i32,
+ half_width: i32,
+ half_height: i32,
+ colour: u16,
+) {
+ for row in 0..=half_height {
+ let width = half_width - row;
+ if width > 0 {
+ s.rect(x, y - row, width, 1, colour);
+ s.rect(x, y + row, width, 1, colour);
+ }
+ }
+}
+
+fn volume(s: &mut impl Surface, value: u8, max: u8, active: bool) {
+ let colour = if active { WHITE } else { DIM };
+ s.rect(115, VOLUME_Y, 236, 5, DIM);
+ if max > 0 {
+ let width = ((value.min(max) as i32 * 236) / max as i32).clamp(0, 236);
+ s.rect(115, VOLUME_Y, width, 5, ACCENT);
+ }
+ s.rect(87, VOLUME_Y - 11, 15, 3, colour);
+ s.rect(99, VOLUME_Y - 17, 3, 15, colour);
+ s.rect(364, VOLUME_Y - 11, 15, 3, colour);
+ s.rect(364, VOLUME_Y - 17, 3, 15, colour);
+
+ let mut percent = crate::model::Buf::<8>::new();
+ crate::model::percent(&mut percent, value, max);
+ centre(s, C, VOLUME_Y + 17, percent.as_str(), colour);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::Model;
+ use cmf_wp2_ui::Fb;
+
+ #[test]
+ fn every_state_draws_inside_the_circle() {
+ let mut px = vec![0u16; (SIZE * SIZE) as usize];
+ let mut fb = Fb::new(&mut px);
+ let mut m = Model::new();
+ frame(&mut fb, &m);
+ m.status = Status::Ask;
+ frame(&mut fb, &m);
+ m.status = Status::Denied;
+ frame(&mut fb, &m);
+ for y in 0..SIZE {
+ for x in 0..SIZE {
+ let (dx, dy) = (x - C, y - C);
+ if dx * dx + dy * dy > (C - 2) * (C - 2) {
+ assert_eq!(fb.at(x, y), 0, "{x},{y}");
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn controls_have_distinct_touch_targets() {
+ assert_eq!(action(PREV_X, CONTROL_Y, 15), Action::Previous);
+ assert_eq!(action(PLAY_X, CONTROL_Y, 15), Action::Toggle);
+ assert_eq!(action(NEXT_X, CONTROL_Y, 15), Action::Next);
+ assert_eq!(action(75, VOLUME_Y, 15), Action::VolumeDown);
+ assert_eq!(action(390, VOLUME_Y, 15), Action::VolumeUp);
+ assert_eq!(action(C, VOLUME_Y, 15), Action::SetVolume(8));
+ assert_eq!(action(C, VOLUME_Y, 0), Action::None);
+ }
+
+ #[test]
+ fn transport_triangles_point_in_the_right_direction() {
+ let mut px = vec![0u16; (SIZE * SIZE) as usize];
+ let mut fb = Fb::new(&mut px);
+ triangle_left(&mut fb, 100, 100, 12, 11, WHITE);
+ assert_eq!(fb.at(88, 100), WHITE);
+ assert_eq!(fb.at(99, 100), WHITE);
+ assert_eq!(fb.at(100, 100), 0);
+ assert_eq!(fb.at(87, 100), 0);
+ assert_eq!(fb.at(99, 89), WHITE);
+
+ let mut px = vec![0u16; (SIZE * SIZE) as usize];
+ let mut fb = Fb::new(&mut px);
+ triangle_right(&mut fb, 100, 100, 12, 11, WHITE);
+ assert_eq!(fb.at(100, 100), WHITE);
+ assert_eq!(fb.at(111, 100), WHITE);
+ assert_eq!(fb.at(112, 100), 0);
+ }
+}
diff --git a/apps/music-controller/store.md b/apps/music-controller/store.md
new file mode 100644
index 0000000..6cd404d
--- /dev/null
+++ b/apps/music-controller/store.md
@@ -0,0 +1,8 @@
+Control music playback and the phone's music-stream volume from the watch.
+
+The standalone Android **Music Companion** app shows the current track and its notification artwork on the phone. To protect privacy, only generic playback state and volume are sent to the watch; the title, artist and artwork never cross the watch's Bluetooth link. Anyone close enough to read that link can therefore see only whether media is playing and the volume level.
+
+## Requirements
+
+- The [patched firmware](/firmware) with the channel key and the [App Loader](/firmware).
+- The standalone **Android Music Companion** in the `music-companion/` project delivered with this app, with its watch bridge enabled and notification-listener access granted.
diff --git a/apps/music-controller/store.toml b/apps/music-controller/store.toml
new file mode 100644
index 0000000..1d1b385
--- /dev/null
+++ b/apps/music-controller/store.toml
@@ -0,0 +1,5 @@
+name = "Music Controller"
+summary = "Private playback and music-volume controls"
+version = "0.1.0"
+author = "CMF Tech Community"
+screenshots = ["shots/playing.png", "shots/waiting.png"]
From d554efd848c85bf07ff55129f586b23a77d3ec25 Mon Sep 17 00:00:00 2001
From: boxmol71-gif <241158981+boxmol71-gif@users.noreply.github.com>
Date: Fri, 20 Nov 2026 19:32:43 +0000
Subject: [PATCH 2/2] Link the Android companion APK release
---
apps/music-controller/store.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/apps/music-controller/store.md b/apps/music-controller/store.md
index 6cd404d..0d89695 100644
--- a/apps/music-controller/store.md
+++ b/apps/music-controller/store.md
@@ -5,4 +5,4 @@ The standalone Android **Music Companion** app shows the current track and its n
## Requirements
- The [patched firmware](/firmware) with the channel key and the [App Loader](/firmware).
-- The standalone **Android Music Companion** in the `music-companion/` project delivered with this app, with its watch bridge enabled and notification-listener access granted.
+- The standalone [Android Music Companion](https://github.com/boxmol71-gif/music-companion) app. [Download the v0.1.0 companion APK](https://github.com/boxmol71-gif/music-companion/releases/download/v0.1.0/MusicCompanion-0.1.0-debug.apk), then enable its watch bridge and grant notification-listener access.