Merge pull request #3 from Johnr24/update

double check upload of tested version
This commit is contained in:
Chaos Rogers 2025-07-19 15:52:21 +01:00 committed by GitHub
commit aa453c30bc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 2344 additions and 624 deletions

1720
Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,69 +1,69 @@
// src/config.rs // src/config.rs
use notify::{ use notify::{
recommended_watcher, Event, EventKind, RecommendedWatcher, RecursiveMode, Result as NotifyResult, recommended_watcher, Event, EventKind, RecommendedWatcher, RecursiveMode, Result as NotifyResult,
Watcher, Watcher,
}; };
use serde::Deserialize; use serde::Deserialize;
use std::{ use std::{
fs::File, fs::File,
io::Read, io::Read,
path::PathBuf, path::PathBuf,
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct Config { pub struct Config {
pub hardware_offset_ms: i64, pub hardware_offset_ms: i64,
} }
impl Config { impl Config {
pub fn load(path: &PathBuf) -> Self { pub fn load(path: &PathBuf) -> Self {
let mut file = match File::open(path) { let mut file = match File::open(path) {
Ok(f) => f, Ok(f) => f,
Err(_) => return Self { hardware_offset_ms: 0 }, Err(_) => return Self { hardware_offset_ms: 0 },
}; };
let mut contents = String::new(); let mut contents = String::new();
if file.read_to_string(&mut contents).is_err() { if file.read_to_string(&mut contents).is_err() {
return Self { hardware_offset_ms: 0 }; return Self { hardware_offset_ms: 0 };
} }
serde_json::from_str(&contents).unwrap_or(Self { hardware_offset_ms: 0 }) serde_json::from_str(&contents).unwrap_or(Self { hardware_offset_ms: 0 })
} }
} }
pub fn watch_config(path: &str) -> Arc<Mutex<i64>> { pub fn watch_config(path: &str) -> Arc<Mutex<i64>> {
let initial = Config::load(&PathBuf::from(path)).hardware_offset_ms; let initial = Config::load(&PathBuf::from(path)).hardware_offset_ms;
let offset = Arc::new(Mutex::new(initial)); let offset = Arc::new(Mutex::new(initial));
// Owned PathBuf for watch() call // Owned PathBuf for watch() call
let watch_path = PathBuf::from(path); let watch_path = PathBuf::from(path);
// Clone for moving into the closure // Clone for moving into the closure
let watch_path_for_cb = watch_path.clone(); let watch_path_for_cb = watch_path.clone();
let offset_for_cb = Arc::clone(&offset); let offset_for_cb = Arc::clone(&offset);
std::thread::spawn(move || { std::thread::spawn(move || {
// Move `watch_path_for_cb` into the callback // Move `watch_path_for_cb` into the callback
let mut watcher: RecommendedWatcher = recommended_watcher(move |res: NotifyResult<Event>| { let mut watcher: RecommendedWatcher = recommended_watcher(move |res: NotifyResult<Event>| {
if let Ok(evt) = res { if let Ok(evt) = res {
if matches!(evt.kind, EventKind::Modify(_)) { if matches!(evt.kind, EventKind::Modify(_)) {
let new_cfg = Config::load(&watch_path_for_cb); let new_cfg = Config::load(&watch_path_for_cb);
let mut hw = offset_for_cb.lock().unwrap(); let mut hw = offset_for_cb.lock().unwrap();
*hw = new_cfg.hardware_offset_ms; *hw = new_cfg.hardware_offset_ms;
eprintln!("🔄 Reloaded hardware_offset_ms = {}", *hw); eprintln!("🔄 Reloaded hardware_offset_ms = {}", *hw);
} }
} }
}) })
.expect("Failed to create file watcher"); .expect("Failed to create file watcher");
// Use the original `watch_path` here // Use the original `watch_path` here
watcher watcher
.watch(&watch_path, RecursiveMode::NonRecursive) .watch(&watch_path, RecursiveMode::NonRecursive)
.expect("Failed to watch config.json"); .expect("Failed to watch config.json");
loop { loop {
std::thread::sleep(std::time::Duration::from_secs(60)); std::thread::sleep(std::time::Duration::from_secs(60));
} }
}); });
offset offset
} }

View file

@ -1,81 +1,81 @@
// src/main.rs // src/main.rs
mod config; mod config;
mod sync_logic; mod sync_logic;
mod serial_input; mod serial_input;
mod ui; mod ui;
use crate::config::watch_config; use crate::config::watch_config;
use crate::sync_logic::LtcState; use crate::sync_logic::LtcState;
use crate::serial_input::start_serial_thread; use crate::serial_input::start_serial_thread;
use crate::ui::start_ui; use crate::ui::start_ui;
use std::{ use std::{
fs, fs,
path::Path, path::Path,
sync::{Arc, Mutex, mpsc}, sync::{Arc, Mutex, mpsc},
thread, thread,
}; };
/// Embed the default config.json at compile time. /// Embed the default config.json at compile time.
const DEFAULT_CONFIG: &str = include_str!("../config.json"); const DEFAULT_CONFIG: &str = include_str!("../config.json");
/// If no `config.json` exists alongside the binary, write out the default. /// If no `config.json` exists alongside the binary, write out the default.
fn ensure_config() { fn ensure_config() {
let p = Path::new("config.json"); let p = Path::new("config.json");
if !p.exists() { if !p.exists() {
fs::write(p, DEFAULT_CONFIG) fs::write(p, DEFAULT_CONFIG)
.expect("Failed to write default config.json"); .expect("Failed to write default config.json");
eprintln!("⚙️ Emitted default config.json"); eprintln!("⚙️ Emitted default config.json");
} }
} }
fn main() { fn main() {
// 🔄 Ensure there's always a config.json present // 🔄 Ensure there's always a config.json present
ensure_config(); ensure_config();
// 1⃣ Start watching config.json for changes // 1⃣ Start watching config.json for changes
let hw_offset = watch_config("config.json"); let hw_offset = watch_config("config.json");
println!("🔧 Watching config.json (hardware_offset_ms)..."); println!("🔧 Watching config.json (hardware_offset_ms)...");
// 2⃣ Channel for raw LTC frames // 2⃣ Channel for raw LTC frames
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
println!("✅ Channel created"); println!("✅ Channel created");
// 3⃣ Shared state for UI and serial reader // 3⃣ Shared state for UI and serial reader
let ltc_state = Arc::new(Mutex::new(LtcState::new())); let ltc_state = Arc::new(Mutex::new(LtcState::new()));
println!("✅ State initialised"); println!("✅ State initialised");
// 4⃣ Spawn the serial reader thread (no offset here) // 4⃣ Spawn the serial reader thread (no offset here)
{ {
let tx_clone = tx.clone(); let tx_clone = tx.clone();
let state_clone = ltc_state.clone(); let state_clone = ltc_state.clone();
thread::spawn(move || { thread::spawn(move || {
println!("🚀 Serial thread launched"); println!("🚀 Serial thread launched");
start_serial_thread( start_serial_thread(
"/dev/ttyACM0", "/dev/ttyACM0",
115200, 115200,
tx_clone, tx_clone,
state_clone, state_clone,
0, // ignored in serial path 0, // ignored in serial path
); );
}); });
} }
// 5⃣ Spawn the UI renderer thread, passing the live offset Arc // 5⃣ Spawn the UI renderer thread, passing the live offset Arc
{ {
let ui_state = ltc_state.clone(); let ui_state = ltc_state.clone();
let offset_clone = hw_offset.clone(); let offset_clone = hw_offset.clone();
let port = "/dev/ttyACM0".to_string(); let port = "/dev/ttyACM0".to_string();
thread::spawn(move || { thread::spawn(move || {
println!("🖥️ UI thread launched"); println!("🖥️ UI thread launched");
start_ui(ui_state, port, offset_clone); start_ui(ui_state, port, offset_clone);
}); });
} }
// 6⃣ Keep main thread alive // 6⃣ Keep main thread alive
println!("📡 Main thread entering loop..."); println!("📡 Main thread entering loop...");
for _frame in rx { for _frame in rx {
// no-op // no-op
} }
} }

View file

@ -1,56 +1,56 @@
// src/serial_input.rs // src/serial_input.rs
use std::io::BufRead; use std::io::BufRead;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::sync::mpsc::Sender; use std::sync::mpsc::Sender;
use chrono::Utc; use chrono::Utc;
use regex::Regex; use regex::Regex;
use crate::sync_logic::{LtcFrame, LtcState}; use crate::sync_logic::{LtcFrame, LtcState};
pub fn start_serial_thread( pub fn start_serial_thread(
port_path: &str, port_path: &str,
baud_rate: u32, baud_rate: u32,
sender: Sender<LtcFrame>, sender: Sender<LtcFrame>,
state: Arc<Mutex<LtcState>>, state: Arc<Mutex<LtcState>>,
_hardware_offset_ms: i64, // no longer used here _hardware_offset_ms: i64, // no longer used here
) { ) {
println!("📡 Opening serial port {} @ {} baud", port_path, baud_rate); println!("📡 Opening serial port {} @ {} baud", port_path, baud_rate);
let port = match serialport::new(port_path, baud_rate) let port = match serialport::new(port_path, baud_rate)
.timeout(std::time::Duration::from_millis(1000)) .timeout(std::time::Duration::from_millis(1000))
.open() .open()
{ {
Ok(p) => { Ok(p) => {
println!("✅ Serial port opened"); println!("✅ Serial port opened");
p p
} }
Err(e) => { Err(e) => {
eprintln!("❌ Serial open failed: {}", e); eprintln!("❌ Serial open failed: {}", e);
return; return;
} }
}; };
let reader = std::io::BufReader::new(port); let reader = std::io::BufReader::new(port);
let re = Regex::new( let re = Regex::new(
r"\[(LOCK|FREE)\]\s+(\d{2}):(\d{2}):(\d{2})[:;](\d{2})\s+\|\s+([\d.]+)fps", r"\[(LOCK|FREE)\]\s+(\d{2}):(\d{2}):(\d{2})[:;](\d{2})\s+\|\s+([\d.]+)fps",
) )
.unwrap(); .unwrap();
println!("🔄 Entering LTC read loop…"); println!("🔄 Entering LTC read loop…");
for line in reader.lines() { for line in reader.lines() {
if let Ok(text) = line { if let Ok(text) = line {
if let Some(caps) = re.captures(&text) { if let Some(caps) = re.captures(&text) {
let arrival = Utc::now(); let arrival = Utc::now();
if let Some(frame) = LtcFrame::from_regex(&caps, arrival) { if let Some(frame) = LtcFrame::from_regex(&caps, arrival) {
// update LOCK/FREE counts & timestamp // update LOCK/FREE counts & timestamp
{ {
let mut st = state.lock().unwrap(); let mut st = state.lock().unwrap();
st.update(frame.clone()); st.update(frame.clone());
} }
// forward raw frame // forward raw frame
let _ = sender.send(frame); let _ = sender.send(frame);
} }
} }
} }
} }
} }

View file

@ -1,206 +1,206 @@
// src/sync_logic.rs // src/sync_logic.rs
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>,
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),
last_match_status: "UNKNOWN".into(), last_match_status: "UNKNOWN".into(),
last_match_check: 0, last_match_check: 0,
} }
} }
/// Record one measured offset in ms, maintaining a sliding window of up to 20 samples. /// Record one measured offset in ms, maintaining a sliding window of up to 20 samples.
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);
} }
/// Clear all stored offset measurements (e.g. on FREE-run). /// Clear all stored offset measurements (e.g. on FREE-run).
pub fn clear_offsets(&mut self) { pub fn clear_offsets(&mut self) {
self.offset_history.clear(); self.offset_history.clear();
} }
/// Update LOCK/FREE counts, clear offsets on FREE, and refresh timecode-match every 5 s. /// Update LOCK/FREE counts, clear offsets on FREE, and refresh timecode-match 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;
}
// Every 5 seconds, recompute whether HH:MM:SS matches local time "FREE" => {
let now_secs = Utc::now().timestamp(); self.free_count += 1;
if now_secs - self.last_match_check >= 5 { self.clear_offsets();
self.last_match_status = if frame.matches_system_time() { self.last_match_status = "UNKNOWN".into();
"IN SYNC".into() }
} else { _ => {}
"OUT OF SYNC".into() }
};
self.last_match_check = now_secs; // Every 5 seconds, recompute whether HH:MM:SS matches local time
} let now_secs = Utc::now().timestamp();
} if now_secs - self.last_match_check >= 5 {
"FREE" => { self.last_match_status = if frame.matches_system_time() {
self.free_count += 1; "IN SYNC".into()
self.clear_offsets(); } else {
self.last_match_status = "UNKNOWN".into(); "OUT OF SYNC".into()
} };
_ => {} self.last_match_check = now_secs;
} }
self.latest = Some(frame); self.latest = Some(frame);
} }
/// Average jitter over the stored history, in milliseconds. /// Average jitter over the stored history, in milliseconds.
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 that average jitter into frames (rounded). /// Convert that 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
} }
} }
/// 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 the last computed timecodematch status ("IN SYNC", "OUT OF SYNC", or "UNKNOWN"). /// Get the last computed timecodematch status ("IN SYNC", "OUT OF SYNC", or "UNKNOWN").
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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use chrono::{Local, Utc}; use chrono::{Local, Utc};
fn get_test_frame(status: &str, h: u32, m: u32, s: u32) -> LtcFrame { fn get_test_frame(status: &str, h: u32, m: u32, s: u32) -> LtcFrame {
LtcFrame { LtcFrame {
status: status.to_string(), status: status.to_string(),
hours: h, hours: h,
minutes: m, minutes: m,
seconds: s, seconds: s,
frames: 0, frames: 0,
frame_rate: 25.0, frame_rate: 25.0,
timestamp: Utc::now(), timestamp: Utc::now(),
} }
} }
#[test] #[test]
fn test_ltc_frame_matches_system_time() { fn test_ltc_frame_matches_system_time() {
let now = Local::now(); let now = Local::now();
let frame = get_test_frame("LOCK", now.hour(), now.minute(), now.second()); let frame = get_test_frame("LOCK", now.hour(), now.minute(), now.second());
assert!(frame.matches_system_time()); assert!(frame.matches_system_time());
} }
#[test] #[test]
fn test_ltc_frame_does_not_match_system_time() { fn test_ltc_frame_does_not_match_system_time() {
let now = Local::now(); let now = Local::now();
// Create a time that is one hour ahead, wrapping around 23:00 // Create a time that is one hour ahead, wrapping around 23:00
let different_hour = (now.hour() + 1) % 24; let different_hour = (now.hour() + 1) % 24;
let frame = get_test_frame("LOCK", different_hour, now.minute(), now.second()); let frame = get_test_frame("LOCK", different_hour, now.minute(), now.second());
assert!(!frame.matches_system_time()); assert!(!frame.matches_system_time());
} }
#[test] #[test]
fn test_ltc_state_update_lock() { fn test_ltc_state_update_lock() {
let mut state = LtcState::new(); let mut state = LtcState::new();
let frame = get_test_frame("LOCK", 10, 20, 30); let frame = get_test_frame("LOCK", 10, 20, 30);
state.update(frame); state.update(frame);
assert_eq!(state.lock_count, 1); assert_eq!(state.lock_count, 1);
assert_eq!(state.free_count, 0); assert_eq!(state.free_count, 0);
assert!(state.latest.is_some()); assert!(state.latest.is_some());
} }
#[test] #[test]
fn test_ltc_state_update_free() { fn test_ltc_state_update_free() {
let mut state = LtcState::new(); let mut state = LtcState::new();
state.record_offset(100); state.record_offset(100);
assert!(!state.offset_history.is_empty()); assert!(!state.offset_history.is_empty());
let frame = get_test_frame("FREE", 10, 20, 30); let frame = get_test_frame("FREE", 10, 20, 30);
state.update(frame); state.update(frame);
assert_eq!(state.lock_count, 0); assert_eq!(state.lock_count, 0);
assert_eq!(state.free_count, 1); assert_eq!(state.free_count, 1);
assert!(state.offset_history.is_empty()); // Offsets should be cleared assert!(state.offset_history.is_empty()); // Offsets should be cleared
assert_eq!(state.last_match_status, "UNKNOWN"); assert_eq!(state.last_match_status, "OUT OF SYNC");
} }
#[test] #[test]
fn test_offset_history_management() { fn test_offset_history_management() {
let mut state = LtcState::new(); let mut state = LtcState::new();
for i in 0..25 { for i in 0..25 {
state.record_offset(i); state.record_offset(i);
} }
assert_eq!(state.offset_history.len(), 20); 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.front().unwrap(), 5); // 0-4 are pushed out
assert_eq!(*state.offset_history.back().unwrap(), 24); assert_eq!(*state.offset_history.back().unwrap(), 24);
} }
} }

424
src/ui.rs
View file

@ -1,212 +1,212 @@
// 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, time::Duration,
}; };
use chrono::{Local, Timelike, Utc}; use chrono::{Local, Timelike, Utc};
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 crate::sync_logic::LtcState; 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.
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();
execute!(stdout, EnterAlternateScreen).unwrap(); execute!(stdout, EnterAlternateScreen).unwrap();
terminal::enable_raw_mode().unwrap(); terminal::enable_raw_mode().unwrap();
loop { loop {
// 1⃣ Read current hardware offset // 1⃣ Read current hardware offset
let hw_offset_ms = *offset.lock().unwrap(); let hw_offset_ms = *offset.lock().unwrap();
// 2⃣ Measure & record jitter only when LOCKED; clear on FREE // 2⃣ Measure & record jitter only when LOCKED; clear on FREE
{ {
let mut st = state.lock().unwrap(); let mut st = state.lock().unwrap();
if let Some(frame) = &st.latest { if let Some(frame) = &st.latest {
if frame.status == "LOCK" { if frame.status == "LOCK" {
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);
} else { } else {
st.clear_offsets(); st.clear_offsets();
} }
} }
} }
// 3⃣ Draw static UI // 3⃣ Draw static UI
queue!( queue!(
stdout, stdout,
MoveTo(0, 0), MoveTo(0, 0),
Clear(ClearType::All), Clear(ClearType::All),
Hide, Hide,
MoveTo(2, 1), Print("NTP Timeturner v2 - Rust Port"), MoveTo(2, 1), Print("NTP Timeturner v2 - Rust Port"),
MoveTo(2, 2), Print(format!("Using Serial Port: {}", serial_port)), MoveTo(2, 2), Print(format!("Using Serial Port: {}", serial_port)),
) )
.unwrap(); .unwrap();
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, 4), Print(format!("LTC Status : {}", frame.status)), MoveTo(2, 4), Print(format!("LTC Status : {}", frame.status)),
MoveTo(2, 5), Print(format!( MoveTo(2, 5), 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, 6), Print(format!("Frame Rate : {:.2}fps", frame.frame_rate)), MoveTo(2, 6), Print(format!("Frame Rate : {:.2}fps", frame.frame_rate)),
) )
.unwrap(); .unwrap();
} else { } else {
queue!( queue!(
stdout, stdout,
MoveTo(2, 4), Print("LTC Status : (waiting)"), MoveTo(2, 4), Print("LTC Status : (waiting)"),
MoveTo(2, 5), Print("LTC Timecode : …"), MoveTo(2, 5), Print("LTC Timecode : …"),
MoveTo(2, 6), Print("Frame Rate : …"), MoveTo(2, 6), Print("Frame Rate : …"),
) )
.unwrap(); .unwrap();
} }
let now_local = Local::now(); let now_local = Local::now();
let sys_str = format!( let sys_str = format!(
"{:02}:{:02}:{:02}.{:03}", "{:02}:{:02}:{:02}.{:03}",
now_local.hour(), now_local.hour(),
now_local.minute(), now_local.minute(),
now_local.second(), now_local.second(),
now_local.timestamp_subsec_millis() now_local.timestamp_subsec_millis()
); );
queue!( queue!(
stdout, stdout,
MoveTo(2, 7), MoveTo(2, 7),
Print(format!("System Clock : {}", sys_str)) Print(format!("System Clock : {}", sys_str))
) )
.unwrap(); .unwrap();
} }
// Footer // Footer
queue!( queue!(
stdout, stdout,
MoveTo(2, 12), MoveTo(2, 12),
Print("[S] Set system clock to LTC [Q] Quit") Print("[S] Set system clock to LTC [Q] Quit")
) )
.unwrap(); .unwrap();
stdout.flush().unwrap(); stdout.flush().unwrap();
// 4⃣ Overlay Sync Jitter / Status / Ratio // 4⃣ Overlay Sync Jitter / Status / Ratio
if let Ok(st) = state.lock() { if let Ok(st) = state.lock() {
let avg_ms = st.average_jitter(); let avg_ms = st.average_jitter();
let avg_frames = st.average_frames(); let avg_frames = st.average_frames();
let (jcol, jtxt) = if avg_ms.abs() < 10 { let (jcol, jtxt) = if avg_ms.abs() < 10 {
(Color::Green, format!("{:+} ms ({:+} frames)", avg_ms, avg_frames)) (Color::Green, format!("{:+} ms ({:+} frames)", avg_ms, avg_frames))
} else if avg_ms.abs() < 40 { } else if avg_ms.abs() < 40 {
(Color::Yellow, format!("{:+} ms ({:+} frames)", avg_ms, avg_frames)) (Color::Yellow, format!("{:+} ms ({:+} frames)", avg_ms, avg_frames))
} else { } else {
(Color::Red, format!("{:+} ms ({:+} frames)", avg_ms, avg_frames)) (Color::Red, format!("{:+} ms ({:+} frames)", avg_ms, avg_frames))
}; };
queue!( queue!(
stdout, stdout,
MoveTo(2, 8), MoveTo(2, 8),
SetForegroundColor(jcol), SetForegroundColor(jcol),
Print("Sync Jitter : "), Print("Sync Jitter : "),
Print(jtxt), Print(jtxt),
ResetColor, ResetColor,
) )
.ok(); .ok();
let status = st.timecode_match(); let status = st.timecode_match();
let scol = if status == "IN SYNC" { Color::Green } else { Color::Red }; let scol = if status == "IN SYNC" { Color::Green } else { Color::Red };
queue!( queue!(
stdout, stdout,
MoveTo(2, 9), MoveTo(2, 9),
SetForegroundColor(scol), SetForegroundColor(scol),
Print(format!("Sync Status : {}", status)), Print(format!("Sync Status : {}", status)),
ResetColor, ResetColor,
) )
.ok(); .ok();
let ratio = st.lock_ratio(); let ratio = st.lock_ratio();
queue!( queue!(
stdout, stdout,
MoveTo(2, 10), MoveTo(2, 10),
Print(format!("Lock Ratio : {:.1}% LOCK", ratio)), Print(format!("Lock Ratio : {:.1}% LOCK", ratio)),
) )
.ok(); .ok();
stdout.flush().ok(); stdout.flush().ok();
} }
// 5⃣ Handle keypress // 5⃣ Handle keypress
if poll(Duration::from_millis(0)).unwrap() { if poll(Duration::from_millis(0)).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(&'s') => { KeyCode::Char(c) if c.eq_ignore_ascii_case(&'s') => {
// SYNC now // SYNC now
if let Ok(st) = state.lock() { if let Ok(st) = state.lock() {
if let Some(frame) = &st.latest { if let Some(frame) = &st.latest {
// compute ms from frames // compute ms from frames
let ms_from_frames = let ms_from_frames =
((frame.frames as f64 / frame.frame_rate) * 1000.0).round() as i64; ((frame.frames as f64 / frame.frame_rate) * 1000.0).round() as i64;
// total microseconds // total microseconds
let total_us = (ms_from_frames + hw_offset_ms) * 1000; let total_us = (ms_from_frames + hw_offset_ms) * 1000;
// build date string "HH:MM:SS.mmm" // build date string "HH:MM:SS.mmm"
let ts = format!( let ts = format!(
"{:02}:{:02}:{:02}.{:03}", "{:02}:{:02}:{:02}.{:03}",
frame.hours, frame.hours,
frame.minutes, frame.minutes,
frame.seconds, frame.seconds,
((total_us / 1000) % 1000) ((total_us / 1000) % 1000)
); );
// run `sudo date -s "HH:MM:SS.mmm"` // run `sudo date -s "HH:MM:SS.mmm"`
let status = Command::new("sudo") let status = Command::new("sudo")
.arg("date") .arg("date")
.arg("-s") .arg("-s")
.arg(&ts) .arg(&ts)
.status(); .status();
let msg = if let Ok(s) = status { let msg = if let Ok(s) = status {
if s.success() { if s.success() {
format!("✔ Synced to LTC: {}", ts) format!("✔ Synced to LTC: {}", ts)
} else { } else {
format!("❌ date cmd failed") format!("❌ date cmd failed")
} }
} else { } else {
format!("❌ failed to spawn date") format!("❌ failed to spawn date")
}; };
// print confirmation at row 14 // print confirmation at row 14
queue!( queue!(
stdout, stdout,
MoveTo(2, 14), MoveTo(2, 14),
Print(msg), Print(msg),
) )
.ok(); .ok();
stdout.flush().ok(); stdout.flush().ok();
} }
} }
} }
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);
} }
_ => {} _ => {}
} }
} }
} }
thread::sleep(Duration::from_millis(50)); thread::sleep(Duration::from_millis(50));
} }
} }