packServer/desktop/NtpWindow.xaml.cs
2026-10-19 22:04:19 +08:00

413 lines
16 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using YuncangTrace.LocalService.Services;
using YuncangTrace.LocalService.Services.Hik;
namespace YuncangTrace.LocalService;
/// <summary>
/// NTP 校时设置窗:改 NTP 服务器 / 开关 / 间隔,并可立即校时。
///
/// ⚠️ 校时会修改**本机系统时间**,但软件默认以普通权限运行(manifest = asInvoker);
/// 非管理员时点「立即校时 / 同步 NVR 时间」才会用 runas 弹一次 UAC(见 <see cref="ElevatedNtp"/>)。
/// </summary>
public partial class NtpWindow : Window
{
private readonly AppSettings _settings;
private readonly ApiClient _api;
private readonly Session _session;
private readonly int _subjectId;
private readonly DispatcherTimer _clock;
/// <summary>服务模式(设备服务开启):NTP 为强制项,不能停用自动校时</summary>
private readonly bool _serviceMode;
private bool _busy;
public NtpWindow(AppSettings settings, ApiClient api, Session session, int subjectId)
{
InitializeComponent();
_settings = settings;
_api = api;
_session = session;
_subjectId = subjectId;
_serviceMode = settings.DeviceServiceEnabled;
ServerBox.Text = settings.NtpServer;
EnabledBox.IsChecked = settings.NtpEnabled;
StartupBox.IsChecked = settings.NtpSyncOnStartup;
IntervalBox.Text = settings.NtpSyncIntervalMinutes.ToString();
if (_serviceMode)
{
// 服务模式:必须启用 NTP + 启动校时 + 定时校时(间隔 > 0)
EnabledBox.IsChecked = true;
StartupBox.IsChecked = true;
EnabledBox.IsEnabled = false;
StartupBox.IsEnabled = false;
ServiceModeTip.Visibility = Visibility.Visible;
if (settings.NtpSyncIntervalMinutes <= 0) IntervalBox.Text = "30";
}
LocalTimeText.Text = Now();
StatusText.Text = string.IsNullOrWhiteSpace(settings.NtpLastSyncAt)
? "尚未校时"
: $"上次校时:{settings.NtpLastSyncAt}(偏差 {settings.NtpLastOffsetSeconds:+0.00;-0.00} 秒)";
// 服务模式:上次校时是后台服务做的,以它的状态为准
if (AgentPaths.MachineMode)
{
var agent = AgentFiles.LoadStatus();
if (!string.IsNullOrWhiteSpace(agent?.NtpLastSyncAt))
{
StatusText.Text = $"上次校时(后台服务):{agent!.NtpLastSyncAt}"
+ $"(偏差 {agent.NtpLastOffsetSeconds:+0.00;-0.00} 秒)";
}
}
if (!ClockSyncService.IsElevated)
{
StatusText.Text = "提示:修改系统时间需要管理员权限,点「立即校时」时会弹 UAC 确认。";
}
// 每秒刷新一次本机时间(改完系统时间后能直观看到变化)
_clock = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
_clock.Tick += (_, _) => LocalTimeText.Text = Now();
_clock.Start();
Closed += (_, _) => _clock.Stop();
// 打开时自动查询一次(只查询、不修改时间)
Loaded += async (_, _) => await ProbeAsync();
}
private static string Now() => DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
/// <summary>查询 NTP 并展示偏差(不修改系统时间)</summary>
private async Task ProbeAsync()
{
if (_busy) return;
_busy = true;
SyncButton.IsEnabled = false;
try
{
ServerTimeText.Text = "查询中…";
OffsetText.Text = "—";
RttText.Text = "—";
var result = await NtpClient.QueryAsync(ServerBox.Text);
ShowResult(result);
StatusText.Text = Math.Abs(result.Offset.TotalSeconds) < ClockSyncService.MinimumAdjust.TotalSeconds
? "本机时间与 NTP 一致(偏差小于 0.2 秒)"
: "查询成功,可点「立即校时」写入系统时间";
}
catch (Exception ex)
{
ServerTimeText.Text = "—";
OffsetText.Text = "—";
RttText.Text = "—";
StatusText.Text = $"查询失败:{ex.Message}";
}
finally
{
_busy = false;
SyncButton.IsEnabled = true;
}
}
/// <summary>
/// 查询并校准本机时钟:
/// - 服务模式(后台服务在跑)→ 写命令文件,由 LocalSystem 服务校时(**不弹 UAC**);
/// - 已经是管理员 → 直接改;
/// - 否则用 runas 起一个只做校时的临时进程(弹一次 UAC)。
/// </summary>
private static Task<NtpResult> SyncLocalClockAsync(string server)
{
if (ServiceInstaller.IsRunning) return SyncViaServiceAsync(server);
return ClockSyncService.IsElevated
? ClockSyncService.SyncAsync(server)
: ElevatedNtp.SyncAsync(server);
}
/// <summary>让后台服务校时:写命令 → 轮询 agent-status.json 等结果</summary>
private static async Task<NtpResult> SyncViaServiceAsync(string server)
{
var before = AgentFiles.LoadStatus()?.NtpLastSyncAt ?? string.Empty;
AgentFiles.QueueCommand(command =>
{
command.NtpSyncAt = DateTime.UtcNow;
command.NtpServer = server;
});
for (var i = 0; i < 20; i++)
{
await Task.Delay(500);
var status = AgentFiles.LoadStatus();
if (status is null) continue;
if (string.IsNullOrWhiteSpace(status.NtpLastSyncAt)) continue;
if (status.NtpLastSyncAt == before) continue;
var serverTime = status.NtpServerTime is { } time
? new DateTimeOffset(time)
: DateTimeOffset.Now;
return new NtpResult(server, serverTime,
TimeSpan.FromSeconds(status.NtpLastOffsetSeconds),
TimeSpan.FromMilliseconds(status.NtpRoundTripMs));
}
throw new InvalidOperationException("后台服务没有响应校时请求(请确认「YuncangTraceAgent」服务在运行)");
}
/// <summary>服务模式:把 NTP 设置同步给后台服务(定时校时由它执行)</summary>
private void PushNtpSettingsToAgent()
{
if (!AgentPaths.MachineMode && !ServiceInstaller.IsInstalled) return;
var config = AgentFiles.LoadConfig() ?? new AgentConfig
{
ServerBaseUrl = _settings.ServerBaseUrl,
DeviceToken = _settings.DeviceToken,
DeviceSn = _settings.DeviceSn,
DeviceId = _settings.DeviceId,
SubjectId = _settings.SubjectId,
};
config.NtpEnabled = _settings.NtpEnabled;
config.NtpServer = _settings.NtpServer;
config.NtpIntervalMinutes = _settings.NtpSyncIntervalMinutes;
AgentFiles.SaveConfig(config);
}
/// <summary>查询 + 写入系统时间</summary>
private async void Sync_Click(object sender, RoutedEventArgs e)
{
if (_busy) return;
_busy = true;
SyncButton.IsEnabled = false;
try
{
var result = await SyncLocalClockAsync(ServerBox.Text);
LocalTimeText.Text = Now();
ShowResult(result);
_settings.NtpLastSyncAt = Now();
_settings.NtpLastOffsetSeconds = Math.Round(result.Offset.TotalSeconds, 2);
_settings.Save();
StatusText.Text = Math.Abs(result.Offset.TotalSeconds) < ClockSyncService.MinimumAdjust.TotalSeconds
? "本机时间已准确(偏差小于 0.2 秒,未调整)"
: "已校时:系统时间已按 NTP 调整";
AppLog.Write($"[ntp] 手动校时:{result.Server} 偏差 {result.Offset.TotalSeconds:+0.00;-0.00} 秒,往返 {result.RoundTrip.TotalMilliseconds:0} ms");
}
catch (OperationCanceledException)
{
StatusText.Text = "已取消:需要管理员权限才能修改系统时间";
AppLog.Write("[ntp] 手动校时:用户取消了管理员授权");
}
catch (Exception ex)
{
StatusText.Text = $"校时失败:{ex.Message}";
AppLog.Write($"[ntp] 手动校时失败:{ex.Message}");
}
finally
{
_busy = false;
SyncButton.IsEnabled = true;
}
}
private void ShowResult(NtpResult result)
{
ServerTimeText.Text = result.ServerTime.ToString("yyyy-MM-dd HH:mm:ss");
OffsetText.Text = $"{result.Offset.TotalSeconds:+0.00;-0.00} 秒(正数 = 本机慢了)";
RttText.Text = $"{result.RoundTrip.TotalMilliseconds:0} ms";
}
/// <summary>
/// 同步 NVR 时间:拉取当前主体全部录像机,静默把 NTP 写进去(与桌面端同一个服务器),
/// 并把设备时间直接校准到 NTP 时间(立即生效),逐台返回结果。
/// </summary>
private async void SyncNvr_Click(object sender, RoutedEventArgs e)
{
if (_busy) return;
_busy = true;
SyncButton.IsEnabled = false;
SyncNvrButton.IsEnabled = false;
var lines = new List<string>();
try
{
var server = (ServerBox.Text ?? string.Empty).Trim();
if (server.Length == 0) throw new InvalidOperationException("请先填写 NTP 服务器");
var formInterval = int.TryParse((IntervalBox.Text ?? string.Empty).Trim(), out var typed) && typed >= 0
? typed
: _settings.NtpSyncIntervalMinutes;
var interval = Math.Clamp(formInterval > 0 ? formInterval : 60, 1, 1440);
// 先落盘:录像机与桌面端必须用同一个 NTP 地址
_settings.NtpServer = server;
_settings.NtpSyncIntervalMinutes = formInterval;
if (_serviceMode)
{
_settings.NtpEnabled = true;
_settings.NtpSyncOnStartup = true;
}
_settings.Save();
PushNtpSettingsToAgent();
lines.Add($"NTP 服务器:{server}(正在校准本机时间…)");
ShowNvrResult(lines);
// 先校准本机(同时确认 NTP 服务器可用),再把同一个服务器写进录像机
var clock = await SyncLocalClockAsync(server);
var offset = clock.Offset;
_settings.NtpLastSyncAt = Now();
_settings.NtpLastOffsetSeconds = Math.Round(offset.TotalSeconds, 2);
_settings.Save();
LocalTimeText.Text = Now();
lines[0] = $"NTP 服务器:{server}(本机偏差 {offset.TotalSeconds:+0.00;-0.00} 秒,已校准本机)";
lines.Add("正在拉取录像机列表…");
ShowNvrResult(lines);
var nvrs = await _api.NvrsAsync(_session.Token, _subjectId);
lines[lines.Count - 1] = $"当前主体共 {nvrs.Count} 台录像机";
ShowNvrResult(lines);
if (nvrs.Count == 0) return;
var ok = 0;
// 独立的海康会话:不与回放/预览/下载抢同一个 UserID(否则会卡在会话锁上)
using var ntpDevice = new HikDeviceService();
foreach (var nvr in nvrs)
{
var label = string.IsNullOrWhiteSpace(nvr.Name)
? $"{nvr.Host}:{nvr.Port}"
: $"{nvr.Name}({nvr.Host}:{nvr.Port})";
var lineIndex = lines.Count;
lines.Add($"… {label} 正在同步…");
ShowNvrResult(lines);
try
{
var credential = await _api.NvrCredentialAsync(_session.Token, _subjectId, nvr.Id);
// SDK 调用是同步阻塞的,放到线程池,避免界面卡住
var (config, before, after) = await Task.Run(() =>
{
// 设置前的设备时间(给界面看「改前 → 改后」)
var old = ntpDevice.GetDeviceTime(credential.Host, credential.Port,
credential.Username, credential.Password);
// ① 写 NTP(内部 GET→改→SET,保留固件字段)
ntpDevice.SetNtpConfig(credential.Host, credential.Port, credential.Username,
credential.Password, server, interval, true);
// ② 立即生效:把设备时间设为 NTP 时间,并补偿写调用耗时 / 轮询确认
var target = DateTime.Now.Add(offset);
var now = ntpDevice.SetDeviceTimeAndConfirm(credential.Host, credential.Port,
credential.Username, credential.Password, target);
// ③ 回读 NTP 配置
var cfg = ntpDevice.GetNtpConfig(credential.Host, credential.Port,
credential.Username, credential.Password);
return (cfg, old, now);
});
var diff = (after - DateTime.Now.Add(offset)).TotalSeconds;
ok++;
lines[lineIndex] = $"✔ {label}:NTP {config.Server} / {config.IntervalMinutes} 分钟 / "
+ $"{(config.Enabled ? "已启用" : "未启用")};设备时间 {before:HH:mm:ss} → {after:HH:mm:ss}"
+ $"(与 NTP 差 {diff:+0.0;-0.0} 秒)";
}
catch (Exception ex)
{
lines[lineIndex] = $"✘ {label}:{ex.Message}";
}
ShowNvrResult(lines);
}
lines.Add($"完成:{ok}/{nvrs.Count} 台设置成功");
ShowNvrResult(lines);
AppLog.Write($"[ntp] 同步 NVR 完成:{ok}/{nvrs.Count} 台({server},间隔 {interval} 分钟)");
}
catch (OperationCanceledException)
{
lines.Add("已取消:需要管理员权限才能修改本机时间,未写入录像机");
ShowNvrResult(lines);
AppLog.Write("[ntp] 同步 NVR:用户取消了管理员授权");
}
catch (Exception ex)
{
lines.Add($"失败:{ex.Message}");
ShowNvrResult(lines);
AppLog.Write($"[ntp] 同步 NVR 失败:{ex.Message}");
}
finally
{
_busy = false;
SyncButton.IsEnabled = true;
SyncNvrButton.IsEnabled = true;
}
}
private void ShowNvrResult(List<string> lines)
=> NvrResultBox.Text = string.Join(Environment.NewLine, lines);
private void Save_Click(object sender, RoutedEventArgs e)
{
var server = (ServerBox.Text ?? string.Empty).Trim();
if (EnabledBox.IsChecked == true && server.Length == 0)
{
MessageBox.Show(this, "启用 NTP 校时时必须填写服务器地址", "NTP 校时",
MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
if (!int.TryParse((IntervalBox.Text ?? string.Empty).Trim(), out var minutes) || minutes < 0)
{
MessageBox.Show(this, "自动校时间隔必须是不小于 0 的整数(分钟,0 = 仅启动时)", "NTP 校时",
MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
if (_serviceMode && minutes < 5)
{
MessageBox.Show(this, "服务模式下必须保留定时自动校时(间隔至少 5 分钟)", "NTP 校时",
MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
_settings.NtpServer = server.Length == 0 ? "ntp.aliyun.com" : server;
_settings.NtpEnabled = _serviceMode || EnabledBox.IsChecked == true;
_settings.NtpSyncOnStartup = _serviceMode || StartupBox.IsChecked == true;
_settings.NtpSyncIntervalMinutes = minutes;
_settings.Save();
PushNtpSettingsToAgent();
AppLog.Write($"[ntp] 设置已保存:{(_settings.NtpEnabled ? "启用" : "关闭")},服务器 {_settings.NtpServer},"
+ $"启动时{(_settings.NtpSyncOnStartup ? "校时" : "不校时")},间隔 {_settings.NtpSyncIntervalMinutes} 分钟");
DialogResult = true;
}
private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false;
}