|
1 | 1 | //! Temporal change tracking — detect changes in satellite/OSM/weather over time. |
2 | 2 |
|
3 | 3 | use crate::cache::TileCache; |
4 | | -use crate::types::{GeoPoint, GeoScene}; |
| 4 | +use crate::types::GeoPoint; |
| 5 | +#[allow(unused_imports)] |
| 6 | +use crate::types::GeoScene; |
5 | 7 | use anyhow::Result; |
6 | 8 |
|
7 | 9 | /// Fetch current weather (Open Meteo, free, no key). |
@@ -79,3 +81,230 @@ pub struct WeatherData { |
79 | 81 | pub wind_speed_ms: f32, |
80 | 82 | pub weather_code: u16, |
81 | 83 | } |
| 84 | + |
| 85 | +// --------------------------------------------------------------------------- |
| 86 | +// Satellite tile change detection |
| 87 | +// --------------------------------------------------------------------------- |
| 88 | + |
| 89 | +/// Result of comparing two tile snapshots. |
| 90 | +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] |
| 91 | +pub struct TileChangeResult { |
| 92 | + /// 0.0 = identical, 1.0 = completely different. |
| 93 | + pub diff_score: f64, |
| 94 | + /// Number of pixels that changed. |
| 95 | + pub changed_pixels: usize, |
| 96 | + /// Total pixels compared. |
| 97 | + pub total_pixels: usize, |
| 98 | +} |
| 99 | + |
| 100 | +/// Compare a newly-fetched tile against its previously-cached version. |
| 101 | +/// |
| 102 | +/// Returns a `TileChangeResult` with a diff score between 0.0 (identical) and |
| 103 | +/// 1.0 (completely different). When the diff exceeds 0.1 the function stores |
| 104 | +/// a change event as a brain memory via the local ruOS brain endpoint. |
| 105 | +pub async fn detect_tile_changes( |
| 106 | + cache_key: &str, |
| 107 | + new_data: &[u8], |
| 108 | + cache: &TileCache, |
| 109 | +) -> Result<TileChangeResult> { |
| 110 | + let previous = cache.get(cache_key); |
| 111 | + |
| 112 | + let result = match previous { |
| 113 | + Some(ref old_data) => { |
| 114 | + let total = old_data.len().max(new_data.len()).max(1); |
| 115 | + let comparable = old_data.len().min(new_data.len()); |
| 116 | + let mut changed: usize = 0; |
| 117 | + for i in 0..comparable { |
| 118 | + if old_data[i] != new_data[i] { |
| 119 | + changed += 1; |
| 120 | + } |
| 121 | + } |
| 122 | + // Any extra bytes in the longer slice count as changed. |
| 123 | + changed += total - comparable; |
| 124 | + |
| 125 | + TileChangeResult { |
| 126 | + diff_score: changed as f64 / total as f64, |
| 127 | + changed_pixels: changed, |
| 128 | + total_pixels: total, |
| 129 | + } |
| 130 | + } |
| 131 | + None => { |
| 132 | + // No previous data — treat as fully new (score 1.0). |
| 133 | + TileChangeResult { |
| 134 | + diff_score: 1.0, |
| 135 | + changed_pixels: new_data.len(), |
| 136 | + total_pixels: new_data.len().max(1), |
| 137 | + } |
| 138 | + } |
| 139 | + }; |
| 140 | + |
| 141 | + // Persist new snapshot into cache for future comparisons. |
| 142 | + cache.put(cache_key, new_data)?; |
| 143 | + |
| 144 | + // When significant change is detected, store a brain memory. |
| 145 | + if result.diff_score > 0.1 { |
| 146 | + let _ = store_change_event(cache_key, &result).await; |
| 147 | + } |
| 148 | + |
| 149 | + Ok(result) |
| 150 | +} |
| 151 | + |
| 152 | +/// Post a change event to the local ruOS brain. |
| 153 | +async fn store_change_event(cache_key: &str, result: &TileChangeResult) -> Result<()> { |
| 154 | + let client = reqwest::Client::builder() |
| 155 | + .timeout(std::time::Duration::from_secs(5)) |
| 156 | + .build()?; |
| 157 | + |
| 158 | + let body = serde_json::json!({ |
| 159 | + "category": "spatial-change", |
| 160 | + "content": format!( |
| 161 | + "Tile change detected for {cache_key}: diff={:.3}, changed={}/{}", |
| 162 | + result.diff_score, result.changed_pixels, result.total_pixels, |
| 163 | + ), |
| 164 | + }); |
| 165 | + |
| 166 | + client |
| 167 | + .post("http://127.0.0.1:9876/memories") |
| 168 | + .json(&body) |
| 169 | + .send() |
| 170 | + .await?; |
| 171 | + |
| 172 | + Ok(()) |
| 173 | +} |
| 174 | + |
| 175 | +// --------------------------------------------------------------------------- |
| 176 | +// Night mode detection |
| 177 | +// --------------------------------------------------------------------------- |
| 178 | + |
| 179 | +/// Approximate check whether the current time is "night" at a given latitude. |
| 180 | +/// |
| 181 | +/// Uses a simplified sunrise/sunset model based on the solar declination and |
| 182 | +/// hour angle. When it is night the system should rely on CSI data only |
| 183 | +/// (satellite imagery is not useful in darkness). |
| 184 | +pub fn is_night(lat_deg: f64) -> bool { |
| 185 | + let now = chrono::Utc::now(); |
| 186 | + is_night_at(lat_deg, now) |
| 187 | +} |
| 188 | + |
| 189 | +/// Testable version of [`is_night`] that accepts an explicit timestamp. |
| 190 | +pub fn is_night_at(lat_deg: f64, utc: chrono::DateTime<chrono::Utc>) -> bool { |
| 191 | + use chrono::Datelike; |
| 192 | + use std::f64::consts::PI; |
| 193 | + |
| 194 | + let day_of_year = utc.ordinal() as f64; |
| 195 | + let hour_utc = utc.timestamp() % 86400; |
| 196 | + let solar_hour = (hour_utc as f64) / 3600.0; // 0..24 |
| 197 | + |
| 198 | + // Solar declination (Spencer, 1971 — simplified) |
| 199 | + let gamma = 2.0 * PI * (day_of_year - 1.0) / 365.0; |
| 200 | + let decl = 0.006918 |
| 201 | + - 0.399912 * gamma.cos() |
| 202 | + + 0.070257 * gamma.sin() |
| 203 | + - 0.006758 * (2.0 * gamma).cos() |
| 204 | + + 0.000907 * (2.0 * gamma).sin(); |
| 205 | + |
| 206 | + let lat_rad = lat_deg.to_radians(); |
| 207 | + |
| 208 | + // Cosine of the hour angle at sunrise/sunset (geometric, no refraction) |
| 209 | + let cos_ha = -(lat_rad.tan() * decl.tan()); |
| 210 | + |
| 211 | + // Polar day / polar night |
| 212 | + if cos_ha < -1.0 { |
| 213 | + return false; // midnight sun — never night |
| 214 | + } |
| 215 | + if cos_ha > 1.0 { |
| 216 | + return true; // polar night — always night |
| 217 | + } |
| 218 | + |
| 219 | + let ha_sunrise = cos_ha.acos(); // radians, symmetric about solar noon |
| 220 | + let daylight_hours = 2.0 * ha_sunrise * 12.0 / PI; |
| 221 | + let solar_noon = 12.0; // approximation (ignores longitude offset) |
| 222 | + let sunrise = solar_noon - daylight_hours / 2.0; |
| 223 | + let sunset = solar_noon + daylight_hours / 2.0; |
| 224 | + |
| 225 | + solar_hour < sunrise || solar_hour > sunset |
| 226 | +} |
| 227 | + |
| 228 | +// --------------------------------------------------------------------------- |
| 229 | +// Tests |
| 230 | +// --------------------------------------------------------------------------- |
| 231 | + |
| 232 | +#[cfg(test)] |
| 233 | +mod tests { |
| 234 | + use super::*; |
| 235 | + |
| 236 | + #[test] |
| 237 | + fn test_is_night_at_equator_noon() { |
| 238 | + // Noon UTC at equator on March 20 — should be daytime. |
| 239 | + let dt = chrono::NaiveDate::from_ymd_opt(2025, 3, 20) |
| 240 | + .unwrap() |
| 241 | + .and_hms_opt(12, 0, 0) |
| 242 | + .unwrap() |
| 243 | + .and_utc(); |
| 244 | + assert!(!is_night_at(0.0, dt)); |
| 245 | + } |
| 246 | + |
| 247 | + #[test] |
| 248 | + fn test_is_night_at_equator_midnight() { |
| 249 | + // Midnight UTC at equator — should be night. |
| 250 | + let dt = chrono::NaiveDate::from_ymd_opt(2025, 3, 20) |
| 251 | + .unwrap() |
| 252 | + .and_hms_opt(2, 0, 0) |
| 253 | + .unwrap() |
| 254 | + .and_utc(); |
| 255 | + assert!(is_night_at(0.0, dt)); |
| 256 | + } |
| 257 | + |
| 258 | + #[test] |
| 259 | + fn test_midnight_sun_arctic() { |
| 260 | + // Late June at 70 N — midnight sun, never night. |
| 261 | + let dt = chrono::NaiveDate::from_ymd_opt(2025, 6, 21) |
| 262 | + .unwrap() |
| 263 | + .and_hms_opt(0, 0, 0) |
| 264 | + .unwrap() |
| 265 | + .and_utc(); |
| 266 | + assert!(!is_night_at(70.0, dt)); |
| 267 | + } |
| 268 | + |
| 269 | + #[test] |
| 270 | + fn test_polar_night_arctic() { |
| 271 | + // Late December at 80 N — polar night, always night. |
| 272 | + let dt = chrono::NaiveDate::from_ymd_opt(2025, 12, 21) |
| 273 | + .unwrap() |
| 274 | + .and_hms_opt(12, 0, 0) |
| 275 | + .unwrap() |
| 276 | + .and_utc(); |
| 277 | + assert!(is_night_at(80.0, dt)); |
| 278 | + } |
| 279 | + |
| 280 | + #[test] |
| 281 | + fn test_detect_tile_changes_identical() { |
| 282 | + let cache = TileCache::new("/tmp/ruview-test-tile-changes"); |
| 283 | + let data = vec![1u8, 2, 3, 4, 5]; |
| 284 | + // Prime the cache. |
| 285 | + cache.put("test_tile_ident", &data).unwrap(); |
| 286 | + |
| 287 | + let rt = tokio::runtime::Builder::new_current_thread() |
| 288 | + .enable_all() |
| 289 | + .build() |
| 290 | + .unwrap(); |
| 291 | + let result = rt.block_on(detect_tile_changes("test_tile_ident", &data, &cache)).unwrap(); |
| 292 | + assert!((result.diff_score - 0.0).abs() < 1e-9); |
| 293 | + assert_eq!(result.changed_pixels, 0); |
| 294 | + } |
| 295 | + |
| 296 | + #[test] |
| 297 | + fn test_detect_tile_changes_fully_different() { |
| 298 | + let cache = TileCache::new("/tmp/ruview-test-tile-changes"); |
| 299 | + let old = vec![0u8; 100]; |
| 300 | + let new = vec![255u8; 100]; |
| 301 | + cache.put("test_tile_diff", &old).unwrap(); |
| 302 | + |
| 303 | + let rt = tokio::runtime::Builder::new_current_thread() |
| 304 | + .enable_all() |
| 305 | + .build() |
| 306 | + .unwrap(); |
| 307 | + let result = rt.block_on(detect_tile_changes("test_tile_diff", &new, &cache)).unwrap(); |
| 308 | + assert!((result.diff_score - 1.0).abs() < 1e-9); |
| 309 | + } |
| 310 | +} |
0 commit comments