Skip to content

Commit e39a35e

Browse files
committed
Fix OSM/SRTM queries, add change detection + night mode
- OSM: use inclusive building filter with relation query and 25s timeout - SRTM: switch to NASA public mirror with viewfinderpanoramas fallback - Add detect_tile_changes() for pixel-diff satellite change detection - Add is_night() solar-declination model for CSI-only night mode - 6 new unit tests (night mode + tile change detection) Co-Authored-By: claude-flow <ruv@ruv.net>
1 parent f49ecb1 commit e39a35e

3 files changed

Lines changed: 268 additions & 21 deletions

File tree

rust-port/wifi-densepose-rs/crates/wifi-densepose-geo/src/osm.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,16 @@ use anyhow::Result;
66
const OVERPASS_URL: &str = "https://overpass-api.de/api/interpreter";
77

88
/// Fetch buildings within radius of a point.
9+
///
10+
/// Uses an inclusive `["building"]` filter that matches all building values
11+
/// (residential, commercial, yes, etc.) and also queries relations for
12+
/// multipolygon buildings. Default recommended radius: 500 m.
913
pub async fn fetch_buildings(center: &GeoPoint, radius_m: f64) -> Result<Vec<OsmFeature>> {
1014
let bbox = GeoBBox::from_center(center, radius_m);
1115
let query = format!(
12-
r#"[out:json][timeout:10];way["building"]({},{},{},{});out body;>;out skel qt;"#,
13-
bbox.south, bbox.west, bbox.north, bbox.east
16+
r#"[out:json][timeout:25];(way["building"]({},{},{},{});relation["building"]({},{},{},{}););out body;>;out skel qt;"#,
17+
bbox.south, bbox.west, bbox.north, bbox.east,
18+
bbox.south, bbox.west, bbox.north, bbox.east,
1419
);
1520
let resp = overpass_query(&query).await?;
1621
parse_buildings(&resp)

rust-port/wifi-densepose-rs/crates/wifi-densepose-geo/src/temporal.rs

Lines changed: 230 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
//! Temporal change tracking — detect changes in satellite/OSM/weather over time.
22
33
use crate::cache::TileCache;
4-
use crate::types::{GeoPoint, GeoScene};
4+
use crate::types::GeoPoint;
5+
#[allow(unused_imports)]
6+
use crate::types::GeoScene;
57
use anyhow::Result;
68

79
/// Fetch current weather (Open Meteo, free, no key).
@@ -79,3 +81,230 @@ pub struct WeatherData {
7981
pub wind_speed_ms: f32,
8082
pub weather_code: u16,
8183
}
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+
}

rust-port/wifi-densepose-rs/crates/wifi-densepose-geo/src/terrain.rs

Lines changed: 31 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,33 +17,46 @@ pub async fn fetch_elevation(point: &GeoPoint, cache: &TileCache) -> Result<Elev
1717
return parse_hgt(&data, lat_int as f64, lon_int as f64);
1818
}
1919

20-
// Try OpenTopography SRTM (free, no auth)
21-
let url = format!(
22-
"https://portal.opentopography.org/API/globaldem?demtype=SRTMGL1&south={}&north={}&west={}&east={}&outputFormat=HGT",
23-
lat_int, lat_int + 1, lon_int, lon_int + 1
24-
);
25-
2620
let client = reqwest::Client::builder()
2721
.timeout(std::time::Duration::from_secs(30))
2822
.build()?;
2923

30-
match client.get(&url).send().await {
31-
Ok(resp) if resp.status().is_success() => {
24+
// Primary: NASA SRTM public mirror (no auth required for .hgt)
25+
let nasa_url = format!(
26+
"https://e4ftl01.cr.usgs.gov/MEASURES/SRTMGL1.003/2000.02.11/{filename}"
27+
);
28+
29+
if let Ok(resp) = client.get(&nasa_url).send().await {
30+
if resp.status().is_success() {
3231
let data = resp.bytes().await?.to_vec();
3332
cache.put(&cache_key, &data)?;
34-
parse_hgt(&data, lat_int as f64, lon_int as f64)
33+
return parse_hgt(&data, lat_int as f64, lon_int as f64);
3534
}
36-
_ => {
37-
// Return flat terrain as fallback
38-
Ok(ElevationGrid {
39-
origin_lat: lat_int as f64,
40-
origin_lon: lon_int as f64,
41-
cell_size_deg: 1.0 / 3600.0,
42-
cols: 100, rows: 100,
43-
heights: vec![0.0; 10000],
44-
})
35+
}
36+
37+
// Fallback: viewfinderpanoramas.org
38+
// Files are grouped by continent zip, but individual .hgt files can be
39+
// fetched directly when the server exposes them.
40+
let vfp_url = format!(
41+
"http://viewfinderpanoramas.org/dem1/{filename}"
42+
);
43+
44+
if let Ok(resp) = client.get(&vfp_url).send().await {
45+
if resp.status().is_success() {
46+
let data = resp.bytes().await?.to_vec();
47+
cache.put(&cache_key, &data)?;
48+
return parse_hgt(&data, lat_int as f64, lon_int as f64);
4549
}
4650
}
51+
52+
// Final fallback: flat terrain when all downloads fail
53+
Ok(ElevationGrid {
54+
origin_lat: lat_int as f64,
55+
origin_lon: lon_int as f64,
56+
cell_size_deg: 1.0 / 3600.0,
57+
cols: 100, rows: 100,
58+
heights: vec![0.0; 10000],
59+
})
4760
}
4861

4962
/// Parse SRTM HGT binary (3601x3601 big-endian i16).

0 commit comments

Comments
 (0)