diff --git a/README.md b/README.md
index c906306..82fd062 100644
--- a/README.md
+++ b/README.md
@@ -16,6 +16,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 by the hour (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 0cbab23..9f38d6f 100644
--- a/apps/Cargo.lock
+++ b/apps/Cargo.lock
@@ -147,6 +147,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/README.md b/apps/weather/README.md
new file mode 100644
index 0000000..7572b4a
--- /dev/null
+++ b/apps/weather/README.md
@@ -0,0 +1,41 @@
+# Weather
+
+The store's page is [`store.md`](store.md). This is the contract of the widget card, which the watch
+(`src/model.rs`, `Model::columns`) and FMC Companion both write: the same forecast at the same hour gives the same
+bytes, so change both sides together.
+
+## The card (stub 10 and its loader)
+
+A v2 `columns` record (the SDK's `docs/widget-push.md`) of at most four columns: now, then the three hours after the
+one that contains now. Hours that aren't known give no column. Without the current weather the phone writes nothing
+and the watch keeps its text card; so does a watch that answers `-22` to the record.
+
+- Caption: `Now`, then `HH:00` (24 h, zero-padded, `00:00` after `23:00`).
+- Hours count from the forecast's own first hour and the phone's clock, never from a stale first entry.
+- Value: whole degrees C and `°` (U+00B0), no unit. Now is the current record's 0.1° rounded, halves away from zero,
+ never `-0`; an hour is its entry's temperature.
+- Icon: the index of the condition, from the WMO code of the current record or of that hour. At night index 0 becomes
+ 8 and index 1 becomes 9; the other six have one drawing.
+- Night is bit 7 of an hourly entry's precip byte: that entry's for its column, and for Now that of the entry that
+ contains now, as on the Now page. No such entry means day. Nothing else says what is night (no sunrise of the
+ phone's or the watch's own), so both write the same bytes.
+
+| Index | `widget-icons/` | `model::Icon` | WMO codes |
+|---|---|---|---|
+| 0 | `00-clear.svg` | `Clear` | 0 |
+| 1 | `01-partly.svg` | `Partly` | 1, 2 |
+| 2 | `02-cloud.svg` | `Cloud` | anything not listed here |
+| 3 | `03-fog.svg` | `Fog` | 45, 48 |
+| 4 | `04-drizzle.svg` | `Drizzle` | 51-57 |
+| 5 | `05-rain.svg` | `Rain` | 61-67, 80-82 |
+| 6 | `06-snow.svg` | `Snow` | 71-77, 85, 86 |
+| 7 | `07-storm.svg` | `Storm` | 95-99 |
+| 8 | `08-clear-night.svg` | `Clear` at night | 0 |
+| 9 | `09-partly-night.svg` | `Partly` at night | 1, 2 |
+
+The index is the file's place in name order and is stored on watches and sent by phones: append, never reorder.
+
+Test vectors (87 bytes each, `src/model_tests.rs`, `columns_golden_bytes` and `columns_golden_bytes_at_night`):
+
+- `wp2apps.install.columns_record([("Now",6,"-3°"),("23:00",2,"-4°"),("00:00",0,"-5°"),("01:00",7,"0°")])`
+- `wp2apps.install.columns_record([("Now",8,"-3°"),("23:00",9,"-4°"),("00:00",2,"-5°"),("01:00",7,"0°")])`
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..413a8a5
--- /dev/null
+++ b/apps/weather/src/main.rs
@@ -0,0 +1,193 @@
+//! 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`): from stub 10 now and the next three hours in columns with the app's own
+//! icons (`widget-icons/`, README.md), before that the place, the temperature with the condition, high and low;
+//! written whenever it changes while the app runs, a new hour too.
+//!
+//! 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, Card, Got, Model, Widget, 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),
+ widget: Widget,
+ }
+
+ 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 it changes.
+ fn card(&mut self) {
+ let api = self.api;
+ self.widget.update(self.model, wall(api), |card| match card {
+ Card::Columns((rec, n)) => api.widget_v2(&rec[..*n]),
+ Card::Text(t, v) => api.widget(t.as_str(), v.as_str()),
+ });
+ }
+
+ 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), widget: Widget::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..a20fcb8
--- /dev/null
+++ b/apps/weather/src/model.rs
@@ -0,0 +1,641 @@
+//! 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 cmf_wp2_app::{Column, columns_record};
+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;
+/// Columns of the widget card: now and the three hours after it.
+const COLUMNS: usize = 4;
+/// What a write answers when the watch can't draw the record (a stub before 10, a loader without templates).
+const E_UNSUPPORTED: i32 = -22;
+/// And when NAND failed.
+const E_IO: i32 = -5;
+/// 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,
+}
+
+/// The order is a contract: a value is the index of its drawing by day in `widget-icons/` and of the icon in the card
+/// FMC Companion pushes (README.md next to `Cargo.toml`). The night's drawings follow these ([`widget_icon`]).
+#[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,
+ }
+}
+
+/// The index in `widget-icons/`, append only: the conditions, then clear and partly cloudy at night.
+fn widget_icon(code: u8, night: bool) -> u8 {
+ match icon(code) {
+ Icon::Clear if night => 8,
+ Icon::Partly if night => 9,
+ i => i as u8,
+ }
+}
+
+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, PartialEq, Eq)]
+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]))
+ }
+
+ /// Whether it is night now: what the hourly entry that contains now says, day without one.
+ pub fn night_now(&self, wall: i32) -> bool {
+ self.hour_at(0, wall).is_some_and(|(_, is_now, h)| is_now && h.night)
+ }
+
+ /// `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 text 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 columns card (stub 10): now and those of the next three hours that are known. `None` without the current
+ /// weather. FMC Companion pushes the same bytes for the same forecast and hour (README.md next to `Cargo.toml`).
+ /// The `°` is real here: the stub draws it, unlike the fonts an app gets ([`DEG`]).
+ pub fn columns(&self, wall: i32) -> Option {
+ let now = self.now?;
+ let mut cols = [(Line::new(), 0, Line::new()); COLUMNS];
+ let _ = cols[0].0.write_str("Now");
+ cols[0].1 = widget_icon(now.code, self.night_now(wall));
+ let _ = write!(cols[0].2, "{}°", deg(now.temp));
+ let mut n = 1;
+ // not `hour_at`: with the watch's clock behind the answer, that would show hours further ahead than three
+ let next = wall.div_euclid(60) + 1 - self.base();
+ for i in next..next + COLUMNS as i32 - 1 {
+ if !(0..self.data.nh as i32).contains(&i) {
+ continue;
+ }
+ let (h, (caption, pic, value)) = (self.data.hours[i as usize], &mut cols[n]);
+ let _ = write!(caption, "{:02}:00", hour_label(self.data.hour0, i as u8));
+ *pic = widget_icon(h.code, h.night);
+ let _ = write!(value, "{}°", h.temp);
+ n += 1;
+ }
+ let cols: [Column; COLUMNS] = core::array::from_fn(|i| Column {
+ caption: cols[i].0.as_str(),
+ icon: Some(cols[i].1),
+ value: cols[i].2.as_str(),
+ });
+ columns_record(&cols[..n])
+ }
+
+ /// 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))
+ }
+}
+
+/// A v2 widget record and its length.
+pub type Record = ([u8; 128], usize);
+
+#[derive(PartialEq, Eq)]
+pub enum Card {
+ Columns(Record),
+ Text(Line, Line),
+}
+
+/// What this run wrote to the card left of the face.
+pub struct Widget {
+ /// The watch refused columns: text for the rest of the run.
+ text_only: bool,
+ last: Option,
+}
+
+impl Widget {
+ pub const fn new() -> Self {
+ Widget { text_only: false, last: None }
+ }
+
+ /// Writes the card when it changed: columns, or the text card without weather or on a watch that can't draw them.
+ pub fn update(&mut self, m: &Model, wall: i32, mut write: impl FnMut(&Card) -> i32) {
+ let text = || {
+ let (t, v) = m.card(wall);
+ Card::Text(t, v)
+ };
+ let columns = if self.text_only { None } else { m.columns(wall) };
+ let mut card = columns.map_or_else(text, Card::Columns);
+ if self.last.as_ref() == Some(&card) {
+ return;
+ }
+ let mut rc = write(&card);
+ if rc == E_UNSUPPORTED && matches!(card, Card::Columns(_)) {
+ self.text_only = true;
+ card = text();
+ rc = write(&card);
+ }
+ self.last = (rc != E_IO).then_some(card);
+ }
+}
+
+#[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..8fb736b
--- /dev/null
+++ b/apps/weather/src/model_tests.rs
@@ -0,0 +1,636 @@
+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));
+}
+
+// The columns card. The phone pushes the same bytes (fmctools/companion): change neither side alone.
+
+/// The current weather, and hourly entries from `first` o'clock: (temperature, code).
+fn forecast(temp: i16, code: u8, first: u8, list: &[(i8, u8)]) -> Vec> {
+ let t = temp.to_le_bytes();
+ let mut h = Vec::from([2, first]);
+ for &(t, c) in list {
+ h.extend([t as u8, c, 0]);
+ }
+ Vec::from([Vec::from([0, t[0], t[1], code, 5, 80, 0]), h])
+}
+
+/// `recs` of [`forecast`] with the night bit in the hourly entries `which`.
+fn at_night(mut recs: Vec>, which: std::ops::Range) -> Vec> {
+ for i in which {
+ recs[1][2 + 3 * i + 2] |= 0x80;
+ }
+ recs
+}
+
+/// What stub 10 draws from the record at `wall`: caption, icon, value. Its own parser, with Weather's ten icons.
+fn drawn(m: &Model, wall: i32) -> Vec<(std::string::String, Option, std::string::String)> {
+ let Some((rec, n)) = m.columns(wall) else { return Vec::new() };
+ // the loader's and the stub's own check; and every icon is one the package has
+ assert!(wp2_core::widget::accepts(&rec[..n], 10), "stub 10 would not draw {:?}", &rec[..n]);
+ let cols = rec[3..n].chunks_exact(21);
+ assert!(cols.clone().all(|c| c[10] < 10), "no such icon in the package");
+ cols.map(|c| (text(&c[..10]), Some(c[10]), text(&c[11..]))).collect()
+}
+
+fn text(b: &[u8]) -> std::string::String {
+ core::str::from_utf8(b).unwrap().trim_end_matches('\0').into()
+}
+
+fn at(day: i32, hour: i32, minute: i32) -> i32 {
+ day * 1440 + hour * 60 + minute
+}
+
+fn captions(m: &Model, wall: i32) -> Vec {
+ drawn(m, wall).into_iter().map(|c| c.0).collect()
+}
+
+#[test]
+fn columns_golden_bytes() {
+ // wp2apps.install.columns_record([("Now",6,"-3°"),("23:00",2,"-4°"),("00:00",0,"-5°"),("01:00",7,"0°")])
+ let golden = concat!(
+ "ff0104",
+ "4e6f7700000000000000", "06", "2d33c2b0000000000000",
+ "32333a30300000000000", "02", "2d34c2b0000000000000",
+ "30303a30300000000000", "00", "2d35c2b0000000000000",
+ "30313a30300000000000", "07", "30c2b000000000000000",
+ );
+ let now = at(20_777, 22, 20);
+ let m = answered_at(&forecast(-34, 71, 22, &[(9, 1), (-4, 3), (-5, 0), (0, 95), (8, 45)]), "", now);
+ let (rec, n) = m.columns(now).expect("a card");
+ let hex: std::string::String = rec[..n].iter().map(|b| std::format!("{b:02x}")).collect();
+ assert_eq!((n, hex.as_str()), (87, golden));
+}
+
+#[test]
+fn columns_golden_bytes_at_night() {
+ // wp2apps.install.columns_record([("Now",8,"-3°"),("23:00",9,"-4°"),("00:00",2,"-5°"),("01:00",7,"0°")])
+ let golden = concat!(
+ "ff0104",
+ "4e6f7700000000000000", "08", "2d33c2b0000000000000",
+ "32333a30300000000000", "09", "2d34c2b0000000000000",
+ "30303a30300000000000", "02", "2d35c2b0000000000000",
+ "30313a30300000000000", "07", "30c2b000000000000000",
+ );
+ let now = at(20_777, 22, 20);
+ let recs = at_night(forecast(-34, 0, 22, &[(9, 45), (-4, 2), (-5, 3), (0, 95), (8, 0)]), 0..5);
+ let m = answered_at(&recs, "", now);
+ let (rec, n) = m.columns(now).expect("a card");
+ let hex: std::string::String = rec[..n].iter().map(|b| std::format!("{b:02x}")).collect();
+ assert_eq!((n, hex.as_str()), (87, golden));
+}
+
+fn pictures(m: &Model, wall: i32) -> Vec