using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; using YuncangTrace.LocalService.Services; using YuncangTrace.LocalService.Services.Scan; namespace YuncangTrace.LocalService.Views; /// /// 「面单摄像头」页签:每路识别任务的状态 + **最近识别到的条码**。 /// /// 数据来源: /// - 服务模式(本机跑的就是后台服务):读后台服务写的 agent-status.json 的 LabelScan /// —— 真正拉流识别的是服务进程,界面只展示; /// - 普通模式:直接读本进程 的运行时状态。 /// /// 识别本身在 :ffmpeg 拉 RTSP → 灰度帧 → ZXing → 上报。 /// public partial class LabelCameraView : UserControl { private static readonly TimeSpan AgentPollInterval = TimeSpan.FromMilliseconds(300); private readonly ScanService _scan; private readonly ObservableCollection _rows = new(); private readonly DispatcherTimer _agentTimer = new() { Interval = AgentPollInterval }; private DateTime _agentStatusAt; private bool _refreshing; private static bool IsAgentMode => AgentPaths.MachineMode && !AgentPaths.IsServiceProcess; public LabelCameraView(ScanService scan) { InitializeComponent(); _scan = scan; CameraList.ItemsSource = _rows; // 事件一直挂着(切页签/隐藏到托盘都会触发 Unloaded,退订就再也不刷新了) _scan.LabelScan.Changed += OnLabelScanChanged; Loaded += (_, _) => Refresh(); if (IsAgentMode) { _agentTimer.Tick += (_, _) => ApplyAgentStatus(); _agentTimer.Start(); } Refresh(); } /// 列表行(界面显示用;按 原地更新,避免每次命中都清空重画) public sealed class LabelRow : INotifyPropertyChanged { private string _channelText = string.Empty; private string _stateText = string.Empty; private string _codeText = "—"; private string _firstSeenText = "—"; private string _lastHitText = "—"; private string _streamText = "—"; private string _decodeText = "—"; private string _hitsText = "—"; private string _errorText = string.Empty; public LabelRow(string key) { Key = key; } /// 工作台|摄像头|通道:配置变了就是新的一行 public string Key { get; } public string WorkstationName { get; init; } = string.Empty; public string CameraName { get; init; } = string.Empty; public string Summary { get; set; } = string.Empty; public string ChannelText { get => _channelText; set => Set(ref _channelText, value); } public string StateText { get => _stateText; set => Set(ref _stateText, value); } /// 最近识别到的条码(条码本身,不带时间) public string CodeText { get => _codeText; set => Set(ref _codeText, value); } /// 首次识别时间:也就是这条记录真正用的时间,面单不拿走就不变 public string FirstSeenText { get => _firstSeenText; set => Set(ref _firstSeenText, value); } /// 最近一次命中时间:每秒都在变,只用来看摄像头有没有在扫 public string LastHitText { get => _lastHitText; set => Set(ref _lastHitText, value); } /// 当前码流(主/子 + 分辨率) public string StreamText { get => _streamText; set => Set(ref _streamText, value); } /// 最近一帧解码耗时 public string DecodeText { get => _decodeText; set => Set(ref _decodeText, value); } public string HitsText { get => _hitsText; set => Set(ref _hitsText, value); } public string ErrorText { get => _errorText; set => Set(ref _errorText, value); } public event PropertyChangedEventHandler? PropertyChanged; private void Set(ref string field, string value, [CallerMemberName] string? name = null) { if (string.Equals(field, value, StringComparison.Ordinal)) return; field = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } } /// 一行要显示的内容(与行对象解耦,方便按 key 比对增量更新) private sealed record RowData( string Key, string WorkstationName, string CameraName, string ChannelText, string StateText, string CodeText, string FirstSeenText, string LastHitText, string StreamText, string DecodeText, string HitsText, string ErrorText, string Summary); /// 按 key 增量更新列表(新增/删除/原地改),不整体重画 private void Render(IReadOnlyList data) { for (var index = _rows.Count - 1; index >= 0; index--) { if (data.Any(item => item.Key == _rows[index].Key)) continue; _rows.RemoveAt(index); } for (var index = 0; index < data.Count; index++) { var item = data[index]; var row = _rows.FirstOrDefault(existing => existing.Key == item.Key); if (row is null) { row = new LabelRow(item.Key) { WorkstationName = item.WorkstationName, CameraName = item.CameraName }; _rows.Insert(Math.Min(index, _rows.Count), row); } row.ChannelText = item.ChannelText; row.StateText = item.StateText; row.CodeText = item.CodeText; row.FirstSeenText = item.FirstSeenText; row.LastHitText = item.LastHitText; row.StreamText = item.StreamText; row.DecodeText = item.DecodeText; row.HitsText = item.HitsText; row.ErrorText = item.ErrorText; row.Summary = item.Summary; } } private void OnLabelScanChanged() { if (Dispatcher.CheckAccess()) Refresh(); else Dispatcher.Invoke(Refresh); } /// 服务模式:读后台服务写的运行状态(有变化才重画) private void ApplyAgentStatus() { var status = AgentFiles.LoadStatus(); if (status is null || status.UpdatedAt == _agentStatusAt) return; _agentStatusAt = status.UpdatedAt; Refresh(); } /// 重新渲染(保持选中项不需要:这里只展示) public void Refresh() { var label = IsAgentMode ? AgentFiles.LoadStatus()?.LabelScan : null; if (IsAgentMode && label is not null) { StatusText.Text = string.IsNullOrWhiteSpace(label.StatusText) ? "还没拉取" : label.StatusText; SetWarnings(label.Warnings); RefreshButton.Content = "由后台服务拉取"; RefreshButton.IsEnabled = false; Render(label.Items.Select(item => new RowData( $"{item.WorkstationId}|{item.CameraId}|{item.ChannelId}", string.IsNullOrWhiteSpace(item.WorkstationName) ? "—" : item.WorkstationName, item.CameraName, string.IsNullOrWhiteSpace(item.ChannelName) ? item.ChannelId : $"{item.ChannelId}「{item.ChannelName}」", item.StateText, string.IsNullOrEmpty(item.LastCode) ? "—" : item.LastCode, item.LastCodeAt?.ToString("MM-dd HH:mm:ss") ?? "—", item.LastHitAt?.ToString("HH:mm:ss.fff") ?? "—", string.IsNullOrWhiteSpace(item.StreamText) ? "—" : item.StreamText, item.LastDecodeMs > 0 ? $"{item.LastDecodeMs:0}ms" : "—", item.Hits > 0 ? item.Hits.ToString() : "—", item.LastError ?? string.Empty, item.Summary)).ToList()); return; } var snapshot = _scan.LabelScan.Snapshot; StatusText.Text = snapshot.StatusText; SetWarnings(snapshot.Warnings.Select(item => item.Display).ToList()); RefreshButton.Content = "刷新配置"; RefreshButton.IsEnabled = !_refreshing && !_scan.LabelScan.Refreshing; Render(_scan.LabelScan.Runtimes.Select(runtime => new RowData( $"{runtime.WorkstationId}|{runtime.CameraId}|{runtime.ChannelId}", string.IsNullOrWhiteSpace(runtime.WorkstationName) ? "—" : runtime.WorkstationName, runtime.CameraName, string.IsNullOrWhiteSpace(runtime.ChannelName) ? runtime.ChannelId : $"{runtime.ChannelId}「{runtime.ChannelName}」", runtime.StateText, string.IsNullOrEmpty(runtime.LastCode) ? "—" : runtime.LastCode, runtime.LastCodeAt?.ToString("MM-dd HH:mm:ss") ?? "—", runtime.LastHitAt?.ToString("HH:mm:ss.fff") ?? "—", string.IsNullOrWhiteSpace(runtime.StreamText) ? "—" : runtime.StreamText, runtime.LastDecodeMs > 0 ? $"{runtime.LastDecodeMs:0}ms" : "—", runtime.Hits > 0 ? runtime.Hits.ToString() : "—", runtime.LastError ?? string.Empty, runtime.Summary)).ToList()); } private void SetWarnings(System.Collections.Generic.IReadOnlyList warnings) { WarnText.Text = warnings.Count == 0 ? string.Empty : string.Join(Environment.NewLine, warnings.Select(item => $"⚠ {item}")); } /// 手动刷新配置(服务模式下由后台服务负责,这里不可用) private async void Refresh_Click(object sender, RoutedEventArgs e) { _refreshing = true; RefreshButton.IsEnabled = false; try { await _scan.LabelScan.RefreshAsync("手动刷新"); } finally { _refreshing = false; Refresh(); } } }