Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/core/config_sanitizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ pub struct SanitizeResult {
pub keys_pruned: u16,
}

/// Instance config keys owned by the web UI rather than an engine schema:
/// `screen_title` is the free-form name on every screen card.
pub const UI_KEYS: &[&str] = &["screen_title"];

pub struct ConfigSanitizer;

impl ConfigSanitizer {
Expand Down Expand Up @@ -244,8 +248,11 @@ impl ConfigSanitizer {
// Prune keys that are no longer part of the engine schema (e.g. after an
// OTA that removed or renamed a field). Keeps config.json aligned with the
// current descriptor instead of carrying stale/obsolete values forever.
// UI-level keys that every screen card can set (not part of any engine
// schema) are kept too, as on ESP32.
let before = inst.config.len();
inst.config.retain(|k, _| valid_keys.contains(k));
inst.config
.retain(|k, _| valid_keys.contains(k) || UI_KEYS.contains(&k.as_str()));
let pruned = before - inst.config.len();
if pruned > 0 {
result.keys_pruned += pruned as u16;
Expand Down
84 changes: 81 additions & 3 deletions src/engines/mqtt_data/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use crate::core::engine_contract::{
use crate::core::i18n::{self, Lang};
use crate::core::matrix::IDrawingSurface;
use crate::engines::dashboard::font::{draw_text_scaled, measure_text};
use crate::engines::renderers::tiny_font::{draw_tiny_text, tiny_text_width, TINY_H};
use crate::engines::renderers::weather_page::draw_weather_page;
use arc_swap::ArcSwapOption;
use linkme::distributed_slice;
Expand Down Expand Up @@ -113,6 +114,11 @@ impl Shared {
self.pages.get(idx).and_then(|s| s.load_full())
}

/// Whether topic `idx` has a payload (no reference-count traffic).
pub fn has_page(&self, idx: usize) -> bool {
self.pages.get(idx).is_some_and(|s| s.load().is_some())
}

pub fn state(&self) -> u8 {
self.state.load(Ordering::Acquire)
}
Expand Down Expand Up @@ -283,15 +289,56 @@ pub fn notice_for(state: u8, connected_for: Option<Duration>) -> Notice {
}
}

/// Longest screen title (in characters) kept for the waiting label, so
/// "<TITLE> INCOMING..." fits the ESP32's fixed 32-byte buffer too.
pub const WAITING_TITLE_MAX_CHARS: usize = 19;

/// The engine's default name in each UI language: a screen still titled like
/// this has no real title, so it keeps the plain CONNECTING notice.
const DEFAULT_TITLES: [&str; 4] = ["MQTT DATA", "DONNEES MQTT", "DONNÉES MQTT", "DATOS MQTT"];

/// The label shown while connecting, from the screen's `screen_title`:
/// trimmed, uppercased, cut to [`WAITING_TITLE_MAX_CHARS`], plus " INCOMING...".
/// Empty when there is no title or it is the engine's default name, so the
/// i18n CONNECTING notice is used instead.
pub fn waiting_label(screen_title: &str) -> String {
let title: String = screen_title
.trim()
.to_uppercase()
.chars()
.take(WAITING_TITLE_MAX_CHARS)
.collect();
let title = title.trim_end();
if title.is_empty() || DEFAULT_TITLES.contains(&title) {
return String::new();
}
format!("{} INCOMING...", title)
}

/// Draws a notice centred in the 5x7 font.
pub fn draw_notice(m: &mut dyn IDrawingSurface, notice: Notice, lang: Lang) {
draw_notice_with(m, notice, lang, "");
}

/// Like [`draw_notice`], but a non-empty `waiting` label (see [`waiting_label`])
/// replaces the CONNECTING text. A label too wide for the 5x7 font on this
/// panel is drawn in the 3x5 tiny font instead.
pub fn draw_notice_with(m: &mut dyn IDrawingSurface, notice: Notice, lang: Lang, waiting: &str) {
let (w, h) = (m.width() as i32, m.height() as i32);
if notice == Notice::Connecting && !waiting.is_empty() && measure_text(waiting) > w {
let x = ((w - tiny_text_width(waiting)) / 2).max(0);
let y = ((h - TINY_H) / 2).max(0);
m.clear();
draw_tiny_text(m, waiting, x, y, 0, w, NOTICE_COLOR);
return;
}
let (text, color) = match notice {
Notice::Connecting if !waiting.is_empty() => (waiting, NOTICE_COLOR),
Notice::Connecting => (i18n::connecting_label(lang), NOTICE_COLOR),
Notice::NoConnection => (i18n::no_connection_label(lang), NO_CONNECTION_COLOR),
Notice::NoData => (i18n::no_data_label(lang), NOTICE_COLOR),
Notice::Unsupported => (i18n::unsupported_label(lang), UNSUPPORTED_COLOR),
};
let (w, h) = (m.width() as i32, m.height() as i32);
let x = ((w - measure_text(text)) / 2).max(0);
let y = ((h - 7) / 2).max(0);
m.clear();
Expand Down Expand Up @@ -335,6 +382,8 @@ pub fn page_durations(pages: &[PageRef], seconds_of_topic: impl Fn(usize) -> u32

pub struct MqttDataEngine {
topics: Vec<String>,
/// "<SCREEN TITLE> INCOMING..." shown instead of CONNECTING; empty = default.
waiting: String,
lang: Lang,
lang_code: String,
active: bool,
Expand All @@ -351,6 +400,7 @@ impl MqttDataEngine {
pub fn new() -> Self {
Self {
topics: Vec::new(),
waiting: String::new(),
lang: Lang::En,
lang_code: "en".to_string(),
active: false,
Expand All @@ -360,6 +410,26 @@ impl MqttDataEngine {

fn read_config(&mut self, config: &dyn EngineConfig) {
self.topics = parse_topics(&config.get_string("topics", ""));
self.waiting = waiting_label(&config.get_string("screen_title", ""));
}

/// The notice the current page shows when it has no payload yet, or
/// `None` when it has data.
fn pending_notice(&self) -> Option<Notice> {
let Some(s) = self.session.as_ref() else {
return Some(Notice::Connecting);
};
let page = s.pages.get(s.current)?;
if s.shared.has_page(page.topic) {
return None;
}
let at = s.shared.connected_at_ms.load(Ordering::Acquire);
let connected_for = (at > 0).then(|| {
s.started
.elapsed()
.saturating_sub(Duration::from_millis(at))
});
Some(notice_for(s.shared.state(), connected_for))
}

/// Whether a session (thread, client, buffers) currently exists.
Expand Down Expand Up @@ -530,7 +600,7 @@ impl Engine for MqttDataEngine {
fn render(&mut self, ctx: &mut EngineContext) {
let lang = self.lang;
let Some(s) = self.session.as_mut() else {
draw_notice(ctx.surface, Notice::Connecting, lang);
draw_notice_with(ctx.surface, Notice::Connecting, lang, &self.waiting);
return;
};
let Some(page) = s.pages.get(s.current).copied() else {
Expand Down Expand Up @@ -567,15 +637,23 @@ impl Engine for MqttDataEngine {
.elapsed()
.saturating_sub(Duration::from_millis(at))
});
draw_notice(
draw_notice_with(
ctx.surface,
notice_for(s.shared.state(), connected_for),
lang,
&self.waiting,
);
}
}
}

/// Fast frames only while CONNECTING is shown, so the first payload is
/// drawn as soon as it lands (the idle loop sleeps 200 ms per frame);
/// pages with data stay on the static cadence.
fn is_realtime(&self) -> bool {
self.active && self.pending_notice() == Some(Notice::Connecting)
}

/// The engine decides when its slot ends: after one full cycle of its pages.
fn self_paced(&self) -> bool {
true
Expand Down
67 changes: 65 additions & 2 deletions tests/test_mqtt_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ use arcadematrix::core::matrix::MockSurface;
use arcadematrix::core::registry::EngineRegistry;
use arcadematrix::engines::mqtt_data::payload::{parse_page, PageData, DEFAULT_PAGE_SECONDS};
use arcadematrix::engines::mqtt_data::{
build_pages, data_client_id, draw_notice, notice_for, parse_topics, MqttDataEngine, Notice,
PageRef, NO_DATA_AFTER, STATE_CONNECTED, STATE_CONNECTING, STATE_FAILED,
build_pages, data_client_id, draw_notice, draw_notice_with, notice_for, parse_topics,
waiting_label, MqttDataEngine, Notice, PageRef, NO_DATA_AFTER, STATE_CONNECTED,
STATE_CONNECTING, STATE_FAILED,
};
use std::collections::HashMap;
use std::time::{Duration, Instant};
Expand Down Expand Up @@ -219,6 +220,68 @@ fn notices_are_centred_on_128x32() {
assert_eq!((x0, x1), (10, 10 + 106)); // "NON PRIS EN CHARGE" = 107 px
}

#[test]
fn waiting_label_comes_from_screen_title() {
assert_eq!(waiting_label("Weather"), "WEATHER INCOMING...");
assert_eq!(waiting_label(" back yard "), "BACK YARD INCOMING...");
assert_eq!(waiting_label("Météo"), "MÉTÉO INCOMING...");
// No title, or still the engine's default name: plain CONNECTING.
for t in [
"",
" ",
"MQTT Data",
"mqtt data",
"Données MQTT",
"Donnees MQTT",
"Datos MQTT",
] {
assert_eq!(waiting_label(t), "", "{t:?}");
}
// Long titles are cut to 19 characters (fits the ESP32's 32-byte buffer).
assert_eq!(
waiting_label("A very long screen title here"),
"A VERY LONG SCREEN INCOMING..."
);
}

#[test]
fn waiting_label_replaces_connecting_only() {
let grey = (0x78, 0x78, 0x78);
let mut m = MockSurface::new(128, 32);
draw_notice_with(&mut m, Notice::Connecting, Lang::En, "WEATHER INCOMING...");
let (x0, y0, x1, y1) = bbox(&m, grey).unwrap();
// 19 chars in 5x7 (measure 113 px, ink 111 px: the dots are narrow),
// centred, same rows as CONNECTING.
assert_eq!((x0, y0, y1), (7, 12, 18));
assert_eq!(x1 - x0, 110);
// Other notices ignore it.
let red = (0xB4, 0x50, 0x50);
draw_notice_with(
&mut m,
Notice::NoConnection,
Lang::En,
"WEATHER INCOMING...",
);
assert_eq!(bbox(&m, red).map(|b| (b.0, b.2)), Some((25, 25 + 76)));
// Empty label = the plain notice.
let mut a = MockSurface::new(128, 32);
let mut b = MockSurface::new(128, 32);
draw_notice(&mut a, Notice::Connecting, Lang::En);
draw_notice_with(&mut b, Notice::Connecting, Lang::En, "");
assert_eq!(a.canvas, b.canvas);
}

#[test]
fn waiting_label_too_wide_uses_tiny_font() {
let grey = (0x78, 0x78, 0x78);
let mut m = MockSurface::new(64, 32);
draw_notice_with(&mut m, Notice::Connecting, Lang::En, "WEATHER INCOMING...");
let (x0, y0, x1, y1) = bbox(&m, grey).unwrap();
// 3x5 glyphs, rows 13..17, nothing clipped at the left edge.
assert_eq!((y0, y1), (13, 17));
assert!(x0 <= 1 && x1 <= 63, "{x0}..{x1}");
}

#[test]
fn weather_topic_expands_to_its_slides() {
use arcadematrix::api::DayForecast;
Expand Down
19 changes: 19 additions & 0 deletions tests/test_sanitizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,25 @@ fn prunes_keys_not_in_schema() {
assert_eq!(res.keys_pruned, 1);
}

#[test]
fn keeps_screen_title_outside_the_schema() {
let mut cfg = HashMap::new();
cfg.insert("count".to_string(), "5".to_string());
cfg.insert("screen_title".to_string(), "Living Room".to_string());
cfg.insert("obsolete_key".to_string(), "stale".to_string());
let mut s = settings_with(cfg);

let res = ConfigSanitizer::sanitize_instances(&mut s);
let c = &s.instances[0].config;

assert_eq!(
c.get("screen_title").map(String::as_str),
Some("Living Room")
);
assert!(!c.contains_key("obsolete_key"));
assert_eq!(res.keys_pruned, 1);
}

#[test]
fn recreates_missing_rotatable_instances_referenced_by_rotation() {
use arcadematrix::core::config::{OverlayConfig, RotationEntry};
Expand Down
Loading