-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
1958 lines (1718 loc) · 77 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
1958 lines (1718 loc) · 77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
namespace dji_cloud_tool
{
public partial class MainWindow : Window
{
private readonly MqttManager _mqttManager = new();
private readonly DispatcherTimer _uiTimer = new();
private readonly ConcurrentQueue<(string Topic, string Payload)> _incomingMessages = new();
// Settings file path
private readonly string _settingsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dji_cloud_tool_config.json");
// UI bound collections
private readonly ObservableCollection<DeviceItem> _devices = new();
private readonly ObservableCollection<MqttTopicItem> _topics = new();
private readonly ObservableCollection<OsdTelemetryItem> _translations = new();
private readonly ObservableCollection<OsdTelemetryItem> _filteredTranslations = new();
private readonly ObservableCollection<MqttMessageItem> _logs = new();
private readonly ObservableCollection<MqttMessageItem> _filteredLogs = new();
private readonly ObservableCollection<DockDebugLogItem> _dockDebugLogs = new();
// Active device states
private readonly TelemetryDashboardViewModel _telemetryVm = new();
private readonly Dictionary<string, Dictionary<string, string>> _deviceTelemetryStore = new();
private readonly Dictionary<string, DateTime> _deviceHeartbeats = new();
private DeviceItem? _selectedDevice;
private MqttTopicItem? _selectedTopicFilter;
private bool _isPaused = false;
private MqttMessageItem? _lastDisplayedLog;
public MainWindow()
{
InitializeComponent();
// Set bindings
TreeDevices.ItemsSource = _devices;
ListTopics.ItemsSource = _topics;
GridTranslations.ItemsSource = _filteredTranslations;
GridLogs.ItemsSource = _filteredLogs;
GridDockDebugLogs.ItemsSource = _dockDebugLogs;
// Bind Telemetry Dashboard panel
GridDockTelemetry.DataContext = _telemetryVm;
GridDroneTelemetry.DataContext = _telemetryVm;
// Initialize Event Subscriptions
_mqttManager.ConnectionStatusChanged += MqttManager_ConnectionStatusChanged;
_mqttManager.MessageReceived += MqttManager_MessageReceived;
// Load Config
LoadConfig();
UpdateLogSnFilterCombo();
UpdateDockSnCombo();
// Set up UI Timer
_uiTimer.Interval = TimeSpan.FromMilliseconds(500);
_uiTimer.Tick += UiTimer_Tick;
_uiTimer.Start();
// Setup default publisher templates
ComboPayloadTemplates.SelectedIndex = 0;
}
#region CONFIGURATION AND PERSISTENCE
private void LoadConfig()
{
try
{
if (File.Exists(_settingsPath))
{
string json = File.ReadAllText(_settingsPath);
var config = JsonSerializer.Deserialize<AppConfig>(json);
if (config != null)
{
TxtBroker.Text = config.Broker;
TxtPort.Text = config.Port.ToString();
TxtUsername.Text = config.Username;
TxtPassword.Password = config.Password;
TxtClientId.Text = config.ClientId;
ChkUseTls.IsChecked = config.UseTls;
ChkIgnoreCert.IsChecked = config.IgnoreCertErrors;
_devices.Clear();
foreach (var dev in config.Devices)
{
var deviceItem = new DeviceItem
{
Sn = dev.Sn,
Name = dev.Name,
Type = dev.Type,
IsOnline = false
};
foreach (var sub in dev.SubDevices)
{
deviceItem.SubDevices.Add(new DeviceItem
{
Sn = sub.Sn,
Name = sub.Name,
Type = sub.Type,
IsOnline = false
});
}
_devices.Add(deviceItem);
}
_topics.Clear();
// Populate default standard topics first
RebuildDefaultTopics();
// Add custom topics
foreach (var customTopic in config.CustomTopics)
{
if (!_topics.Any(t => t.Topic == customTopic))
{
_topics.Add(new MqttTopicItem { Topic = customTopic, IsEnabled = true, IsSystem = false });
}
}
return;
}
}
}
catch (Exception ex)
{
MessageBox.Show($"加载配置文件失败: {ex.Message}", "配置错误", MessageBoxButton.OK, MessageBoxImage.Warning);
}
// Fallback default topics if config not found
RebuildDefaultTopics();
}
private void SaveConfig()
{
try
{
var config = new AppConfig
{
Broker = TxtBroker.Text,
Port = int.TryParse(TxtPort.Text, out int port) ? port : 1883,
Username = TxtUsername.Text,
Password = TxtPassword.Password,
ClientId = TxtClientId.Text,
UseTls = ChkUseTls.IsChecked ?? false,
IgnoreCertErrors = ChkIgnoreCert.IsChecked ?? true,
Devices = _devices.Select(d => new DeviceConfigItem
{
Sn = d.Sn,
Name = d.Name,
Type = d.Type,
SubDevices = d.SubDevices.Select(s => new DeviceConfigItem
{
Sn = s.Sn,
Name = s.Name,
Type = s.Type
}).ToList()
}).ToList(),
CustomTopics = _topics.Where(t => !t.IsSystem).Select(t => t.Topic).ToList()
};
string json = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(_settingsPath, json);
// Re-populate SN filter combobox
UpdateLogSnFilterCombo();
}
catch (Exception ex)
{
// Background save failure is logged to system
System.Diagnostics.Debug.WriteLine($"Failed to save config: {ex.Message}");
}
}
private void RebuildDefaultTopics()
{
// Remove existing system topics
var customOnes = _topics.Where(t => !t.IsSystem).ToList();
_topics.Clear();
// Add global wildcard auto-discovery topic
_topics.Add(new MqttTopicItem { Topic = "thing/product/+/events", IsEnabled = true, IsSystem = true });
// Generate system topics for each device
foreach (var dev in _devices)
{
AddSystemTopicsForDevice(dev);
foreach (var sub in dev.SubDevices)
{
AddSystemTopicsForDevice(sub);
}
}
// Put custom ones back
foreach (var t in customOnes)
{
_topics.Add(t);
}
// Refresh Downlink ComboBox
UpdateDownlinkTopics();
}
private void AddSystemTopicsForDevice(DeviceItem dev)
{
string osdTopic = $"thing/product/{dev.Sn}/osd";
string stateTopic = $"thing/product/{dev.Sn}/state";
string statusTopic = $"sys/product/{dev.Sn}/status";
if (!_topics.Any(t => t.Topic == osdTopic))
_topics.Add(new MqttTopicItem { Topic = osdTopic, IsEnabled = true, IsSystem = true });
if (!_topics.Any(t => t.Topic == stateTopic))
_topics.Add(new MqttTopicItem { Topic = stateTopic, IsEnabled = true, IsSystem = true });
if (!_topics.Any(t => t.Topic == statusTopic))
_topics.Add(new MqttTopicItem { Topic = statusTopic, IsEnabled = true, IsSystem = true });
if (dev.Type == "设备" || dev.Type == "网关")
{
string eventsTopic = $"thing/product/{dev.Sn}/events";
string requestsTopic = $"thing/product/{dev.Sn}/requests";
string servicesReplyTopic = $"thing/product/{dev.Sn}/services_reply";
if (!_topics.Any(t => t.Topic == eventsTopic))
_topics.Add(new MqttTopicItem { Topic = eventsTopic, IsEnabled = true, IsSystem = true });
if (!_topics.Any(t => t.Topic == requestsTopic))
_topics.Add(new MqttTopicItem { Topic = requestsTopic, IsEnabled = true, IsSystem = true });
if (!_topics.Any(t => t.Topic == servicesReplyTopic))
_topics.Add(new MqttTopicItem { Topic = servicesReplyTopic, IsEnabled = true, IsSystem = true });
}
}
private void UpdateDownlinkTopics()
{
if (ComboDownlinkTopic == null) return;
string currentText = ComboDownlinkTopic.Text;
ComboDownlinkTopic.Items.Clear();
foreach (var dev in _devices)
{
if (dev.Type == "设备" || dev.Type == "网关")
{
ComboDownlinkTopic.Items.Add($"thing/product/{dev.Sn}/services");
ComboDownlinkTopic.Items.Add($"thing/product/{dev.Sn}/property/set");
}
else
{
ComboDownlinkTopic.Items.Add($"thing/product/{dev.Sn}/services");
}
foreach (var sub in dev.SubDevices)
{
ComboDownlinkTopic.Items.Add($"thing/product/{sub.Sn}/services");
}
}
if (!string.IsNullOrEmpty(currentText))
{
ComboDownlinkTopic.Text = currentText;
}
else if (ComboDownlinkTopic.Items.Count > 0)
{
ComboDownlinkTopic.SelectedIndex = 0;
}
UpdateDockSnCombo();
}
#endregion
#region MQTT CONNECTION MANAGEMENT
private async void BtnMqttConnect_Click(object sender, RoutedEventArgs e)
{
if (_mqttManager.IsConnected)
{
BtnMqttConnect.IsEnabled = false;
await _mqttManager.DisconnectAsync();
BtnMqttConnect.IsEnabled = true;
return;
}
string broker = TxtBroker.Text.Trim();
if (!int.TryParse(TxtPort.Text, out int port))
{
MessageBox.Show("端口必须是数字!", "输入错误", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
string username = TxtUsername.Text.Trim();
string password = TxtPassword.Password;
string clientId = TxtClientId.Text.Trim();
bool useTls = ChkUseTls.IsChecked ?? false;
bool ignoreCert = ChkIgnoreCert.IsChecked ?? true;
if (string.IsNullOrEmpty(broker))
{
MessageBox.Show("Broker 地址不能为空!", "输入错误", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
BtnMqttConnect.IsEnabled = false;
BtnMqttConnect.Content = "正在连接...";
try
{
await _mqttManager.ConnectAsync(broker, port, username, password, clientId, useTls, ignoreCert);
SaveConfig();
// Connect successful, subscribe to enabled topics
var activeTopics = _topics.Where(t => t.IsEnabled).Select(t => t.Topic).ToList();
if (activeTopics.Count > 0)
{
await _mqttManager.SubscribeAsync(activeTopics);
}
}
catch (Exception ex)
{
MessageBox.Show($"连接失败: {ex.Message}", "连接错误", MessageBoxButton.OK, MessageBoxImage.Error);
MqttStatusIndicator.Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Red);
BtnMqttConnect.Content = "连 接 Broker";
}
finally
{
BtnMqttConnect.IsEnabled = true;
}
}
private void MqttManager_ConnectionStatusChanged(bool connected)
{
Dispatcher.Invoke(() =>
{
if (connected)
{
MqttStatusIndicator.Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(16, 185, 129)); // Green
MqttStatusIndicator.ToolTip = "已连接";
BtnMqttConnect.Content = "断开连接";
}
else
{
MqttStatusIndicator.Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(239, 68, 68)); // Red
MqttStatusIndicator.ToolTip = "已断开";
BtnMqttConnect.Content = "连 接 Broker";
}
});
}
private void MqttManager_MessageReceived(string topic, string payload)
{
// Queue messages for thread-safe UI batch processing
_incomingMessages.Enqueue((topic, payload));
}
#endregion
#region BACKGROUND WORKER / UI TIMER TICK
private void UiTimer_Tick(object? sender, EventArgs e)
{
// Process queued MQTT messages
int processCount = 0;
bool stateChanged = false;
while (_incomingMessages.TryDequeue(out var msg) && processCount < 150)
{
processCount++;
stateChanged = true;
// Log entry
if (!_isPaused)
{
var logItem = new MqttMessageItem
{
Timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
Topic = msg.Topic,
Payload = msg.Payload
};
_logs.Add(logItem);
if (_logs.Count > 500)
{
_logs.RemoveAt(0);
}
}
// Check and parse dock debug responses / events
ParseDockDebugResponse(msg.Topic, msg.Payload);
CheckAndAutoReplyDockRequest(msg.Topic, msg.Payload);
// Analyze payload and extract target device
// DJI Cloud Topics:
// thing/product/{sn}/osd
// thing/product/{sn}/state
// sys/product/{sn}/status
string[] parts = msg.Topic.Split('/');
if (parts.Length >= 3)
{
string sn = parts[2];
// Update device active state
_deviceHeartbeats[sn] = DateTime.Now;
SetDeviceOnlineStatus(sn, true);
string? gatewaySn = null;
bool isEvents = parts.Contains("events");
try
{
using var doc = JsonDocument.Parse(msg.Payload);
if (doc.RootElement.TryGetProperty("gateway", out var gatewayProp))
{
gatewaySn = gatewayProp.GetString();
}
}
catch { }
// Perform automatic classification and registry mapping
AutoRegisterDevice(sn, gatewaySn, isEvents);
// Parse telemetry
if (parts.Contains("osd") || parts.Contains("state"))
{
try
{
using var doc = JsonDocument.Parse(msg.Payload);
if (doc.RootElement.TryGetProperty("data", out var dataProp) && dataProp.ValueKind == JsonValueKind.Object)
{
if (!_deviceTelemetryStore.ContainsKey(sn))
{
_deviceTelemetryStore[sn] = new Dictionary<string, string>();
}
var telemetryMap = _deviceTelemetryStore[sn];
FlattenJson("data", dataProp, telemetryMap);
// Auto-discover subdevice (drone inside dock)
if (telemetryMap.TryGetValue("data.sub_device.device_sn", out string? droneSn) && !string.IsNullOrEmpty(droneSn))
{
bool online = false;
if (telemetryMap.TryGetValue("data.sub_device.device_online_status", out string? onlineVal))
{
online = (onlineVal == "1");
}
LinkSubDevice(sn, droneSn, online);
}
}
}
catch
{
// Skip invalid JSON formats
}
}
else if (parts.Contains("status"))
{
// Parse status message: sys/product/{sn}/status
try
{
using var doc = JsonDocument.Parse(msg.Payload);
if (doc.RootElement.TryGetProperty("status", out var statusProp))
{
string statusStr = statusProp.GetString() ?? "";
bool online = statusStr.Equals("online", StringComparison.OrdinalIgnoreCase);
SetDeviceOnlineStatus(sn, online);
}
}
catch { }
}
}
}
// Scan for device timeouts (Offline detection)
var now = DateTime.Now;
foreach (var sn in _deviceHeartbeats.Keys.ToList())
{
if ((now - _deviceHeartbeats[sn]).TotalSeconds > 15)
{
SetDeviceOnlineStatus(sn, false);
}
}
// Update UI telemetry panel if device selected
if (_selectedDevice != null)
{
string activeSn = _selectedDevice.Sn;
if (_deviceTelemetryStore.TryGetValue(activeSn, out var telemetry))
{
UpdateOsdDashboard(activeSn, telemetry);
if (stateChanged)
{
RefreshTranslationTable(telemetry);
}
}
else
{
_telemetryVm.Reset();
_filteredTranslations.Clear();
_translations.Clear();
}
}
// Refresh raw logs table (append to bottom, and only auto-scroll if nothing is selected)
if (stateChanged && !_isPaused)
{
ApplyLogFilter();
if (GridLogs != null && GridLogs.SelectedItem == null && _filteredLogs.Count > 0)
{
GridLogs.ScrollIntoView(_filteredLogs[_filteredLogs.Count - 1]);
}
}
}
private void FlattenJson(string prefix, JsonElement element, Dictionary<string, string> target)
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
foreach (var property in element.EnumerateObject())
{
string nextPrefix = string.IsNullOrEmpty(prefix) ? property.Name : $"{prefix}.{property.Name}";
FlattenJson(nextPrefix, property.Value, target);
}
break;
case JsonValueKind.Array:
int idx = 0;
foreach (var item in element.EnumerateArray())
{
string nextPrefix = $"{prefix}.{idx}";
FlattenJson(nextPrefix, item, target);
idx++;
}
break;
case JsonValueKind.String:
target[prefix] = element.GetString() ?? "";
break;
case JsonValueKind.Number:
target[prefix] = element.GetRawText();
break;
case JsonValueKind.True:
target[prefix] = "true";
break;
case JsonValueKind.False:
target[prefix] = "false";
break;
case JsonValueKind.Null:
target[prefix] = "null";
break;
}
}
#endregion
#region TELEMETRY RENDERING AND TRANSLATION
private void UpdateOsdDashboard(string sn, Dictionary<string, string> flatData)
{
bool isDock = _selectedDevice?.Type == "设备" || _selectedDevice?.Type == "网关";
if (isDock)
{
GridDockTelemetry.Visibility = Visibility.Visible;
GridDroneTelemetry.Visibility = Visibility.Collapsed;
_telemetryVm.CoverState = GetTranslatedVal(flatData, "cover_state", isDock);
_telemetryVm.AirConditionerState = GetTranslatedVal(flatData, "air_conditioner.air_conditioner_state", isDock);
_telemetryVm.DroneInDock = GetTranslatedVal(flatData, "drone_in_dock", isDock);
_telemetryVm.ChargingState = GetTranslatedVal(flatData, "drone_charge_state.state", isDock);
string cap = GetRawVal(flatData, "drone_charge_state.capacity_percent");
_telemetryVm.DroneBatteryPercent = string.IsNullOrEmpty(cap) ? "未知" : cap + " %";
_telemetryVm.EnvironmentTemp = GetRawVal(flatData, "environment_temperature") + " °C";
_telemetryVm.CabinTemp = GetRawVal(flatData, "temperature") + " °C";
_telemetryVm.Humidity = GetRawVal(flatData, "humidity") + " %";
_telemetryVm.WindSpeed = GetRawVal(flatData, "wind_speed") + " m/s";
_telemetryVm.Rainfall = GetTranslatedVal(flatData, "rainfall", isDock);
string gps = GetRawVal(flatData, "position_state.gps_number");
_telemetryVm.GpsCount = string.IsNullOrEmpty(gps) ? "未知" : gps + " 颗";
_telemetryVm.RtkStatus = GetTranslatedVal(flatData, "position_state.quality", isDock);
string volt = GetRawVal(flatData, "working_voltage");
_telemetryVm.WorkingVoltage = string.IsNullOrEmpty(volt) ? "未知" : volt + " mV";
string cur = GetRawVal(flatData, "working_current");
_telemetryVm.WorkingCurrent = string.IsNullOrEmpty(cur) ? "未知" : cur + " mA";
_telemetryVm.EmergencyStop = GetTranslatedVal(flatData, "emergency_stop_state", isDock);
_telemetryVm.DockState = GetTranslatedVal(flatData, "mode_code", isDock);
}
else
{
GridDockTelemetry.Visibility = Visibility.Collapsed;
GridDroneTelemetry.Visibility = Visibility.Visible;
string lat = GetRawVal(flatData, "latitude");
string lng = GetRawVal(flatData, "longitude");
string alt = GetRawVal(flatData, "height");
string relAlt = GetRawVal(flatData, "elevation");
if (!string.IsNullOrEmpty(lat))
{
_telemetryVm.DronePosition = $"{lat}, {lng}\n高度: {alt} m | 相对高: {relAlt} m";
}
else
{
_telemetryVm.DronePosition = "未知";
}
string pitch = GetRawVal(flatData, "attitude_pitch");
string roll = GetRawVal(flatData, "attitude_roll");
string yaw = GetRawVal(flatData, "attitude_head");
if (!string.IsNullOrEmpty(pitch))
{
_telemetryVm.DroneAttitude = $"俯仰: {pitch}° | 横滚: {roll}° | 偏航: {yaw}°";
}
else
{
_telemetryVm.DroneAttitude = "未知";
}
string hSpeed = GetRawVal(flatData, "horizontal_speed");
string vSpeed = GetRawVal(flatData, "vertical_speed");
if (!string.IsNullOrEmpty(hSpeed))
{
_telemetryVm.DroneSpeeds = $"水平: {hSpeed} m/s | 垂直: {vSpeed} m/s";
}
else
{
_telemetryVm.DroneSpeeds = "未知";
}
string cap = GetRawVal(flatData, "battery.capacity_percent");
string battVolt = GetRawVal(flatData, "battery.voltage");
string battTemp = GetRawVal(flatData, "battery.temperature");
if (!string.IsNullOrEmpty(cap))
{
_telemetryVm.DroneBattery = $"{cap}% ({battVolt} mV | {battTemp} °C)";
}
else
{
_telemetryVm.DroneBattery = "未知";
}
string gps = GetRawVal(flatData, "position_state.gps_number");
string rtk = GetRawVal(flatData, "position_state.rtk_number");
string rtkFixed = GetTranslatedVal(flatData, "position_state.is_fixed", isDock);
if (!string.IsNullOrEmpty(gps))
{
_telemetryVm.DroneSats = $"GPS: {gps} 颗 | RTK: {rtk} 颗 ({rtkFixed})";
}
else
{
_telemetryVm.DroneSats = "未知";
}
_telemetryVm.DroneState = GetTranslatedVal(flatData, "mode_code", isDock);
_telemetryVm.DroneStateReason = GetTranslatedVal(flatData, "mode_code_reason", isDock);
string wSpeed = GetRawVal(flatData, "wind_speed");
string wDir = GetTranslatedVal(flatData, "wind_direction", isDock);
if (!string.IsNullOrEmpty(wSpeed))
{
_telemetryVm.WindSpeed = $"{wSpeed} m/s ({wDir})";
}
else
{
_telemetryVm.WindSpeed = "未知";
}
}
}
private string GetRawVal(Dictionary<string, string> flatData, string key)
{
// 1. Direct lookup
string fullKey = key.StartsWith("data.") ? key : "data." + key;
if (flatData.TryGetValue(fullKey, out var val))
{
return val;
}
// 2. Fuzzy lookup (ends with "." + key, handling component subkeys like data.52-0-0.latitude)
string suffix = "." + key;
var match = flatData.Keys.FirstOrDefault(k => k.EndsWith(suffix, StringComparison.OrdinalIgnoreCase));
if (match != null)
{
return flatData[match];
}
return "";
}
private string GetTranslatedVal(Dictionary<string, string> flatData, string key, bool isDock)
{
// 1. Direct lookup
string fullKey = key.StartsWith("data.") ? key : "data." + key;
if (flatData.TryGetValue(fullKey, out var val))
{
var result = TranslationDictionary.Translate(fullKey, val, isDock);
return result.TranslatedValue;
}
// 2. Fuzzy lookup (ends with "." + key, handling component subkeys like data.52-0-0.latitude)
string suffix = "." + key;
var match = flatData.Keys.FirstOrDefault(k => k.EndsWith(suffix, StringComparison.OrdinalIgnoreCase));
if (match != null)
{
var result = TranslationDictionary.Translate(match, flatData[match], isDock);
return result.TranslatedValue;
}
return "未知";
}
private void RefreshTranslationTable(Dictionary<string, string> flatData)
{
bool isDock = _selectedDevice?.Type == "设备" || _selectedDevice?.Type == "网关";
// Update translations collection
_translations.Clear();
foreach (var kvp in flatData)
{
var details = TranslationDictionary.Translate(kvp.Key, kvp.Value, isDock);
_translations.Add(new OsdTelemetryItem
{
Key = kvp.Key,
Label = details.Label,
Category = details.Category,
Value = details.TranslatedValue
});
}
ApplyTranslationFilter();
}
private void ApplyTranslationFilter()
{
string filterText = TxtSearchTranslation.Text.Trim();
_filteredTranslations.Clear();
var query = _translations.AsEnumerable();
if (!string.IsNullOrEmpty(filterText))
{
query = query.Where(t =>
t.Key.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
t.Label.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
t.Category.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
t.Value.Contains(filterText, StringComparison.OrdinalIgnoreCase)
);
}
// Order by Category then Key
var sorted = query.OrderBy(t => t.Category).ThenBy(t => t.Key);
foreach (var item in sorted)
{
_filteredTranslations.Add(item);
}
}
#endregion
#region DEVICE MANAGEMENT
private void BtnAddDevice_Click(object sender, RoutedEventArgs e)
{
string sn = TxtAddDeviceSn.Text.Trim();
string name = TxtAddDeviceName.Text.Trim();
string type = (ComboDeviceType.SelectedItem as ComboBoxItem)?.Content?.ToString() == "无人机" ? "无人机" : "网关";
if (string.IsNullOrEmpty(sn))
{
MessageBox.Show("设备 SN 不能为空!", "输入错误", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
if (string.IsNullOrEmpty(name))
{
name = $"设备 {sn.Substring(Math.Max(0, sn.Length - 4))}";
}
if (_devices.Any(d => d.Sn == sn) || _devices.Any(d => d.SubDevices.Any(s => s.Sn == sn)))
{
MessageBox.Show("此设备 SN 已存在!", "输入错误", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
var newDevice = new DeviceItem
{
Sn = sn,
Name = name,
Type = type,
IsOnline = false
};
_devices.Add(newDevice);
// Generate standard topics for it
RebuildDefaultTopics();
// Re-subscribe if connected
TriggerAutoResubscribe();
SaveConfig();
TxtAddDeviceSn.Clear();
TxtAddDeviceName.Clear();
}
private void BtnDeleteDevice_Click(object sender, RoutedEventArgs e)
{
if (_selectedDevice == null)
{
MessageBox.Show("请先在设备树中选择一个要删除的设备!", "删除设备", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
var result = MessageBox.Show($"确定要删除设备 {_selectedDevice.Name} ({_selectedDevice.Sn}) 吗?", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
// Remove root device
if (_devices.Contains(_selectedDevice))
{
_devices.Remove(_selectedDevice);
}
else
{
// Check if it is a subdevice
foreach (var root in _devices)
{
if (root.SubDevices.Contains(_selectedDevice))
{
root.SubDevices.Remove(_selectedDevice);
break;
}
}
}
_selectedDevice = null;
TxtSelectedDeviceName.Text = "[无]";
TxtSelectedDeviceSn.Text = "-";
TxtSelectedDeviceType.Text = "-";
_telemetryVm.Reset();
_translations.Clear();
_filteredTranslations.Clear();
RebuildDefaultTopics();
TriggerAutoResubscribe();
SaveConfig();
}
}
private void SetDeviceOnlineStatus(string sn, bool isOnline)
{
// Traverse devices list
foreach (var dev in _devices)
{
if (dev.Sn == sn)
{
if (dev.IsOnline != isOnline)
{
dev.IsOnline = isOnline;
}
return;
}
foreach (var sub in dev.SubDevices)
{
if (sub.Sn == sn)
{
if (sub.IsOnline != isOnline)
{
sub.IsOnline = isOnline;
}
return;
}
}
}
}
private void LinkSubDevice(string parentSn, string subSn, bool subOnline)
{
// Find parent
var parent = _devices.FirstOrDefault(d => d.Sn == parentSn);
if (parent != null)
{
// Check if already contains sub SN
var sub = parent.SubDevices.FirstOrDefault(s => s.Sn == subSn);
if (sub == null)
{
// Link new drone sub-device
var subDev = new DeviceItem
{
Sn = subSn,
Name = $"停机坪飞机 ({subSn.Substring(Math.Max(0, subSn.Length - 4))})",
Type = "无人机",
IsOnline = subOnline
};
parent.SubDevices.Add(subDev);
RebuildDefaultTopics();
TriggerAutoResubscribe();
SaveConfig();
}
else
{
// Update state if changed
if (sub.IsOnline != subOnline)
{
sub.IsOnline = subOnline;
}
}
}
}
private void AutoRegisterDevice(string deviceSn, string? gatewaySn, bool isEventsTopic)
{
if (!string.IsNullOrEmpty(gatewaySn))
{
if (deviceSn == gatewaySn)
{
// Topic SN matches gateway SN: this is a Gateway (网关) or Device (设备)
string targetType = isEventsTopic ? "设备" : "网关";
var existingRoot = _devices.FirstOrDefault(d => d.Sn == deviceSn);
if (existingRoot != null)
{
// Upgrade to "设备" if we receive events
if (existingRoot.Type != "设备" && targetType == "设备")
{
existingRoot.Type = "设备";
if (existingRoot.Name.StartsWith("网关"))
{
existingRoot.Name = existingRoot.Name.Replace("网关", "机场设备");
}
SaveConfig();
}
}
else
{
// Look up if registered elsewhere
DeviceItem? foundAsSub = null;
foreach (var r in _devices)
{
foundAsSub = r.SubDevices.FirstOrDefault(s => s.Sn == deviceSn);
if (foundAsSub != null) break;
}
if (foundAsSub != null)
{
// Move from subdevices to root (since it is a gateway)
foreach (var r in _devices)
{
if (r.SubDevices.Contains(foundAsSub))
{
r.SubDevices.Remove(foundAsSub);
break;
}
}
foundAsSub.Type = targetType;
_devices.Add(foundAsSub);
SaveConfig();
}
else
{
// Add new root gateway
var newDev = new DeviceItem
{
Sn = deviceSn,
Name = targetType == "设备" ? $"机场设备 {deviceSn.Substring(Math.Max(0, deviceSn.Length - 4))}" : $"网关 {deviceSn.Substring(Math.Max(0, deviceSn.Length - 4))}",
Type = targetType,
IsOnline = true
};
_devices.Add(newDev);
RebuildDefaultTopics();
TriggerAutoResubscribe();
SaveConfig();
}
}
}
else
{
// Topic SN != gateway SN: this is a Drone (无人机)
// Check if parent gateway exists
var parentGateway = _devices.FirstOrDefault(d => d.Sn == gatewaySn);
if (parentGateway == null)
{
// Auto-create parent gateway
parentGateway = new DeviceItem