mirror of
https://github.com/cjfranko/NTP-Timeturner.git
synced 2025-11-08 18:32:02 +00:00
Merge pull request #5 from cjfranko/ntp-server-daemon
ntp service implemented
This commit is contained in:
commit
4087df80d3
2 changed files with 126 additions and 61 deletions
|
|
@ -10,4 +10,5 @@ crossterm = "0.27"
|
||||||
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"
|
||||||
notify = "5.1.0"
|
notify = "5.1.0"
|
||||||
|
get_if_addrs = "0.5"
|
||||||
184
src/ui.rs
184
src/ui.rs
|
|
@ -17,50 +17,83 @@ use crossterm::{
|
||||||
terminal::{self, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
|
terminal::{self, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::sync_logic::LtcState;
|
use get_if_addrs::get_if_addrs;
|
||||||
use std::collections::VecDeque;
|
use std::collections::VecDeque;
|
||||||
|
use crate::sync_logic::LtcState;
|
||||||
|
|
||||||
/// Launch the TUI; reads `offset` live from the file-watcher and performs auto-sync if out of sync.
|
/// Check if the ntpd service is active
|
||||||
|
fn ntp_service_active() -> bool {
|
||||||
|
if let Ok(output) = Command::new("systemctl").args(&["is-active", "ntpd"]).output() {
|
||||||
|
output.status.success() && String::from_utf8_lossy(&output.stdout).trim() == "active"
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggle the ntpd 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, "ntpd"]).status();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Launch the full-featured TUI; reads `offset` live and performs auto-sync if out of sync.
|
||||||
pub fn start_ui(
|
pub fn start_ui(
|
||||||
state: Arc<Mutex<LtcState>>,
|
state: Arc<Mutex<LtcState>>,
|
||||||
serial_port: String,
|
serial_port: String,
|
||||||
offset: Arc<Mutex<i64>>,
|
offset: Arc<Mutex<i64>>,
|
||||||
) {
|
) {
|
||||||
let mut stdout = stdout();
|
let mut stdout = stdout();
|
||||||
|
// Enter alternate screen and hide cursor
|
||||||
execute!(stdout, EnterAlternateScreen, Hide).unwrap();
|
execute!(stdout, EnterAlternateScreen, Hide).unwrap();
|
||||||
terminal::enable_raw_mode().unwrap();
|
terminal::enable_raw_mode().unwrap();
|
||||||
|
|
||||||
// Recent log of messages (last 10)
|
// Recent log of messages (last 10)
|
||||||
let mut logs: VecDeque<String> = VecDeque::with_capacity(10);
|
let mut logs: VecDeque<String> = VecDeque::with_capacity(10);
|
||||||
|
// Tracks when we first detected out-of-sync
|
||||||
let mut out_of_sync_since: Option<Instant> = None;
|
let mut out_of_sync_since: Option<Instant> = None;
|
||||||
|
|
||||||
// Delta display cache: update 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
|
// 1️⃣ Read hardware offset from watcher
|
||||||
let hw_offset_ms = *offset.lock().unwrap();
|
let hw_offset_ms = *offset.lock().unwrap();
|
||||||
|
|
||||||
// 2️⃣ Measure & record jitter and Timecode Δ when LOCKED; clear both on FREE
|
// 2️⃣ Check NTP service status and gather network interfaces
|
||||||
|
let ntp_active = ntp_service_active();
|
||||||
|
let interfaces: Vec<String> = 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();
|
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" {
|
||||||
let measured = (Utc::now() - frame.timestamp).num_milliseconds() - hw_offset_ms;
|
// Jitter in ms
|
||||||
|
let now = Utc::now();
|
||||||
|
let raw = (now - frame.timestamp).num_milliseconds();
|
||||||
|
let measured = raw - hw_offset_ms;
|
||||||
st.record_offset(measured);
|
st.record_offset(measured);
|
||||||
|
|
||||||
|
// Timecode delta: how far system clock differs from LTC
|
||||||
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(
|
let base_time = NaiveTime::from_hms_opt(
|
||||||
frame.hours,
|
frame.hours,
|
||||||
frame.minutes,
|
frame.minutes,
|
||||||
frame.seconds,
|
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).single().unwrap_or(local);
|
let ltc_dt = Local.from_local_datetime(&offset_dt)
|
||||||
|
.single()
|
||||||
|
.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 {
|
||||||
|
|
@ -70,8 +103,8 @@ pub fn start_ui(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3️⃣ Compute averages and status
|
// 4️⃣ Compute averages & statuses
|
||||||
let (avg_ms, avg_frames, status, 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(),
|
||||||
|
|
@ -82,12 +115,12 @@ pub fn start_ui(
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
// 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;
|
||||||
// compute frames from ms
|
// Recompute frames equivalent
|
||||||
if let Ok(st) = state.lock() {
|
if let Ok(st2) = state.lock() {
|
||||||
if let Some(frame) = &st.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;
|
||||||
}
|
}
|
||||||
|
|
@ -95,12 +128,13 @@ pub fn start_ui(
|
||||||
last_delta_update = Instant::now();
|
last_delta_update = Instant::now();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Auto-sync: if OUT OF SYNC or Δ >10ms for 5s
|
// 6️⃣ Auto-sync if "OUT OF SYNC" or Δ >10ms for 5s
|
||||||
if status == "OUT OF SYNC" || cached_delta_ms.abs() > 10 {
|
if status_str == "OUT OF SYNC" || cached_delta_ms.abs() > 10 {
|
||||||
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) {
|
||||||
if let Ok(stlock) = state.lock() {
|
// Perform sync to LTC
|
||||||
if let Some(frame) = &stlock.latest {
|
if let Ok(stl) = state.lock() {
|
||||||
|
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;
|
||||||
|
|
@ -108,16 +142,23 @@ pub fn start_ui(
|
||||||
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.minute(), ltc_dt.second(), ltc_dt.timestamp_subsec_millis());
|
ltc_dt.hour(),
|
||||||
let res = Command::new("sudo").arg("date").arg("-s").arg(&ts).status();
|
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()) {
|
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 {
|
||||||
|
|
@ -138,44 +179,48 @@ pub fn start_ui(
|
||||||
out_of_sync_since = None;
|
out_of_sync_since = None;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4️⃣ Draw static UI
|
// 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("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)),
|
||||||
|
MoveTo(2, 3), Print(format!("NTP Server : {}", if ntp_active { "ACTIVE" } else { "INACTIVE" })),
|
||||||
|
MoveTo(2, 4), Print(format!("Interfaces : {}", interfaces.join(", "))),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
// 5️⃣ Draw LTC & 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, 4), Print(format!("LTC Status : {}", frame.status)),
|
MoveTo(2, 6), Print(format!("LTC Status : {}", frame.status)),
|
||||||
MoveTo(2, 5), 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, 6), 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, 4), Print("LTC Status : (waiting)"),
|
MoveTo(2, 6), Print("LTC Status : (waiting)"),
|
||||||
MoveTo(2, 5), Print("LTC Timecode : …"),
|
MoveTo(2, 7), Print("LTC Timecode : …"),
|
||||||
MoveTo(2, 6), Print("Frame Rate : …"),
|
MoveTo(2, 8), Print("Frame Rate : …"),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
let now_local = Local::now();
|
let now_local = Local::now();
|
||||||
let sys_str = 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, 7), Print(format!("System Clock : {}", sys_str))).unwrap();
|
);
|
||||||
|
queue!(stdout, MoveTo(2, 9), Print(format!("System Clock : {}", sys_ts))).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6️⃣ Overlay in new order
|
// 9️⃣ Overlay metrics in new order
|
||||||
|
// Timecode Δ line
|
||||||
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 {
|
||||||
|
|
@ -185,19 +230,27 @@ pub fn start_ui(
|
||||||
};
|
};
|
||||||
queue!(
|
queue!(
|
||||||
stdout,
|
stdout,
|
||||||
MoveTo(2, 8), 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 == "IN SYNC" { Color::Green } else { Color::Red };
|
// Sync Status line
|
||||||
|
let scol = if status_str == "IN SYNC" {
|
||||||
|
Color::Green
|
||||||
|
} else {
|
||||||
|
Color::Red
|
||||||
|
};
|
||||||
queue!(
|
queue!(
|
||||||
stdout,
|
stdout,
|
||||||
MoveTo(2, 9), SetForegroundColor(scol), Print(format!("Sync Status : {}", status)), ResetColor,
|
MoveTo(2, 12), SetForegroundColor(scol),
|
||||||
|
Print(format!("Sync Status : {}", status_str)),
|
||||||
|
ResetColor,
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
// Sync Jitter line
|
||||||
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 {
|
||||||
|
|
@ -214,40 +267,39 @@ pub fn start_ui(
|
||||||
};
|
};
|
||||||
queue!(
|
queue!(
|
||||||
stdout,
|
stdout,
|
||||||
MoveTo(2, 10), SetForegroundColor(jcol), Print(format!("Sync Jitter : {}", jstatus)), ResetColor,
|
MoveTo(2, 13), SetForegroundColor(jcol),
|
||||||
|
Print(format!("Sync Jitter : {}", jstatus)),
|
||||||
|
ResetColor,
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
queue!(
|
// Lock Ratio line
|
||||||
stdout,
|
queue!(stdout,
|
||||||
MoveTo(2, 11), Print(format!("Lock Ratio : {:.1}% LOCK", ratio)),
|
MoveTo(2, 14), Print(format!("Lock Ratio : {:.1}% LOCK", lock_ratio)),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
// Footer
|
// 10️⃣ Footer and logs
|
||||||
queue!(
|
queue!(stdout,
|
||||||
stdout,
|
MoveTo(2, 16), Print("[S] Set system clock to LTC [Q] Quit"),
|
||||||
MoveTo(2, 13), Print("[S] Set system clock to LTC [Q] Quit"),
|
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
// 7️⃣ Recent logs
|
|
||||||
for (i, log_msg) in logs.iter().enumerate() {
|
for (i, log_msg) in logs.iter().enumerate() {
|
||||||
queue!(stdout, MoveTo(2, 15 + 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();
|
||||||
|
|
||||||
// 8️⃣ Handle manual sync/quit
|
// 11️⃣ Handle manual sync and quit keys
|
||||||
if poll(Duration::from_millis(0)).unwrap() {
|
if poll(Duration::from_millis(50)).unwrap() {
|
||||||
if let Event::Key(evt) = read().unwrap() {
|
if let Event::Key(evt) = read().unwrap() {
|
||||||
if let KeyCode::Char(c) = evt.code {
|
match evt.code {
|
||||||
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);
|
||||||
}
|
}
|
||||||
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();
|
||||||
|
|
@ -264,19 +316,31 @@ pub fn start_ui(
|
||||||
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!(
|
||||||
ltc_dt.hour(), ltc_dt.minute(), ltc_dt.second(), ltc_dt.timestamp_subsec_millis());
|
"{:02}:{:02}:{:02}.{:03}",
|
||||||
let res = Command::new("sudo").arg("date").arg("-s").arg(&ts).status();
|
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()) {
|
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 { logs.pop_front(); }
|
if logs.len() == 10 {
|
||||||
|
logs.pop_front();
|
||||||
|
}
|
||||||
logs.push_back(msg);
|
logs.push_back(msg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue