diff --git a/README.md b/README.md
index 3fe30b5..1c7c642 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) |
+| [`weather`](apps/weather) | Now, the next hours and the week ahead, in stock LVGL parts; a page next to the face and a widget card (needs FMC Companion) |
| [`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 1a2ed0c..f9ecff1 100644
--- a/apps/Cargo.lock
+++ b/apps/Cargo.lock
@@ -123,6 +123,15 @@ dependencies = [
"cmf-wp2-app",
]
+[[package]]
+name = "weather"
+version = "0.1.0"
+dependencies = [
+ "cmf-wp2-app",
+ "companion-rpc",
+ "wp2-core",
+]
+
[[package]]
name = "wp2-core"
version = "0.1.0"
diff --git a/apps/weather/Cargo.toml b/apps/weather/Cargo.toml
new file mode 100644
index 0000000..1d5c8a6
--- /dev/null
+++ b/apps/weather/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "weather"
+edition.workspace = true
+license.workspace = true
+version.workspace = true
+
+[dependencies]
+cmf-wp2-app.workspace = true
+companion-rpc.workspace = true
+
+[dev-dependencies]
+wp2-core.workspace = true
+
+[[bin]]
+name = "weather"
+bench = false
diff --git a/apps/weather/icon.svg b/apps/weather/icon.svg
new file mode 100644
index 0000000..6c97534
--- /dev/null
+++ b/apps/weather/icon.svg
@@ -0,0 +1,21 @@
+
diff --git a/apps/weather/shots/card.png b/apps/weather/shots/card.png
new file mode 100644
index 0000000..6c208e3
Binary files /dev/null and b/apps/weather/shots/card.png differ
diff --git a/apps/weather/shots/days.png b/apps/weather/shots/days.png
new file mode 100644
index 0000000..a06ee0f
Binary files /dev/null and b/apps/weather/shots/days.png differ
diff --git a/apps/weather/shots/hours.png b/apps/weather/shots/hours.png
new file mode 100644
index 0000000..a5fbf0f
Binary files /dev/null and b/apps/weather/shots/hours.png differ
diff --git a/apps/weather/shots/now.png b/apps/weather/shots/now.png
new file mode 100644
index 0000000..e75aa80
Binary files /dev/null and b/apps/weather/shots/now.png differ
diff --git a/apps/weather/src/main.rs b/apps/weather/src/main.rs
new file mode 100644
index 0000000..0214e28
--- /dev/null
+++ b/apps/weather/src/main.rs
@@ -0,0 +1,192 @@
+//! weather: now, the next hours and the next days, from FMC Companion (`location` for the place, `weather`).
+//!
+//! - The menu app is three pages in the stock pager (`screen::pages_view`): now, hours, days. The crown or a
+//! swipe pages; the hours and days scroll first. BUTTON exits.
+//! - The page next to the watch face (`app_features!(PAGE)`) is the now screen alone (`screen::face_view`).
+//! - The card left of the face (`WIDGET`): the place, the temperature with the condition, high and low; written
+//! whenever it changes while the app runs.
+//!
+//! The weather comes from the phone at start and every 15 minutes while shown, and is kept in the app's storage so
+//! it opens at once without the phone (`model.rs`).
+#![cfg_attr(target_os = "none", no_std, no_main)]
+
+#[cfg_attr(not(target_os = "none"), allow(dead_code))]
+mod model;
+#[cfg_attr(not(target_os = "none"), allow(dead_code))]
+mod screen;
+
+#[cfg(not(target_os = "none"))]
+fn main() {}
+
+#[cfg(target_os = "none")]
+mod device {
+ use crate::model::{BLOB_MAX, Got, Line, Model, wall_min};
+ use crate::screen::{self, View};
+ use cmf_wp2_app::lv::{Batch, Lv, ROOT};
+ use cmf_wp2_app::{Api, BUTTON, MESSAGE, MSG_MAX, PAUSE, RESUME};
+
+ cmf_wp2_app::entry!(main);
+ cmf_wp2_app::app_icon!();
+ cmf_wp2_app::app_features!(cmf_wp2_app::WIDGET | cmf_wp2_app::PAGE);
+
+ /// How often to look at the clock: a new hour moves the hours, the "Updated" line ages.
+ const TICK_MS: u32 = 60_000;
+ /// On the page next to the face, coming back asks the phone only when the copy is older than this.
+ const FRESH_MIN: i32 = 30;
+
+ static mut STORE: [u8; BLOB_MAX] = [0; BLOB_MAX];
+ static mut MODEL: Model = Model::new();
+
+ fn wall(api: &Api) -> 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))
+ }
+
+ struct App {
+ api: &'static Api,
+ lv: Lv,
+ b: Batch,
+ model: &'static mut Model,
+ view: View,
+ /// The pager's page, kept over a redraw.
+ page: usize,
+ on_page: bool,
+ /// What the screen shows depends on, besides the data.
+ shown: (i32, bool, i32),
+ card: (Line, Line),
+ }
+
+ impl App {
+ /// The hour, whether the phone is silent, and the age once it is worth a line.
+ fn key(&self, w: i32) -> (i32, bool, i32) {
+ let stale = self.model.stale_min(w);
+ (w.div_euclid(60), self.model.silent(), if self.model.now.is_some() && stale > 45 { stale / 10 } else { 0 })
+ }
+
+ fn draw(&mut self) {
+ let (lv, w) = (self.lv, wall(self.api));
+ let mut flush = |b: &mut Batch| b.submit(&lv);
+ let r = screen::leave(&mut self.b, self.view.root)
+ .and_then(|_| {
+ if self.on_page {
+ screen::face_view(&mut self.b, &mut flush, self.model, w)
+ } else {
+ screen::pages_view(&mut self.b, &mut flush, self.model, w, self.page)
+ }
+ })
+ .and_then(|v| self.b.submit(&lv).map(|_| v));
+ match r {
+ Ok(v) => self.view = v,
+ Err(_) => self.b.clear(), // or the records left in it fail every later draw
+ }
+ self.shown = self.key(w);
+ }
+
+ fn save(&mut self) {
+ let blob = unsafe { &mut *core::ptr::addr_of_mut!(STORE) };
+ let n = self.model.save(blob);
+ if n > 0 {
+ self.api.save(&blob[..n]); // on change: the app can end without notice
+ }
+ }
+
+ /// The card, when its text changes.
+ fn card(&mut self) {
+ let (t, v) = self.model.card(wall(self.api));
+ if t.as_str() != self.card.0.as_str() || v.as_str() != self.card.1.as_str() {
+ self.api.widget(t.as_str(), v.as_str());
+ self.card = (t, v);
+ }
+ }
+
+ fn poll(&mut self) {
+ let now = self.api.now();
+ while let Some(req) = self.model.poll(now) {
+ if self.api.send(&req) == -11 {
+ break; // outbox full: the retry timer sends it again
+ } // -107 with no phone: the retry timer covers it too
+ }
+ }
+
+ fn message(&mut self, m: &[u8]) {
+ let got = self.model.reply(m, self.api.now(), wall(self.api));
+ if got == Got::Saved {
+ self.save();
+ }
+ if got != Got::Nothing {
+ self.draw();
+ self.card();
+ }
+ }
+
+ /// The clock moved, or the phone went silent.
+ fn tick(&mut self) {
+ if self.key(wall(self.api)) != self.shown {
+ self.draw();
+ self.card();
+ }
+ }
+ }
+
+ fn main(api: &'static Api) -> i32 {
+ let Some(lv) = api.lv() else { return -95 }; // loader older than ABI 1.2
+ let Some(mut b) = Batch::new() else { return -1 };
+ if screen::fonts(&mut b).and_then(|_| b.submit(&lv)).is_err() {
+ return 1;
+ }
+ if screen::theme(&mut b).and_then(|_| b.submit(&lv)).is_err() {
+ return 2;
+ }
+ let model = unsafe { &mut *core::ptr::addr_of_mut!(MODEL) };
+ let blob = unsafe { &mut *core::ptr::addr_of_mut!(STORE) };
+ let n = api.load(blob);
+ if n > 0 {
+ model.load(&blob[..n as usize]);
+ }
+ model.ask_now(api.now());
+ let view = View { root: ROOT, pager: None, bars: [ROOT; 3] };
+ let mut app =
+ App { api, lv, b, model, view, page: 0, on_page: api.on_page(), shown: (0, false, 0), card: (Line::new(), Line::new()) };
+ app.draw();
+ app.card();
+ let mut paused = false;
+ let mut msg = [0u8; MSG_MAX];
+ loop {
+ if !paused {
+ app.poll();
+ }
+ let wait = if paused { u32::MAX } else { app.model.wait(api.now()).min(TICK_MS) };
+ let e = api.event(wait);
+ if !paused {
+ app.tick();
+ }
+ let Some(e) = e else { continue };
+ match e.kind {
+ BUTTON => break,
+ PAUSE => paused = true,
+ RESUME => {
+ paused = false;
+ if app.model.now.is_none() || app.model.stale_min(wall(api)) > FRESH_MIN {
+ app.model.ask_now(api.now());
+ }
+ app.tick();
+ }
+ MESSAGE => {
+ while let Some(m) = api.recv(&mut msg) {
+ app.message(m);
+ }
+ }
+ _ if !paused => {
+ // the pager settled on a page: move its dots
+ if let Some(p) = app.view.pager.as_mut() {
+ if let Ok(Some(i)) = p.event(&mut app.b, &e) {
+ app.page = i;
+ let _ = app.b.submit(&lv);
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ 0
+ }
+}
diff --git a/apps/weather/src/model.rs b/apps/weather/src/model.rs
new file mode 100644
index 0000000..4394608
--- /dev/null
+++ b/apps/weather/src/model.rs
@@ -0,0 +1,546 @@
+//! Weather's state, without `Api`: the two calls to the phone (`location` once for the place, `weather` every 15
+//! minutes while open), what they answered, the cache blob, and the texts and geometry the screens show.
+//!
+//! Hours and days count from the phone's answer: a cached answer moves with the clock, so the hours that passed and
+//! yesterday drop out instead of being shown as now and today. They count from the phone's hour, not the watch's
+//! at the moment the answer came (`Model::base`): the two clocks can sit on either side of an hour or of midnight.
+
+use companion_rpc as rpc;
+use core::fmt::Write;
+
+/// After a temperature in text: nothing. The watch's fonts have no degree sign (it draws as a blank the width of
+/// a letter, seen in the emulator), so texts carry plain numbers and the now screen draws a ring instead.
+pub const DEG: &str = "";
+/// A fresh answer this often while the app is open; the phone itself caches for 30 minutes.
+pub const PERIOD_MS: u32 = 15 * 60_000;
+/// While the phone waits for the user's "allow".
+pub const ASK_AGAIN_MS: u32 = 10_000;
+/// Hours asked for and shown.
+pub const ASK_HOURS: u8 = 12;
+pub const HOURS: usize = 24;
+pub const DAYS: usize = 7;
+const MAGIC: &[u8; 2] = b"W1";
+pub const BLOB_MAX: usize = 2 + 4 + 1 + rpc::TEXT_MAX + 8 + HOURS * 3 + 1 + DAYS * 5;
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Status {
+ /// No answer to this run's request yet.
+ Waiting,
+ Ok,
+ Ask,
+ Denied,
+ Unavailable,
+}
+
+/// What a message changed.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Got {
+ Nothing,
+ /// The status: redraw.
+ Changed,
+ /// The data: redraw and store.
+ Saved,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Icon {
+ Clear,
+ Partly,
+ Cloud,
+ Fog,
+ Drizzle,
+ Rain,
+ Snow,
+ Storm,
+}
+
+/// `temp` in 0.1 °C, `wind` m/s, `humidity` %.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub struct Now {
+ pub temp: i16,
+ pub code: u8,
+ pub wind: u8,
+ pub humidity: u8,
+}
+
+/// `day` counts from the day of the answer; `min`/`max` °C, `precip` %.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub struct Day {
+ pub day: i8,
+ pub min: i8,
+ pub max: i8,
+ pub code: u8,
+ pub precip: u8,
+}
+
+const NO_HOUR: rpc::Hour = rpc::Hour { temp: 0, code: 0, precip: 0, night: false };
+const NO_DAY: Day = Day { day: 0, min: 0, max: 0, code: 0, precip: 0 };
+
+/// One answer of `weather`.
+#[derive(Clone, Copy)]
+struct Data {
+ now: Option,
+ /// Minutes the phone's data was old when it answered.
+ age: u8,
+ hour0: u8,
+ nh: usize,
+ hours: [rpc::Hour; HOURS],
+ nd: usize,
+ /// Sorted by `day`, each day once.
+ days: [Day; DAYS],
+}
+
+const EMPTY: Data = Data { now: None, age: 0, hour0: 0, nh: 0, hours: [NO_HOUR; HOURS], nd: 0, days: [NO_DAY; DAYS] };
+
+pub struct Model {
+ pub status: Status,
+ pub now: Option,
+ /// The last answer had no hours: a companion from before them (or a source without).
+ pub no_hours: bool,
+ data: Data,
+ pending: Data,
+ /// Wall minutes of the answer `data` is.
+ at: i32,
+ place: rpc::Text,
+ /// `location` answered in this run, with a place or a refusal.
+ located: bool,
+ /// Ask with hours; off once the phone called that a bad request.
+ with_hours: bool,
+ weather: rpc::Call,
+ location: rpc::Call,
+ ids: u8,
+}
+
+/// Days since 1970-01-01 of a civil date.
+pub fn days(y: i32, m: u32, d: u32) -> i32 {
+ let y = if m <= 2 { y - 1 } else { y };
+ let (era, yoe) = (y.div_euclid(400), y.rem_euclid(400));
+ let doy = (153 * ((m as i32 + 9) % 12) + 2) / 5 + d as i32 - 1;
+ era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468
+}
+
+/// Wall-clock minutes since 1970: what `at` and every `wall` argument are.
+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
+}
+
+pub fn icon(code: u8) -> Icon {
+ match code {
+ 0 => Icon::Clear,
+ 1 | 2 => Icon::Partly,
+ 45 | 48 => Icon::Fog,
+ 51..=57 => Icon::Drizzle,
+ 61..=67 | 80..=82 => Icon::Rain,
+ 71..=77 | 85 | 86 => Icon::Snow,
+ 95..=99 => Icon::Storm,
+ _ => Icon::Cloud,
+ }
+}
+
+pub fn condition(code: u8) -> &'static str {
+ match icon(code) {
+ Icon::Clear => "Clear",
+ Icon::Partly => "Partly cloudy",
+ Icon::Cloud => "Cloudy",
+ Icon::Fog => "Fog",
+ Icon::Drizzle => "Drizzle",
+ Icon::Rain => "Rain",
+ Icon::Snow => "Snow",
+ Icon::Storm => "Storm",
+ }
+}
+
+/// 0.1 °C to whole degrees, halves away from zero; −0.4 is 0, never "-0".
+pub fn deg(t10: i16) -> i16 {
+ let t = t10 as i32;
+ (if t >= 0 { (t + 5) / 10 } else { -((5 - t) / 10) }) as i16
+}
+
+/// A short text built in place; what doesn't fit is cut at a character.
+#[derive(Clone, Copy)]
+pub struct Line {
+ buf: [u8; 64],
+ len: usize,
+}
+
+impl Line {
+ pub const fn new() -> Line {
+ Line { buf: [0; 64], len: 0 }
+ }
+ pub fn as_str(&self) -> &str {
+ core::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
+ }
+}
+
+impl Write for Line {
+ fn write_str(&mut self, s: &str) -> core::fmt::Result {
+ let s = rpc::utf8_cut(s.as_bytes(), self.buf.len() - self.len);
+ self.buf[self.len..self.len + s.len()].copy_from_slice(s.as_bytes());
+ self.len += s.len();
+ Ok(())
+ }
+}
+
+/// "-3".
+pub fn temp_text(deg: i16) -> Line {
+ let mut l = Line::new();
+ let _ = write!(l, "{deg}{DEG}");
+ l
+}
+
+/// The hour of day of entry `i` of hours that start at `first`.
+pub fn hour_label(first: u8, i: u8) -> u8 {
+ ((first as u16 + i as u16) % 24) as u8
+}
+
+/// Of a day number (days since 1970, a Thursday).
+pub fn weekday(abs_day: i32) -> &'static str {
+ ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][(abs_day + 3).rem_euclid(7) as usize]
+}
+
+/// Where a day's `min..max` lies on a track `width` wide that spans the week's `lo..hi`: (x, length), the length
+/// at least `min_len` and always inside the track.
+pub fn bar(min: i8, max: i8, lo: i8, hi: i8, width: i16, min_len: i16) -> (i16, i16) {
+ if hi <= lo {
+ return (0, width);
+ }
+ let (lo, hi, w) = (lo as i32, hi as i32, width as i32);
+ let (a, b) = ((min as i32).clamp(lo, hi), (max as i32).clamp(lo, hi));
+ let (a, b) = (a.min(b), a.max(b));
+ let x = (a - lo) * w / (hi - lo);
+ let len = ((b - lo) * w / (hi - lo) - x).max(min_len as i32).min(w);
+ (x.min(w - len) as i16, len as i16)
+}
+
+/// "Updated 50 min ago" once the data is older than the phone's own cache keeps it.
+pub fn updated(stale_min: i32) -> Option {
+ if stale_min <= 45 {
+ return None;
+ }
+ let mut l = Line::new();
+ let _ = match stale_min {
+ ..90 => write!(l, "Updated {stale_min} min ago"),
+ ..2880 => write!(l, "Updated {} h ago", stale_min / 60),
+ _ => write!(l, "Updated {} d ago", stale_min / 1440),
+ };
+ Some(l)
+}
+
+struct Rd<'a>(&'a [u8]);
+
+impl<'a> Rd<'a> {
+ fn take(&mut self, n: usize) -> Option<&'a [u8]> {
+ if self.0.len() < n {
+ return None;
+ }
+ let (a, b) = self.0.split_at(n);
+ self.0 = b;
+ Some(a)
+ }
+ fn u8(&mut self) -> Option {
+ self.take(1).map(|b| b[0])
+ }
+}
+
+impl Model {
+ pub const fn new() -> Self {
+ Model {
+ status: Status::Waiting,
+ now: None,
+ no_hours: false,
+ data: EMPTY,
+ pending: EMPTY,
+ at: 0,
+ place: rpc::Text::EMPTY,
+ located: false,
+ with_hours: true,
+ weather: rpc::Call::new(60_000),
+ location: rpc::Call::new(60_000),
+ ids: 0,
+ }
+ }
+
+ /// Ask at once (start, `RESUME`, the page shown again); the place only until the phone answered about it.
+ pub fn ask_now(&mut self, now: u32) {
+ self.weather.now(now);
+ if !self.located {
+ self.location.now(now);
+ }
+ }
+
+ /// A request to send now, if one is due.
+ pub fn poll(&mut self, now: u32) -> Option {
+ if let Some(id) = self.location.due(now, &mut self.ids) {
+ return Some(rpc::location(id));
+ }
+ let id = self.weather.due(now, &mut self.ids)?;
+ self.pending = EMPTY;
+ Some(rpc::weather(id, DAYS as u8, if self.with_hours { ASK_HOURS } else { 0 }))
+ }
+
+ /// Ms until [`Model::poll`] has something to do.
+ pub fn wait(&self, now: u32) -> u32 {
+ self.weather.wait(now).min(self.location.wait(now))
+ }
+
+ /// The phone left the last weather request unanswered.
+ pub fn silent(&self) -> bool {
+ self.weather.silent()
+ }
+
+ /// One message from the phone, at `now` ms and `wall` minutes.
+ pub fn reply(&mut self, m: &[u8], now: u32, wall: i32) -> Got {
+ match self.location.take(m) {
+ rpc::Got::Nothing => {}
+ rpc::Got::Status(rpc::ASK) => {
+ self.location.after(now, ASK_AGAIN_MS);
+ return Got::Nothing;
+ }
+ // denied, no fix: the weather shows without a place
+ rpc::Got::Status(_) => {
+ self.located = true;
+ self.location.stop();
+ return Got::Nothing;
+ }
+ rpc::Got::Record { record, .. } => {
+ self.located = true;
+ self.location.stop();
+ let Some(l) = rpc::Location::decode(record) else { return Got::Nothing };
+ self.place = l.place;
+ return Got::Saved;
+ }
+ }
+ match self.weather.take(m) {
+ rpc::Got::Nothing => Got::Nothing,
+ // a companion from before hours (Android): once more the old way
+ rpc::Got::Status(rpc::BAD_REQUEST) if self.with_hours => {
+ self.with_hours = false;
+ self.weather.now(now);
+ Got::Nothing
+ }
+ rpc::Got::Status(s) => {
+ self.status = match s {
+ rpc::ASK => Status::Ask,
+ rpc::DENIED => Status::Denied,
+ _ => Status::Unavailable, // OK without records too
+ };
+ self.weather.after(now, if self.status == Status::Ask { ASK_AGAIN_MS } else { PERIOD_MS });
+ Got::Changed
+ }
+ // any order; one that doesn't decode is left out
+ rpc::Got::Record { record, last, .. } => {
+ self.record(record);
+ if !last {
+ return Got::Nothing;
+ }
+ self.weather.after(now, PERIOD_MS);
+ if self.pending.now.is_none() {
+ self.status = Status::Unavailable;
+ return Got::Changed;
+ }
+ self.data = self.pending;
+ self.now = self.data.now;
+ self.at = wall;
+ self.no_hours = self.data.nh == 0;
+ self.status = Status::Ok;
+ Got::Saved
+ }
+ }
+ }
+
+ fn record(&mut self, record: &[u8]) {
+ let p = &mut self.pending;
+ match rpc::Weather::decode(record) {
+ Some(rpc::Weather::Now { temp, code, wind, humidity, age }) => {
+ p.now = Some(Now { temp, code, wind, humidity });
+ p.age = age;
+ }
+ Some(w @ rpc::Weather::Hours { hour, n, .. }) => {
+ p.hour0 = hour % 24;
+ p.nh = (n as usize).min(HOURS);
+ for i in 0..p.nh {
+ p.hours[i] = w.hour(i).unwrap_or(NO_HOUR);
+ }
+ }
+ Some(rpc::Weather::Day { day, min, max, code, precip }) => {
+ Self::add_day(p, Day { day, min, max, code, precip });
+ }
+ None => {}
+ }
+ }
+
+ /// Keeps `days` sorted; a day before the answer's, a repeat or an eighth is dropped.
+ fn add_day(p: &mut Data, d: Day) {
+ if d.day < 0 || p.nd == DAYS || p.days[..p.nd].iter().any(|x| x.day == d.day) {
+ return;
+ }
+ let at = p.days[..p.nd].iter().position(|x| x.day > d.day).unwrap_or(p.nd);
+ p.days.copy_within(at..p.nd, at + 1);
+ p.days[at] = d;
+ p.nd += 1;
+ }
+
+ /// The locality, empty when the phone gave none.
+ pub fn place(&self) -> &str {
+ self.place.as_str()
+ }
+
+ /// Minutes since the phone fetched what is shown.
+ pub fn stale_min(&self, wall: i32) -> i32 {
+ wall - self.at + self.data.age as i32
+ }
+
+ /// The hour (hours since 1970, wall clock) the phone was in when it answered: the first hourly entry's, and
+ /// the one its day 0 is the day of. The watch's own hour at `at`, moved to the nearest one that is `hour0`
+ /// o'clock; without hours, the watch's.
+ fn base(&self) -> i32 {
+ let h = self.at.div_euclid(60);
+ if self.data.nh == 0 {
+ return h;
+ }
+ h + (self.data.hour0 as i32 - h.rem_euclid(24) + 36).rem_euclid(24) - 12
+ }
+
+ /// Hours of the answer that passed by `wall`.
+ fn hours_gone(&self, wall: i32) -> usize {
+ (wall.div_euclid(60) - self.base()).clamp(0, self.data.nh as i32) as usize
+ }
+
+ pub fn hours_len(&self, wall: i32) -> usize {
+ self.data.nh - self.hours_gone(wall)
+ }
+
+ /// Row `k` of the hours at `wall`: the hour of day, whether it is the current hour, the hour.
+ pub fn hour_at(&self, k: usize, wall: i32) -> Option<(u8, bool, rpc::Hour)> {
+ let i = self.hours_gone(wall) + k;
+ if i >= self.data.nh {
+ return None;
+ }
+ let is_now = self.base() + i as i32 == wall.div_euclid(60);
+ Some((hour_label(self.data.hour0, i as u8), is_now, self.data.hours[i]))
+ }
+
+ /// `wall`'s day counted from the answer's.
+ fn today_index(&self, wall: i32) -> i32 {
+ wall.div_euclid(1440) - self.base().div_euclid(24)
+ }
+
+ fn shown_days(&self, wall: i32) -> &[Day] {
+ let t = self.today_index(wall);
+ let d = &self.data.days[..self.data.nd];
+ &d[d.iter().position(|x| x.day as i32 >= t).unwrap_or(d.len())..]
+ }
+
+ pub fn days_len(&self, wall: i32) -> usize {
+ self.shown_days(wall).len()
+ }
+
+ /// Row `k` of the days at `wall`: the day's number (days since 1970), whether it is today, the day.
+ pub fn day_at(&self, k: usize, wall: i32) -> Option<(i32, bool, Day)> {
+ let d = *self.shown_days(wall).get(k)?;
+ Some((self.base().div_euclid(24) + d.day as i32, d.day as i32 == self.today_index(wall), d))
+ }
+
+ pub fn today(&self, wall: i32) -> Option {
+ self.day_at(0, wall).filter(|x| x.1).map(|x| x.2)
+ }
+
+ /// Lowest min and highest max of the days shown.
+ pub fn range(&self, wall: i32) -> (i8, i8) {
+ let d = self.shown_days(wall);
+ (d.iter().map(|x| x.min).min().unwrap_or(0), d.iter().map(|x| x.max).max().unwrap_or(0))
+ }
+
+ /// The widget card: title (≤ 23 bytes) and value (≤ 39 bytes, two lines).
+ pub fn card(&self, wall: i32) -> (Line, Line) {
+ let (mut t, mut v) = (Line::new(), Line::new());
+ let place = rpc::utf8_cut(self.place.as_str().as_bytes(), 23);
+ let _ = t.write_str(if place.is_empty() { "Weather" } else { place });
+ let Some(n) = self.now else {
+ let _ = v.write_str("Open the app");
+ return (t, v);
+ };
+ let _ = write!(v, "{}{DEG} {}", deg(n.temp), condition(n.code));
+ if let Some(d) = self.today(wall) {
+ let _ = write!(v, "\nH {}{DEG} L {}{DEG}", d.max, d.min);
+ }
+ (t, v)
+ }
+
+ /// The cache blob; 0 before the first answer.
+ pub fn save(&self, out: &mut [u8]) -> usize {
+ let (Some(n), d) = (self.data.now, &self.data) else { return 0 };
+ let place = self.place.as_str().as_bytes();
+ let len = 2 + 4 + 1 + place.len() + 8 + d.nh * 3 + 1 + d.nd * 5;
+ if out.len() < len {
+ return 0;
+ }
+ let mut k = 0;
+ let mut put = |b: &[u8]| {
+ out[k..k + b.len()].copy_from_slice(b);
+ k += b.len();
+ };
+ put(MAGIC);
+ put(&self.at.to_le_bytes());
+ put(&[place.len() as u8]);
+ put(place);
+ put(&n.temp.to_le_bytes());
+ put(&[n.code, n.wind, n.humidity, d.age, d.hour0, d.nh as u8]);
+ for h in &d.hours[..d.nh] {
+ put(&[h.temp as u8, h.code, h.precip | (h.night as u8) << 7]);
+ }
+ put(&[d.nd as u8]);
+ for x in &d.days[..d.nd] {
+ put(&[x.day as u8, x.min as u8, x.max as u8, x.code, x.precip]);
+ }
+ len
+ }
+
+ /// Reads a blob of [`Model::save`]; anything else (another version, cut short, counts out of range) is left
+ /// alone and the model stays as it was.
+ pub fn load(&mut self, b: &[u8]) -> bool {
+ let Some((at, place, data)) = Self::parse(b) else { return false };
+ (self.at, self.place, self.data, self.now) = (at, place, data, data.now);
+ self.no_hours = false; // not known until the phone answers
+ true
+ }
+
+ fn parse(b: &[u8]) -> Option<(i32, rpc::Text, Data)> {
+ let mut r = Rd(b);
+ if r.take(2)? != MAGIC {
+ return None;
+ }
+ let at = i32::from_le_bytes(r.take(4)?.try_into().ok()?);
+ let n = r.u8()? as usize;
+ let place = core::str::from_utf8(r.take(n)?).ok()?;
+ let mut d = EMPTY;
+ let temp = i16::from_le_bytes(r.take(2)?.try_into().ok()?);
+ d.now = Some(Now { temp, code: r.u8()?, wind: r.u8()?, humidity: r.u8()? });
+ d.age = r.u8()?;
+ d.hour0 = r.u8()?;
+ d.nh = r.u8()? as usize;
+ if d.hour0 > 23 || d.nh > HOURS {
+ return None;
+ }
+ for i in 0..d.nh {
+ let e = r.take(3)?;
+ d.hours[i] = rpc::Hour { temp: e[0] as i8, code: e[1], precip: e[2] & 0x7F, night: e[2] & 0x80 != 0 };
+ }
+ let nd = r.u8()? as usize;
+ if nd > DAYS {
+ return None;
+ }
+ for _ in 0..nd {
+ let e = r.take(5)?;
+ Self::add_day(&mut d, Day { day: e[0] as i8, min: e[1] as i8, max: e[2] as i8, code: e[3], precip: e[4] });
+ }
+ if !r.0.is_empty() || d.nd != nd {
+ return None;
+ }
+ Some((at, rpc::Text::new(place.as_bytes()), d))
+ }
+}
+
+#[cfg(test)]
+#[path = "model_tests.rs"]
+mod tests;
diff --git a/apps/weather/src/model_tests.rs b/apps/weather/src/model_tests.rs
new file mode 100644
index 0000000..4b462b9
--- /dev/null
+++ b/apps/weather/src/model_tests.rs
@@ -0,0 +1,340 @@
+extern crate std;
+use super::*;
+use std::vec::Vec;
+
+// 2026-11-20 (a Friday) 13:20
+const WALL: i32 = 20_777 * 1440 + 13 * 60 + 20;
+
+fn msg(id: u8, status: u8, index: u8, total: u8, record: &[u8]) -> Vec {
+ [&b"R1A"[..], &[id, status, index, total], record].concat()
+}
+
+/// The id of the request the model sends now.
+fn sent(m: &mut Model, now: u32) -> Vec> {
+ let mut out = Vec::new();
+ while let Some(q) = m.poll(now) {
+ out.push(q.to_vec());
+ }
+ out
+}
+
+const NOW: [u8; 7] = [0, 0xDE, 0xFF, 71, 5, 88, 10]; // -3.4°, snow, 5 m/s, 88 %, 10 min old
+fn hours(first: u8, n: usize) -> Vec {
+ let mut r = Vec::from([2, first]);
+ for i in 0..n {
+ r.extend([(i as i8 - 4) as u8, 3, if i >= 6 { 0x80 | 40 } else { 20 }]);
+ }
+ r
+}
+fn day(d: i8, min: i8, max: i8) -> [u8; 6] {
+ [1, d as u8, min as u8, max as u8, 3, 40]
+}
+
+/// A model that asked and got `recs` as its weather, at WALL; the place refused.
+fn answered(recs: &[Vec]) -> Model {
+ answered_in(recs, "")
+}
+
+fn answered_in(recs: &[Vec], place: &str) -> Model {
+ answered_at(recs, place, WALL)
+}
+
+/// The same, with the watch's clock at `wall` when the answer comes.
+fn answered_at(recs: &[Vec], place: &str, wall: i32) -> Model {
+ let mut m = Model::new();
+ m.ask_now(0);
+ let q = sent(&mut m, 0);
+ let l = q.iter().find(|q| q[4] == 0x20).expect("asks the place");
+ if place.is_empty() {
+ m.reply(&msg(l[3], rpc::DENIED, 0, 0, &[]), 50, wall);
+ } else {
+ m.reply(&msg(l[3], 0, 0, 1, &[&[0u8; 6][..], place.as_bytes()].concat()), 50, wall);
+ }
+ let weather = q.iter().find(|q| q[4] == 0x30).expect("asks the weather");
+ for (i, r) in recs.iter().enumerate() {
+ m.reply(&msg(weather[3], 0, i as u8, recs.len() as u8, r), 100, wall);
+ }
+ m
+}
+
+fn week() -> Vec> {
+ let mut v = Vec::from([NOW.to_vec(), hours(13, 12)]);
+ for d in 0..7 {
+ v.push(day(d, -5 - d, 1 - d).to_vec());
+ }
+ v
+}
+
+#[test]
+fn asks_location_and_weather_with_hours() {
+ let mut m = Model::new();
+ m.ask_now(0);
+ let q = sent(&mut m, 0);
+ assert_eq!(q.len(), 2);
+ assert!(q.iter().any(|q| q[4] == 0x20 && q.len() == 5), "location");
+ assert!(q.iter().any(|q| q[4] == 0x30 && q[5..] == [7, 12]), "7 days, 12 hours");
+ assert_eq!(m.status, Status::Waiting);
+}
+
+#[test]
+fn an_answer_fills_now_hours_and_days() {
+ let m = answered(&week());
+ assert_eq!(m.status, Status::Ok);
+ assert_eq!(m.now, Some(Now { temp: -34, code: 71, wind: 5, humidity: 88 }));
+ assert_eq!(m.hours_len(WALL), 12);
+ let (hod, is_now, h) = m.hour_at(0, WALL).unwrap();
+ assert_eq!((hod, is_now, h.temp, h.night), (13, true, -4, false));
+ let (hod, is_now, h) = m.hour_at(11, WALL).unwrap();
+ assert_eq!((hod, is_now, h.temp, h.night, h.precip), (0, false, 7, true, 40), "13 + 11 is midnight");
+ assert_eq!(m.hour_at(12, WALL), None);
+ assert_eq!(m.days_len(WALL), 7);
+ assert_eq!(m.day_at(0, WALL).map(|(d, today, x)| (d, today, x.min, x.max)), Some((20_777, true, -5, 1)));
+ assert_eq!(m.day_at(6, WALL).map(|(d, today, x)| (d, today, x.min)), Some((20_783, false, -11)));
+ assert_eq!(m.today(WALL).map(|d| (d.min, d.max)), Some((-5, 1)));
+ assert_eq!(m.range(WALL), (-11, 1));
+ assert_eq!(m.stale_min(WALL), 10);
+ assert!(!m.no_hours);
+}
+
+#[test]
+fn records_in_any_order_and_days_sorted() {
+ let mut v = week();
+ v.reverse();
+ let m = answered(&v);
+ assert_eq!(m.day_at(0, WALL).map(|(d, ..)| d), Some(20_777));
+ assert_eq!(m.day_at(6, WALL).map(|(d, ..)| d), Some(20_783));
+ assert!(m.now.is_some());
+}
+
+#[test]
+fn a_cache_moves_with_the_clock() {
+ let m = answered(&week());
+ // three hours later: the hours that passed are gone, the labels stay absolute
+ let later = WALL + 3 * 60;
+ assert_eq!(m.hours_len(later), 9);
+ assert_eq!(m.hour_at(0, later).map(|(h, n, x)| (h, n, x.temp)), Some((16, true, -1)));
+ assert_eq!(m.stale_min(later), 190);
+ // two days later: today is the third day of the answer; the hours are all past
+ let later = WALL + 2 * 1440;
+ assert_eq!(m.hours_len(later), 0);
+ assert_eq!(m.days_len(later), 5);
+ assert_eq!(m.day_at(0, later).map(|(d, t, x)| (d, t, x.min)), Some((20_779, true, -7)));
+ assert_eq!(m.today(later).map(|d| d.max), Some(-1));
+ // a clock set back: nothing before the answer's first hour
+ assert_eq!(m.hours_len(WALL - 600), 12);
+ // ten days later: no day left
+ assert_eq!((m.days_len(WALL + 10 * 1440), m.today(WALL + 10 * 1440)), (0, None));
+}
+
+#[test]
+fn fewer_hours_than_asked_or_none() {
+ let m = answered(&[NOW.to_vec(), hours(22, 5), day(0, 1, 2).to_vec()]);
+ assert_eq!(m.hours_len(WALL), 5);
+ assert_eq!((0..5).map(|k| m.hour_at(k, WALL).unwrap().0).collect::>(), [22, 23, 0, 1, 2]);
+ assert_eq!(m.hour_at(5, WALL), None);
+ // an hourly record without entries, and no hourly record (an iPhone with an old companion)
+ let m = answered(&[NOW.to_vec(), hours(13, 0)]);
+ assert_eq!((m.hours_len(WALL), m.hour_at(0, WALL), m.no_hours), (0, None, true));
+ let m = answered(&[NOW.to_vec(), day(0, 1, 2).to_vec()]);
+ assert_eq!((m.hours_len(WALL), m.no_hours, m.status), (0, true, Status::Ok));
+}
+
+#[test]
+fn an_old_android_companion_is_asked_again_without_hours() {
+ let mut m = Model::new();
+ m.ask_now(0);
+ let q = sent(&mut m, 0);
+ let w = q.iter().find(|q| q[4] == 0x30).unwrap();
+ assert_eq!(m.reply(&msg(w[3], rpc::BAD_REQUEST, 0, 0, &[]), 10, WALL), Got::Nothing);
+ let q = sent(&mut m, 10);
+ assert_eq!(q.len(), 1);
+ assert_eq!(q[0][4..], [0x30, 7], "days only");
+ m.reply(&msg(q[0][3], 0, 0, 2, &NOW), 20, WALL);
+ assert_eq!(m.reply(&msg(q[0][3], 0, 1, 2, &day(0, 1, 2)), 20, WALL), Got::Saved);
+ assert!(m.no_hours && m.status == Status::Ok);
+ // and BAD_REQUEST to that is not asked a third time at once
+ m.ask_now(30);
+ let q = sent(&mut m, 30);
+ let w = q.iter().find(|q| q[4] == 0x30).unwrap();
+ assert_eq!(w[5..], [7]);
+ assert_eq!(m.reply(&msg(w[3], rpc::BAD_REQUEST, 0, 0, &[]), 40, WALL), Got::Changed);
+ assert!(sent(&mut m, 40).iter().all(|q| q[4] != 0x30));
+}
+
+#[test]
+fn statuses_keep_the_cache() {
+ let mut m = answered(&week());
+ for (s, want, again) in [
+ (rpc::ASK, Status::Ask, ASK_AGAIN_MS),
+ (rpc::DENIED, Status::Denied, PERIOD_MS),
+ (rpc::UNAVAILABLE, Status::Unavailable, PERIOD_MS),
+ ] {
+ m.ask_now(1000);
+ let q = sent(&mut m, 1000);
+ let w = q.iter().find(|q| q[4] == 0x30).unwrap();
+ assert_eq!(m.reply(&msg(w[3], s, 0, 0, &[]), 1100, WALL), Got::Changed);
+ assert_eq!((m.status, m.wait(1100)), (want, again));
+ assert!(m.now.is_some() && m.days_len(WALL) == 7, "the last answer stays");
+ }
+ // an answer without the current record is no answer
+ m.ask_now(2000);
+ let q = sent(&mut m, 2000);
+ let w = q.iter().find(|q| q[4] == 0x30).unwrap();
+ m.reply(&msg(w[3], 0, 0, 1, &day(0, 9, 9)), 2100, WALL);
+ assert_eq!(m.status, Status::Unavailable);
+ assert_eq!(m.today(WALL).map(|d| d.max), Some(1));
+}
+
+#[test]
+fn the_place_comes_from_location_and_its_refusal_is_not_an_error() {
+ let mut m = Model::new();
+ m.ask_now(0);
+ let q = sent(&mut m, 0);
+ let l = q.iter().find(|q| q[4] == 0x20).unwrap();
+ let rec = [&[0x2Cu8, 2, 0x78, 1, 5, 0][..], "Москва".as_bytes()].concat();
+ assert_eq!(m.reply(&msg(l[3], 0, 0, 1, &rec), 10, WALL), Got::Saved);
+ assert_eq!(m.place(), "Москва");
+ let mut m = Model::new();
+ m.ask_now(0);
+ let q = sent(&mut m, 0);
+ let l = q.iter().find(|q| q[4] == 0x20).unwrap();
+ assert_eq!(m.reply(&msg(l[3], rpc::DENIED, 0, 0, &[]), 10, WALL), Got::Nothing);
+ assert_eq!((m.place(), m.status), ("", Status::Waiting));
+ // answered once, it is not asked again while the app runs
+ m.ask_now(100);
+ assert!(sent(&mut m, 100).iter().all(|q| q[4] != 0x20));
+}
+
+#[test]
+fn save_and_load() {
+ let m = answered_in(&week(), "Berlin");
+ let mut blob = [0u8; BLOB_MAX];
+ let n = m.save(&mut blob);
+ assert!(n > 0 && n <= BLOB_MAX);
+ let mut back = Model::new();
+ assert!(back.load(&blob[..n]));
+ assert_eq!(back.place(), "Berlin");
+ assert_eq!(back.now, m.now);
+ assert_eq!(back.status, Status::Waiting, "a cache is not an answer");
+ assert_eq!((back.hours_len(WALL), back.days_len(WALL), back.stale_min(WALL)), (12, 7, 10));
+ assert_eq!(back.hour_at(11, WALL), m.hour_at(11, WALL));
+ assert_eq!(back.day_at(6, WALL), m.day_at(6, WALL));
+ // another version, cut short, empty, garbage counts: ignored, the model stays empty
+ let mut other = blob;
+ other[1] = b'9';
+ for bad in [&other[..n], &blob[..n - 1], &blob[..3], &[][..]] {
+ let mut x = Model::new();
+ assert!(!x.load(bad));
+ assert!(x.now.is_none() && x.days_len(WALL) == 0 && x.hours_len(WALL) == 0 && x.place().is_empty());
+ }
+ // nothing to save before the first answer
+ assert_eq!(Model::new().save(&mut blob), 0);
+}
+
+#[test]
+fn temperatures() {
+ assert_eq!([deg(-34), deg(-35), deg(-4), deg(4), deg(5), deg(0), deg(-5), deg(216)], [-3, -4, 0, 0, 1, 0, -1, 22]);
+ // the watch's fonts have no degree sign (it draws as a blank): plain numbers
+ assert_eq!(temp_text(0).as_str(), "0");
+ assert_eq!(temp_text(-12).as_str(), "-12");
+ assert_eq!(temp_text(deg(-4)).as_str(), "0", "never -0");
+}
+
+#[test]
+fn hour_labels_wrap_at_midnight() {
+ assert_eq!([hour_label(22, 0), hour_label(22, 1), hour_label(22, 2), hour_label(22, 3)], [22, 23, 0, 1]);
+ assert_eq!(hour_label(23, 23), 22);
+}
+
+#[test]
+fn weekdays() {
+ assert_eq!(weekday(20_777), "Fri");
+ assert_eq!(weekday(20_779), "Sun");
+ assert_eq!(weekday(20_780), "Mon");
+ assert_eq!(wall_min(2026, 11, 20, 13, 20), WALL);
+}
+
+#[test]
+fn icons_and_names() {
+ for (code, i, name) in [
+ (0, Icon::Clear, "Clear"), (1, Icon::Partly, "Partly cloudy"), (2, Icon::Partly, "Partly cloudy"),
+ (3, Icon::Cloud, "Cloudy"), (45, Icon::Fog, "Fog"), (48, Icon::Fog, "Fog"), (55, Icon::Drizzle, "Drizzle"),
+ (63, Icon::Rain, "Rain"), (81, Icon::Rain, "Rain"), (73, Icon::Snow, "Snow"), (86, Icon::Snow, "Snow"),
+ (95, Icon::Storm, "Storm"), (99, Icon::Storm, "Storm"), (200, Icon::Cloud, "Cloudy"),
+ ] {
+ assert_eq!((icon(code), condition(code)), (i, name), "{code}");
+ }
+}
+
+#[test]
+fn bars_stay_in_the_track() {
+ // (x, length) of a day's range within the week's, on a track 100 wide, at least 12 long
+ assert_eq!(bar(-9, 1, -9, 1, 100, 12), (0, 100));
+ assert_eq!(bar(-5, 1, -9, 1, 100, 12), (40, 60));
+ assert_eq!(bar(3, 3, 3, 3, 100, 12), (0, 100), "a week of one temperature");
+ assert_eq!(bar(1, 1, -9, 1, 100, 12), (88, 12), "a point at the warm end keeps its length inside");
+ assert_eq!(bar(-9, -9, -9, 1, 100, 12), (0, 12));
+ for (min, max) in [(-128i8, 127i8), (5, -5), (0, 0)] {
+ let (x, len) = bar(min, max, -20, 20, 100, 12);
+ assert!(x >= 0 && len >= 12 && x + len <= 100, "{min}..{max}: {x}+{len}");
+ }
+}
+
+#[test]
+fn updated_line() {
+ assert_eq!(updated(10).map(|l| l.as_str().len()), None);
+ assert_eq!(updated(45).map(|_| ()), None);
+ assert_eq!(updated(46).unwrap().as_str(), "Updated 46 min ago");
+ assert_eq!(updated(190).unwrap().as_str(), "Updated 3 h ago");
+ assert_eq!(updated(3 * 1440 + 5).unwrap().as_str(), "Updated 3 d ago");
+ assert_eq!(updated(-500).map(|_| ()), None, "a clock set back");
+}
+
+#[test]
+fn the_card() {
+ let m = Model::new();
+ let (t, v) = m.card(WALL);
+ assert_eq!((t.as_str(), v.as_str()), ("Weather", "Open the app"));
+ let m = answered(&week());
+ let (t, v) = m.card(WALL);
+ assert_eq!((t.as_str(), v.as_str()), ("Weather", "-3 Snow\nH 1 L -5"));
+ let m = answered_in(&week(), "Санкт-Петербург и область");
+ let (t, v) = m.card(WALL);
+ assert!(t.as_str().len() <= 23 && t.as_str().starts_with("Санкт-Петер"), "{}", t.as_str());
+ assert!(v.as_str().len() <= 39);
+ // no day for today: the first line alone
+ let m = answered(&[NOW.to_vec()]);
+ assert_eq!(m.card(WALL).1.as_str(), "-3 Snow");
+}
+
+#[test]
+fn hours_and_days_count_from_the_phones_clock_not_the_watchs() {
+ // the phone answered in its 13th hour; the watch got it at 14:02: 13 is past, 14 is now
+ let at = 20_777 * 1440 + 14 * 60 + 2;
+ let m = answered_at(&week(), "", at);
+ assert_eq!(m.hours_len(at), 11);
+ assert_eq!(m.hour_at(0, at).map(|(h, n, x)| (h, n, x.temp)), Some((14, true, -3)));
+ // the other way: the phone is already in 14, the watch still at 13:59; nothing is past, 14 is not now yet
+ let at = 20_777 * 1440 + 13 * 60 + 59;
+ let mut v = week();
+ v[1] = hours(14, 12);
+ let m = answered_at(&v, "", at);
+ assert_eq!(m.hours_len(at), 12);
+ assert_eq!(m.hour_at(0, at).map(|(h, n, _)| (h, n)), Some((14, false)));
+ assert_eq!(m.hour_at(0, at + 1).map(|(h, n, _)| (h, n)), Some((14, true)));
+ // midnight: the phone answered at 23:59 of the 20th, the watch got it at 00:01 of the 21st
+ let at = 20_778 * 1440 + 1;
+ let mut v = week();
+ v[1] = hours(23, 12);
+ let m = answered_at(&v, "", at);
+ assert_eq!(m.day_at(0, at).map(|(d, today, x)| (d, today, x.min)), Some((20_778, true, -6)), "the phone's tomorrow");
+ assert_eq!(m.days_len(at), 6);
+ assert_eq!(m.hour_at(0, at).map(|(h, n, _)| (h, n)), Some((0, true)));
+ // and it survives the cache
+ let mut blob = [0u8; BLOB_MAX];
+ let n = m.save(&mut blob);
+ let mut back = Model::new();
+ assert!(back.load(&blob[..n]));
+ assert_eq!(back.day_at(0, at), m.day_at(0, at));
+ assert_eq!(back.hour_at(0, at), m.hour_at(0, at));
+}
diff --git a/apps/weather/src/screen.rs b/apps/weather/src/screen.rs
new file mode 100644
index 0000000..7520886
--- /dev/null
+++ b/apps/weather/src/screen.rs
@@ -0,0 +1,395 @@
+//! The screens, from the watch's own LVGL parts and stock fonts (`cmf_wp2_app::stock`):
+//! - in the menu app, three pages in the stock vertical pager: now (place, temperature, condition, high and low,
+//! wind and humidity), the next hours, the next days with a range bar each;
+//! - on the page next to the watch face, the now screen alone;
+//! - before the first answer, one line saying what is missing.
+//!
+//! LVGL here has no images, so a condition icon is two to four plain rounded objects: a disc for the sun, a pill
+//! and a bump for a cloud, short pills for rain. Each screen is one root under `ROOT`; leaving it deletes the root
+//! and everything in it.
+
+use crate::model::{self, Icon, Line, Model, Status};
+use cmf_wp2_app::lv::*;
+use cmf_wp2_app::stock::{self, BLACK, CIRCLE, GREY, Pager, SCREEN, WHITE};
+use core::fmt::Write;
+
+/// Font slots: the system font is 0.
+pub const F24: u8 = 1;
+pub const F48: u8 = 2;
+
+const SUN: i32 = 0xFE60; // #FFCC00
+const MOON: i32 = 0xE73D; // #E5E5EA
+const CLOUD: i32 = 0xD69A; // #D1D1D6
+const STORM: i32 = 0x8C72; // #8E8E93
+const WET: i32 = 0x669F; // #64D2FF
+const TRACK: i32 = 0x39C7; // #3A3A3C
+
+const MSG_W: i32 = 300;
+/// The top of the now screen's content: the place; the rest hangs below it.
+const NOW_Y: i32 = 92;
+/// The first row of the hours and days pages, and their rows' height.
+const ROWS_Y: i32 = 96;
+const HOUR_H: i32 = 58;
+const DAY_H: i32 = 54;
+/// The range bar's track.
+const BAR_W: i16 = 70;
+const BAR_H: i16 = 8;
+
+// bytes one row with its icon can take: flush first when fewer are left
+const GROUP: usize = 760;
+
+pub type Flush<'a> = dyn FnMut(&mut Batch) -> Result<(), LvError> + 'a;
+
+/// Flushes unless a group of records still fits: called before each one, and none is longer than GROUP (the
+/// tests build the views from every fill level).
+fn room(b: &mut Batch, flush: &mut Flush) -> Result<(), LvError> {
+ if b.bytes().len() + GROUP > BUF { flush(b) } else { Ok(()) }
+}
+
+/// The fonts, in a batch of their own.
+pub fn fonts(b: &mut Batch) -> Result<(), LvError> {
+ stock::font(b)?;
+ b.font(F24, StockFont::F24M)?;
+ b.font(F48, StockFont::F48M)
+}
+
+/// Black behind everything, the system font and white text: first, once.
+pub fn theme(b: &mut Batch) -> Result<(), LvError> {
+ stock::theme(b)?;
+ b.style(ROOT, Prop::BgColor, 0, BLACK)
+}
+
+/// What to say instead of the weather while there is none to show.
+pub fn message(m: &Model) -> &'static str {
+ match m.status {
+ Status::Ask => "Allow Weather in FMC Companion on your phone",
+ Status::Denied => "Turn Weather on in FMC Companion",
+ Status::Unavailable => "No weather right now",
+ _ if m.silent() => "Open FMC Companion on your phone",
+ _ => "Asking your phone...",
+ }
+}
+
+/// A line under the weather from the cache, when the phone isn't giving a fresh one.
+pub fn note(m: &Model, wall: i32) -> Option {
+ let fixed = match m.status {
+ Status::Ask => Some("Allow Weather in FMC Companion"),
+ Status::Denied => Some("Weather is off in FMC Companion"),
+ _ if m.silent() => Some("Phone not reachable"),
+ _ => None,
+ };
+ match fixed {
+ Some(t) => {
+ let mut l = Line::new();
+ let _ = l.write_str(t);
+ Some(l)
+ }
+ None => model::updated(m.stale_min(wall)),
+ }
+}
+
+/// The range bar's colour for a day, by the middle of its range: cold blue to hot red.
+pub fn bar_color(min: i8, max: i8) -> i32 {
+ match (min as i32 + max as i32).div_euclid(2) {
+ ..0 => 0x351F, // #30A0FF
+ ..10 => 0x5EDC, // #5AD8E6
+ ..18 => 0x9F09, // #9BE04A
+ ..25 => SUN,
+ ..32 => 0xFCA0, // #FF9500
+ _ => 0xFA27, // #FF453A
+ }
+}
+
+fn plain(b: &mut Batch, o: Obj) -> Result<(), LvError> {
+ for p in [Prop::PadTop, Prop::PadBottom, Prop::PadLeft, Prop::PadRight, Prop::BorderWidth, Prop::BgOpa, Prop::Radius] {
+ b.style(o, p, 0, 0)?;
+ }
+ Ok(())
+}
+
+/// A full-screen root, hidden until the screen is built.
+fn root(b: &mut Batch) -> Result {
+ let r = b.create(Class::Obj, ROOT)?;
+ b.size(r, SCREEN, SCREEN)?;
+ plain(b, r)?;
+ b.flags(r, &[Flag::Hidden], &[Flag::Scrollable])?;
+ Ok(r)
+}
+
+/// A label `w` wide whose centre is `cx` right of the parent's and whose top is at `y`; `align` 1 left, 2 centre,
+/// 3 right.
+fn label(b: &mut Batch, parent: Obj, text: &str, w: i32, cx: i32, y: i32, align: i32) -> Result {
+ let l = b.create(Class::Label, parent)?;
+ b.size(l, w, CONTENT)?;
+ b.style(l, Prop::TextAlign, 0, align)?;
+ b.text(l, text)?;
+ b.align(l, Align::TopMid, cx as i16, y as i16)?;
+ Ok(l)
+}
+
+fn small(b: &mut Batch, l: Obj, color: i32) -> Result<(), LvError> {
+ b.style(l, Prop::TextFont, 0, F24 as i32)?;
+ b.style(l, Prop::TextColor, 0, color)
+}
+
+/// A filled rounded shape, centre `cx` right of the parent's, top at `y`.
+fn shape(b: &mut Batch, parent: Obj, cx: i32, y: i32, w: i32, h: i32, color: i32) -> Result {
+ let o = b.create(Class::Obj, parent)?;
+ b.size(o, w, h)?;
+ b.style(o, Prop::Radius, 0, CIRCLE)?;
+ b.style(o, Prop::BorderWidth, 0, 0)?;
+ b.style(o, Prop::BgColor, 0, color)?;
+ b.style(o, Prop::BgOpa, 0, 255)?;
+ b.flags(o, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ b.align(o, Align::TopMid, cx as i16, y as i16)?;
+ Ok(o)
+}
+
+/// A condition icon in a box 48 wide and 40 high at scale `s`/40, centred at `cx`, top at `y`: at most four
+/// objects. It sits on black: the moon's bite is a black disc.
+pub fn icon(b: &mut Batch, parent: Obj, kind: Icon, night: bool, cx: i32, y: i32, s: i32) -> Result<(), LvError> {
+ let u = |n: i32| n * s / 40;
+ let disc = |b: &mut Batch, dx: i32, dy: i32, d: i32, color: i32| shape(b, parent, cx + u(dx), y + u(dy), u(d), u(d), color).map(|_| ());
+ // a cloud whose top is `dy` down the box
+ let cloud = |b: &mut Batch, dy: i32, color: i32| -> Result<(), LvError> {
+ shape(b, parent, cx - u(5), y + u(dy), u(22), u(22), color)?;
+ shape(b, parent, cx, y + u(dy + 10), u(40), u(18), color).map(|_| ())
+ };
+ // what falls from a cloud at the top of the box
+ let fall = |b: &mut Batch, w: i32, h: i32, color: i32| -> Result<(), LvError> {
+ shape(b, parent, cx - u(8), y + u(31), u(w), u(h), color)?;
+ shape(b, parent, cx + u(8), y + u(31), u(w), u(h), color).map(|_| ())
+ };
+ match kind {
+ Icon::Clear if night => {
+ disc(b, 0, 7, 26, MOON)?;
+ disc(b, 8, 3, 22, BLACK)
+ }
+ Icon::Clear => disc(b, 0, 6, 28, SUN),
+ Icon::Partly => {
+ disc(b, 10, 2, 20, if night { MOON } else { SUN })?;
+ cloud(b, 8, CLOUD)
+ }
+ Icon::Cloud => cloud(b, 6, CLOUD),
+ Icon::Fog => {
+ for dy in [8, 18, 28] {
+ shape(b, parent, cx, y + u(dy), u(40), u(5), STORM)?;
+ }
+ Ok(())
+ }
+ Icon::Drizzle => {
+ cloud(b, 2, CLOUD)?;
+ fall(b, 4, 5, WET)
+ }
+ Icon::Rain => {
+ cloud(b, 2, CLOUD)?;
+ fall(b, 4, 9, WET)
+ }
+ Icon::Snow => {
+ cloud(b, 2, CLOUD)?;
+ fall(b, 6, 6, WHITE)
+ }
+ Icon::Storm => {
+ cloud(b, 2, STORM)?;
+ shape(b, parent, cx, y + u(30), u(6), u(10), SUN).map(|_| ())
+ }
+ }
+}
+
+/// The now screen's content, into a full-screen `parent`.
+fn now_content(b: &mut Batch, flush: &mut Flush, parent: Obj, m: &Model, wall: i32) -> Result<(), LvError> {
+ let Some(n) = m.now else { return Ok(()) };
+ room(b, flush)?;
+ if !m.place().is_empty() {
+ let l = label(b, parent, m.place(), MSG_W, 0, NOW_Y, 2)?;
+ b.long_mode(l, LongMode::Dot)?;
+ small(b, l, GREY)?;
+ }
+ // the temperature and, since the fonts have no degree sign, a ring after it: a row as wide as the two, moved
+ // right by half the ring so the number stays in the middle
+ room(b, flush)?;
+ let row = b.create(Class::Obj, parent)?;
+ b.size(row, CONTENT, CONTENT)?;
+ plain(b, row)?;
+ b.flags(row, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ b.flex(row, Flow::Row, FlexAlign::Start, FlexAlign::Start, FlexAlign::Start)?;
+ b.style(row, Prop::PadColumn, 0, 4)?;
+ b.align(row, Align::TopMid, 9, (NOW_Y + 36) as i16)?;
+ let t = b.create(Class::Label, row)?;
+ b.text(t, model::temp_text(model::deg(n.temp)).as_str())?;
+ b.style(t, Prop::TextFont, 0, F48 as i32)?;
+ let ring = b.create(Class::Obj, row)?;
+ b.size(ring, 14, 14)?;
+ b.style(ring, Prop::Radius, 0, CIRCLE)?;
+ b.style(ring, Prop::BgOpa, 0, 0)?;
+ b.style(ring, Prop::BorderWidth, 0, 3)?;
+ b.style(ring, Prop::BorderColor, 0, WHITE)?;
+ b.style(ring, Prop::TranslateY, 0, 8)?;
+ b.flags(ring, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ // night for the icon: what the current hour says, when there are hours
+ let night = m.hour_at(0, wall).is_some_and(|(_, is_now, h)| is_now && h.night);
+ room(b, flush)?;
+ icon(b, parent, model::icon(n.code), night, 0, NOW_Y + 98, 52)?;
+ room(b, flush)?;
+ label(b, parent, model::condition(n.code), MSG_W, 0, NOW_Y + 158, 2)?;
+ let mut y = NOW_Y + 204;
+ if let Some(d) = m.today(wall) {
+ let mut l = Line::new();
+ let _ = write!(l, "H:{} L:{}", model::temp_text(d.max as i16).as_str(), model::temp_text(d.min as i16).as_str());
+ let h = label(b, parent, l.as_str(), MSG_W, 0, y, 2)?;
+ small(b, h, WHITE)?;
+ y += 36;
+ }
+ let mut l = Line::new();
+ let _ = write!(l, "{} m/s {}%", n.wind, n.humidity);
+ let w = label(b, parent, l.as_str(), MSG_W, 0, y, 2)?;
+ small(b, w, GREY)?;
+ if let Some(t) = note(m, wall) {
+ let l = label(b, parent, t.as_str(), 280, 0, y + 36, 2)?;
+ small(b, l, GREY)?;
+ b.long_mode(l, LongMode::Wrap)?;
+ }
+ Ok(())
+}
+
+/// A grey line in the middle of a page that has nothing else.
+fn empty(b: &mut Batch, parent: Obj, text: &str) -> Result<(), LvError> {
+ let l = label(b, parent, text, MSG_W, 0, 180, 2)?;
+ b.style(l, Prop::TextColor, 0, GREY)?;
+ b.long_mode(l, LongMode::Wrap)
+}
+
+/// What the hours page says without hours.
+pub fn no_hours_text(m: &Model) -> &'static str {
+ if m.no_hours { "Update FMC Companion for the hourly forecast" } else { "No hours to show yet" }
+}
+
+fn hours_content(b: &mut Batch, flush: &mut Flush, page: Obj, m: &Model, wall: i32) -> Result<(), LvError> {
+ let n = m.hours_len(wall).min(model::ASK_HOURS as usize);
+ if n == 0 {
+ room(b, flush)?;
+ return empty(b, page, no_hours_text(m));
+ }
+ for k in 0..n {
+ let Some((hod, is_now, h)) = m.hour_at(k, wall) else { break };
+ room(b, flush)?;
+ let y = ROWS_Y + k as i32 * HOUR_H;
+ let mut l = Line::new();
+ let _ = if is_now { l.write_str("Now") } else { write!(l, "{hod:02}") };
+ let t = label(b, page, l.as_str(), 80, -110, y + 8, 1)?;
+ if !is_now {
+ b.style(t, Prop::TextColor, 0, GREY)?;
+ }
+ icon(b, page, model::icon(h.code), h.night, -22, y + 6, 40)?;
+ if h.precip >= 30 {
+ let mut l = Line::new();
+ let _ = write!(l, "{}%", h.precip);
+ let p = label(b, page, l.as_str(), 64, 42, y + 14, 2)?;
+ small(b, p, WET)?;
+ }
+ label(b, page, model::temp_text(h.temp as i16).as_str(), 80, 110, y + 8, 3)?;
+ }
+ b.style(page, Prop::PadBottom, 0, 130) // the last row can scroll up clear of the round edge
+}
+
+fn days_content(b: &mut Batch, flush: &mut Flush, page: Obj, m: &Model, wall: i32) -> Result<(), LvError> {
+ let n = m.days_len(wall);
+ if n == 0 {
+ room(b, flush)?;
+ return empty(b, page, "No forecast to show yet");
+ }
+ let (lo, hi) = m.range(wall);
+ for k in 0..n {
+ let Some((abs, today, d)) = m.day_at(k, wall) else { break };
+ room(b, flush)?;
+ let y = ROWS_Y + k as i32 * DAY_H;
+ label(b, page, if today { "Today" } else { model::weekday(abs) }, 96, -112, y + 6, 1)?;
+ icon(b, page, model::icon(d.code), false, -34, y + 4, 40)?;
+ let lo_l = label(b, page, model::temp_text(d.min as i16).as_str(), 56, 6, y + 12, 3)?;
+ small(b, lo_l, GREY)?;
+ room(b, flush)?;
+ let track = shape(b, page, 73, y + 22, BAR_W as i32, BAR_H as i32, TRACK)?;
+ b.style(track, Prop::PadLeft, 0, 0)?;
+ let (x, len) = model::bar(d.min, d.max, lo, hi, BAR_W, BAR_H);
+ let seg = b.create(Class::Obj, track)?;
+ b.size(seg, len as i32, BAR_H as i32)?;
+ b.style(seg, Prop::Radius, 0, CIRCLE)?;
+ b.style(seg, Prop::BorderWidth, 0, 0)?;
+ b.style(seg, Prop::BgColor, 0, bar_color(d.min, d.max))?;
+ b.style(seg, Prop::BgOpa, 0, 255)?;
+ b.flags(seg, &[], &[Flag::Clickable, Flag::Scrollable])?;
+ b.align(seg, Align::LeftMid, x, 0)?;
+ let hi_l = label(b, page, model::temp_text(d.max as i16).as_str(), 56, 138, y + 12, 3)?;
+ small(b, hi_l, WHITE)?;
+ }
+ b.style(page, Prop::PadBottom, 0, 130)
+}
+
+/// A screen: its root, and the pager when it has pages.
+#[derive(Clone, Copy)]
+pub struct View {
+ pub root: Obj,
+ pub pager: Option>,
+ /// The stock round scroll bar of each page that scrolls (hours, days); `ROOT` for the rest.
+ pub bars: [Obj; 3],
+}
+
+
+/// One line in the middle of the screen.
+pub fn message_view(b: &mut Batch, flush: &mut Flush, text: &str) -> Result {
+ room(b, flush)?;
+ let r = root(b)?;
+ let l = label(b, r, text, MSG_W, 0, 170, 2)?;
+ b.style(l, Prop::TextColor, 0, GREY)?;
+ b.long_mode(l, LongMode::Wrap)?;
+ b.flags(r, &[], &[Flag::Hidden])?;
+ Ok(View { root: r, pager: None, bars: [ROOT; 3] })
+}
+
+/// The menu app: now, hours, days, opened on `page`.
+pub fn pages_view(b: &mut Batch, flush: &mut Flush, m: &Model, wall: i32, page: usize) -> Result {
+ if m.now.is_none() {
+ return message_view(b, flush, message(m));
+ }
+ room(b, flush)?;
+ let mut p = stock::pager::<3>(b, 3)?;
+ b.flags(p.root, &[Flag::Hidden], &[])?;
+ now_content(b, flush, p.pages[0], m, wall)?;
+ hours_content(b, flush, p.pages[1], m, wall)?;
+ days_content(b, flush, p.pages[2], m, wall)?;
+ room(b, flush)?;
+ let mut bars = [ROOT; 3];
+ for i in 1..3 {
+ bars[i] = b.scroll_bar(p.pages[i])?;
+ }
+ // a scroll bar takes the crown for its list, which then never pages on at its end: the pager keeps it, scrolls
+ // the page first and pages at its end, and the bar shows while the page scrolls
+ b.knob(p.obj)?;
+ let page = page.min(2);
+ if page > 0 {
+ p.jump(b, page)?;
+ }
+ b.flags(p.root, &[], &[Flag::Hidden])?;
+ Ok(View { root: p.root, pager: Some(p), bars })
+}
+
+/// The page next to the watch face: the now screen alone.
+pub fn face_view(b: &mut Batch, flush: &mut Flush, m: &Model, wall: i32) -> Result {
+ if m.now.is_none() {
+ return message_view(b, flush, message(m));
+ }
+ room(b, flush)?;
+ let r = root(b)?;
+ now_content(b, flush, r, m, wall)?;
+ b.flags(r, &[], &[Flag::Hidden])?;
+ Ok(View { root: r, pager: None, bars: [ROOT; 3] })
+}
+
+/// Deletes a screen.
+pub fn leave(b: &mut Batch, root: Obj) -> Result<(), LvError> {
+ if root != ROOT { b.del(root) } else { Ok(()) }
+}
+
+#[cfg(test)]
+#[path = "screen_tests.rs"]
+mod tests;
diff --git a/apps/weather/src/screen_tests.rs b/apps/weather/src/screen_tests.rs
new file mode 100644
index 0000000..58f5936
--- /dev/null
+++ b/apps/weather/src/screen_tests.rs
@@ -0,0 +1,256 @@
+extern crate std;
+use super::*;
+use companion_rpc as rpc;
+use std::boxed::Box;
+use std::vec::Vec;
+use wp2_core::lvcmd::{self, Table};
+
+// 2026-11-20 13:20
+const WALL: i32 = 20_777 * 1440 + 13 * 60 + 20;
+const FONTS: u8 = 0b111;
+
+fn batch() -> Batch {
+ Batch::with_buf(Box::leak(Box::new([0; BUF])))
+}
+
+/// Runs `build` with a flush that validates each batch against the loader's table and applies it; returns the
+/// result and the batches' sizes.
+fn run(t: &mut Table, b: &mut Batch, build: impl FnOnce(&mut Batch, &mut Flush) -> Result) -> (T, Vec) {
+ let sizes = std::cell::RefCell::new(Vec::new());
+ let mut flush = |b: &mut Batch| -> Result<(), LvError> {
+ assert_eq!(lvcmd::validate(b.bytes(), t, FONTS), Ok(()));
+ for r in lvcmd::records(b.bytes()) {
+ lvcmd::apply(t, &r.unwrap());
+ }
+ sizes.borrow_mut().push(b.bytes().len());
+ b.clear();
+ Ok(())
+ };
+ let out = build(b, &mut flush).unwrap();
+ flush(b).unwrap();
+ (out, sizes.into_inner())
+}
+
+fn msg(id: u8, status: u8, index: u8, total: u8, record: &[u8]) -> Vec {
+ [&b"R1A"[..], &[id, status, index, total], record].concat()
+}
+
+/// A model the phone answered with `recs` at WALL, in "Санкт-Петербург".
+fn answered(recs: &[Vec]) -> Model {
+ let mut m = Model::new();
+ m.ask_now(0);
+ while let Some(q) = m.poll(0) {
+ if q[4] == 0x20 {
+ m.reply(&msg(q[3], 0, 0, 1, &[&[0u8; 6][..], "Санкт-Петербург".as_bytes()].concat()), 10, WALL);
+ } else {
+ for (i, r) in recs.iter().enumerate() {
+ m.reply(&msg(q[3], 0, i as u8, recs.len() as u8, r), 10, WALL);
+ }
+ }
+ }
+ m
+}
+
+/// Every hour and day with `code`, the hours at night with rain likely: the most objects a code can cost.
+fn full(code: u8, hours: usize, days: i8) -> Model {
+ let mut v = Vec::from([[0, 0x38, 0xFF, code, 12, 100, 200].to_vec()]); // -20.0°
+ if hours > 0 {
+ let mut h = Vec::from([2, 13]);
+ for _ in 0..hours {
+ h.extend([(-128i8) as u8, code, 0x80 | 100]);
+ }
+ v.push(h);
+ }
+ for d in 0..days {
+ v.push([1, d as u8, (-128i8) as u8, 127, code, 100].to_vec());
+ }
+ answered(&v)
+}
+
+fn live(t: &Table) -> usize {
+ (0..lvcmd::MAX_OBJS as u16).filter(|&h| t.class(h).is_some()).count()
+}
+
+#[test]
+fn fonts_validate_on_their_own() {
+ let mut b = batch();
+ fonts(&mut b).unwrap();
+ assert_eq!(lvcmd::validate(b.bytes(), &Table::new(), 0), Ok(()));
+}
+
+#[test]
+fn every_icon_builds_within_four_objects() {
+ for kind in [Icon::Clear, Icon::Partly, Icon::Cloud, Icon::Fog, Icon::Drizzle, Icon::Rain, Icon::Snow, Icon::Storm] {
+ for night in [false, true] {
+ let mut t = Table::new();
+ let mut b = batch();
+ run(&mut t, &mut b, |b, _| {
+ theme(b)?;
+ icon(b, ROOT, kind, night, 0, 0, 40)
+ });
+ let n = live(&t) - 1; // the root
+ assert!((1..=4).contains(&n), "{kind:?} night {night}: {n}");
+ }
+ }
+}
+
+#[test]
+fn the_pages_validate_within_the_budgets_and_free_everything() {
+ // every WMO group, with all 12 hours and 7 days, then the short and empty shapes
+ let mut models = Vec::new();
+ for code in [0, 2, 3, 45, 55, 63, 73, 95] {
+ models.push(full(code, 24, 7));
+ }
+ models.extend([full(63, 0, 7), full(63, 5, 0), full(63, 0, 0), full(63, 1, 1)]);
+ for m in &models {
+ let mut t = Table::new();
+ let mut b = batch();
+ let before = {
+ run(&mut t, &mut b, |b, _| theme(b));
+ live(&t)
+ };
+ for page in 0..3 {
+ let (v, sizes) = run(&mut t, &mut b, |b, f| pages_view(b, f, m, WALL, page));
+ assert!(sizes.iter().all(|&s| s <= BUF));
+ let p = v.pager.expect("pages");
+ assert_eq!((p.at, p.n), (page, 3));
+ assert_eq!(v.bars[0], ROOT, "now has no scroll bar");
+ for bar in &v.bars[1..] {
+ assert_eq!(t.class(bar.0), Some(lvcmd::Class::ScrollBar));
+ }
+ assert!(live(&t) <= lvcmd::MAX_OBJS, "{} objects", live(&t));
+ std::println!("page {page}: {} objects, batches {sizes:?}", live(&t));
+ // leaving frees every handle
+ run(&mut t, &mut b, |b, _| leave(b, v.root));
+ assert_eq!(live(&t), before);
+ }
+ let (v, _) = run(&mut t, &mut b, |b, f| face_view(b, f, m, WALL));
+ assert!(v.pager.is_none());
+ run(&mut t, &mut b, |b, _| leave(b, v.root));
+ assert_eq!(live(&t), before);
+ }
+}
+
+#[test]
+fn a_stale_cache_still_builds() {
+ // three days later: no hours left, four days left, "Updated 3 d ago"
+ let m = full(63, 12, 7);
+ let later = WALL + 3 * 1440;
+ let mut t = Table::new();
+ let mut b = batch();
+ run(&mut t, &mut b, |b, f| {
+ theme(b)?;
+ pages_view(b, f, &m, later, 1)
+ });
+ assert_eq!(note(&m, later).unwrap().as_str(), "Updated 3 d ago");
+ assert_eq!((m.hours_len(later), m.days_len(later)), (0, 4));
+}
+
+#[test]
+fn without_weather_it_says_why() {
+ let mut m = Model::new();
+ assert_eq!(message(&m), "Asking your phone...");
+ for (s, want) in [
+ (rpc::ASK, "Allow Weather in FMC Companion on your phone"),
+ (rpc::DENIED, "Turn Weather on in FMC Companion"),
+ (rpc::UNAVAILABLE, "No weather right now"),
+ ] {
+ m.ask_now(0);
+ while let Some(q) = m.poll(0) {
+ if q[4] == 0x30 {
+ m.reply(&msg(q[3], s, 0, 0, &[]), 10, WALL);
+ }
+ }
+ assert_eq!(message(&m), want);
+ }
+ // the phone never answers: after the first retry it is told what to open
+ let mut m = Model::new();
+ m.ask_now(0);
+ while m.poll(0).is_some() {}
+ while m.poll(10_000).is_some() {}
+ assert_eq!(message(&m), "Open FMC Companion on your phone");
+ let mut t = Table::new();
+ let mut b = batch();
+ for build in [pages_view as fn(&mut Batch, &mut Flush, &Model, i32, usize) -> Result] {
+ let (v, _) = run(&mut t, &mut b, |b, f| {
+ theme(b)?;
+ build(b, f, &m, WALL, 0)
+ });
+ assert!(v.pager.is_none());
+ }
+ let (v, _) = run(&mut t, &mut b, |b, f| face_view(b, f, &m, WALL));
+ assert!(v.pager.is_none());
+}
+
+#[test]
+fn notes_and_empty_pages() {
+ let m = full(63, 0, 7);
+ assert!(m.no_hours);
+ assert_eq!(no_hours_text(&m), "Update FMC Companion for the hourly forecast");
+ assert_eq!(note(&m, WALL).unwrap().as_str(), "Updated 200 min ago".replace("200 min", "3 h"));
+ let m = full(63, 12, 7);
+ assert_eq!(no_hours_text(&m), "No hours to show yet");
+}
+
+#[test]
+fn bar_colours_run_cold_to_hot() {
+ let c = [(-20, -10), (-2, 6), (8, 14), (15, 25), (22, 30), (30, 40)].map(|(a, b)| bar_color(a, b));
+ for i in 0..c.len() {
+ for j in 0..i {
+ assert_ne!(c[i], c[j]);
+ }
+ }
+ assert_eq!(bar_color(-128, -128), c[0]);
+ assert_eq!(bar_color(127, 127), c[5]);
+}
+
+/// What the emulator's fake phone answers: mixed hours and days, in "Berlin" (the pager came out black there).
+fn mixed(hour0: u8) -> Model {
+ let hours = [(-3, 2, 10, 0), (-3, 2, 10, 0), (-4, 3, 20, 0), (-4, 3, 30, 0), (-5, 71, 60, 1), (-5, 71, 70, 1),
+ (-6, 73, 80, 1), (-6, 3, 20, 1), (-6, 0, 0, 1), (-5, 0, 0, 1), (-4, 1, 10, 1), (-3, 61, 40, 1)];
+ let days = [(-6, -2, 2, 20), (-8, -3, 71, 70), (-4, 1, 3, 30), (0, 5, 61, 80), (2, 8, 1, 10), (4, 11, 0, 0), (-1, 6, 95, 60)];
+ let mut v = Vec::from([[0, 0xDE, 0xFF, 2, 5, 78, 3].to_vec()]);
+ let mut h = Vec::from([2, hour0]);
+ for (t, code, p, night) in hours {
+ h.extend([t as i8 as u8, code, p | night << 7]);
+ }
+ v.push(h);
+ for (d, (lo, hi, code, p)) in days.iter().enumerate() {
+ v.push([1, d as u8, *lo as i8 as u8, *hi as i8 as u8, *code, *p].to_vec());
+ }
+ answered(&v)
+}
+
+/// A view is built into whatever the batch already holds, so no group of records may be longer than the room
+/// asked for before it: every fill level the batch can start at, every icon.
+#[test]
+fn the_views_build_from_any_fill_level() {
+ let mut models = Vec::from([mixed(22), mixed(9)]);
+ for code in [0, 2, 3, 45, 55, 63, 73, 95] {
+ models.push(full(code, 12, 7));
+ }
+ for (i, m) in models.iter().enumerate() {
+ for fill in 0..200 {
+ let mut t = Table::new();
+ let mut b = batch();
+ let mut flush = |b: &mut Batch| -> Result<(), LvError> {
+ assert_eq!(lvcmd::validate(b.bytes(), &t, FONTS), Ok(()));
+ for r in lvcmd::records(b.bytes()) {
+ lvcmd::apply(&mut t, &r.unwrap());
+ }
+ b.clear();
+ Ok(())
+ };
+ for _ in 0..fill {
+ if b.style(ROOT, Prop::BgColor, 0, BLACK).is_err() {
+ break; // full to the brim is a fill level too
+ }
+ }
+ let at = b.bytes().len();
+ let r = pages_view(&mut b, &mut flush, m, WALL, 0).map(|_| ());
+ assert_eq!(r, Ok(()), "model {i}, {at} bytes in the batch");
+ let r = face_view(&mut b, &mut flush, m, WALL).map(|_| ());
+ assert_eq!(r, Ok(()), "model {i}, the face page");
+ }
+ }
+}
diff --git a/apps/weather/store.md b/apps/weather/store.md
new file mode 100644
index 0000000..5c498b9
--- /dev/null
+++ b/apps/weather/store.md
@@ -0,0 +1,22 @@
+The weather where your phone is, in three pages you turn with the crown or a swipe:
+
+- **Now**: the place, the temperature, the condition, today's high and low, wind and humidity.
+- **Hours**: the next 12 hours with the temperature and, when it is likely, the chance of rain or snow.
+- **Days**: the week ahead, each day with its low, its high and a bar that shows where they sit in the week.
+
+Long-press **Weather** in Apps and choose **Add page** to keep the Now screen one swipe from the watch face, or
+**Add widget** for a card with the temperature, the condition and today's high and low.
+
+The watch asks the phone when you open the app and every 15 minutes while it's shown, and keeps the last answer, so
+it opens at once without the phone and says how old the weather is. Temperatures are in °C.
+
+The first time, the watch says "Allow Weather in FMC Companion on your phone": open FMC Companion, Apps, Weather, and
+allow it (the phone then asks for your location). The watch gets the weather and the name of the place, never where
+you are.
+
+## Requirements
+
+- A phone with **FMC Companion** (iOS or Android), paired with the watch. The hours need FMC Companion from
+ 2026-11-20 or later; with an older one the Hours page asks you to update it and the rest works.
+- The [patched firmware](/firmware) with the channel key (2026-11-13 or later) and the [App Loader](/firmware)
+ (2026-11-15 or later for the page and the widget).
diff --git a/apps/weather/store.toml b/apps/weather/store.toml
new file mode 100644
index 0000000..fc81177
--- /dev/null
+++ b/apps/weather/store.toml
@@ -0,0 +1,6 @@
+# The app's listing in the FMC store (README.md, "store.toml"). The page's body is store.md.
+name = "Weather"
+summary = "Now, the next hours and the week ahead where you are, with a page next to the watch face and a widget card"
+version = "0.1.0"
+author = "Egor Kolesnikov"
+screenshots = ["shots/now.png", "shots/hours.png", "shots/days.png", "shots/card.png"]