mirror of
https://github.com/cjfranko/NTP-Timeturner.git
synced 2025-11-08 18:32:02 +00:00
fixed issues around delta
This commit is contained in:
parent
2d57d05908
commit
7527a30aa9
1 changed files with 144 additions and 88 deletions
232
src/ui.rs
232
src/ui.rs
|
|
@ -1,6 +1,4 @@
|
||||||
// src/ui.rs
|
use std::{
|
||||||
|
|
||||||
use std::{
|
|
||||||
io::{stdout, Write},
|
io::{stdout, Write},
|
||||||
process::{self, Command},
|
process::{self, Command},
|
||||||
sync::{Arc, Mutex},
|
sync::{Arc, Mutex},
|
||||||
|
|
@ -11,7 +9,7 @@ use std::collections::VecDeque;
|
||||||
|
|
||||||
use chrono::{
|
use chrono::{
|
||||||
DateTime, Local, Timelike, Utc,
|
DateTime, Local, Timelike, Utc,
|
||||||
Duration as ChronoDuration,
|
NaiveTime, TimeZone,
|
||||||
};
|
};
|
||||||
use crossterm::{
|
use crossterm::{
|
||||||
cursor::{Hide, MoveTo, Show},
|
cursor::{Hide, MoveTo, Show},
|
||||||
|
|
@ -80,11 +78,19 @@ pub fn start_ui(
|
||||||
let measured = raw - hw_offset_ms;
|
let measured = raw - hw_offset_ms;
|
||||||
st.record_offset(measured);
|
st.record_offset(measured);
|
||||||
|
|
||||||
// Δ via UTC lane
|
// Δ = system clock - LTC timecode (use LOCAL time)
|
||||||
let sub_ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0).round() as i64;
|
let today_local = Local::now().date_naive();
|
||||||
let ltc_arrival = frame.timestamp
|
let ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0)
|
||||||
+ ChronoDuration::milliseconds(hw_offset_ms + sub_ms);
|
.round() as u32;
|
||||||
let delta_ms = (Utc::now() - ltc_arrival).num_milliseconds();
|
let tc_naive = NaiveTime::from_hms_milli_opt(
|
||||||
|
frame.hours, frame.minutes, frame.seconds, ms,
|
||||||
|
).expect("Invalid LTC timecode");
|
||||||
|
let naive_dt_local = today_local.and_time(tc_naive);
|
||||||
|
let dt_local = Local
|
||||||
|
.from_local_datetime(&naive_dt_local)
|
||||||
|
.single()
|
||||||
|
.expect("Invalid local time");
|
||||||
|
let delta_ms = (Local::now() - dt_local).num_milliseconds();
|
||||||
st.record_clock_delta(delta_ms);
|
st.record_clock_delta(delta_ms);
|
||||||
} else {
|
} else {
|
||||||
st.clear_offsets();
|
st.clear_offsets();
|
||||||
|
|
@ -94,7 +100,7 @@ pub fn start_ui(
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4️⃣ averages & status override
|
// 4️⃣ averages & status override
|
||||||
let (avg_ms, _avg_frames, _, lock_ratio, avg_delta) = {
|
let (avg_jitter_ms, _avg_frames, _, lock_ratio, avg_delta) = {
|
||||||
let st = state.lock().unwrap();
|
let st = state.lock().unwrap();
|
||||||
(
|
(
|
||||||
st.average_jitter(),
|
st.average_jitter(),
|
||||||
|
|
@ -105,36 +111,54 @@ pub fn start_ui(
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
let sync_status = if avg_delta.abs() <= 5 { "IN SYNC" } else { "OUT OF SYNC" };
|
// 5️⃣ cache Δ once/sec & Δ in frames
|
||||||
|
|
||||||
// 5️⃣ cache Δ once/sec
|
|
||||||
if last_delta_update.elapsed() >= Duration::from_secs(1) {
|
if last_delta_update.elapsed() >= Duration::from_secs(1) {
|
||||||
cached_delta_ms = avg_delta;
|
cached_delta_ms = avg_delta;
|
||||||
cached_delta_frames = avg_ms; // or recalc from frame if you like
|
if let Some(frame) = &state.lock().unwrap().latest {
|
||||||
|
let frame_ms = 1000.0 / frame.frame_rate;
|
||||||
|
cached_delta_frames = ((avg_delta as f64 / frame_ms).round()) as i64;
|
||||||
|
} else {
|
||||||
|
cached_delta_frames = 0;
|
||||||
|
}
|
||||||
last_delta_update = Instant::now();
|
last_delta_update = Instant::now();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6️⃣ auto‑sync
|
// 6️⃣ sync status wording
|
||||||
if sync_status == "OUT OF SYNC" {
|
let sync_status = if cached_delta_ms.abs() <= 5 {
|
||||||
|
"IN SYNC"
|
||||||
|
} else if cached_delta_ms > 5 {
|
||||||
|
"CLOCK AHEAD"
|
||||||
|
} else {
|
||||||
|
"CLOCK BEHIND"
|
||||||
|
};
|
||||||
|
|
||||||
|
// 7️⃣ auto‑sync (same as manual but delayed)
|
||||||
|
if sync_status != "IN SYNC" {
|
||||||
if let Some(start) = out_of_sync_since {
|
if let Some(start) = out_of_sync_since {
|
||||||
if start.elapsed() >= Duration::from_secs(5) {
|
if start.elapsed() >= Duration::from_secs(5) {
|
||||||
// sync exactly to LTC arrival
|
|
||||||
if let Some(frame) = &state.lock().unwrap().latest {
|
if let Some(frame) = &state.lock().unwrap().latest {
|
||||||
let sub_ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0).round() as i64;
|
let today_local = Local::now().date_naive();
|
||||||
let ltc_arrival = frame.timestamp
|
let ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0)
|
||||||
+ ChronoDuration::milliseconds(hw_offset_ms + sub_ms);
|
.round() as u32;
|
||||||
// format from UTC instant into local time
|
let timecode = NaiveTime::from_hms_milli_opt(
|
||||||
let ts_local: DateTime<Local> =
|
frame.hours, frame.minutes, frame.seconds, ms,
|
||||||
DateTime::from(ltc_arrival);
|
).expect("Invalid LTC timecode");
|
||||||
let ts = format!(
|
let naive_dt = today_local.and_time(timecode);
|
||||||
"{:02}:{:02}:{:02}.{:03}",
|
let dt_local = Local
|
||||||
ts_local.hour(),
|
.from_local_datetime(&naive_dt)
|
||||||
ts_local.minute(),
|
.single()
|
||||||
ts_local.second(),
|
.expect("Ambiguous or invalid local time");
|
||||||
ts_local.timestamp_subsec_millis()
|
let ts = dt_local.format("%H:%M:%S.%3f").to_string();
|
||||||
);
|
|
||||||
let res = Command::new("sudo").arg("date").arg("-s").arg(&ts).status();
|
let success = Command::new("sudo")
|
||||||
let entry = if res.as_ref().map_or(false, |s| s.success()) {
|
.arg("date")
|
||||||
|
.arg("-s")
|
||||||
|
.arg(&ts)
|
||||||
|
.status()
|
||||||
|
.map(|s| s.success())
|
||||||
|
.unwrap_or(false);
|
||||||
|
|
||||||
|
let entry = if success {
|
||||||
format!("🔄 Auto‑synced to LTC: {}", ts)
|
format!("🔄 Auto‑synced to LTC: {}", ts)
|
||||||
} else {
|
} else {
|
||||||
"❌ Auto‑sync failed".into()
|
"❌ Auto‑sync failed".into()
|
||||||
|
|
@ -151,50 +175,59 @@ pub fn start_ui(
|
||||||
out_of_sync_since = None;
|
out_of_sync_since = None;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 7️⃣ header
|
// 8️⃣ header & LTC metrics display
|
||||||
queue!(
|
{
|
||||||
stdout,
|
let st = state.lock().unwrap();
|
||||||
MoveTo(0, 0), Clear(ClearType::All),
|
let opt = st.latest.as_ref();
|
||||||
MoveTo(2, 1), Print("Have Blue - NTP Timeturner"),
|
let status_str = opt.map(|f| f.status.as_str()).unwrap_or("(waiting)");
|
||||||
MoveTo(2, 2), Print(format!("Serial Port : {}", serial_port)),
|
let tc_str = match opt {
|
||||||
MoveTo(2, 3), Print(format!("Chrony Service : {}", if ntp_active { "RUNNING" } else { "MISSING" })),
|
Some(f) => format!("LTC Timecode : {:02}:{:02}:{:02}:{:02}",
|
||||||
MoveTo(2, 4), Print(format!("Interfaces : {}", interfaces.join(", "))),
|
f.hours, f.minutes, f.seconds, f.frames),
|
||||||
).unwrap();
|
None => "LTC Timecode : …".to_string(),
|
||||||
|
};
|
||||||
|
let fr_str = match opt {
|
||||||
|
Some(f) => format!("Frame Rate : {:.2}fps", f.frame_rate),
|
||||||
|
None => "Frame Rate : …".to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
// 8️⃣ LTC & system clock
|
|
||||||
if let Some(frame) = &state.lock().unwrap().latest {
|
|
||||||
queue!(
|
queue!(
|
||||||
stdout,
|
stdout,
|
||||||
MoveTo(2, 6), Print(format!("LTC Status : {}", frame.status)),
|
MoveTo(0, 0), Clear(ClearType::All),
|
||||||
MoveTo(2, 7), Print(format!("LTC Timecode : {:02}:{:02}:{:02}:{:02}",
|
MoveTo(2, 1), Print("Have Blue - NTP Timeturner"),
|
||||||
frame.hours, frame.minutes, frame.seconds, frame.frames
|
MoveTo(2, 2), Print(format!("Serial Port : {}", serial_port)),
|
||||||
)),
|
MoveTo(2, 3), Print(format!("Chrony Service : {}",
|
||||||
MoveTo(2, 8), Print(format!("Frame Rate : {:.2}fps", frame.frame_rate)),
|
if ntp_active { "RUNNING" } else { "MISSING" })),
|
||||||
).unwrap();
|
MoveTo(2, 4), Print(format!("Interfaces : {}",
|
||||||
} else {
|
interfaces.join(", "))),
|
||||||
queue!(
|
MoveTo(2, 6), Print(format!("LTC Status : {}", status_str)),
|
||||||
stdout,
|
MoveTo(2, 7), Print(tc_str),
|
||||||
MoveTo(2, 6), Print("LTC Status : (waiting)"),
|
MoveTo(2, 8), Print(fr_str),
|
||||||
MoveTo(2, 7), Print("LTC Timecode : …"),
|
|
||||||
MoveTo(2, 8), Print("Frame Rate : …"),
|
|
||||||
).unwrap();
|
).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
// show Pi’s own clock
|
// system clock
|
||||||
let now_local: DateTime<Local> = DateTime::from(Utc::now());
|
let now_local: DateTime<Local> = DateTime::from(Utc::now());
|
||||||
let sys_ts = format!(
|
let sys_ts = format!(
|
||||||
"{:02}:{:02}:{:02}.{:03}",
|
"{:02}:{:02}:{:02}.{:03}",
|
||||||
now_local.hour(),
|
now_local.hour(),
|
||||||
now_local.minute(),
|
now_local.minute(),
|
||||||
now_local.second(),
|
now_local.second(),
|
||||||
now_local.timestamp_subsec_millis()
|
now_local.timestamp_subsec_millis(),
|
||||||
);
|
);
|
||||||
queue!(stdout, MoveTo(2, 9), Print(format!("System Clock : {}", sys_ts))).unwrap();
|
queue!(stdout,
|
||||||
|
MoveTo(2, 9), Print(format!(
|
||||||
|
"System Clock : {}",
|
||||||
|
sys_ts
|
||||||
|
))).unwrap();
|
||||||
|
|
||||||
// 9️⃣ metrics
|
// Δ display
|
||||||
let dcol = if cached_delta_ms.abs() < 20 { Color::Green }
|
let dcol = if cached_delta_ms.abs() < 20 {
|
||||||
else if cached_delta_ms.abs() < 100 { Color::Yellow }
|
Color::Green
|
||||||
else { Color::Red };
|
} else if cached_delta_ms.abs() < 100 {
|
||||||
|
Color::Yellow
|
||||||
|
} else {
|
||||||
|
Color::Red
|
||||||
|
};
|
||||||
queue!(
|
queue!(
|
||||||
stdout,
|
stdout,
|
||||||
MoveTo(2, 11), SetForegroundColor(dcol),
|
MoveTo(2, 11), SetForegroundColor(dcol),
|
||||||
|
|
@ -202,7 +235,12 @@ pub fn start_ui(
|
||||||
ResetColor,
|
ResetColor,
|
||||||
).unwrap();
|
).unwrap();
|
||||||
|
|
||||||
let scol = if sync_status == "IN SYNC" { Color::Green } else { Color::Red };
|
// sync status
|
||||||
|
let scol = if sync_status == "IN SYNC" {
|
||||||
|
Color::Green
|
||||||
|
} else {
|
||||||
|
Color::Red
|
||||||
|
};
|
||||||
queue!(
|
queue!(
|
||||||
stdout,
|
stdout,
|
||||||
MoveTo(2, 12), SetForegroundColor(scol),
|
MoveTo(2, 12), SetForegroundColor(scol),
|
||||||
|
|
@ -210,25 +248,35 @@ pub fn start_ui(
|
||||||
ResetColor,
|
ResetColor,
|
||||||
).unwrap();
|
).unwrap();
|
||||||
|
|
||||||
let jstatus = if avg_ms.abs() < 10 { "GOOD" }
|
// jitter & lock ratio
|
||||||
else if avg_ms.abs() < 40 { "AVERAGE" }
|
let jstatus = if avg_jitter_ms.abs() < 10 {
|
||||||
else { "BAD" };
|
"GOOD"
|
||||||
let jcol = if jstatus == "GOOD" { Color::Green }
|
} else if avg_jitter_ms.abs() < 40 {
|
||||||
else if jstatus == "AVERAGE" { Color::Yellow }
|
"AVERAGE"
|
||||||
else { Color::Red };
|
} else {
|
||||||
|
"BAD"
|
||||||
|
};
|
||||||
|
let jcol = if jstatus == "GOOD" {
|
||||||
|
Color::Green
|
||||||
|
} else if jstatus == "AVERAGE" {
|
||||||
|
Color::Yellow
|
||||||
|
} else {
|
||||||
|
Color::Red
|
||||||
|
};
|
||||||
queue!(
|
queue!(
|
||||||
stdout,
|
stdout,
|
||||||
MoveTo(2, 13), SetForegroundColor(jcol),
|
MoveTo(2, 13), SetForegroundColor(jcol),
|
||||||
Print(format!("Sync Jitter : {}", jstatus)),
|
Print(format!("Sync Jitter : {}", jstatus)),
|
||||||
ResetColor,
|
ResetColor,
|
||||||
).unwrap();
|
).unwrap();
|
||||||
|
|
||||||
queue!(
|
queue!(
|
||||||
stdout,
|
stdout,
|
||||||
MoveTo(2, 14), Print(format!("Lock Ratio : {:.1}% LOCK", lock_ratio)),
|
MoveTo(2, 14), Print(format!("Lock Ratio : {:.1}% LOCK",
|
||||||
|
lock_ratio
|
||||||
|
)),
|
||||||
).unwrap();
|
).unwrap();
|
||||||
|
|
||||||
// 10️⃣ footer + logs
|
// footer + logs
|
||||||
queue!(
|
queue!(
|
||||||
stdout,
|
stdout,
|
||||||
MoveTo(2, 16), Print("[S] Sync sys clock to LTC [Q] Quit"),
|
MoveTo(2, 16), Print("[S] Sync sys clock to LTC [Q] Quit"),
|
||||||
|
|
@ -239,7 +287,7 @@ pub fn start_ui(
|
||||||
|
|
||||||
stdout.flush().unwrap();
|
stdout.flush().unwrap();
|
||||||
|
|
||||||
// 11️⃣ manual sync & quit
|
// manual sync & quit
|
||||||
if poll(Duration::from_millis(50)).unwrap() {
|
if poll(Duration::from_millis(50)).unwrap() {
|
||||||
if let Event::Key(evt) = read().unwrap() {
|
if let Event::Key(evt) = read().unwrap() {
|
||||||
match evt.code {
|
match evt.code {
|
||||||
|
|
@ -250,25 +298,33 @@ pub fn start_ui(
|
||||||
}
|
}
|
||||||
KeyCode::Char(c) if c.eq_ignore_ascii_case(&'s') => {
|
KeyCode::Char(c) if c.eq_ignore_ascii_case(&'s') => {
|
||||||
if let Some(frame) = &state.lock().unwrap().latest {
|
if let Some(frame) = &state.lock().unwrap().latest {
|
||||||
// compute the exact timestamp again
|
let today_local = Local::now().date_naive();
|
||||||
let sub_ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0).round() as i64;
|
let ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0)
|
||||||
let ltc_arrival = frame.timestamp
|
.round() as u32;
|
||||||
+ ChronoDuration::milliseconds(hw_offset_ms + sub_ms);
|
let timecode = NaiveTime::from_hms_milli_opt(
|
||||||
let ts_local: DateTime<Local> = DateTime::from(ltc_arrival);
|
frame.hours, frame.minutes, frame.seconds, ms,
|
||||||
let ts = format!(
|
).expect("Invalid LTC timecode");
|
||||||
"{:02}:{:02}:{:02}.{:03}",
|
let naive_dt = today_local.and_time(timecode);
|
||||||
ts_local.hour(),
|
let dt_local = Local
|
||||||
ts_local.minute(),
|
.from_local_datetime(&naive_dt)
|
||||||
ts_local.second(),
|
.single()
|
||||||
ts_local.timestamp_subsec_millis()
|
.expect("Ambiguous or invalid local time");
|
||||||
);
|
let ts = dt_local.format("%H:%M:%S.%3f").to_string();
|
||||||
let res = Command::new("sudo").arg("date").arg("-s").arg(&ts).status();
|
|
||||||
let entry = if res.as_ref().map_or(false, |s| s.success()) {
|
let success = Command::new("sudo")
|
||||||
|
.arg("date")
|
||||||
|
.arg("-s")
|
||||||
|
.arg(&ts)
|
||||||
|
.status()
|
||||||
|
.map(|s| s.success())
|
||||||
|
.unwrap_or(false);
|
||||||
|
|
||||||
|
let entry = if success {
|
||||||
format!("✔ Synced exactly to LTC: {}", ts)
|
format!("✔ Synced exactly to LTC: {}", ts)
|
||||||
} else {
|
} else {
|
||||||
"❌ date cmd failed".into()
|
"❌ date cmd failed".into()
|
||||||
};
|
};
|
||||||
if logs.len() == 10 { logs.pop_front() }
|
if logs.len() == 10 { logs.pop_front(); }
|
||||||
logs.push_back(entry);
|
logs.push_back(entry);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue