diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..ff82f28 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: "cargo" + directory: "/" # Location of Cargo.toml + schedule: + interval: "weekly" \ No newline at end of file diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..596ae03 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,70 @@ +name: Build for Raspberry Pi + +on: + push: + branches: + - main + pull_request: + branches: + - main + +env: + CARGO_TERM_COLOR: always + # Target for 64-bit Raspberry Pi (Raspberry Pi OS) + RUST_TARGET: aarch64-unknown-linux-gnu + +jobs: + build: + name: Build for aarch64 + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ env.RUST_TARGET }} + + + + - name: Install cross-compilation dependencies + run: | + sudo dpkg --add-architecture arm64 + # Configure sources for ARM64 packages - all ARM64 packages come from ports.ubuntu.com + sudo tee /etc/apt/sources.list.d/arm64.list > /dev/null <<'EOF' + deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports jammy main restricted universe multiverse + deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports jammy-updates main restricted universe multiverse + deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports jammy-backports main restricted universe multiverse + deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports jammy-security main restricted universe multiverse + EOF + # Modify existing sources to exclude arm64 architecture + sudo sed -i 's/^deb /deb [arch=amd64] /' /etc/apt/sources.list + sudo apt-get update -y + # Install build tools and cross-compilation libraries for Raspberry Pi 5 + sudo apt-get install -y gcc-aarch64-linux-gnu libudev-dev:arm64 pkg-config cmake libudev-dev + # Ensure pkg-config can find ARM64 libraries + sudo apt-get install -y libpkgconf3:arm64 + - name: Install Rust dependencies + run: cargo fetch --target ${{ env.RUST_TARGET }} + - name: Build release binary + run: cargo build --release --target ${{ env.RUST_TARGET }} + env: + # Set linker for the target + CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc + # Configure pkg-config for cross-compilation + PKG_CONFIG_ALLOW_CROSS: 1 + PKG_CONFIG_PATH: /usr/lib/aarch64-linux-gnu/pkgconfig + PKG_CONFIG_LIBDIR: /usr/lib/aarch64-linux-gnu/pkgconfig + PKG_CONFIG_SYSROOT_DIR: / + PKG_CONFIG_ALLOW_SYSTEM_LIBS: 1 + PKG_CONFIG_ALLOW_SYSTEM_CFLAGS: 1 + # Add library path for the cross-compiler's linker + RUSTFLAGS: -L/usr/lib/aarch64-linux-gnu + - name: Run tests on native platform + run: cargo test --release --bin ntp_timeturner + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: timeturner-aarch64 + path: target/${{ env.RUST_TARGET }}/release/ntp_timeturner diff --git a/.gitignore b/.gitignore index 6038104..76c8dc4 100644 --- a/.gitignore +++ b/.gitignore @@ -358,4 +358,22 @@ MigrationBackup/ .ionide/ # Fody - auto-generated XML schema -FodyWeavers.xsd \ No newline at end of file +FodyWeavers.xsd +.aider* +# Generated by Cargo +# will have compiled files and executables +debug +target +# These are backup files generated by rustfmt +**/*.rs.bk +# MSVC Windows builds of rustc generate these, which store debugging information +# Generated by cargo mutants +# Contains mutation testing data +**/mutants.out*/ +# RustRover +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ +cargo.lock \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index 8fec13a..6127547 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,9 +6,10 @@ edition = "2021" [dependencies] serialport = "4.2" chrono = "0.4" -crossterm = "0.27" +crossterm = "0.29" regex = "1.11" serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" -notify = "5.1.0" -get_if_addrs = "0.5" \ No newline at end of file +serde_json = "1.0.141" +notify = "8.1.0" +get_if_addrs = "0.5" + diff --git a/README.md b/README.md index 5cdb470..beea897 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,13 @@ Inspired by the TimeTurner in the Harry Potter series, this project synchronises --- -## 🚀 Installation +## 🚀 Installation (to update) + +For Rust install you can do +```bash +cargo install --git https://github.com/cjfranko/NTP-Timeturner +``` Clone and run the installer: ```bash diff --git a/src/sync_logic.rs b/src/sync_logic.rs index 0a001bf..0afa002 100644 --- a/src/sync_logic.rs +++ b/src/sync_logic.rs @@ -1,163 +1,294 @@ -use chrono::{DateTime, Local, Timelike, Utc}; -use regex::Captures; -use std::collections::VecDeque; - -#[derive(Clone, Debug)] -pub struct LtcFrame { - pub status: String, - pub hours: u32, - pub minutes: u32, - pub seconds: u32, - pub frames: u32, - pub frame_rate: f64, - pub timestamp: DateTime, // arrival stamp -} - -impl LtcFrame { - pub fn from_regex(caps: &Captures, timestamp: DateTime) -> Option { - Some(Self { - status: caps[1].to_string(), - hours: caps[2].parse().ok()?, - minutes: caps[3].parse().ok()?, - seconds: caps[4].parse().ok()?, - frames: caps[5].parse().ok()?, - frame_rate: caps[6].parse().ok()?, - timestamp, - }) - } - - /// Compare just HH:MM:SS against local time. - pub fn matches_system_time(&self) -> bool { - let local = Local::now(); - local.hour() == self.hours - && local.minute() == self.minutes - && local.second() == self.seconds - } -} - -pub struct LtcState { - pub latest: Option, - pub lock_count: u32, - 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, -} - -impl LtcState { - pub fn new() -> Self { - Self { - latest: None, - 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 jitter offset in ms. - pub fn record_offset(&mut self, offset_ms: i64) { - if self.offset_history.len() == 20 { - self.offset_history.pop_front(); - } - self.offset_history.push_back(offset_ms); - } - - /// 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(); - } - - /// 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" => { - self.lock_count += 1; - } - "FREE" => { - self.free_count += 1; - self.clear_offsets(); - self.clear_clock_deltas(); - self.last_match_status = "UNKNOWN".into(); - } - _ => {} - } - - // 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 let Some(frame) = &self.latest { - if frame.matches_system_time() { "IN SYNC" } else { "OUT OF SYNC" } - } else { - "UNKNOWN" - } - .into(); - self.last_match_check = now_secs; - } - - self.latest = Some(frame); - } - - /// 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 - } - } - - /// 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; - (self.average_jitter() as f64 / ms_per_frame).round() as i64 - } else { - 0 - } - } - - /// 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 - } - } - - /// Get timecode-match status. - pub fn timecode_match(&self) -> &str { - &self.last_match_status - } -} \ No newline at end of file +use chrono::{DateTime, Local, Timelike, Utc}; +use regex::Captures; +use std::collections::VecDeque; + +#[derive(Clone, Debug)] +pub struct LtcFrame { + pub status: String, + pub hours: u32, + pub minutes: u32, + pub seconds: u32, + pub frames: u32, + pub frame_rate: f64, + pub timestamp: DateTime, // arrival stamp +} + +impl LtcFrame { + pub fn from_regex(caps: &Captures, timestamp: DateTime) -> Option { + Some(Self { + status: caps[1].to_string(), + hours: caps[2].parse().ok()?, + minutes: caps[3].parse().ok()?, + seconds: caps[4].parse().ok()?, + frames: caps[5].parse().ok()?, + frame_rate: caps[6].parse().ok()?, + timestamp, + }) + } + + /// Compare just HH:MM:SS against local time. + pub fn matches_system_time(&self) -> bool { + let local = Local::now(); + local.hour() == self.hours + && local.minute() == self.minutes + && local.second() == self.seconds + } +} + +pub struct LtcState { + pub latest: Option, + pub lock_count: u32, + 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, +} + +impl LtcState { + pub fn new() -> Self { + Self { + latest: None, + 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 jitter offset in ms. + pub fn record_offset(&mut self, offset_ms: i64) { + if self.offset_history.len() == 20 { + self.offset_history.pop_front(); + } + self.offset_history.push_back(offset_ms); + } + + /// 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(); + } + + /// 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" => { + self.lock_count += 1; + + // 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" + } else { + "OUT OF SYNC" + } + .into(); + self.last_match_check = now_secs; + } + } + "FREE" => { + self.free_count += 1; + self.clear_offsets(); + self.clear_clock_deltas(); + self.last_match_status = "UNKNOWN".into(); + } + _ => {} + } + + self.latest = Some(frame); + } + + /// 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 + } + } + + /// 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; + (self.average_jitter() as f64 / ms_per_frame).round() as i64 + } else { + 0 + } + } + + /// 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 + } + } + + /// Get timecode-match status. + pub fn timecode_match(&self) -> &str { + &self.last_match_status + } +} +// This module provides the logic for handling LTC (Linear Timecode) frames and maintaining state. +#[cfg(test)] +mod tests { + use super::*; + use chrono::{Local, Utc}; + + fn get_test_frame(status: &str, h: u32, m: u32, s: u32) -> LtcFrame { + LtcFrame { + status: status.to_string(), + hours: h, + minutes: m, + seconds: s, + frames: 0, + frame_rate: 25.0, + timestamp: Utc::now(), + } + } + + #[test] + fn test_ltc_frame_matches_system_time() { + let now = Local::now(); + let frame = get_test_frame("LOCK", now.hour(), now.minute(), now.second()); + assert!(frame.matches_system_time()); + } + + #[test] + fn test_ltc_frame_does_not_match_system_time() { + let now = Local::now(); + // Create a time that is one hour ahead, wrapping around 23:00 + let different_hour = (now.hour() + 1) % 24; + let frame = get_test_frame("LOCK", different_hour, now.minute(), now.second()); + assert!(!frame.matches_system_time()); + } + + #[test] + fn test_ltc_state_update_lock() { + let mut state = LtcState::new(); + let frame = get_test_frame("LOCK", 10, 20, 30); + state.update(frame); + assert_eq!(state.lock_count, 1); + assert_eq!(state.free_count, 0); + assert!(state.latest.is_some()); + } + + #[test] + fn test_ltc_state_update_free() { + let mut state = LtcState::new(); + state.record_offset(100); + assert!(!state.offset_history.is_empty()); + + let frame = get_test_frame("FREE", 10, 20, 30); + state.update(frame); + assert_eq!(state.lock_count, 0); + assert_eq!(state.free_count, 1); + assert!(state.offset_history.is_empty()); // Offsets should be cleared + assert_eq!(state.last_match_status, "UNKNOWN"); + } + + #[test] + fn test_offset_history_management() { + let mut state = LtcState::new(); + for i in 0..25 { + state.record_offset(i); + } + assert_eq!(state.offset_history.len(), 20); + assert_eq!(*state.offset_history.front().unwrap(), 5); // 0-4 are pushed out + assert_eq!(*state.offset_history.back().unwrap(), 24); + } + + #[test] + fn test_timecode_match_status_in_sync() { + let mut state = LtcState::new(); + state.last_match_check = 0; // Force check to run + + let now = Local::now(); + let frame_in_sync = get_test_frame("LOCK", now.hour(), now.minute(), now.second()); + state.update(frame_in_sync); + assert_eq!(state.timecode_match(), "IN SYNC"); + } + + #[test] + fn test_timecode_match_status_out_of_sync() { + let mut state = LtcState::new(); + state.last_match_check = 0; // Force check to run + + let now = Local::now(); + let different_hour = (now.hour() + 1) % 24; + let frame_out_of_sync = get_test_frame("LOCK", different_hour, now.minute(), now.second()); + state.update(frame_out_of_sync); + + assert_eq!(state.timecode_match(), "OUT OF SYNC"); + } + + #[test] + fn test_timecode_match_throttling() { + let mut state = LtcState::new(); + let now = Local::now(); + + // First call. With the bug, status becomes UNKNOWN. With fix, OUT OF SYNC. + // The test is written for the fixed behavior. + state.last_match_check = 0; + let frame_out_of_sync = + get_test_frame("LOCK", (now.hour() + 1) % 24, now.minute(), now.second()); + state.update(frame_out_of_sync.clone()); + assert_eq!( + state.timecode_match(), + "OUT OF SYNC", + "Initial status should be out of sync" + ); + + // Second call, immediately. Check should be throttled. + // Status should not change, even though we pass an in-sync frame. + let frame_in_sync = get_test_frame("LOCK", now.hour(), now.minute(), now.second()); + state.update(frame_in_sync.clone()); + assert_eq!( + state.timecode_match(), + "OUT OF SYNC", + "Status should not change due to throttling" + ); + + // Third call, forcing check to run again. + // Status should now update to IN SYNC. + state.last_match_check = 0; + state.update(frame_in_sync.clone()); + assert_eq!( + state.timecode_match(), + "IN SYNC", + "Status should update after throttle period" + ); + } +} diff --git a/src/ui.rs b/src/ui.rs index 61d1419..3260aff 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -1,347 +1,347 @@ -// src/ui.rs - -use std::{ - io::{stdout, Write}, - process::{self, Command}, - sync::{Arc, Mutex}, - thread, - time::{Duration, Instant}, -}; -use std::collections::VecDeque; - -use chrono::{Local, Timelike, Utc, NaiveTime, Duration as ChronoDuration, TimeZone}; -use crossterm::{ - cursor::{Hide, MoveTo, Show}, - event::{poll, read, Event, KeyCode}, - execute, queue, - style::{Color, Print, ResetColor, SetForegroundColor}, - terminal::{self, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen}, -}; - -use get_if_addrs::get_if_addrs; -use crate::sync_logic::LtcState; - -/// Check if the Chrony service is active -fn ntp_service_active() -> bool { - if let Ok(output) = Command::new("systemctl").args(&["is-active", "chrony"]).output() { - output.status.success() - && String::from_utf8_lossy(&output.stdout).trim() == "active" - } else { - false - } -} - -/// Toggle the Chrony service (start if `start` is true, stop otherwise) -#[allow(dead_code)] -fn ntp_service_toggle(start: bool) { - let action = if start { "start" } else { "stop" }; - 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( - state: Arc>, - serial_port: String, - offset: Arc>, -) { - let mut stdout = stdout(); - // Enter alternate screen and hide cursor - execute!(stdout, EnterAlternateScreen, Hide).unwrap(); - terminal::enable_raw_mode().unwrap(); - - // Recent log of messages (last 10) - let mut logs: VecDeque = VecDeque::with_capacity(10); - // Tracks when we first detected out-of-sync - let mut out_of_sync_since: Option = None; - - // For caching the timecode delta display once per second - let mut last_delta_update = Instant::now() - Duration::from_secs(1); - let mut cached_delta_ms: i64 = 0; - let mut cached_delta_frames: i64 = 0; - - loop { - // 1️⃣ Read hardware offset from watcher - let hw_offset_ms = *offset.lock().unwrap(); - - // 2️⃣ Check Chrony status and gather network interfaces - let ntp_active = ntp_service_active(); - let interfaces: Vec = get_if_addrs() - .unwrap_or_default() - .into_iter() - .filter(|ifa| !ifa.is_loopback()) - .map(|ifa| ifa.ip().to_string()) - .collect(); - - // 3️⃣ Measure & record jitter and Timecode Δ when LOCKED; clear on FREE - { - let mut st = state.lock().unwrap(); - if let Some(frame) = st.latest.clone() { - if frame.status == "LOCK" { - // Jitter in ms - let now = Utc::now(); - let raw = (now - frame.timestamp).num_milliseconds(); - let measured = raw - hw_offset_ms; - st.record_offset(measured); - - // Timecode delta - 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 offset_dt = local.date_naive().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(); - } - } - } - - // 4️⃣ Compute averages & statuses -let (avg_ms, _avg_frames, status_str, lock_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(), - ) - }; - - // 5️⃣ Update cached delta once per second - if last_delta_update.elapsed() >= Duration::from_secs(1) { - cached_delta_ms = avg_delta; - // Recompute frames equivalent - 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(); - } - - // 6️⃣ Auto-sync if "OUT OF SYNC" or Δ >5ms for 5s - if status_str == "OUT OF SYNC" || cached_delta_ms.abs() > 5 { - if let Some(start) = out_of_sync_since { - if start.elapsed() >= Duration::from_secs(5) { - // Perform sync to LTC - if let Ok(stl) = state.lock() { - if let Some(frame) = &stl.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() - }; - if logs.len() == 10 { - logs.pop_front(); - } - logs.push_back(msg); - } - } - out_of_sync_since = None; - } - } else { - out_of_sync_since = Some(Instant::now()); - } - } else { - out_of_sync_since = None; - } - - // 7️⃣ Draw static UI header - queue!( - stdout, - MoveTo(0, 0), Clear(ClearType::All), - MoveTo(2, 1), Print("Have Blue - NTP Timeturner - FrameWorks Testing"), - MoveTo(2, 2), Print(format!("Serial Port : {}", serial_port)), - MoveTo(2, 3), Print(format!("Chrony Service : {}", if ntp_active { "RUNNING" } else { "MISSING" })), - MoveTo(2, 4), Print(format!("Interfaces : {}", interfaces.join(", "))), - ) - .unwrap(); - - // 8️⃣ Draw LTC and System Clock - if let Ok(st) = state.lock() { - if let Some(frame) = &st.latest { - queue!( - stdout, - MoveTo(2, 6), Print(format!("LTC Status : {}", frame.status)), - MoveTo(2, 7), Print(format!( - "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(); - } 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 - let dcol = if cached_delta_ms.abs() < 20 { - Color::Green - } else if cached_delta_ms.abs() < 100 { - Color::Yellow - } else { - Color::Red - }; - queue!( - stdout, - MoveTo(2, 11), SetForegroundColor(dcol), - Print(format!("Timecode Δ : {:+} ms ({:+} frames)", cached_delta_ms, cached_delta_frames)), - ResetColor, - ) - .unwrap(); - - let scol = if status_str == "IN SYNC" { - Color::Green - } else { - Color::Red - }; - queue!( - stdout, - MoveTo(2, 12), SetForegroundColor(scol), - Print(format!("Sync Status : {}", status_str)), - ResetColor, - ) - .unwrap(); - - let jstatus = if avg_ms.abs() < 10 { - "GOOD" - } else if avg_ms.abs() < 40 { - "AVERAGE" - } else { - "BAD" - }; - let jcol = if jstatus == "GOOD" { - Color::Green - } else if jstatus == "AVERAGE" { - Color::Yellow - } else { - Color::Red - }; - queue!( - stdout, - MoveTo(2, 13), SetForegroundColor(jcol), - Print(format!("Sync Jitter : {}", jstatus)), - ResetColor, - ) - .unwrap(); - - queue!( - stdout, - MoveTo(2, 14), Print(format!("Lock Ratio : {:.1}% LOCK", lock_ratio)), - ) - .unwrap(); - - // 10️⃣ Footer and logs - queue!( - stdout, - MoveTo(2, 16), Print("[S] Sync system clock to LTC [Q] Quit"), - ) - .unwrap(); - for (i, log_msg) in logs.iter().enumerate() { - queue!(stdout, MoveTo(2, 18 + i as u16), Print(log_msg)).unwrap(); - } - - stdout.flush().unwrap(); - - // 11️⃣ Handle manual sync and quit keys - if poll(Duration::from_millis(50)).unwrap() { - if let Event::Key(evt) = read().unwrap() { - match evt.code { - KeyCode::Char(c) if c.eq_ignore_ascii_case(&'q') => { - execute!(stdout, Show, LeaveAlternateScreen).unwrap(); - terminal::disable_raw_mode().unwrap(); - process::exit(0); - } - KeyCode::Char(c) if c.eq_ignore_ascii_case(&'s') => { - if let Ok(stlock) = state.lock() { - if let Some(frame) = &stlock.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() - }; - if logs.len() == 10 { - logs.pop_front(); - } - logs.push_back(msg); - } - } - } - _ => {} - } - } - } - - thread::sleep(Duration::from_millis(25)); - } -} +// src/ui.rs + +use std::{ + io::{stdout, Write}, + process::{self, Command}, + sync::{Arc, Mutex}, + thread, + time::{Duration, Instant}, +}; +use std::collections::VecDeque; + +use chrono::{Local, Timelike, Utc, NaiveTime, Duration as ChronoDuration, TimeZone}; +use crossterm::{ + cursor::{Hide, MoveTo, Show}, + event::{poll, read, Event, KeyCode}, + execute, queue, + style::{Color, Print, ResetColor, SetForegroundColor}, + terminal::{self, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen}, +}; + +use get_if_addrs::get_if_addrs; +use crate::sync_logic::LtcState; + +/// Check if the Chrony service is active +fn ntp_service_active() -> bool { + if let Ok(output) = Command::new("systemctl").args(&["is-active", "chrony"]).output() { + output.status.success() + && String::from_utf8_lossy(&output.stdout).trim() == "active" + } else { + false + } +} + +/// Toggle the Chrony service (start if `start` is true, stop otherwise) + +fn _ntp_service_toggle(start: bool) { + let action = if start { "start" } else { "stop" }; + 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( + state: Arc>, + serial_port: String, + offset: Arc>, +) { + let mut stdout = stdout(); + // Enter alternate screen and hide cursor + execute!(stdout, EnterAlternateScreen, Hide).unwrap(); + terminal::enable_raw_mode().unwrap(); + + // Recent log of messages (last 10) + let mut logs: VecDeque = VecDeque::with_capacity(10); + // Tracks when we first detected out-of-sync + let mut out_of_sync_since: Option = None; + + // For caching the timecode delta display once per second + let mut last_delta_update = Instant::now() - Duration::from_secs(1); + let mut cached_delta_ms: i64 = 0; + let mut cached_delta_frames: i64 = 0; + + loop { + // 1️⃣ Read hardware offset from watcher + let hw_offset_ms = *offset.lock().unwrap(); + + // 2️⃣ Check Chrony status and gather network interfaces + let ntp_active = ntp_service_active(); + let interfaces: Vec = get_if_addrs() + .unwrap_or_default() + .into_iter() + .filter(|ifa| !ifa.is_loopback()) + .map(|ifa| ifa.ip().to_string()) + .collect(); + + // 3️⃣ Measure & record jitter and Timecode Δ when LOCKED; clear on FREE + { + let mut st = state.lock().unwrap(); + if let Some(frame) = st.latest.clone() { + if frame.status == "LOCK" { + // Jitter in ms + let now = Utc::now(); + let raw = (now - frame.timestamp).num_milliseconds(); + let measured = raw - hw_offset_ms; + st.record_offset(measured); + + // Timecode delta + 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 offset_dt = local.date_naive().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(); + } + } + } + + // 4️⃣ Compute averages & statuses +let (avg_ms, _avg_frames, status_str, lock_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(), + ) + }; + + // 5️⃣ Update cached delta once per second + if last_delta_update.elapsed() >= Duration::from_secs(1) { + cached_delta_ms = avg_delta; + // Recompute frames equivalent + 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(); + } + + // 6️⃣ Auto-sync if "OUT OF SYNC" or Δ >5ms for 5s + if status_str == "OUT OF SYNC" || cached_delta_ms.abs() > 5 { + if let Some(start) = out_of_sync_since { + if start.elapsed() >= Duration::from_secs(5) { + // Perform sync to LTC + if let Ok(stl) = state.lock() { + if let Some(frame) = &stl.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() + }; + if logs.len() == 10 { + logs.pop_front(); + } + logs.push_back(msg); + } + } + out_of_sync_since = None; + } + } else { + out_of_sync_since = Some(Instant::now()); + } + } else { + out_of_sync_since = None; + } + + // 7️⃣ Draw static UI header + queue!( + stdout, + MoveTo(0, 0), Clear(ClearType::All), + MoveTo(2, 1), Print("Have Blue - NTP Timeturner - FrameWorks Testing"), + MoveTo(2, 2), Print(format!("Serial Port : {}", serial_port)), + MoveTo(2, 3), Print(format!("Chrony Service : {}", if ntp_active { "RUNNING" } else { "MISSING" })), + MoveTo(2, 4), Print(format!("Interfaces : {}", interfaces.join(", "))), + ) + .unwrap(); + + // 8️⃣ Draw LTC and System Clock + if let Ok(st) = state.lock() { + if let Some(frame) = &st.latest { + queue!( + stdout, + MoveTo(2, 6), Print(format!("LTC Status : {}", frame.status)), + MoveTo(2, 7), Print(format!( + "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(); + } 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 + let dcol = if cached_delta_ms.abs() < 20 { + Color::Green + } else if cached_delta_ms.abs() < 100 { + Color::Yellow + } else { + Color::Red + }; + queue!( + stdout, + MoveTo(2, 11), SetForegroundColor(dcol), + Print(format!("Timecode Δ : {:+} ms ({:+} frames)", cached_delta_ms, cached_delta_frames)), + ResetColor, + ) + .unwrap(); + + let scol = if status_str == "IN SYNC" { + Color::Green + } else { + Color::Red + }; + queue!( + stdout, + MoveTo(2, 12), SetForegroundColor(scol), + Print(format!("Sync Status : {}", status_str)), + ResetColor, + ) + .unwrap(); + + let jstatus = if avg_ms.abs() < 10 { + "GOOD" + } else if avg_ms.abs() < 40 { + "AVERAGE" + } else { + "BAD" + }; + let jcol = if jstatus == "GOOD" { + Color::Green + } else if jstatus == "AVERAGE" { + Color::Yellow + } else { + Color::Red + }; + queue!( + stdout, + MoveTo(2, 13), SetForegroundColor(jcol), + Print(format!("Sync Jitter : {}", jstatus)), + ResetColor, + ) + .unwrap(); + + queue!( + stdout, + MoveTo(2, 14), Print(format!("Lock Ratio : {:.1}% LOCK", lock_ratio)), + ) + .unwrap(); + + // 10️⃣ Footer and logs + queue!( + stdout, + MoveTo(2, 16), Print("[S] Sync system clock to LTC [Q] Quit"), + ) + .unwrap(); + for (i, log_msg) in logs.iter().enumerate() { + queue!(stdout, MoveTo(2, 18 + i as u16), Print(log_msg)).unwrap(); + } + + stdout.flush().unwrap(); + + // 11️⃣ Handle manual sync and quit keys + if poll(Duration::from_millis(50)).unwrap() { + if let Event::Key(evt) = read().unwrap() { + match evt.code { + KeyCode::Char(c) if c.eq_ignore_ascii_case(&'q') => { + execute!(stdout, Show, LeaveAlternateScreen).unwrap(); + terminal::disable_raw_mode().unwrap(); + process::exit(0); + } + KeyCode::Char(c) if c.eq_ignore_ascii_case(&'s') => { + if let Ok(stlock) = state.lock() { + if let Some(frame) = &stlock.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() + }; + if logs.len() == 10 { + logs.pop_front(); + } + logs.push_back(msg); + } + } + } + _ => {} + } + } + } + + thread::sleep(Duration::from_millis(25)); + } +}