internal data sources (clock, static text), connection indicator, rendering fixes
DataSourceConfig refactored to enum: External/Clock/StaticText. Clock generates formatted time via chrono, static text emits configured string. ESP32: connection status indicator (green/red dot bottom-right), per-widget clear before redraw, RenderEvent enum for local + server messages. Polling uses DataUpdate instead of ScreenUpdate to avoid wiping widget state. Empty mappings passthrough raw source data for internal sources.
This commit is contained in:
@@ -18,6 +18,8 @@ pub fn data_source_type_to_str(t: &DataSourceType) -> &'static str {
|
||||
DataSourceType::Rss => "rss",
|
||||
DataSourceType::HttpJson => "http_json",
|
||||
DataSourceType::Webhook => "webhook",
|
||||
DataSourceType::Clock => "clock",
|
||||
DataSourceType::StaticText => "static_text",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +30,8 @@ fn data_source_type_from_str(s: &str) -> Result<DataSourceType, SqliteConfigErro
|
||||
"rss" => Ok(DataSourceType::Rss),
|
||||
"http_json" => Ok(DataSourceType::HttpJson),
|
||||
"webhook" => Ok(DataSourceType::Webhook),
|
||||
"clock" => Ok(DataSourceType::Clock),
|
||||
"static_text" => Ok(DataSourceType::StaticText),
|
||||
_ => Err(SqliteConfigError::Serialization(format!(
|
||||
"unknown source type: {s}"
|
||||
))),
|
||||
@@ -38,33 +42,54 @@ pub fn data_source_config_to_json(
|
||||
config: &DataSourceConfig,
|
||||
secrets: Option<&(dyn SecretStore + Send + Sync)>,
|
||||
) -> Result<String, SqliteConfigError> {
|
||||
let api_key = config.api_key.as_ref().map(|k| match secrets {
|
||||
Some(s) => s.encrypt(k),
|
||||
None => k.clone(),
|
||||
});
|
||||
let v = match config {
|
||||
DataSourceConfig::External {
|
||||
url,
|
||||
headers,
|
||||
api_key,
|
||||
} => {
|
||||
let api_key = api_key.as_ref().map(|k| match secrets {
|
||||
Some(s) => s.encrypt(k),
|
||||
None => k.clone(),
|
||||
});
|
||||
|
||||
let headers: Vec<(String, String)> = config
|
||||
.headers
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
let val = if is_sensitive_key(k) {
|
||||
match secrets {
|
||||
Some(s) => s.encrypt(v),
|
||||
None => v.clone(),
|
||||
}
|
||||
} else {
|
||||
v.clone()
|
||||
};
|
||||
(k.clone(), val)
|
||||
})
|
||||
.collect();
|
||||
let headers: Vec<(String, String)> = headers
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
let val = if is_sensitive_key(k) {
|
||||
match secrets {
|
||||
Some(s) => s.encrypt(v),
|
||||
None => v.clone(),
|
||||
}
|
||||
} else {
|
||||
v.clone()
|
||||
};
|
||||
(k.clone(), val)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let v = serde_json::json!({
|
||||
"url": config.url,
|
||||
"headers": headers,
|
||||
"api_key": api_key,
|
||||
"encrypted": secrets.is_some(),
|
||||
});
|
||||
serde_json::json!({
|
||||
"type": "external",
|
||||
"url": url,
|
||||
"headers": headers,
|
||||
"api_key": api_key,
|
||||
"encrypted": secrets.is_some(),
|
||||
})
|
||||
}
|
||||
DataSourceConfig::Clock { format, timezone } => {
|
||||
serde_json::json!({
|
||||
"type": "clock",
|
||||
"format": format,
|
||||
"timezone": timezone,
|
||||
})
|
||||
}
|
||||
DataSourceConfig::StaticText { text } => {
|
||||
serde_json::json!({
|
||||
"type": "static_text",
|
||||
"text": text,
|
||||
})
|
||||
}
|
||||
};
|
||||
serde_json::to_string(&v).map_err(|e| SqliteConfigError::Serialization(e.to_string()))
|
||||
}
|
||||
|
||||
@@ -75,47 +100,61 @@ fn data_source_config_from_json(
|
||||
let v: serde_json::Value =
|
||||
serde_json::from_str(json).map_err(|e| SqliteConfigError::Serialization(e.to_string()))?;
|
||||
|
||||
let encrypted = v["encrypted"].as_bool().unwrap_or(false);
|
||||
let config_type = v["type"].as_str().unwrap_or("external");
|
||||
|
||||
let url = v["url"].as_str().map(String::from);
|
||||
|
||||
let api_key = v["api_key"].as_str().map(|k| {
|
||||
if encrypted {
|
||||
match secrets {
|
||||
Some(s) => s.decrypt(k),
|
||||
None => k.to_string(),
|
||||
}
|
||||
} else {
|
||||
k.to_string()
|
||||
match config_type {
|
||||
"clock" => {
|
||||
let format = v["format"].as_str().unwrap_or("%H:%M:%S").to_string();
|
||||
let timezone = v["timezone"].as_str().unwrap_or("UTC").to_string();
|
||||
Ok(DataSourceConfig::Clock { format, timezone })
|
||||
}
|
||||
});
|
||||
"static_text" => {
|
||||
let text = v["text"].as_str().unwrap_or("").to_string();
|
||||
Ok(DataSourceConfig::StaticText { text })
|
||||
}
|
||||
_ => {
|
||||
let encrypted = v["encrypted"].as_bool().unwrap_or(false);
|
||||
let url = v["url"].as_str().map(String::from);
|
||||
|
||||
let headers = match v["headers"].as_array() {
|
||||
Some(arr) => arr
|
||||
.iter()
|
||||
.filter_map(|h| {
|
||||
let pair = h.as_array()?;
|
||||
let key: String = pair[0].as_str()?.into();
|
||||
let raw_val: &str = pair[1].as_str()?;
|
||||
let val = if encrypted && is_sensitive_key(&key) {
|
||||
let api_key = v["api_key"].as_str().map(|k| {
|
||||
if encrypted {
|
||||
match secrets {
|
||||
Some(s) => s.decrypt(raw_val),
|
||||
None => raw_val.to_string(),
|
||||
Some(s) => s.decrypt(k),
|
||||
None => k.to_string(),
|
||||
}
|
||||
} else {
|
||||
raw_val.to_string()
|
||||
};
|
||||
Some((key, val))
|
||||
})
|
||||
.collect(),
|
||||
None => vec![],
|
||||
};
|
||||
k.to_string()
|
||||
}
|
||||
});
|
||||
|
||||
Ok(DataSourceConfig {
|
||||
url,
|
||||
headers,
|
||||
api_key,
|
||||
})
|
||||
let headers = match v["headers"].as_array() {
|
||||
Some(arr) => arr
|
||||
.iter()
|
||||
.filter_map(|h| {
|
||||
let pair = h.as_array()?;
|
||||
let key: String = pair[0].as_str()?.into();
|
||||
let raw_val: &str = pair[1].as_str()?;
|
||||
let val = if encrypted && is_sensitive_key(&key) {
|
||||
match secrets {
|
||||
Some(s) => s.decrypt(raw_val),
|
||||
None => raw_val.to_string(),
|
||||
}
|
||||
} else {
|
||||
raw_val.to_string()
|
||||
};
|
||||
Some((key, val))
|
||||
})
|
||||
.collect(),
|
||||
None => vec![],
|
||||
};
|
||||
|
||||
Ok(DataSourceConfig::External {
|
||||
url,
|
||||
headers,
|
||||
api_key,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn data_source_from_row(
|
||||
|
||||
@@ -36,7 +36,7 @@ fn weather_source() -> DataSource {
|
||||
name: "openweather".into(),
|
||||
source_type: DataSourceType::Weather,
|
||||
poll_interval: Duration::from_secs(300),
|
||||
config: DataSourceConfig {
|
||||
config: DataSourceConfig::External {
|
||||
url: Some("https://api.openweather.org".into()),
|
||||
headers: vec![],
|
||||
api_key: Some("test-key".into()),
|
||||
@@ -125,8 +125,13 @@ async fn save_and_retrieve_data_source() {
|
||||
assert_eq!(ds.name, "openweather");
|
||||
assert_eq!(ds.source_type, DataSourceType::Weather);
|
||||
assert_eq!(ds.poll_interval, Duration::from_secs(300));
|
||||
assert_eq!(ds.config.url, Some("https://api.openweather.org".into()));
|
||||
assert_eq!(ds.config.api_key, Some("test-key".into()));
|
||||
match &ds.config {
|
||||
DataSourceConfig::External { url, api_key, .. } => {
|
||||
assert_eq!(*url, Some("https://api.openweather.org".into()));
|
||||
assert_eq!(*api_key, Some("test-key".into()));
|
||||
}
|
||||
_ => panic!("expected External config"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -171,9 +171,7 @@ async fn create_and_get_data_source() {
|
||||
"name": "weather_api",
|
||||
"source_type": "weather",
|
||||
"poll_interval_secs": 300,
|
||||
"url": "https://api.openweather.org",
|
||||
"api_key": "test-key",
|
||||
"headers": []
|
||||
"config": {"type": "external", "url": "https://api.openweather.org", "api_key": "test-key", "headers": []}
|
||||
}"#;
|
||||
|
||||
let resp = app
|
||||
|
||||
@@ -47,15 +47,23 @@ impl DataSourcePort for HttpJsonAdapter {
|
||||
type Error = HttpJsonError;
|
||||
|
||||
async fn poll(&self, source: &DataSource) -> Result<Value, Self::Error> {
|
||||
let url = source.config.url.as_ref().ok_or(HttpJsonError::NoUrl)?;
|
||||
let domain::DataSourceConfig::External {
|
||||
ref url,
|
||||
ref headers,
|
||||
ref api_key,
|
||||
} = source.config
|
||||
else {
|
||||
return Err(HttpJsonError::NoUrl);
|
||||
};
|
||||
let url = url.as_ref().ok_or(HttpJsonError::NoUrl)?;
|
||||
|
||||
let mut req = self.client.get(url);
|
||||
|
||||
for (key, val) in &source.config.headers {
|
||||
for (key, val) in headers {
|
||||
req = req.header(key, val);
|
||||
}
|
||||
|
||||
if let Some(api_key) = &source.config.api_key {
|
||||
if let Some(api_key) = api_key {
|
||||
req = req.header("Authorization", format!("Bearer {api_key}"));
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ fn make_source(url: String) -> DataSource {
|
||||
name: "test".into(),
|
||||
source_type: DataSourceType::HttpJson,
|
||||
poll_interval: Duration::from_secs(60),
|
||||
config: DataSourceConfig {
|
||||
config: DataSourceConfig::External {
|
||||
url: Some(url),
|
||||
headers: vec![],
|
||||
api_key: None,
|
||||
@@ -82,7 +82,7 @@ async fn returns_error_when_no_url() {
|
||||
name: "bad".into(),
|
||||
source_type: DataSourceType::HttpJson,
|
||||
poll_interval: Duration::from_secs(60),
|
||||
config: DataSourceConfig {
|
||||
config: DataSourceConfig::External {
|
||||
url: None,
|
||||
headers: vec![],
|
||||
api_key: None,
|
||||
|
||||
@@ -38,11 +38,19 @@ impl DataSourcePort for MediaAdapter {
|
||||
type Error = MediaError;
|
||||
|
||||
async fn poll(&self, source: &DataSource) -> Result<Value, Self::Error> {
|
||||
let base_url = source.config.url.as_ref().ok_or(MediaError::NoUrl)?;
|
||||
let username = find_header(&source.config.headers, "username")
|
||||
.ok_or(MediaError::MissingField("username"))?;
|
||||
let password = find_header(&source.config.headers, "password")
|
||||
.ok_or(MediaError::MissingField("password"))?;
|
||||
let domain::DataSourceConfig::External {
|
||||
ref url,
|
||||
ref headers,
|
||||
..
|
||||
} = source.config
|
||||
else {
|
||||
return Err(MediaError::NoUrl);
|
||||
};
|
||||
let base_url = url.as_ref().ok_or(MediaError::NoUrl)?;
|
||||
let username =
|
||||
find_header(headers, "username").ok_or(MediaError::MissingField("username"))?;
|
||||
let password =
|
||||
find_header(headers, "password").ok_or(MediaError::MissingField("password"))?;
|
||||
|
||||
let salt: String = (0..12).map(|_| fastrand::alphanumeric()).collect();
|
||||
let token = subsonic_token(password, &salt);
|
||||
|
||||
@@ -45,7 +45,7 @@ fn make_source(url: String) -> DataSource {
|
||||
name: "navidrome".into(),
|
||||
source_type: DataSourceType::Media,
|
||||
poll_interval: Duration::from_secs(5),
|
||||
config: DataSourceConfig {
|
||||
config: DataSourceConfig::External {
|
||||
url: Some(url),
|
||||
headers: vec![
|
||||
("username".into(), "test".into()),
|
||||
|
||||
@@ -28,7 +28,10 @@ impl DataSourcePort for RssAdapter {
|
||||
type Error = RssError;
|
||||
|
||||
async fn poll(&self, source: &DataSource) -> Result<Value, Self::Error> {
|
||||
let url = source.config.url.as_ref().ok_or(RssError::NoUrl)?;
|
||||
let domain::DataSourceConfig::External { ref url, .. } = source.config else {
|
||||
return Err(RssError::NoUrl);
|
||||
};
|
||||
let url = url.as_ref().ok_or(RssError::NoUrl)?;
|
||||
|
||||
let resp = self
|
||||
.client
|
||||
|
||||
@@ -2,60 +2,128 @@ use domain::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum DataSourceConfigDto {
|
||||
#[serde(rename = "external")]
|
||||
External {
|
||||
#[serde(default)]
|
||||
url: Option<String>,
|
||||
#[serde(default)]
|
||||
api_key: Option<String>,
|
||||
#[serde(default)]
|
||||
headers: Vec<(String, String)>,
|
||||
},
|
||||
#[serde(rename = "clock")]
|
||||
Clock {
|
||||
#[serde(default = "default_clock_format")]
|
||||
format: String,
|
||||
#[serde(default = "default_timezone")]
|
||||
timezone: String,
|
||||
},
|
||||
#[serde(rename = "static_text")]
|
||||
StaticText {
|
||||
#[serde(default)]
|
||||
text: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn default_clock_format() -> String {
|
||||
"%H:%M:%S".into()
|
||||
}
|
||||
|
||||
fn default_timezone() -> String {
|
||||
"UTC".into()
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct DataSourceDto {
|
||||
pub id: u16,
|
||||
pub name: String,
|
||||
pub source_type: String,
|
||||
pub poll_interval_secs: u64,
|
||||
pub url: Option<String>,
|
||||
pub api_key: Option<String>,
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub config: DataSourceConfigDto,
|
||||
}
|
||||
|
||||
fn source_type_to_str(t: &DataSourceType) -> &'static str {
|
||||
match t {
|
||||
DataSourceType::Weather => "weather",
|
||||
DataSourceType::Media => "media",
|
||||
DataSourceType::Rss => "rss",
|
||||
DataSourceType::HttpJson => "http_json",
|
||||
DataSourceType::Webhook => "webhook",
|
||||
DataSourceType::Clock => "clock",
|
||||
DataSourceType::StaticText => "static_text",
|
||||
}
|
||||
}
|
||||
|
||||
fn source_type_from_str(s: &str) -> Result<DataSourceType, String> {
|
||||
match s {
|
||||
"weather" => Ok(DataSourceType::Weather),
|
||||
"media" => Ok(DataSourceType::Media),
|
||||
"rss" => Ok(DataSourceType::Rss),
|
||||
"http_json" => Ok(DataSourceType::HttpJson),
|
||||
"webhook" => Ok(DataSourceType::Webhook),
|
||||
"clock" => Ok(DataSourceType::Clock),
|
||||
"static_text" => Ok(DataSourceType::StaticText),
|
||||
t => Err(format!("unknown source_type: {t}")),
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&DataSource> for DataSourceDto {
|
||||
fn from(ds: &DataSource) -> Self {
|
||||
let config = match &ds.config {
|
||||
DataSourceConfig::External {
|
||||
url,
|
||||
api_key,
|
||||
headers,
|
||||
} => DataSourceConfigDto::External {
|
||||
url: url.clone(),
|
||||
api_key: api_key.clone(),
|
||||
headers: headers.clone(),
|
||||
},
|
||||
DataSourceConfig::Clock { format, timezone } => DataSourceConfigDto::Clock {
|
||||
format: format.clone(),
|
||||
timezone: timezone.clone(),
|
||||
},
|
||||
DataSourceConfig::StaticText { text } => {
|
||||
DataSourceConfigDto::StaticText { text: text.clone() }
|
||||
}
|
||||
};
|
||||
Self {
|
||||
id: ds.id,
|
||||
name: ds.name.clone(),
|
||||
source_type: match ds.source_type {
|
||||
DataSourceType::Weather => "weather",
|
||||
DataSourceType::Media => "media",
|
||||
|
||||
DataSourceType::Rss => "rss",
|
||||
DataSourceType::HttpJson => "http_json",
|
||||
DataSourceType::Webhook => "webhook",
|
||||
}
|
||||
.into(),
|
||||
source_type: source_type_to_str(&ds.source_type).into(),
|
||||
poll_interval_secs: ds.poll_interval.as_secs(),
|
||||
url: ds.config.url.clone(),
|
||||
api_key: ds.config.api_key.clone(),
|
||||
headers: ds.config.headers.clone(),
|
||||
config,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DataSourceDto {
|
||||
pub fn into_domain(self) -> Result<DataSource, String> {
|
||||
let source_type = match self.source_type.as_str() {
|
||||
"weather" => DataSourceType::Weather,
|
||||
"media" => DataSourceType::Media,
|
||||
|
||||
"rss" => DataSourceType::Rss,
|
||||
"http_json" => DataSourceType::HttpJson,
|
||||
"webhook" => DataSourceType::Webhook,
|
||||
t => return Err(format!("unknown source_type: {t}")),
|
||||
let source_type = source_type_from_str(&self.source_type)?;
|
||||
let config = match self.config {
|
||||
DataSourceConfigDto::External {
|
||||
url,
|
||||
api_key,
|
||||
headers,
|
||||
} => DataSourceConfig::External {
|
||||
url,
|
||||
api_key,
|
||||
headers,
|
||||
},
|
||||
DataSourceConfigDto::Clock { format, timezone } => {
|
||||
DataSourceConfig::Clock { format, timezone }
|
||||
}
|
||||
DataSourceConfigDto::StaticText { text } => DataSourceConfig::StaticText { text },
|
||||
};
|
||||
Ok(DataSource {
|
||||
id: self.id,
|
||||
name: self.name,
|
||||
source_type,
|
||||
poll_interval: Duration::from_secs(self.poll_interval_secs),
|
||||
config: DataSourceConfig {
|
||||
url: self.url,
|
||||
api_key: self.api_key,
|
||||
headers: self.headers,
|
||||
},
|
||||
config,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ async fn create_data_source_rejects_invalid() {
|
||||
name: "bad".into(),
|
||||
source_type: DataSourceType::HttpJson,
|
||||
poll_interval: Duration::from_secs(60),
|
||||
config: DataSourceConfig {
|
||||
config: DataSourceConfig::External {
|
||||
url: None,
|
||||
headers: vec![],
|
||||
api_key: None,
|
||||
@@ -70,7 +70,7 @@ async fn create_data_source_persists_valid_and_emits_event() {
|
||||
name: "weather".into(),
|
||||
source_type: DataSourceType::Weather,
|
||||
poll_interval: Duration::from_secs(300),
|
||||
config: DataSourceConfig {
|
||||
config: DataSourceConfig::External {
|
||||
url: Some("https://api.weather.com".into()),
|
||||
headers: vec![],
|
||||
api_key: None,
|
||||
|
||||
@@ -19,3 +19,5 @@ anyhow.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
dotenvy.workspace = true
|
||||
chrono.workspace = true
|
||||
chrono-tz.workspace = true
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
use anyhow::Result;
|
||||
use application::DataProjection;
|
||||
use chrono::Utc;
|
||||
use chrono_tz::Tz;
|
||||
use config_sqlite::SqliteConfigStore;
|
||||
use domain::{
|
||||
BroadcastPort, ConfigRepository, DataSource, DataSourcePort, DataSourceType, Value, WidgetState,
|
||||
BroadcastPort, ConfigRepository, DataSource, DataSourceConfig, DataSourcePort, DataSourceType,
|
||||
Value, WidgetState,
|
||||
};
|
||||
use http_json::HttpJsonAdapter;
|
||||
use media_adapter::MediaAdapter;
|
||||
use rss_adapter::RssAdapter;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tcp_server::TcpBroadcaster;
|
||||
@@ -117,14 +120,6 @@ async fn poll_loop(
|
||||
}
|
||||
};
|
||||
|
||||
let layout = match config.get_layout().await {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
warn!(error = %e, "failed to fetch layout");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let changed: Vec<(u16, WidgetState)> = projection
|
||||
.apply_poll_result(source.id, &result, &widgets)
|
||||
.await;
|
||||
@@ -137,9 +132,7 @@ async fn poll_loop(
|
||||
Some((*id, hint, state.clone()))
|
||||
})
|
||||
.collect();
|
||||
if let Some(l) = &layout
|
||||
&& let Err(e) = broadcaster.push_screen_update(l, &with_hints).await
|
||||
{
|
||||
if let Err(e) = broadcaster.push_data_update(&with_hints).await {
|
||||
warn!(error = %e, "failed to push update");
|
||||
}
|
||||
info!(source = %source.name, count = changed.len(), "pushed widget updates");
|
||||
@@ -166,8 +159,33 @@ async fn poll_source(
|
||||
.poll(source)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}")),
|
||||
DataSourceType::Clock => Ok(generate_clock(&source.config)),
|
||||
DataSourceType::StaticText => Ok(generate_static_text(&source.config)),
|
||||
DataSourceType::Webhook => Err(anyhow::anyhow!(
|
||||
"webhook sources are push-based, not polled"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_clock(config: &DataSourceConfig) -> Value {
|
||||
let (fmt, tz_name) = match config {
|
||||
DataSourceConfig::Clock { format, timezone } => (format.as_str(), timezone.as_str()),
|
||||
_ => ("%H:%M:%S", "UTC"),
|
||||
};
|
||||
let tz: Tz = tz_name.parse().unwrap_or(chrono_tz::UTC);
|
||||
let now = Utc::now().with_timezone(&tz);
|
||||
let formatted = now.format(fmt).to_string();
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("time".into(), Value::String(formatted));
|
||||
Value::Object(map)
|
||||
}
|
||||
|
||||
fn generate_static_text(config: &DataSourceConfig) -> Value {
|
||||
let text = match config {
|
||||
DataSourceConfig::StaticText { text } => text.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("text".into(), Value::String(text));
|
||||
Value::Object(map)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ use embedded_graphics::{
|
||||
mono_font::{ascii::FONT_6X10, ascii::FONT_10X20, MonoTextStyle},
|
||||
pixelcolor::Rgb565,
|
||||
prelude::*,
|
||||
primitives::{PrimitiveStyle, Rectangle},
|
||||
primitives::{Circle, PrimitiveStyle, Rectangle},
|
||||
text::Text,
|
||||
};
|
||||
|
||||
@@ -27,6 +27,7 @@ pub struct Esp32DisplayAdapter {
|
||||
trait ErasedDisplay {
|
||||
fn draw_text_span(&mut self, text: &str, x: u16, y: u16, color: Rgb565, font: FontSize) -> Result<(), DisplayError>;
|
||||
fn fill_rect(&mut self, bounds: BoundingBox, color: Rgb565) -> Result<(), DisplayError>;
|
||||
fn fill_circle(&mut self, x: u16, y: u16, diameter: u16, color: Rgb565) -> Result<(), DisplayError>;
|
||||
fn flush(&mut self) -> Result<(), DisplayError>;
|
||||
}
|
||||
|
||||
@@ -57,6 +58,14 @@ where
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fill_circle(&mut self, x: u16, y: u16, diameter: u16, color: Rgb565) -> Result<(), DisplayError> {
|
||||
Circle::new(Point::new(x as i32, y as i32), diameter as u32)
|
||||
.into_styled(PrimitiveStyle::with_fill(color))
|
||||
.draw(self)
|
||||
.map_err(|e| DisplayError::Draw(format!("{e:?}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> Result<(), DisplayError> {
|
||||
Ok(())
|
||||
}
|
||||
@@ -100,3 +109,9 @@ impl DisplayPort for Esp32DisplayAdapter {
|
||||
self.inner.flush()
|
||||
}
|
||||
}
|
||||
|
||||
impl Esp32DisplayAdapter {
|
||||
pub fn fill_circle(&mut self, x: u16, y: u16, diameter: u16, color: Color) -> Result<(), DisplayError> {
|
||||
self.inner.fill_circle(x, y, diameter, to_rgb565(color))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ fn run_station(
|
||||
info!("Connecting WiFi...");
|
||||
match hal::wifi::init(modem, sysloop.clone(), nvs.clone(), &cfg.wifi_ssid, &cfg.wifi_pass) {
|
||||
Ok(_wifi) => {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let (tx, rx) = mpsc::channel::<tasks::RenderEvent>();
|
||||
tasks::network::spawn(cfg.server_addr, tx);
|
||||
tasks::render::run(config::SCREEN, display, rx);
|
||||
}
|
||||
|
||||
@@ -1,2 +1,9 @@
|
||||
pub mod network;
|
||||
pub mod render;
|
||||
|
||||
use protocol::ServerMessage;
|
||||
|
||||
pub enum RenderEvent {
|
||||
Server(ServerMessage),
|
||||
ConnectionStatus(bool),
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
use std::sync::mpsc;
|
||||
use std::thread;
|
||||
use client_domain::NetworkPort;
|
||||
use protocol::{ServerMessage, decode_server_message};
|
||||
use protocol::decode_server_message;
|
||||
use super::RenderEvent;
|
||||
use crate::config::{NET_THREAD_STACK_SIZE, NET_POLL_INTERVAL, NET_RECONNECT_DELAY};
|
||||
use crate::adapters::network::Esp32Network;
|
||||
use log::*;
|
||||
|
||||
pub fn spawn(server_addr: String, tx: mpsc::Sender<ServerMessage>) {
|
||||
pub fn spawn(server_addr: String, tx: mpsc::Sender<RenderEvent>) {
|
||||
thread::Builder::new()
|
||||
.stack_size(NET_THREAD_STACK_SIZE)
|
||||
.name("net".into())
|
||||
@@ -14,16 +15,20 @@ pub fn spawn(server_addr: String, tx: mpsc::Sender<ServerMessage>) {
|
||||
.expect("failed to spawn network thread");
|
||||
}
|
||||
|
||||
fn run(server_addr: String, tx: mpsc::Sender<ServerMessage>) {
|
||||
fn run(server_addr: String, tx: mpsc::Sender<RenderEvent>) {
|
||||
let mut net = Esp32Network::new();
|
||||
|
||||
loop {
|
||||
if !net.is_connected() {
|
||||
info!("Connecting to server {server_addr}...");
|
||||
match net.connect(&server_addr) {
|
||||
Ok(()) => info!("Server connected"),
|
||||
Ok(()) => {
|
||||
info!("Server connected");
|
||||
let _ = tx.send(RenderEvent::ConnectionStatus(true));
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Connection failed: {e}, retrying...");
|
||||
let _ = tx.send(RenderEvent::ConnectionStatus(false));
|
||||
thread::sleep(NET_RECONNECT_DELAY);
|
||||
continue;
|
||||
}
|
||||
@@ -33,7 +38,7 @@ fn run(server_addr: String, tx: mpsc::Sender<ServerMessage>) {
|
||||
match net.receive() {
|
||||
Ok(Some(payload)) => {
|
||||
match decode_server_message(&payload) {
|
||||
Ok(msg) => { let _ = tx.send(msg); }
|
||||
Ok(msg) => { let _ = tx.send(RenderEvent::Server(msg)); }
|
||||
Err(e) => error!("Decode error: {e}"),
|
||||
}
|
||||
}
|
||||
@@ -43,6 +48,7 @@ fn run(server_addr: String, tx: mpsc::Sender<ServerMessage>) {
|
||||
Err(e) => {
|
||||
error!("Receive error: {e}, reconnecting...");
|
||||
let _ = net.disconnect();
|
||||
let _ = tx.send(RenderEvent::ConnectionStatus(false));
|
||||
thread::sleep(NET_RECONNECT_DELAY);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,16 +2,21 @@ use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::collections::HashMap;
|
||||
use client_domain::{
|
||||
BoundingBox, DisplayPort, FontMetrics, RenderEngine, ScrollState, ThemeConfig,
|
||||
BoundingBox, Color, DisplayPort, FontMetrics, RenderEngine, ScrollState, ThemeConfig,
|
||||
};
|
||||
use client_application::{ClientApp, RepaintCommand};
|
||||
use domain::{DisplayHint, Value};
|
||||
use protocol::ServerMessage;
|
||||
use super::RenderEvent;
|
||||
use crate::config::RENDER_POLL_INTERVAL;
|
||||
use crate::adapters::display::Esp32DisplayAdapter;
|
||||
use log::*;
|
||||
|
||||
const SCROLL_TICK: Duration = Duration::from_millis(50);
|
||||
const INDICATOR_DIAMETER: u16 = 8;
|
||||
const INDICATOR_MARGIN: u16 = 4;
|
||||
const COLOR_CONNECTED: Color = Color(0, 200, 0);
|
||||
const COLOR_DISCONNECTED: Color = Color(200, 0, 0);
|
||||
|
||||
struct WidgetCache {
|
||||
hint: DisplayHint,
|
||||
@@ -23,7 +28,7 @@ struct WidgetCache {
|
||||
pub fn run(
|
||||
screen: BoundingBox,
|
||||
mut display: Esp32DisplayAdapter,
|
||||
rx: mpsc::Receiver<ServerMessage>,
|
||||
rx: mpsc::Receiver<RenderEvent>,
|
||||
) {
|
||||
let metrics = FontMetrics {
|
||||
small: (6, 10),
|
||||
@@ -34,13 +39,23 @@ pub fn run(
|
||||
let mut widgets: HashMap<u16, WidgetCache> = HashMap::new();
|
||||
let mut first_update = true;
|
||||
let mut last_tick = Instant::now();
|
||||
let mut connected = false;
|
||||
|
||||
info!("Render loop started");
|
||||
draw_indicator(&mut display, screen, connected);
|
||||
display.flush().unwrap();
|
||||
|
||||
loop {
|
||||
let timeout = RENDER_POLL_INTERVAL.min(SCROLL_TICK);
|
||||
match rx.recv_timeout(timeout) {
|
||||
Ok(msg) => {
|
||||
Ok(RenderEvent::ConnectionStatus(status)) => {
|
||||
if status != connected {
|
||||
connected = status;
|
||||
draw_indicator(&mut display, screen, connected);
|
||||
display.flush().unwrap();
|
||||
}
|
||||
}
|
||||
Ok(RenderEvent::Server(msg)) => {
|
||||
let is_screen_update = matches!(msg, ServerMessage::ScreenUpdate { .. });
|
||||
let repaints = app.handle_message(msg);
|
||||
|
||||
@@ -49,19 +64,20 @@ pub fn run(
|
||||
engine.set_theme(app.theme().clone());
|
||||
}
|
||||
|
||||
let bg = engine.theme().background;
|
||||
if !repaints.is_empty() && (first_update || is_screen_update || theme_changed) {
|
||||
let bg = engine.theme().background;
|
||||
display.fill_rect(screen, bg).unwrap();
|
||||
first_update = false;
|
||||
}
|
||||
|
||||
for cmd in &repaints {
|
||||
let cache = update_cache(&engine, cmd);
|
||||
display.fill_rect(cache.bounds, bg).unwrap();
|
||||
draw_widget(&engine, &mut display, &cache);
|
||||
widgets.insert(cmd.widget_id, cache);
|
||||
}
|
||||
|
||||
if !repaints.is_empty() {
|
||||
draw_indicator(&mut display, screen, connected);
|
||||
display.flush().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -86,11 +102,19 @@ pub fn run(
|
||||
}
|
||||
}
|
||||
if needs_flush {
|
||||
draw_indicator(&mut display, screen, connected);
|
||||
display.flush().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_indicator(display: &mut Esp32DisplayAdapter, screen: BoundingBox, connected: bool) {
|
||||
let color = if connected { COLOR_CONNECTED } else { COLOR_DISCONNECTED };
|
||||
let x = screen.x + screen.width - INDICATOR_DIAMETER - INDICATOR_MARGIN;
|
||||
let y = screen.y + screen.height - INDICATOR_DIAMETER - INDICATOR_MARGIN;
|
||||
display.fill_circle(x, y, INDICATOR_DIAMETER, color).unwrap();
|
||||
}
|
||||
|
||||
fn update_cache(engine: &RenderEngine, cmd: &RepaintCommand) -> WidgetCache {
|
||||
let hint: DisplayHint = cmd.display_hint.clone().into();
|
||||
let data: Vec<(String, Value)> = cmd.state.data
|
||||
|
||||
@@ -9,13 +9,24 @@ pub enum DataSourceType {
|
||||
Rss,
|
||||
HttpJson,
|
||||
Webhook,
|
||||
Clock,
|
||||
StaticText,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DataSourceConfig {
|
||||
pub url: Option<String>,
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub api_key: Option<String>,
|
||||
pub enum DataSourceConfig {
|
||||
External {
|
||||
url: Option<String>,
|
||||
headers: Vec<(String, String)>,
|
||||
api_key: Option<String>,
|
||||
},
|
||||
Clock {
|
||||
format: String,
|
||||
timezone: String,
|
||||
},
|
||||
StaticText {
|
||||
text: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -38,18 +49,28 @@ impl DataSource {
|
||||
pub fn validate(&self) -> Vec<DataSourceValidationError> {
|
||||
let mut errors = Vec::new();
|
||||
|
||||
let is_webhook = self.source_type == DataSourceType::Webhook;
|
||||
|
||||
if is_webhook {
|
||||
if !self.poll_interval.is_zero() {
|
||||
errors.push(DataSourceValidationError::PollIntervalNotAllowed);
|
||||
match self.source_type {
|
||||
DataSourceType::Webhook => {
|
||||
if !self.poll_interval.is_zero() {
|
||||
errors.push(DataSourceValidationError::PollIntervalNotAllowed);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if self.poll_interval.is_zero() {
|
||||
errors.push(DataSourceValidationError::PollIntervalRequired);
|
||||
DataSourceType::Clock | DataSourceType::StaticText => {
|
||||
// Internal sources: poll_interval optional, no url needed
|
||||
}
|
||||
if self.requires_url() && self.config.url.is_none() {
|
||||
errors.push(DataSourceValidationError::UrlRequired);
|
||||
_ => {
|
||||
if self.poll_interval.is_zero() {
|
||||
errors.push(DataSourceValidationError::PollIntervalRequired);
|
||||
}
|
||||
if self.requires_url() {
|
||||
let has_url = matches!(
|
||||
&self.config,
|
||||
DataSourceConfig::External { url: Some(_), .. }
|
||||
);
|
||||
if !has_url {
|
||||
errors.push(DataSourceValidationError::UrlRequired);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,15 @@ impl WidgetConfig {
|
||||
}
|
||||
|
||||
pub fn extract(&self, raw: &Value) -> WidgetState {
|
||||
let has_mappings = self.mappings.iter().any(|m| !m.source_path.is_empty());
|
||||
if !has_mappings {
|
||||
let data = match raw {
|
||||
Value::Object(map) => map.clone(),
|
||||
_ => BTreeMap::new(),
|
||||
};
|
||||
return WidgetState { data, error: None };
|
||||
}
|
||||
|
||||
let budget = self.max_data_size as usize;
|
||||
let mut used = 0usize;
|
||||
let mut data = BTreeMap::new();
|
||||
|
||||
@@ -7,7 +7,7 @@ fn make_source(source_type: DataSourceType, url: Option<&str>, poll: Duration) -
|
||||
name: "test".into(),
|
||||
source_type,
|
||||
poll_interval: poll,
|
||||
config: DataSourceConfig {
|
||||
config: DataSourceConfig::External {
|
||||
url: url.map(Into::into),
|
||||
headers: vec![],
|
||||
api_key: None,
|
||||
|
||||
Reference in New Issue
Block a user