using System; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using Newtonsoft.Json.Linq; using OxyPlot; namespace YKC { public partial class DashboardPage : Page { private Timer _timer; public class PileRow { public int Index { get; set; } public string Serial { get; set; } = "--"; public string StatusText { get; set; } = "--"; public string Gun1Text { get; set; } = "--"; public string Gun2Text { get; set; } = "--"; } public ObservableCollection Rows { get; } = new ObservableCollection(); public DashboardPage() { InitializeComponent(); dgPiles.ItemsSource = Rows; Loaded += (s, e) => { Dispatcher.BeginInvoke(new Action(() => RefreshData()), System.Windows.Threading.DispatcherPriority.Background); _timer = new Timer((_) => Dispatcher.BeginInvoke(new Action(RefreshData)), null, 5000, 5000); }; Unloaded += (s, e) => _timer?.Dispose(); } private void Refresh_Click(object sender, RoutedEventArgs e) => RefreshData(); private void RefreshData() { try { var result = UdpClientHolder.Instance.SendSync(new JObject { ["cmd"] = Config.Cmd["GET_STATUS"] }); if (result.Value("success") == false && result["piles"] == null) { Dispatcher.BeginInvoke(new Action(() => txtConnStatus.Text = "无响应")); return; } Dispatcher.BeginInvoke(new Action(() => txtConnStatus.Text = "在线")); var piles = result["piles"] as JArray ?? new JArray(); int online = 0, charging = 0; var rows = new ObservableCollection(); foreach (var p in piles) { bool isOnline = p.Value("is_online"); if (isOnline) online++; var guns = p["guns"] as JArray ?? new JArray(); foreach (var g in guns) if (g.Value("status") == 3) charging++; rows.Add(new PileRow { Index = rows.Count + 1, Serial = p.Value("serial") ?? "--", StatusText = isOnline ? "在线" : "离线", Gun1Text = guns.Count > 0 ? GunStatusText(guns[0].Value("status")) : "--", Gun2Text = guns.Count > 1 ? GunStatusText(guns[1].Value("status")) : "--", }); } Dispatcher.BeginInvoke(new Action(() => { txtOnlineCount.Text = online.ToString(); txtChargingCount.Text = charging.ToString(); Rows.Clear(); foreach (var r in rows) Rows.Add(r); })); } catch { } } private string GunStatusText(int status) { switch (status) { case 0: return "离线"; case 1: return "故障"; case 2: return "空闲"; case 3: return "充电中"; default: return status.ToString(); } } } }