updated ui.rs to localise the system clock from ssh clock

This commit is contained in:
Chris Frankland-Wright 2025-07-21 14:33:09 +01:00
parent d40d3e5b13
commit 2d57d05908

307
src/ui.rs
View file

@ -9,7 +9,10 @@ use std::{
}; };
use std::collections::VecDeque; use std::collections::VecDeque;
use chrono::{Local, Timelike, Utc, NaiveTime, Duration as ChronoDuration, TimeZone}; use chrono::{
DateTime, Local, Timelike, Utc,
Duration as ChronoDuration,
};
use crossterm::{ use crossterm::{
cursor::{Hide, MoveTo, Show}, cursor::{Hide, MoveTo, Show},
event::{poll, read, Event, KeyCode}, event::{poll, read, Event, KeyCode},
@ -21,7 +24,7 @@ use crossterm::{
use get_if_addrs::get_if_addrs; use get_if_addrs::get_if_addrs;
use crate::sync_logic::LtcState; use crate::sync_logic::LtcState;
/// Check if the Chrony service is active /// Check if Chrony is active
fn ntp_service_active() -> bool { fn ntp_service_active() -> bool {
if let Ok(output) = Command::new("systemctl").args(&["is-active", "chrony"]).output() { if let Ok(output) = Command::new("systemctl").args(&["is-active", "chrony"]).output() {
output.status.success() output.status.success()
@ -31,39 +34,33 @@ fn ntp_service_active() -> bool {
} }
} }
/// Toggle the Chrony service (start if `start` is true, stop otherwise) /// Toggle Chrony (not used yet)
#[allow(dead_code)] #[allow(dead_code)]
fn ntp_service_toggle(start: bool) { fn ntp_service_toggle(start: bool) {
let action = if start { "start" } else { "stop" }; let action = if start { "start" } else { "stop" };
let _ = Command::new("systemctl").args(&[action, "chrony"]).status(); let _ = Command::new("systemctl").args(&[action, "chrony"]).status();
} }
/// Launch the full-featured TUI; reads `offset` live and performs auto-sync if out of sync.
pub fn start_ui( pub fn start_ui(
state: Arc<Mutex<LtcState>>, state: Arc<Mutex<LtcState>>,
serial_port: String, serial_port: String,
offset: Arc<Mutex<i64>>, offset: Arc<Mutex<i64>>,
) { ) {
let mut stdout = stdout(); let mut stdout = stdout();
// Enter alternate screen and hide cursor
execute!(stdout, EnterAlternateScreen, Hide).unwrap(); execute!(stdout, EnterAlternateScreen, Hide).unwrap();
terminal::enable_raw_mode().unwrap(); terminal::enable_raw_mode().unwrap();
// Recent log of messages (last 10)
let mut logs: VecDeque<String> = VecDeque::with_capacity(10); let mut logs: VecDeque<String> = VecDeque::with_capacity(10);
// Tracks when we first detected out-of-sync
let mut out_of_sync_since: Option<Instant> = None; let mut out_of_sync_since: Option<Instant> = None;
// For caching the timecode delta display once per second
let mut last_delta_update = Instant::now() - Duration::from_secs(1); let mut last_delta_update = Instant::now() - Duration::from_secs(1);
let mut cached_delta_ms: i64 = 0; let mut cached_delta_ms: i64 = 0;
let mut cached_delta_frames: i64 = 0; let mut cached_delta_frames: i64 = 0;
loop { loop {
// 1 Read hardware offset from watcher // 1 hardware offset
let hw_offset_ms = *offset.lock().unwrap(); let hw_offset_ms = *offset.lock().unwrap();
// 2⃣ Check Chrony status and gather network interfaces // 2⃣ Chrony + interfaces
let ntp_active = ntp_service_active(); let ntp_active = ntp_service_active();
let interfaces: Vec<String> = get_if_addrs() let interfaces: Vec<String> = get_if_addrs()
.unwrap_or_default() .unwrap_or_default()
@ -72,28 +69,22 @@ pub fn start_ui(
.map(|ifa| ifa.ip().to_string()) .map(|ifa| ifa.ip().to_string())
.collect(); .collect();
// 3Measure & record jitter and Timecode Δ when LOCKED; clear on FREE // 3jitter + Δ
{ {
let mut st = state.lock().unwrap(); let mut st = state.lock().unwrap();
if let Some(frame) = st.latest.clone() { if let Some(frame) = st.latest.clone() {
if frame.status == "LOCK" { if frame.status == "LOCK" {
// Jitter in ms // jitter
let now = Utc::now(); let now_utc = Utc::now();
let raw = (now - frame.timestamp).num_milliseconds(); let raw = (now_utc - frame.timestamp).num_milliseconds();
let measured = raw - hw_offset_ms; let measured = raw - hw_offset_ms;
st.record_offset(measured); st.record_offset(measured);
// Timecode delta // Δ via UTC lane
let local = Local::now();
let sub_ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0).round() as i64; let sub_ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0).round() as i64;
let base_time = NaiveTime::from_hms_opt(frame.hours, frame.minutes, frame.seconds) let ltc_arrival = frame.timestamp
.unwrap_or(local.time()); + ChronoDuration::milliseconds(hw_offset_ms + sub_ms);
let offset_dt = local.date_naive().and_time(base_time) let delta_ms = (Utc::now() - ltc_arrival).num_milliseconds();
+ ChronoDuration::milliseconds(sub_ms);
let ltc_dt = Local.from_local_datetime(&offset_dt)
.single()
.unwrap_or(local);
let delta_ms = local.signed_duration_since(ltc_dt).num_milliseconds();
st.record_clock_delta(delta_ms); st.record_clock_delta(delta_ms);
} else { } else {
st.clear_offsets(); st.clear_offsets();
@ -102,8 +93,8 @@ pub fn start_ui(
} }
} }
// 4 Compute averages & statuses // 4 averages & status override
let (avg_ms, _avg_frames, status_str, lock_ratio, avg_delta) = { let (avg_ms, _avg_frames, _, lock_ratio, avg_delta) = {
let st = state.lock().unwrap(); let st = state.lock().unwrap();
( (
st.average_jitter(), st.average_jitter(),
@ -114,60 +105,42 @@ let (avg_ms, _avg_frames, status_str, lock_ratio, avg_delta) = {
) )
}; };
// 5⃣ Update cached delta once per second let sync_status = if avg_delta.abs() <= 5 { "IN SYNC" } else { "OUT OF SYNC" };
// 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;
// Recompute frames equivalent cached_delta_frames = avg_ms; // or recalc from frame if you like
if let Ok(st2) = state.lock() {
if let Some(frame) = &st2.latest {
let ms_pf = 1000.0 / frame.frame_rate;
cached_delta_frames = (cached_delta_ms as f64 / ms_pf).round() as i64;
}
}
last_delta_update = Instant::now(); last_delta_update = Instant::now();
} }
// 6Auto-sync if "OUT OF SYNC" or Δ >5ms for 5s // 6⃣ autosync
if status_str == "OUT OF SYNC" || cached_delta_ms.abs() > 5 { if sync_status == "OUT OF 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) {
// Perform sync to LTC // sync exactly to LTC arrival
if let Ok(stl) = state.lock() { if let Some(frame) = &state.lock().unwrap().latest {
if let Some(frame) = &stl.latest { let sub_ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0).round() as i64;
let local_now = Local::now(); let ltc_arrival = frame.timestamp
let sub_ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0) + ChronoDuration::milliseconds(hw_offset_ms + sub_ms);
.round() as i64; // format from UTC instant into local time
let base_time = NaiveTime::from_hms_opt( let ts_local: DateTime<Local> =
frame.hours, DateTime::from(ltc_arrival);
frame.minutes, let ts = format!(
frame.seconds, "{:02}:{:02}:{:02}.{:03}",
).unwrap_or(local_now.time()); ts_local.hour(),
let offset_dt = local_now.date_naive().and_time(base_time) ts_local.minute(),
+ ChronoDuration::milliseconds(sub_ms); ts_local.second(),
let ltc_dt = Local.from_local_datetime(&offset_dt) ts_local.timestamp_subsec_millis()
.single() );
.unwrap_or(local_now); let res = Command::new("sudo").arg("date").arg("-s").arg(&ts).status();
let ts = format!("{:02}:{:02}:{:02}.{:03}", let entry = if res.as_ref().map_or(false, |s| s.success()) {
ltc_dt.hour(), format!("🔄 Autosynced to LTC: {}", ts)
ltc_dt.minute(), } else {
ltc_dt.second(), "❌ Autosync failed".into()
ltc_dt.timestamp_subsec_millis() };
); if logs.len() == 10 { logs.pop_front(); }
let res = Command::new("sudo") logs.push_back(entry);
.arg("date")
.arg("-s")
.arg(&ts)
.status();
let msg = if res.as_ref().map_or(false, |s| s.success()) {
format!("🔄 Auto-synced to LTC: {}", ts)
} else {
"❌ Auto-sync failed".into()
};
if logs.len() == 10 {
logs.pop_front();
}
logs.push_back(msg);
}
} }
out_of_sync_since = None; out_of_sync_since = None;
} }
@ -178,116 +151,95 @@ let (avg_ms, _avg_frames, status_str, lock_ratio, avg_delta) = {
out_of_sync_since = None; out_of_sync_since = None;
} }
// 7 Draw static UI header // 7 header
queue!( queue!(
stdout, stdout,
MoveTo(0, 0), Clear(ClearType::All), MoveTo(0, 0), Clear(ClearType::All),
MoveTo(2, 1), Print("Have Blue - NTP Timeturner - FrameWorks Testing"), MoveTo(2, 1), Print("Have Blue - NTP Timeturner"),
MoveTo(2, 2), Print(format!("Serial Port : {}", serial_port)), MoveTo(2, 2), Print(format!("Serial Port : {}", serial_port)),
MoveTo(2, 3), Print(format!("Chrony Service : {}", if ntp_active { "RUNNING" } else { "MISSING" })), MoveTo(2, 3), Print(format!("Chrony Service : {}", if ntp_active { "RUNNING" } else { "MISSING" })),
MoveTo(2, 4), Print(format!("Interfaces : {}", interfaces.join(", "))), MoveTo(2, 4), Print(format!("Interfaces : {}", interfaces.join(", "))),
) ).unwrap();
.unwrap();
// 8⃣ Draw LTC and System Clock // 8⃣ LTC & system clock
if let Ok(st) = state.lock() { if let Some(frame) = &state.lock().unwrap().latest {
if let Some(frame) = &st.latest { queue!(
queue!( stdout,
stdout, MoveTo(2, 6), Print(format!("LTC Status : {}", frame.status)),
MoveTo(2, 6), Print(format!("LTC Status : {}", frame.status)), MoveTo(2, 7), Print(format!("LTC Timecode : {:02}:{:02}:{:02}:{:02}",
MoveTo(2, 7), Print(format!( frame.hours, frame.minutes, frame.seconds, frame.frames
"LTC Timecode : {:02}:{:02}:{:02}:{:02}", )),
frame.hours, frame.minutes, frame.seconds, frame.frames MoveTo(2, 8), Print(format!("Frame Rate : {:.2}fps", frame.frame_rate)),
)), ).unwrap();
MoveTo(2, 8), Print(format!("Frame Rate : {:.2}fps", frame.frame_rate)), } else {
) queue!(
.unwrap(); stdout,
} else { MoveTo(2, 6), Print("LTC Status : (waiting)"),
queue!( MoveTo(2, 7), Print("LTC Timecode : …"),
stdout, MoveTo(2, 8), Print("Frame Rate : …"),
MoveTo(2, 6), Print("LTC Status : (waiting)"), ).unwrap();
MoveTo(2, 7), Print("LTC Timecode : …"),
MoveTo(2, 8), Print("Frame Rate : …"),
)
.unwrap();
}
let now_local = Local::now();
let sys_ts = format!("{:02}:{:02}:{:02}.{:03}",
now_local.hour(), now_local.minute(), now_local.second(), now_local.timestamp_subsec_millis()
);
queue!(stdout, MoveTo(2, 9), Print(format!("System Clock : {}", sys_ts))).unwrap();
} }
// 9⃣ Overlay metrics in new order // show Pis own clock
let dcol = if cached_delta_ms.abs() < 20 { let now_local: DateTime<Local> = DateTime::from(Utc::now());
Color::Green let sys_ts = format!(
} else if cached_delta_ms.abs() < 100 { "{:02}:{:02}:{:02}.{:03}",
Color::Yellow now_local.hour(),
} else { now_local.minute(),
Color::Red now_local.second(),
}; now_local.timestamp_subsec_millis()
);
queue!(stdout, MoveTo(2, 9), Print(format!("System Clock : {}", sys_ts))).unwrap();
// 9⃣ metrics
let dcol = if cached_delta_ms.abs() < 20 { Color::Green }
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),
Print(format!("Timecode Δ : {:+} ms ({:+} frames)", cached_delta_ms, cached_delta_frames)), Print(format!("Timecode Δ : {:+} ms ({:+} frames)", cached_delta_ms, cached_delta_frames)),
ResetColor, ResetColor,
) ).unwrap();
.unwrap();
let scol = if status_str == "IN SYNC" { let scol = if sync_status == "IN SYNC" { Color::Green } else { Color::Red };
Color::Green
} else {
Color::Red
};
queue!( queue!(
stdout, stdout,
MoveTo(2, 12), SetForegroundColor(scol), MoveTo(2, 12), SetForegroundColor(scol),
Print(format!("Sync Status : {}", status_str)), Print(format!("Sync Status : {}", sync_status)),
ResetColor, ResetColor,
) ).unwrap();
.unwrap();
let jstatus = if avg_ms.abs() < 10 { let jstatus = if avg_ms.abs() < 10 { "GOOD" }
"GOOD" else if avg_ms.abs() < 40 { "AVERAGE" }
} else if avg_ms.abs() < 40 { else { "BAD" };
"AVERAGE" let jcol = if jstatus == "GOOD" { Color::Green }
} else { else if jstatus == "AVERAGE" { Color::Yellow }
"BAD" else { Color::Red };
};
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();
// 10Footer and logs // 10footer + logs
queue!( queue!(
stdout, stdout,
MoveTo(2, 16), Print("[S] Sync system clock to LTC [Q] Quit"), MoveTo(2, 16), Print("[S] Sync sys clock to LTC [Q] Quit"),
) ).unwrap();
.unwrap(); for (i, msg) in logs.iter().enumerate() {
for (i, log_msg) in logs.iter().enumerate() { queue!(stdout, MoveTo(2, 18 + i as u16), Print(msg)).unwrap();
queue!(stdout, MoveTo(2, 18 + i as u16), Print(log_msg)).unwrap();
} }
stdout.flush().unwrap(); stdout.flush().unwrap();
// 11Handle manual sync and quit keys // 11manual 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 {
@ -297,44 +249,27 @@ let (avg_ms, _avg_frames, status_str, lock_ratio, avg_delta) = {
process::exit(0); process::exit(0);
} }
KeyCode::Char(c) if c.eq_ignore_ascii_case(&'s') => { KeyCode::Char(c) if c.eq_ignore_ascii_case(&'s') => {
if let Ok(stlock) = state.lock() { if let Some(frame) = &state.lock().unwrap().latest {
if let Some(frame) = &stlock.latest { // compute the exact timestamp again
let local_now = Local::now(); let sub_ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0).round() as i64;
let sub_ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0) let ltc_arrival = frame.timestamp
.round() as i64; + ChronoDuration::milliseconds(hw_offset_ms + sub_ms);
let base_time = NaiveTime::from_hms_opt( let ts_local: DateTime<Local> = DateTime::from(ltc_arrival);
frame.hours, let ts = format!(
frame.minutes, "{:02}:{:02}:{:02}.{:03}",
frame.seconds, ts_local.hour(),
) ts_local.minute(),
.unwrap_or(local_now.time()); ts_local.second(),
let offset_dt = local_now.date_naive().and_time(base_time) ts_local.timestamp_subsec_millis()
+ ChronoDuration::milliseconds(sub_ms); );
let ltc_dt = Local.from_local_datetime(&offset_dt) let res = Command::new("sudo").arg("date").arg("-s").arg(&ts).status();
.single() let entry = if res.as_ref().map_or(false, |s| s.success()) {
.unwrap_or(local_now); format!("✔ Synced exactly to LTC: {}", ts)
let ts = format!( } else {
"{:02}:{:02}:{:02}.{:03}", "❌ date cmd failed".into()
ltc_dt.hour(), };
ltc_dt.minute(), if logs.len() == 10 { logs.pop_front() }
ltc_dt.second(), logs.push_back(entry);
ltc_dt.timestamp_subsec_millis(),
);
let res = Command::new("sudo")
.arg("date")
.arg("-s")
.arg(&ts)
.status();
let msg = if res.as_ref().map_or(false, |s| s.success()) {
format!("✔ Synced exactly to LTC: {}", ts)
} else {
"❌ date cmd failed".into()
};
if logs.len() == 10 {
logs.pop_front();
}
logs.push_back(msg);
}
} }
} }
_ => {} _ => {}