force commit of ui.rs

This commit is contained in:
Chris Frankland-Wright 2025-07-21 15:38:29 +01:00 committed by GitHub
parent a0115b556b
commit 80a4fbe538
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

341
src/ui.rs
View file

@ -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},
@ -9,7 +7,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,
NaiveTime, TimeZone,
};
use crossterm::{ use crossterm::{
cursor::{Hide, MoveTo, Show}, cursor::{Hide, MoveTo, Show},
event::{poll, read, Event, KeyCode}, event::{poll, read, Event, KeyCode},
@ -21,7 +22,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 +32,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)]
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 +67,30 @@ 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 // Δ = system clock - LTC timecode (use LOCAL time)
let local = Local::now(); 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 base_time = NaiveTime::from_hms_opt(frame.hours, frame.minutes, frame.seconds) .round() as u32;
.unwrap_or(local.time()); let tc_naive = NaiveTime::from_hms_milli_opt(
let offset_dt = local.date_naive().and_time(base_time) frame.hours, frame.minutes, frame.seconds, ms,
+ ChronoDuration::milliseconds(sub_ms); ).expect("Invalid LTC timecode");
let ltc_dt = Local.from_local_datetime(&offset_dt) let naive_dt_local = today_local.and_time(tc_naive);
let dt_local = Local
.from_local_datetime(&naive_dt_local)
.single() .single()
.unwrap_or(local); .expect("Invalid local time");
let delta_ms = local.signed_duration_since(ltc_dt).num_milliseconds(); 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();
@ -102,8 +99,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_jitter_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 +111,60 @@ let (avg_ms, _avg_frames, status_str, lock_ratio, avg_delta) = {
) )
}; };
// 5Update cached delta once per second // 5cache Δ once/sec & Δ in frames
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 if let Some(frame) = &state.lock().unwrap().latest {
if let Ok(st2) = state.lock() { let frame_ms = 1000.0 / frame.frame_rate;
if let Some(frame) = &st2.latest { cached_delta_frames = ((avg_delta as f64 / frame_ms).round()) as i64;
let ms_pf = 1000.0 / frame.frame_rate; } else {
cached_delta_frames = (cached_delta_ms as f64 / ms_pf).round() as i64; cached_delta_frames = 0;
}
} }
last_delta_update = Instant::now(); last_delta_update = Instant::now();
} }
// 6⃣ Auto-sync if "OUT OF SYNC" or Δ >5ms for 5s // 6⃣ sync status wording
if status_str == "OUT OF SYNC" || cached_delta_ms.abs() > 5 { let sync_status = if cached_delta_ms.abs() <= 8 {
"IN SYNC"
} else if cached_delta_ms > 10 {
"CLOCK AHEAD"
} else {
"CLOCK BEHIND"
};
// 7⃣ autosync (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) {
// Perform sync to LTC if let Some(frame) = &state.lock().unwrap().latest {
if let Ok(stl) = state.lock() { let today_local = Local::now().date_naive();
if let Some(frame) = &stl.latest { let ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0)
let local_now = Local::now(); .round() as u32;
let sub_ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0) let timecode = NaiveTime::from_hms_milli_opt(
.round() as i64; frame.hours, frame.minutes, frame.seconds, ms,
let base_time = NaiveTime::from_hms_opt( ).expect("Invalid LTC timecode");
frame.hours, let naive_dt = today_local.and_time(timecode);
frame.minutes, let dt_local = Local
frame.seconds, .from_local_datetime(&naive_dt)
).unwrap_or(local_now.time()); .single()
let offset_dt = local_now.date_naive().and_time(base_time) .expect("Ambiguous or invalid local time");
+ ChronoDuration::milliseconds(sub_ms); let ts = dt_local.format("%H:%M:%S.%3f").to_string();
let ltc_dt = Local.from_local_datetime(&offset_dt)
.single() let success = Command::new("sudo")
.unwrap_or(local_now); .arg("date")
let ts = format!("{:02}:{:02}:{:02}.{:03}", .arg("-s")
ltc_dt.hour(), .arg(&ts)
ltc_dt.minute(), .status()
ltc_dt.second(), .map(|s| s.success())
ltc_dt.timestamp_subsec_millis() .unwrap_or(false);
);
let res = Command::new("sudo") let entry = if success {
.arg("date") format!("🔄 Autosynced to LTC: {}", ts)
.arg("-s") } else {
.arg(&ts) "❌ Autosync failed".into()
.status(); };
let msg = if res.as_ref().map_or(false, |s| s.success()) { if logs.len() == 10 { logs.pop_front(); }
format!("🔄 Auto-synced to LTC: {}", ts) logs.push_back(entry);
} 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,47 +175,52 @@ 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 // 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 - FrameWorks Testing"), 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),
) None => "LTC Timecode : …".to_string(),
.unwrap(); };
let fr_str = match opt {
Some(f) => format!("Frame Rate : {:.2}fps", f.frame_rate),
None => "Frame Rate : …".to_string(),
};
// 8⃣ Draw LTC and System Clock queue!(
if let Ok(st) = state.lock() { stdout,
if let Some(frame) = &st.latest { MoveTo(0, 0), Clear(ClearType::All),
queue!( MoveTo(2, 1), Print("Have Blue - NTP Timeturner"),
stdout, MoveTo(2, 2), Print(format!("Serial Port : {}", serial_port)),
MoveTo(2, 6), Print(format!("LTC Status : {}", frame.status)), MoveTo(2, 3), Print(format!("Chrony Service : {}",
MoveTo(2, 7), Print(format!( if ntp_active { "RUNNING" } else { "MISSING" })),
"LTC Timecode : {:02}:{:02}:{:02}:{:02}", MoveTo(2, 4), Print(format!("Interfaces : {}",
frame.hours, frame.minutes, frame.seconds, frame.frames interfaces.join(", "))),
)), MoveTo(2, 6), Print(format!("LTC Status : {}", status_str)),
MoveTo(2, 8), Print(format!("Frame Rate : {:.2}fps", frame.frame_rate)), MoveTo(2, 7), Print(tc_str),
) MoveTo(2, 8), Print(fr_str),
.unwrap(); ).unwrap();
} else {
queue!(
stdout,
MoveTo(2, 6), Print("LTC Status : (waiting)"),
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 // system clock
let now_local: DateTime<Local> = DateTime::from(Utc::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();
// Δ display
let dcol = if cached_delta_ms.abs() < 20 { let dcol = if cached_delta_ms.abs() < 20 {
Color::Green Color::Green
} else if cached_delta_ms.abs() < 100 { } else if cached_delta_ms.abs() < 100 {
@ -231,10 +233,10 @@ let (avg_ms, _avg_frames, status_str, lock_ratio, avg_delta) = {
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" { // sync status
let scol = if sync_status == "IN SYNC" {
Color::Green Color::Green
} else { } else {
Color::Red Color::Red
@ -242,14 +244,14 @@ let (avg_ms, _avg_frames, status_str, lock_ratio, avg_delta) = {
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 { // jitter & lock ratio
let jstatus = if avg_jitter_ms.abs() < 10 {
"GOOD" "GOOD"
} else if avg_ms.abs() < 40 { } else if avg_jitter_ms.abs() < 40 {
"AVERAGE" "AVERAGE"
} else { } else {
"BAD" "BAD"
@ -266,28 +268,26 @@ let (avg_ms, _avg_frames, status_str, lock_ratio, avg_delta) = {
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 and logs // footer + logs
queue!( queue!(
stdout, stdout,
MoveTo(2, 16), Print("[S] Sync system clock to LTC [Q] Quit"), MoveTo(2, 16), Print("[S] Sync System 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();
// 11⃣ Handle manual sync and quit keys // 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 {
@ -297,44 +297,35 @@ 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 { let today_local = Local::now().date_naive();
let local_now = Local::now(); let ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0)
let sub_ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0) .round() as u32;
.round() as i64; let timecode = NaiveTime::from_hms_milli_opt(
let base_time = NaiveTime::from_hms_opt( frame.hours, frame.minutes, frame.seconds, ms,
frame.hours, ).expect("Invalid LTC timecode");
frame.minutes, let naive_dt = today_local.and_time(timecode);
frame.seconds, let dt_local = Local
) .from_local_datetime(&naive_dt)
.unwrap_or(local_now.time()); .single()
let offset_dt = local_now.date_naive().and_time(base_time) .expect("Ambiguous or invalid local time");
+ ChronoDuration::milliseconds(sub_ms); let ts = dt_local.format("%H:%M:%S.%3f").to_string();
let ltc_dt = Local.from_local_datetime(&offset_dt)
.single() let success = Command::new("sudo")
.unwrap_or(local_now); .arg("date")
let ts = format!( .arg("-s")
"{:02}:{:02}:{:02}.{:03}", .arg(&ts)
ltc_dt.hour(), .status()
ltc_dt.minute(), .map(|s| s.success())
ltc_dt.second(), .unwrap_or(false);
ltc_dt.timestamp_subsec_millis(),
); let entry = if success {
let res = Command::new("sudo") format!("✔ Synced exactly to LTC: {}", ts)
.arg("date") } else {
.arg("-s") "❌ date cmd failed".into()
.arg(&ts) };
.status(); if logs.len() == 10 { logs.pop_front(); }
let msg = if res.as_ref().map_or(false, |s| s.success()) { logs.push_back(entry);
format!("✔ Synced exactly to LTC: {}", ts)
} else {
"❌ date cmd failed".into()
};
if logs.len() == 10 {
logs.pop_front();
}
logs.push_back(msg);
}
} }
} }
_ => {} _ => {}