From ad915c4aeb097e1501327c4bd50d66e292efde9b Mon Sep 17 00:00:00 2001 From: Chris Frankland-Wright Date: Sun, 20 Jul 2025 12:42:12 +0100 Subject: [PATCH] implemented sync drift detect and auto sync if out of sync --- src/sync_logic.rs | 60 +++++++--- src/ui.rs | 285 +++++++++++++++++++++++++--------------------- 2 files changed, 199 insertions(+), 146 deletions(-) diff --git a/src/sync_logic.rs b/src/sync_logic.rs index 3b9f435..0a001bf 100644 --- a/src/sync_logic.rs +++ b/src/sync_logic.rs @@ -1,6 +1,4 @@ -// src/sync_logic.rs - -use chrono::{DateTime, Local, Timelike, Utc}; +use chrono::{DateTime, Local, Timelike, Utc}; use regex::Captures; use std::collections::VecDeque; @@ -43,6 +41,8 @@ pub struct LtcState { pub free_count: u32, /// Stores the last up-to-20 raw offset measurements in ms. pub offset_history: VecDeque, + /// Stores the last up-to-20 timecode Δ measurements in ms. + pub clock_delta_history: VecDeque, pub last_match_status: String, pub last_match_check: i64, } @@ -54,12 +54,13 @@ impl LtcState { lock_count: 0, free_count: 0, offset_history: VecDeque::with_capacity(20), + clock_delta_history: VecDeque::with_capacity(20), last_match_status: "UNKNOWN".into(), last_match_check: 0, } } - /// Record one measured offset in ms, maintaining a sliding window of up to 20 samples. + /// Record one measured jitter offset in ms. pub fn record_offset(&mut self, offset_ms: i64) { if self.offset_history.len() == 20 { self.offset_history.pop_front(); @@ -67,12 +68,25 @@ impl LtcState { self.offset_history.push_back(offset_ms); } - /// Clear all stored offset measurements (e.g. on FREE-run). + /// Record one timecode Δ in ms. + pub fn record_clock_delta(&mut self, delta_ms: i64) { + if self.clock_delta_history.len() == 20 { + self.clock_delta_history.pop_front(); + } + self.clock_delta_history.push_back(delta_ms); + } + + /// Clear all stored jitter measurements. pub fn clear_offsets(&mut self) { self.offset_history.clear(); } - /// Update LOCK/FREE counts, clear offsets on FREE, and refresh timecode-match every 5 s. + /// Clear all stored timecode Δ measurements. + pub fn clear_clock_deltas(&mut self) { + self.clock_delta_history.clear(); + } + + /// Update LOCK/FREE counts and timecode-match status every 5 s. pub fn update(&mut self, frame: LtcFrame) { match frame.status.as_str() { "LOCK" => { @@ -81,36 +95,38 @@ impl LtcState { "FREE" => { self.free_count += 1; self.clear_offsets(); + self.clear_clock_deltas(); self.last_match_status = "UNKNOWN".into(); } _ => {} } - // Every 5 seconds, recompute whether HH:MM:SS matches local time + // Recompute timecode-match every 5 seconds let now_secs = Utc::now().timestamp(); if now_secs - self.last_match_check >= 5 { - self.last_match_status = if frame.matches_system_time() { - "IN SYNC".into() + self.last_match_status = if let Some(frame) = &self.latest { + if frame.matches_system_time() { "IN SYNC" } else { "OUT OF SYNC" } } else { - "OUT OF SYNC".into() - }; + "UNKNOWN" + } + .into(); self.last_match_check = now_secs; } self.latest = Some(frame); } - /// Average jitter over the stored history, in milliseconds. + /// Average jitter over stored history, in ms. pub fn average_jitter(&self) -> i64 { if self.offset_history.is_empty() { 0 } else { let sum: i64 = self.offset_history.iter().sum(); - sum / (self.offset_history.len() as i64) + sum / self.offset_history.len() as i64 } } - /// Convert that average jitter into frames (rounded). + /// Convert average jitter into frames (rounded). pub fn average_frames(&self) -> i64 { if let Some(frame) = &self.latest { let ms_per_frame = 1000.0 / frame.frame_rate; @@ -120,18 +136,28 @@ impl LtcState { } } + /// Average timecode Δ over stored history, in ms. + pub fn average_clock_delta(&self) -> i64 { + if self.clock_delta_history.is_empty() { + 0 + } else { + let sum: i64 = self.clock_delta_history.iter().sum(); + sum / self.clock_delta_history.len() as i64 + } + } + /// Percentage of samples seen in LOCK state versus total. pub fn lock_ratio(&self) -> f64 { let total = self.lock_count + self.free_count; if total == 0 { 0.0 } else { - (self.lock_count as f64 / total as f64) * 100.0 + self.lock_count as f64 / total as f64 * 100.0 } } - /// Get the last computed timecode‐match status ("IN SYNC", "OUT OF SYNC", or "UNKNOWN"). + /// Get timecode-match status. pub fn timecode_match(&self) -> &str { &self.last_match_status } -} +} \ No newline at end of file diff --git a/src/ui.rs b/src/ui.rs index 68dd064..0e454b4 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -5,10 +5,10 @@ use std::{ process::{self, Command}, sync::{Arc, Mutex}, thread, - time::Duration, + time::{Duration, Instant}, }; -use chrono::{Local, Timelike, Utc}; +use chrono::{Local, Timelike, Utc, NaiveTime, Duration as ChronoDuration, TimeZone}; use crossterm::{ cursor::{Hide, MoveTo, Show}, event::{poll, read, Event, KeyCode}, @@ -19,46 +19,110 @@ use crossterm::{ use crate::sync_logic::LtcState; -/// Launch the TUI; reads `offset` live from the file-watcher. +/// Launch the TUI; reads `offset` live from the file-watcher and performs auto-sync if out of sync. pub fn start_ui( state: Arc>, serial_port: String, offset: Arc>, ) { let mut stdout = stdout(); - execute!(stdout, EnterAlternateScreen).unwrap(); + execute!(stdout, EnterAlternateScreen, Hide).unwrap(); terminal::enable_raw_mode().unwrap(); + // Track when delta goes out of threshold + let mut out_of_sync_since: Option = None; + loop { - // 1️⃣ Read current hardware offset + // 1️⃣ Read hardware offset let hw_offset_ms = *offset.lock().unwrap(); - // 2️⃣ Measure & record jitter only when LOCKED; clear on FREE + // 2️⃣ Measure & record jitter and Timecode Δ when LOCKED; clear both on FREE { let mut st = state.lock().unwrap(); - if let Some(frame) = &st.latest { + if let Some(frame) = st.latest.clone() { if frame.status == "LOCK" { + // Jitter measurement let now = Utc::now(); - let raw = (now - frame.timestamp).num_milliseconds(); - let measured = raw - hw_offset_ms; + let measured = (now - frame.timestamp).num_milliseconds() - hw_offset_ms; st.record_offset(measured); + // Timecode Δ measurement + let local = Local::now(); + 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, + ).unwrap_or(local.time()); + let today = local.date_naive(); + let offset_dt = today.and_time(base_time) + 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); } else { st.clear_offsets(); + st.clear_clock_deltas(); } } } - // 3️⃣ Draw static UI + // 3️⃣ Compute averages and status + let (avg_ms, avg_frames, status, ratio, avg_delta) = { + let st = state.lock().unwrap(); + ( + st.average_jitter(), + st.average_frames(), + st.timecode_match().to_string(), + st.lock_ratio(), + st.average_clock_delta(), + ) + }; + + // Auto-sync: if OUT OF SYNC or Δ >10ms for 5s + if status == "OUT OF SYNC" || avg_delta.abs() > 10 { + if let Some(start) = out_of_sync_since { + if start.elapsed() >= Duration::from_secs(5) { + // perform sync + if let Ok(st) = state.lock() { + if let Some(frame) = &st.latest { + let local_now = Local::now(); + 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, + ).unwrap_or(local_now.time()); + let offset_dt = local_now.date_naive().and_time(base_time) + + ChronoDuration::milliseconds(sub_ms); + let ltc_dt = Local.from_local_datetime(&offset_dt).single().unwrap_or(local_now); + let ts = format!("{:02}:{:02}:{:02}.{:03}", ltc_dt.hour(), ltc_dt.minute(), ltc_dt.second(), 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!("🔄 Auto-synced to LTC: {}", ts) + } else { + "❌ Auto-sync failed".into() + }; + queue!(stdout, MoveTo(2, 14), Print(msg)).unwrap(); + stdout.flush().unwrap(); + } + } + out_of_sync_since = None; + } + } else { + out_of_sync_since = Some(Instant::now()); + } + } else { + out_of_sync_since = None; + } + + // 4️⃣ Draw static UI queue!( stdout, - MoveTo(0, 0), - Clear(ClearType::All), - Hide, + MoveTo(0, 0), Clear(ClearType::All), MoveTo(2, 1), Print("NTP Timeturner v2 - Rust Port"), MoveTo(2, 2), Print(format!("Using Serial Port: {}", serial_port)), - ) - .unwrap(); + ).unwrap(); + // 5️⃣ Draw LTC & System Clock if let Ok(st) = state.lock() { if let Some(frame) = &st.latest { queue!( @@ -69,144 +133,107 @@ pub fn start_ui( frame.hours, frame.minutes, frame.seconds, frame.frames )), MoveTo(2, 6), Print(format!("Frame Rate : {:.2}fps", frame.frame_rate)), - ) - .unwrap(); + ).unwrap(); } else { queue!( stdout, MoveTo(2, 4), Print("LTC Status : (waiting)"), MoveTo(2, 5), Print("LTC Timecode : …"), MoveTo(2, 6), Print("Frame Rate : …"), - ) - .unwrap(); + ).unwrap(); } - let now_local = Local::now(); - let sys_str = format!( - "{:02}:{:02}:{:02}.{:03}", - now_local.hour(), - now_local.minute(), - now_local.second(), - now_local.timestamp_subsec_millis() - ); - queue!( - stdout, - MoveTo(2, 7), - Print(format!("System Clock : {}", sys_str)) - ) - .unwrap(); + let sys_str = format!("{:02}:{:02}:{:02}.{:03}", + now_local.hour(), now_local.minute(), now_local.second(), now_local.timestamp_subsec_millis()); + queue!(stdout, MoveTo(2, 7), Print(format!("System Clock : {}", sys_str))).unwrap(); } - // Footer + // 6️⃣ Overlay in new order: Delta, Status, Jitter, Ratio + // Timecode Δ below System Clock + let dcol = if avg_delta.abs() < 20 { + Color::Green + } else if avg_delta.abs() < 100 { + Color::Yellow + } else { + Color::Red + }; queue!( stdout, - MoveTo(2, 12), - Print("[S] Set system clock to LTC [Q] Quit") - ) - .unwrap(); + MoveTo(2, 8), SetForegroundColor(dcol), Print(format!("Timecode Δ : {:+} ms", avg_delta)), ResetColor, + ).unwrap(); + + // Sync Status + let scol = if status == "IN SYNC" { Color::Green } else { Color::Red }; + queue!( + stdout, + MoveTo(2, 9), SetForegroundColor(scol), Print(format!("Sync Status : {}", status)), ResetColor, + ).unwrap(); + + // Sync Jitter under Status + let (jcol, jtxt) = if avg_ms.abs() < 10 { + (Color::Green, format!("{:+} ms ({:+} frames)", avg_ms, avg_frames)) + } else if avg_ms.abs() < 40 { + (Color::Yellow, format!("{:+} ms ({:+} frames)", avg_ms, avg_frames)) + } else { + (Color::Red, format!("{:+} ms ({:+} frames)", avg_ms, avg_frames)) + }; + queue!( + stdout, + MoveTo(2, 10), SetForegroundColor(jcol), Print("Sync Jitter : "), Print(jtxt), ResetColor, + ).unwrap(); + + // Lock Ratio below Jitter + queue!( + stdout, + MoveTo(2, 11), Print(format!("Lock Ratio : {:.1}% LOCK", ratio)), + ).unwrap(); + + // Blank line at 12, Footer at 13 + queue!( + stdout, + MoveTo(2, 13), Print("[S] Set system clock to LTC [Q] Quit"), + ).unwrap(); stdout.flush().unwrap(); - // 4️⃣ Overlay Sync Jitter / Status / Ratio - if let Ok(st) = state.lock() { - let avg_ms = st.average_jitter(); - let avg_frames = st.average_frames(); - let (jcol, jtxt) = if avg_ms.abs() < 10 { - (Color::Green, format!("{:+} ms ({:+} frames)", avg_ms, avg_frames)) - } else if avg_ms.abs() < 40 { - (Color::Yellow, format!("{:+} ms ({:+} frames)", avg_ms, avg_frames)) - } else { - (Color::Red, format!("{:+} ms ({:+} frames)", avg_ms, avg_frames)) - }; - queue!( - stdout, - MoveTo(2, 8), - SetForegroundColor(jcol), - Print("Sync Jitter : "), - Print(jtxt), - ResetColor, - ) - .ok(); - - let status = st.timecode_match(); - let scol = if status == "IN SYNC" { Color::Green } else { Color::Red }; - queue!( - stdout, - MoveTo(2, 9), - SetForegroundColor(scol), - Print(format!("Sync Status : {}", status)), - ResetColor, - ) - .ok(); - - let ratio = st.lock_ratio(); - queue!( - stdout, - MoveTo(2, 10), - Print(format!("Lock Ratio : {:.1}% LOCK", ratio)), - ) - .ok(); - - stdout.flush().ok(); - } - - // 5️⃣ Handle keypress + // 7️⃣ Handle quit/manual sync in poll if poll(Duration::from_millis(0)).unwrap() { if let Event::Key(evt) = read().unwrap() { - match evt.code { - KeyCode::Char(c) if c.eq_ignore_ascii_case(&'s') => { - // SYNC now - if let Ok(st) = state.lock() { - if let Some(frame) = &st.latest { - // compute ms from frames - let ms_from_frames = - ((frame.frames as f64 / frame.frame_rate) * 1000.0).round() as i64; - // total microseconds - let total_us = (ms_from_frames + hw_offset_ms) * 1000; - // build date string "HH:MM:SS.mmm" - let ts = format!( - "{:02}:{:02}:{:02}.{:03}", - frame.hours, - frame.minutes, - frame.seconds, - ((total_us / 1000) % 1000) - ); - // run `sudo date -s "HH:MM:SS.mmm"` - let status = Command::new("sudo") - .arg("date") - .arg("-s") - .arg(&ts) - .status(); - let msg = if let Ok(s) = status { - if s.success() { - format!("✔ Synced to LTC: {}", ts) - } else { - format!("❌ date cmd failed") - } - } else { - format!("❌ failed to spawn date") - }; - // print confirmation at row 14 - queue!( - stdout, - MoveTo(2, 14), - Print(msg), - ) - .ok(); - stdout.flush().ok(); - } - } - } - KeyCode::Char(c) if c.eq_ignore_ascii_case(&'q') => { + if let KeyCode::Char(c) = evt.code { + if c.eq_ignore_ascii_case(&'q') { execute!(stdout, Show, LeaveAlternateScreen).unwrap(); terminal::disable_raw_mode().unwrap(); process::exit(0); } - _ => {} + if c.eq_ignore_ascii_case(&'s') { + // manual sync logic duplicated... + if let Ok(st) = state.lock() { + if let Some(frame) = &st.latest { + let local_now = Local::now(); + 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, + ).unwrap_or(local_now.time()); + let offset_dt = local_now.date_naive().and_time(base_time) + ChronoDuration::milliseconds(sub_ms); + let ltc_dt = Local.from_local_datetime(&offset_dt).single().unwrap_or(local_now); + let ts = format!("{:02}:{:02}:{:02}.{:03}", ltc_dt.hour(), ltc_dt.minute(), ltc_dt.second(), 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() + }; + queue!(stdout, MoveTo(2, 14), Print(msg)).unwrap(); + stdout.flush().unwrap(); + } + } + } } } } thread::sleep(Duration::from_millis(50)); } -} +} \ No newline at end of file