Merge pull request #2 from Johnr24/withmergeresolve

Feat: Add CI Workflow, Unit Tests, and Fix Sync Logic, update two dependencies to most recent version,
This commit is contained in:
Chaos Rogers 2025-07-21 14:25:39 +01:00 committed by GitHub
commit d55d64ee5f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 747 additions and 516 deletions

6
.github/dependabot.yml vendored Normal file
View file

@ -0,0 +1,6 @@
version: 2
updates:
- package-ecosystem: "cargo"
directory: "/" # Location of Cargo.toml
schedule:
interval: "weekly"

70
.github/workflows/build.yml vendored Normal file
View file

@ -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

20
.gitignore vendored
View file

@ -358,4 +358,22 @@ MigrationBackup/
.ionide/ .ionide/
# Fody - auto-generated XML schema # Fody - auto-generated XML schema
FodyWeavers.xsd 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

View file

@ -6,9 +6,10 @@ edition = "2021"
[dependencies] [dependencies]
serialport = "4.2" serialport = "4.2"
chrono = "0.4" chrono = "0.4"
crossterm = "0.27" crossterm = "0.29"
regex = "1.11" regex = "1.11"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0.141"
notify = "5.1.0" notify = "8.1.0"
get_if_addrs = "0.5" get_if_addrs = "0.5"

View file

@ -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: Clone and run the installer:
```bash ```bash

View file

@ -1,163 +1,294 @@
use chrono::{DateTime, Local, Timelike, Utc}; use chrono::{DateTime, Local, Timelike, Utc};
use regex::Captures; use regex::Captures;
use std::collections::VecDeque; use std::collections::VecDeque;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct LtcFrame { pub struct LtcFrame {
pub status: String, pub status: String,
pub hours: u32, pub hours: u32,
pub minutes: u32, pub minutes: u32,
pub seconds: u32, pub seconds: u32,
pub frames: u32, pub frames: u32,
pub frame_rate: f64, pub frame_rate: f64,
pub timestamp: DateTime<Utc>, // arrival stamp pub timestamp: DateTime<Utc>, // arrival stamp
} }
impl LtcFrame { impl LtcFrame {
pub fn from_regex(caps: &Captures, timestamp: DateTime<Utc>) -> Option<Self> { pub fn from_regex(caps: &Captures, timestamp: DateTime<Utc>) -> Option<Self> {
Some(Self { Some(Self {
status: caps[1].to_string(), status: caps[1].to_string(),
hours: caps[2].parse().ok()?, hours: caps[2].parse().ok()?,
minutes: caps[3].parse().ok()?, minutes: caps[3].parse().ok()?,
seconds: caps[4].parse().ok()?, seconds: caps[4].parse().ok()?,
frames: caps[5].parse().ok()?, frames: caps[5].parse().ok()?,
frame_rate: caps[6].parse().ok()?, frame_rate: caps[6].parse().ok()?,
timestamp, timestamp,
}) })
} }
/// Compare just HH:MM:SS against local time. /// Compare just HH:MM:SS against local time.
pub fn matches_system_time(&self) -> bool { pub fn matches_system_time(&self) -> bool {
let local = Local::now(); let local = Local::now();
local.hour() == self.hours local.hour() == self.hours
&& local.minute() == self.minutes && local.minute() == self.minutes
&& local.second() == self.seconds && local.second() == self.seconds
} }
} }
pub struct LtcState { pub struct LtcState {
pub latest: Option<LtcFrame>, pub latest: Option<LtcFrame>,
pub lock_count: u32, pub lock_count: u32,
pub free_count: u32, pub free_count: u32,
/// Stores the last up-to-20 raw offset measurements in ms. /// Stores the last up-to-20 raw offset measurements in ms.
pub offset_history: VecDeque<i64>, pub offset_history: VecDeque<i64>,
/// Stores the last up-to-20 timecode Δ measurements in ms. /// Stores the last up-to-20 timecode Δ measurements in ms.
pub clock_delta_history: VecDeque<i64>, pub clock_delta_history: VecDeque<i64>,
pub last_match_status: String, pub last_match_status: String,
pub last_match_check: i64, pub last_match_check: i64,
} }
impl LtcState { impl LtcState {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
latest: None, latest: None,
lock_count: 0, lock_count: 0,
free_count: 0, free_count: 0,
offset_history: VecDeque::with_capacity(20), offset_history: VecDeque::with_capacity(20),
clock_delta_history: VecDeque::with_capacity(20), clock_delta_history: VecDeque::with_capacity(20),
last_match_status: "UNKNOWN".into(), last_match_status: "UNKNOWN".into(),
last_match_check: 0, last_match_check: 0,
} }
} }
/// Record one measured jitter offset in ms. /// Record one measured jitter offset in ms.
pub fn record_offset(&mut self, offset_ms: i64) { pub fn record_offset(&mut self, offset_ms: i64) {
if self.offset_history.len() == 20 { if self.offset_history.len() == 20 {
self.offset_history.pop_front(); self.offset_history.pop_front();
} }
self.offset_history.push_back(offset_ms); self.offset_history.push_back(offset_ms);
} }
/// Record one timecode Δ in ms. /// Record one timecode Δ in ms.
pub fn record_clock_delta(&mut self, delta_ms: i64) { pub fn record_clock_delta(&mut self, delta_ms: i64) {
if self.clock_delta_history.len() == 20 { if self.clock_delta_history.len() == 20 {
self.clock_delta_history.pop_front(); self.clock_delta_history.pop_front();
} }
self.clock_delta_history.push_back(delta_ms); self.clock_delta_history.push_back(delta_ms);
} }
/// Clear all stored jitter measurements. /// Clear all stored jitter measurements.
pub fn clear_offsets(&mut self) { pub fn clear_offsets(&mut self) {
self.offset_history.clear(); self.offset_history.clear();
} }
/// Clear all stored timecode Δ measurements. /// Clear all stored timecode Δ measurements.
pub fn clear_clock_deltas(&mut self) { pub fn clear_clock_deltas(&mut self) {
self.clock_delta_history.clear(); self.clock_delta_history.clear();
} }
/// Update LOCK/FREE counts and timecode-match status every 5 s. /// Update LOCK/FREE counts and timecode-match status every 5 s.
pub fn update(&mut self, frame: LtcFrame) { pub fn update(&mut self, frame: LtcFrame) {
match frame.status.as_str() { match frame.status.as_str() {
"LOCK" => { "LOCK" => {
self.lock_count += 1; self.lock_count += 1;
}
"FREE" => { // Recompute timecode-match every 5 seconds
self.free_count += 1; let now_secs = Utc::now().timestamp();
self.clear_offsets(); if now_secs - self.last_match_check >= 5 {
self.clear_clock_deltas(); self.last_match_status = if frame.matches_system_time() {
self.last_match_status = "UNKNOWN".into(); "IN SYNC"
} } else {
_ => {} "OUT OF SYNC"
} }
.into();
// Recompute timecode-match every 5 seconds self.last_match_check = now_secs;
let now_secs = Utc::now().timestamp(); }
if now_secs - self.last_match_check >= 5 { }
self.last_match_status = if let Some(frame) = &self.latest { "FREE" => {
if frame.matches_system_time() { "IN SYNC" } else { "OUT OF SYNC" } self.free_count += 1;
} else { self.clear_offsets();
"UNKNOWN" self.clear_clock_deltas();
} self.last_match_status = "UNKNOWN".into();
.into(); }
self.last_match_check = now_secs; _ => {}
} }
self.latest = Some(frame); self.latest = Some(frame);
} }
/// Average jitter over stored history, in ms. /// Average jitter over stored history, in ms.
pub fn average_jitter(&self) -> i64 { pub fn average_jitter(&self) -> i64 {
if self.offset_history.is_empty() { if self.offset_history.is_empty() {
0 0
} else { } else {
let sum: i64 = self.offset_history.iter().sum(); let sum: i64 = self.offset_history.iter().sum();
sum / self.offset_history.len() as i64 sum / self.offset_history.len() as i64
} }
} }
/// Convert average jitter into frames (rounded). /// Convert average jitter into frames (rounded).
pub fn average_frames(&self) -> i64 { pub fn average_frames(&self) -> i64 {
if let Some(frame) = &self.latest { if let Some(frame) = &self.latest {
let ms_per_frame = 1000.0 / frame.frame_rate; let ms_per_frame = 1000.0 / frame.frame_rate;
(self.average_jitter() as f64 / ms_per_frame).round() as i64 (self.average_jitter() as f64 / ms_per_frame).round() as i64
} else { } else {
0 0
} }
} }
/// Average timecode Δ over stored history, in ms. /// Average timecode Δ over stored history, in ms.
pub fn average_clock_delta(&self) -> i64 { pub fn average_clock_delta(&self) -> i64 {
if self.clock_delta_history.is_empty() { if self.clock_delta_history.is_empty() {
0 0
} else { } else {
let sum: i64 = self.clock_delta_history.iter().sum(); let sum: i64 = self.clock_delta_history.iter().sum();
sum / self.clock_delta_history.len() as i64 sum / self.clock_delta_history.len() as i64
} }
} }
/// Percentage of samples seen in LOCK state versus total. /// Percentage of samples seen in LOCK state versus total.
pub fn lock_ratio(&self) -> f64 { pub fn lock_ratio(&self) -> f64 {
let total = self.lock_count + self.free_count; let total = self.lock_count + self.free_count;
if total == 0 { if total == 0 {
0.0 0.0
} else { } else {
self.lock_count as f64 / total as f64 * 100.0 self.lock_count as f64 / total as f64 * 100.0
} }
} }
/// Get timecode-match status. /// Get timecode-match status.
pub fn timecode_match(&self) -> &str { pub fn timecode_match(&self) -> &str {
&self.last_match_status &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"
);
}
}

694
src/ui.rs
View file

@ -1,347 +1,347 @@
// src/ui.rs // 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},
thread, thread,
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use std::collections::VecDeque; use std::collections::VecDeque;
use chrono::{Local, Timelike, Utc, NaiveTime, Duration as ChronoDuration, TimeZone}; use chrono::{Local, Timelike, Utc, NaiveTime, Duration as ChronoDuration, TimeZone};
use crossterm::{ use crossterm::{
cursor::{Hide, MoveTo, Show}, cursor::{Hide, MoveTo, Show},
event::{poll, read, Event, KeyCode}, event::{poll, read, Event, KeyCode},
execute, queue, execute, queue,
style::{Color, Print, ResetColor, SetForegroundColor}, style::{Color, Print, ResetColor, SetForegroundColor},
terminal::{self, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen}, terminal::{self, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
}; };
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 the Chrony service 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()
&& String::from_utf8_lossy(&output.stdout).trim() == "active" && String::from_utf8_lossy(&output.stdout).trim() == "active"
} else { } else {
false false
} }
} }
/// Toggle the Chrony service (start if `start` is true, stop otherwise) /// Toggle the Chrony service (start if `start` is true, stop otherwise)
#[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. /// 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 // 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) // 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 // 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 // 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⃣ Read hardware offset from watcher
let hw_offset_ms = *offset.lock().unwrap(); let hw_offset_ms = *offset.lock().unwrap();
// 2⃣ Check Chrony status and gather network interfaces // 2⃣ Check Chrony status and gather network 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()
.into_iter() .into_iter()
.filter(|ifa| !ifa.is_loopback()) .filter(|ifa| !ifa.is_loopback())
.map(|ifa| ifa.ip().to_string()) .map(|ifa| ifa.ip().to_string())
.collect(); .collect();
// 3⃣ Measure & record jitter and Timecode Δ when LOCKED; clear on FREE // 3⃣ Measure & record jitter and Timecode Δ when LOCKED; clear on FREE
{ {
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 in ms
let now = Utc::now(); let now = Utc::now();
let raw = (now - frame.timestamp).num_milliseconds(); let raw = (now - 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 // Timecode delta
let local = Local::now(); 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 base_time = NaiveTime::from_hms_opt(frame.hours, frame.minutes, frame.seconds)
.unwrap_or(local.time()); .unwrap_or(local.time());
let offset_dt = local.date_naive().and_time(base_time) let offset_dt = local.date_naive().and_time(base_time)
+ ChronoDuration::milliseconds(sub_ms); + ChronoDuration::milliseconds(sub_ms);
let ltc_dt = Local.from_local_datetime(&offset_dt) let ltc_dt = Local.from_local_datetime(&offset_dt)
.single() .single()
.unwrap_or(local); .unwrap_or(local);
let delta_ms = local.signed_duration_since(ltc_dt).num_milliseconds(); 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();
st.clear_clock_deltas(); st.clear_clock_deltas();
} }
} }
} }
// 4⃣ Compute averages & statuses // 4⃣ Compute averages & statuses
let (avg_ms, _avg_frames, status_str, lock_ratio, avg_delta) = { let (avg_ms, _avg_frames, status_str, lock_ratio, avg_delta) = {
let st = state.lock().unwrap(); let st = state.lock().unwrap();
( (
st.average_jitter(), st.average_jitter(),
st.average_frames(), st.average_frames(),
st.timecode_match().to_string(), st.timecode_match().to_string(),
st.lock_ratio(), st.lock_ratio(),
st.average_clock_delta(), st.average_clock_delta(),
) )
}; };
// 5⃣ Update cached delta once per second // 5⃣ Update cached delta once per second
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 // Recompute frames equivalent
if let Ok(st2) = state.lock() { if let Ok(st2) = state.lock() {
if let Some(frame) = &st2.latest { if let Some(frame) = &st2.latest {
let ms_pf = 1000.0 / frame.frame_rate; let ms_pf = 1000.0 / frame.frame_rate;
cached_delta_frames = (cached_delta_ms as f64 / ms_pf).round() as i64; cached_delta_frames = (cached_delta_ms as f64 / ms_pf).round() as i64;
} }
} }
last_delta_update = Instant::now(); last_delta_update = Instant::now();
} }
// 6⃣ Auto-sync if "OUT OF SYNC" or Δ >5ms for 5s // 6⃣ Auto-sync if "OUT OF SYNC" or Δ >5ms for 5s
if status_str == "OUT OF SYNC" || cached_delta_ms.abs() > 5 { if status_str == "OUT OF SYNC" || cached_delta_ms.abs() > 5 {
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 // Perform sync to LTC
if let Ok(stl) = state.lock() { if let Ok(stl) = state.lock() {
if let Some(frame) = &stl.latest { if let Some(frame) = &stl.latest {
let local_now = Local::now(); let local_now = Local::now();
let sub_ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0) let sub_ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0)
.round() as i64; .round() as i64;
let base_time = NaiveTime::from_hms_opt( let base_time = NaiveTime::from_hms_opt(
frame.hours, frame.hours,
frame.minutes, frame.minutes,
frame.seconds, frame.seconds,
).unwrap_or(local_now.time()); ).unwrap_or(local_now.time());
let offset_dt = local_now.date_naive().and_time(base_time) let offset_dt = local_now.date_naive().and_time(base_time)
+ ChronoDuration::milliseconds(sub_ms); + ChronoDuration::milliseconds(sub_ms);
let ltc_dt = Local.from_local_datetime(&offset_dt) let ltc_dt = Local.from_local_datetime(&offset_dt)
.single() .single()
.unwrap_or(local_now); .unwrap_or(local_now);
let ts = format!("{:02}:{:02}:{:02}.{:03}", let ts = format!("{:02}:{:02}:{:02}.{:03}",
ltc_dt.hour(), ltc_dt.hour(),
ltc_dt.minute(), ltc_dt.minute(),
ltc_dt.second(), ltc_dt.second(),
ltc_dt.timestamp_subsec_millis() ltc_dt.timestamp_subsec_millis()
); );
let res = Command::new("sudo") let res = Command::new("sudo")
.arg("date") .arg("date")
.arg("-s") .arg("-s")
.arg(&ts) .arg(&ts)
.status(); .status();
let msg = if res.as_ref().map_or(false, |s| s.success()) { let msg = if res.as_ref().map_or(false, |s| s.success()) {
format!("🔄 Auto-synced to LTC: {}", ts) format!("🔄 Auto-synced to LTC: {}", ts)
} else { } else {
"❌ Auto-sync failed".into() "❌ Auto-sync failed".into()
}; };
if logs.len() == 10 { if logs.len() == 10 {
logs.pop_front(); logs.pop_front();
} }
logs.push_back(msg); logs.push_back(msg);
} }
} }
out_of_sync_since = None; out_of_sync_since = None;
} }
} else { } else {
out_of_sync_since = Some(Instant::now()); out_of_sync_since = Some(Instant::now());
} }
} else { } else {
out_of_sync_since = None; out_of_sync_since = None;
} }
// 7⃣ Draw static UI header // 7⃣ Draw static UI 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 - FrameWorks Testing"),
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⃣ Draw LTC and System Clock
if let Ok(st) = state.lock() { if let Ok(st) = state.lock() {
if let Some(frame) = &st.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!( MoveTo(2, 7), Print(format!(
"LTC Timecode : {:02}:{:02}:{:02}:{:02}", "LTC Timecode : {:02}:{:02}:{:02}:{:02}",
frame.hours, frame.minutes, frame.seconds, frame.frames frame.hours, frame.minutes, frame.seconds, frame.frames
)), )),
MoveTo(2, 8), Print(format!("Frame Rate : {:.2}fps", frame.frame_rate)), MoveTo(2, 8), Print(format!("Frame Rate : {:.2}fps", frame.frame_rate)),
) )
.unwrap(); .unwrap();
} else { } else {
queue!( queue!(
stdout, stdout,
MoveTo(2, 6), Print("LTC Status : (waiting)"), MoveTo(2, 6), Print("LTC Status : (waiting)"),
MoveTo(2, 7), Print("LTC Timecode : …"), MoveTo(2, 7), Print("LTC Timecode : …"),
MoveTo(2, 8), Print("Frame Rate : …"), MoveTo(2, 8), Print("Frame Rate : …"),
) )
.unwrap(); .unwrap();
} }
let now_local = Local::now(); let now_local = Local::now();
let sys_ts = format!("{:02}:{:02}:{:02}.{:03}", let sys_ts = format!("{:02}:{:02}:{:02}.{:03}",
now_local.hour(), now_local.minute(), now_local.second(), now_local.timestamp_subsec_millis() 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(); queue!(stdout, MoveTo(2, 9), Print(format!("System Clock : {}", sys_ts))).unwrap();
} }
// 9⃣ Overlay metrics in new order // 9⃣ Overlay metrics in new order
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 {
Color::Yellow Color::Yellow
} else { } else {
Color::Red 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 status_str == "IN SYNC" {
Color::Green Color::Green
} else { } else {
Color::Red 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 : {}", status_str)),
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 { } else if avg_ms.abs() < 40 {
"AVERAGE" "AVERAGE"
} else { } else {
"BAD" "BAD"
}; };
let jcol = if jstatus == "GOOD" { let jcol = if jstatus == "GOOD" {
Color::Green Color::Green
} else if jstatus == "AVERAGE" { } else if jstatus == "AVERAGE" {
Color::Yellow Color::Yellow
} else { } else {
Color::Red 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 and logs // 10⃣ Footer and 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, log_msg) in logs.iter().enumerate() { for (i, log_msg) in logs.iter().enumerate() {
queue!(stdout, MoveTo(2, 18 + i as u16), Print(log_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 // 11⃣ Handle manual sync and quit keys
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 {
KeyCode::Char(c) if c.eq_ignore_ascii_case(&'q') => { KeyCode::Char(c) if c.eq_ignore_ascii_case(&'q') => {
execute!(stdout, Show, LeaveAlternateScreen).unwrap(); execute!(stdout, Show, LeaveAlternateScreen).unwrap();
terminal::disable_raw_mode().unwrap(); terminal::disable_raw_mode().unwrap();
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 Ok(stlock) = state.lock() {
if let Some(frame) = &stlock.latest { if let Some(frame) = &stlock.latest {
let local_now = Local::now(); let local_now = Local::now();
let sub_ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0) let sub_ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0)
.round() as i64; .round() as i64;
let base_time = NaiveTime::from_hms_opt( let base_time = NaiveTime::from_hms_opt(
frame.hours, frame.hours,
frame.minutes, frame.minutes,
frame.seconds, frame.seconds,
) )
.unwrap_or(local_now.time()); .unwrap_or(local_now.time());
let offset_dt = local_now.date_naive().and_time(base_time) let offset_dt = local_now.date_naive().and_time(base_time)
+ ChronoDuration::milliseconds(sub_ms); + ChronoDuration::milliseconds(sub_ms);
let ltc_dt = Local.from_local_datetime(&offset_dt) let ltc_dt = Local.from_local_datetime(&offset_dt)
.single() .single()
.unwrap_or(local_now); .unwrap_or(local_now);
let ts = format!( let ts = format!(
"{:02}:{:02}:{:02}.{:03}", "{:02}:{:02}:{:02}.{:03}",
ltc_dt.hour(), ltc_dt.hour(),
ltc_dt.minute(), ltc_dt.minute(),
ltc_dt.second(), ltc_dt.second(),
ltc_dt.timestamp_subsec_millis(), ltc_dt.timestamp_subsec_millis(),
); );
let res = Command::new("sudo") let res = Command::new("sudo")
.arg("date") .arg("date")
.arg("-s") .arg("-s")
.arg(&ts) .arg(&ts)
.status(); .status();
let msg = if res.as_ref().map_or(false, |s| s.success()) { let msg = if res.as_ref().map_or(false, |s| s.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 { if logs.len() == 10 {
logs.pop_front(); logs.pop_front();
} }
logs.push_back(msg); logs.push_back(msg);
} }
} }
} }
_ => {} _ => {}
} }
} }
} }
thread::sleep(Duration::from_millis(25)); thread::sleep(Duration::from_millis(25));
} }
} }