using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
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;
///
/// 「扫码通道」页签(桌面端开启扫码服务后才显示):
/// 通道列表 / 设备发现 / 设备配置,收码与上报由 负责。
///
public partial class ScanTabView : UserControl
{
private readonly ScanService _scan;
private readonly ObservableCollection _rows = new();
/// 发现到的**全部**设备(含已添加的);显示时再按通道过滤
private readonly ObservableCollection _allDevices = new();
/// 界面上显示的设备(已排除已添加为通道的)
private readonly ObservableCollection _devices = new();
/// 服务模式:后台服务写的状态(在线/离线、最近条码)
private readonly DispatcherTimer _agentTimer = new() { Interval = TimeSpan.FromSeconds(1) };
private AgentStatus? _agentStatus;
private DateTime _agentStatusAt;
private static bool IsAgentMode => AgentPaths.MachineMode && !AgentPaths.IsServiceProcess;
public ScanTabView(ScanService scan)
{
InitializeComponent();
_scan = scan;
ChannelList.ItemsSource = _rows;
DeviceList.ItemsSource = _devices;
// 事件**一直挂着**,不在 Unloaded 里退订:
// TabControl 切页签、窗口隐藏到托盘都会触发 Unloaded,退订的话界面就再也不刷新
// (真机踩过:连接明明是好的,界面永远停在“离线”)。
// 切页签也**不停发现**——开关打开就该一直发现,直到用户自己关。
_scan.Changed += OnScanChanged;
_scan.DiscoveredChanged += OnDiscoveredChanged;
Loaded += (_, _) => Refresh();
if (IsAgentMode)
{
_agentTimer.Tick += (_, _) => ApplyAgentStatus();
_agentTimer.Start();
}
Refresh();
}
///
/// 服务模式:把后台服务写的运行状态盖到本地通道对象上(服务才是真正连设备的那一方)。
/// 发现列表也读服务写的 agent-discovered.json。
///
private void ApplyAgentStatus()
{
var status = AgentFiles.LoadStatus();
if (status is null) return;
if (status.UpdatedAt == _agentStatusAt) return; // 没变化不用重画
_agentStatusAt = status.UpdatedAt;
_agentStatus = status;
foreach (var channel in _scan.Channels)
{
var runtime = status.Channels.FirstOrDefault(item =>
item.Mac.Equals(channel.Mac, StringComparison.OrdinalIgnoreCase));
if (runtime is null)
{
channel.Connected = false;
continue;
}
channel.Connected = runtime.Connected;
if (!string.IsNullOrWhiteSpace(runtime.LastIp)) channel.LastIp = runtime.LastIp;
channel.LastCode = runtime.LastCode;
channel.LastCodeAt = runtime.LastCodeAt;
}
var discovered = AgentFiles.LoadDiscovered();
_allDevices.Clear();
foreach (var item in discovered)
{
_allDevices.Add(new DiscoveredDevice(item.Mac, item.Ip, item.HostName, item.Model, item.Firmware, "online"));
}
Refresh();
}
/// 服务模式的通道状态行(数据来自 agent-status.json)
private string BuildAgentStatusText()
{
var status = _agentStatus ?? AgentFiles.LoadStatus();
if (status is null) return "后台扫码服务状态未知(还没写入 agent-status.json)";
if (!status.Running)
{
return "后台扫码服务未运行"
+ (string.IsNullOrWhiteSpace(status.LastError) ? "" : $":{status.LastError}");
}
var online = _rows.Count(item => item.StateText == "在线");
var text = $"后台服务运行中 · 通道 {_rows.Count} 个(在线 {online})";
if (!string.IsNullOrWhiteSpace(status.ChannelSyncStatus)) text += $" · {status.ChannelSyncStatus}";
if (!string.IsNullOrWhiteSpace(status.UploadStatus)) text += $" · {status.UploadStatus}";
else if (status.PendingRecords > 0) text += $" · 待上传 {status.PendingRecords} 条扫码记录";
return text;
}
/// 列表行(界面显示用)
public sealed class ChannelRow
{
public int Number { get; init; }
public string DisplayName { get; init; } = string.Empty;
public string Mac { get; init; } = string.Empty;
public string LastIp { get; init; } = string.Empty;
public string StateText { get; init; } = string.Empty;
public string MuteText { get; init; } = string.Empty;
public string LastCode { get; init; } = string.Empty;
public ScanChannel Source { get; init; } = null!;
}
private void OnScanChanged()
{
Dispatcher.Invoke(Refresh);
}
/// 选中项变了:同步按钮文案/可用性
private void ChannelList_SelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateSelectionButtons();
private void UpdateSelectionButtons()
{
var current = ChannelList.SelectedItem as ChannelRow;
MuteButton.Content = current is not null && current.Source.Muted ? "恢复蜂鸣" : "静音";
MuteButton.IsEnabled = current is not null;
}
/// 重新渲染通道列表(保持选中项)
public void Refresh()
{
var selected = (ChannelList.SelectedItem as ChannelRow)?.Source.Mac;
_rows.Clear();
foreach (var channel in _scan.Channels.OrderBy(item => item.Number))
{
_rows.Add(new ChannelRow
{
Number = channel.Number,
DisplayName = channel.DisplayName,
Mac = channel.Mac,
LastIp = channel.LastIp,
StateText = channel.Connected ? "在线" : "离线",
MuteText = channel.Muted ? "静音" : "—",
LastCode = string.IsNullOrEmpty(channel.LastCode)
? "—"
: $"{channel.LastCode}({channel.LastCodeAt:HH:mm:ss})",
Source = channel,
});
}
if (selected is not null)
{
var hit = _rows.FirstOrDefault(item => item.Source.Mac.Equals(selected, StringComparison.OrdinalIgnoreCase));
if (hit is not null) ChannelList.SelectedItem = hit;
}
UpdateSelectionButtons();
var status = IsAgentMode
? BuildAgentStatusText()
: _scan.Running
? $"扫码服务运行中 · 通道 {_rows.Count} 个(在线 {_rows.Count(item => item.StateText == "在线")})"
: "扫码服务未启动(菜单「服务 → 开启设备服务」后自动启动)";
// 同步/上报都是后台自动重试的,把它的状态摊在同一行里,别让人以为需要手动点
if (!IsAgentMode)
{
if (!string.IsNullOrWhiteSpace(_scan.ChannelSyncStatus)) status += $" · {_scan.ChannelSyncStatus}";
if (!string.IsNullOrWhiteSpace(_scan.UploadStatus)) status += $" · {_scan.UploadStatus}";
else
{
var (_, pending) = ScanRecordStore.Stats();
if (pending > 0) status += $" · 待上传 {pending} 条扫码记录";
}
}
ChannelStatusText.Text = status;
ApplyDeviceFilter();
}
///
/// 按当前通道列表过滤发现结果:**已经添加为通道的设备不再显示**。
///
/// 显示集合与「发现到的全集」分开存:删掉通道后不用重新扫一轮,那台设备自己会回到列表里。
///
private void ApplyDeviceFilter()
{
var added = new HashSet(_scan.Channels.Select(item => item.Mac), StringComparer.OrdinalIgnoreCase);
_devices.Clear();
foreach (var device in _allDevices.Where(item => !added.Contains(item.Mac)))
{
_devices.Add(device);
}
var hidden = _allDevices.Count - _devices.Count;
if (IsAgentMode)
{
DiscoverStatusText.Text = (_devices.Count == 0
? (hidden > 0 ? $"后台服务扫描中…(发现的 {hidden} 台都已添加为通道)" : "后台服务扫描中…")
: $"后台服务扫描中… 未添加 {_devices.Count} 台" + (hidden > 0 ? $"(另有 {hidden} 台已添加)" : ""));
return;
}
if (_scan.Monitoring)
{
DiscoverStatusText.Text = _devices.Count == 0
? (hidden > 0 ? $"正在扫描…(发现的 {hidden} 台都已添加为通道)" : "正在扫描…")
: $"正在扫描… 未添加 {_devices.Count} 台" + (hidden > 0 ? $"(另有 {hidden} 台已添加)" : "");
return;
}
if (_allDevices.Count == 0)
{
DiscoverStatusText.Text = "未开始扫描";
return;
}
DiscoverStatusText.Text = _devices.Count == 0
? (hidden > 0 ? $"发现的 {hidden} 台都已添加为通道" : "未发现设备")
: $"发现 {_devices.Count} 台未添加的设备" + (hidden > 0 ? $"(另有 {hidden} 台已添加)" : "");
}
/// 扫描开关:打开后**常驻发现**(每 3 秒探测一次、socket 一直开着收),直到用户手工停止
private void Discover_Toggle(object sender, RoutedEventArgs e)
{
if (IsAgentMode)
{
DiscoverToggle.IsChecked = true;
ChannelStatusText.Text = "服务模式下设备发现由后台服务常驻执行";
return;
}
if (DiscoverToggle.IsChecked == true)
{
DiscoverToggle.Content = "停止扫描";
_scan.StartDiscovery();
}
else
{
DiscoverToggle.Content = "开始扫描";
_scan.StopDiscovery();
}
}
/// 发现列表变了:整表替换成服务里的当前快照(已按 MAC 去重、已踢掉掉线设备)
private void OnDiscoveredChanged() => Dispatcher.Invoke(() =>
{
var latest = _scan.DiscoveredDevices;
_allDevices.Clear();
foreach (var device in latest) _allDevices.Add(device);
ApplyDeviceFilter();
});
private async void Add_Click(object sender, RoutedEventArgs e)
{
if (DeviceList.SelectedItem is not DiscoveredDevice device)
{
MessageBox.Show(Window.GetWindow(this)!, "请先在下面的列表里选中一台设备", "添加通道",
MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
// 先让用户定通道号 + 设备名(与 AndroidScanCenter 的添加流程一致)
var dialog = new AddChannelWindow(device, _scan.Channels) { Owner = Window.GetWindow(this) };
if (dialog.ShowDialog() != true) return;
AddButton.IsEnabled = false;
AddChannelWindow_ShowStage($"正在添加通道 {dialog.ChannelNumber}…");
try
{
var result = await _scan.AddChannelAsync(
device.Mac, dialog.ChannelName, device.Ip, dialog.ChannelNumber, device.HostName,
stage => Dispatcher.Invoke(() => AddChannelWindow_ShowStage(stage)));
Refresh();
ChannelStatusText.Text = result.Message;
if (!result.Ok)
{
MessageBox.Show(Window.GetWindow(this)!, result.Message, "添加通道",
MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
if (IsAgentMode)
{
ChannelStatusText.Text = result.Message + "(已保存,后台服务会自动重连)";
}
else if (!_scan.Running)
{
MessageBox.Show(Window.GetWindow(this)!,
$"{result.Message}\n\n开启「服务 → 开启设备服务」后才会开始连接设备收码。",
"添加通道", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
_scan.RequestChannelSync();
}
}
catch (Exception ex)
{
ChannelStatusText.Text = $"添加通道失败:{ex.Message}";
MessageBox.Show(Window.GetWindow(this)!, $"添加通道失败:{ex.Message}", "添加通道",
MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
AddButton.IsEnabled = true;
}
}
/// 添加通道过程中的进度文案(回到界面线程再写控件)
private void AddChannelWindow_ShowStage(string text)
{
ChannelStatusText.Text = text;
}
///
/// 静音 / 恢复蜂鸣:只存本地 + 让这条连接重走一遍(连上时整条设置下发)。
/// 已经断开的通道也能设 —— 下次连上自动生效。
///
private void Mute_Click(object sender, RoutedEventArgs e)
{
if (ChannelList.SelectedItem is not ChannelRow row) return;
var muted = !row.Source.Muted;
_scan.SetMuted(row.Source, muted);
Refresh();
ChannelStatusText.Text = muted
? $"通道 {row.Number}「{row.DisplayName}」已设为静音(重新下发设置中)"
: $"通道 {row.Number}「{row.DisplayName}」已恢复蜂鸣(重新下发设置中)";
}
private void Remove_Click(object sender, RoutedEventArgs e)
{
if (ChannelList.SelectedItem is not ChannelRow row) return;
if (MessageBox.Show(Window.GetWindow(this)!, $"确定删除通道「{row.DisplayName}」?", "删除通道",
MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) return;
_scan.RemoveChannel(row.Source);
Refresh();
}
private async void Reconnect_Click(object sender, RoutedEventArgs e)
{
if (IsAgentMode)
{
AgentFiles.QueueCommand(command => command.ReloadChannelsAt = DateTime.UtcNow);
ChannelStatusText.Text = "已通知后台服务重新连接全部通道";
return;
}
if (!_scan.Running)
{
ChannelStatusText.Text = "扫码服务未启动,先开启「服务 → 开启设备服务」";
return;
}
ReconnectButton.IsEnabled = false;
try
{
_scan.Stop();
await _scan.StartAsync();
Refresh();
ChannelStatusText.Text = "已重新连接全部通道";
}
finally
{
ReconnectButton.IsEnabled = true;
}
}
///
/// 串口指令调试:直接把 HEX 字节透传给扫码枪(静音指令对不上枪型号时现场自己试)。
///
private async void RawCommand_Click(object sender, RoutedEventArgs e)
{
if (ChannelList.SelectedItem is not ChannelRow row) return;
var dialog = new ScannerCommandWindow(row.Source) { Owner = Window.GetWindow(this) };
if (dialog.ShowDialog() != true) return;
var ok = await _scan.SendCommandAsync(row.Source, dialog.Payload);
ChannelStatusText.Text = ok
? $"已向通道 {row.Number} 的扫码枪下发 {dialog.Payload.Length} 字节"
: "该通道当前未连接,指令没发出去";
}
private async void ReadConfig_Click(object sender, RoutedEventArgs e)
{
if (ChannelList.SelectedItem is not ChannelRow row) return;
if (string.IsNullOrWhiteSpace(row.Source.LastIp))
{
ConfigText.Text = "该通道还没有 IP,先扫描一次设备";
return;
}
ConfigText.Text = "正在读取…";
try
{
var config = await _scan.ReadConfigAsync(row.Source.LastIp);
ConfigText.Text = config is null
? "读取失败(设备不支持 / 不在线)"
: $"设备名:{config.HostName}\n"
+ $"网络:{(config.DhcpEn ? "DHCP" : "静态")} {config.IpAddr} / {config.Mask} / 网关 {config.GateWay} / DNS {config.Dns}\n"
+ $"登录:{config.User} / {config.Password}";
ChannelStatusText.Text = $"已读取 {row.Source.LastIp} 的配置";
}
catch (Exception ex)
{
ConfigText.Text = $"读取失败:{ex.Message}";
}
}
private async void Restart_Click(object sender, RoutedEventArgs e)
{
if (ChannelList.SelectedItem is not ChannelRow row) return;
if (string.IsNullOrWhiteSpace(row.Source.LastIp))
{
ConfigText.Text = "该通道还没有 IP,先扫描一次设备";
return;
}
if (MessageBox.Show(Window.GetWindow(this)!,
$"重启设备「{row.DisplayName}」({row.Source.LastIp})?\n\n设备上会短暂断连,稍后自动重连。",
"重启设备", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) return;
try
{
var ok = await _scan.RestartAsync(row.Source.LastIp);
ConfigText.Text = ok ? "已下发重启命令(设备可能延迟几十秒才真正复位)" : "重启命令下发失败";
}
catch (Exception ex)
{
ConfigText.Text = $"重启失败:{ex.Message}";
}
}
}