-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMainWindowViewModel.cs
More file actions
479 lines (408 loc) · 16.1 KB
/
Copy pathMainWindowViewModel.cs
File metadata and controls
479 lines (408 loc) · 16.1 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
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using System.Text;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Avalonia.Controls;
using Avalonia.Platform.Storage;
using Avalonia.Controls.ApplicationLifetimes;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PostCodeSerialMonitor.Views;
using PostCodeSerialMonitor.Services;
using PostCodeSerialMonitor.Models;
using PostCodeSerialMonitor.Utils;
using MsBox.Avalonia;
using MsBox.Avalonia.Enums;
using MsBox.Avalonia.Dto;
using Avalonia.Media;
namespace PostCodeSerialMonitor.ViewModels;
public partial class MainWindowViewModel : ViewModelBase
{
private readonly SerialService _serialService;
private readonly ConfigurationService _configurationService;
private readonly ILogger<MainWindowViewModel> _logger;
private SerialLineDecoder _serialLineDecoder;
private MetaUpdateService _metaUpdateService;
private MetaDefinitionService _metaDefinitionService;
private GithubUpdateService _githubUpdateService;
private IStorageProvider? _storageProvider;
public ObservableCollection<PortInfo> SerialPorts { get; } = new();
public ObservableCollection<ConsoleType> ConsoleModels { get; } = new();
public ObservableCollection<LogEntry> LogEntries { get; } = new();
public ObservableCollection<string> RawLogEntries { get; } = new();
private string lastConnectedPicoFwVersion = Assets.Resources.Unavailable;
[ObservableProperty]
private ConsoleType selectedConsoleModel;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(CanToggleConnection))]
private PortInfo? selectedPort;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(CanToggleConnection))]
[NotifyPropertyChangedFor(nameof(ConnectionButtonText))]
[NotifyPropertyChangedFor(nameof(ConnectionButtonIcon))]
private bool isConnected;
public bool CanToggleConnection => IsConnected || SelectedPort != null;
public string ConnectionButtonText => IsConnected ? Assets.Resources.Disconnect : Assets.Resources.Connect;
public StreamGeometry? ConnectionButtonIcon =>
Avalonia.Application.Current?.Resources.TryGetResource(
IsConnected ? "plug_disconnected_regular" : "play_regular", null, out var resource) == true
? resource as StreamGeometry
: null;
[ObservableProperty]
private int selectedTabIndex;
[ObservableProperty]
private bool mirrorDisplay;
[ObservableProperty]
private bool portraitMode;
[ObservableProperty]
private bool printTimestamps;
[ObservableProperty]
private bool showTimestamps;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsDescriptionInlineMode))]
[NotifyPropertyChangedFor(nameof(IsDescriptionNewLineMode))]
[NotifyPropertyChangedFor(nameof(IsDescriptionBottomPanelMode))]
private string descriptionDisplayMode = "NewLine";
public bool IsDescriptionInlineMode => DescriptionDisplayMode == "Inline";
public bool IsDescriptionNewLineMode => DescriptionDisplayMode == "NewLine";
public bool IsDescriptionBottomPanelMode => DescriptionDisplayMode == "BottomPanel";
[ObservableProperty]
private string i2cScanOutput = Assets.Resources.ScanButtonText;
[ObservableProperty]
private string firmwareVersion = Assets.Resources.NotConnected;
[ObservableProperty]
private string buildDate = string.Empty;
[ObservableProperty]
private string metadataLastUpdate = Assets.Resources.Never;
[ObservableProperty]
private string appVersion;
[ObservableProperty]
private bool debugModeUnlocked;
[ObservableProperty]
private LogEntry? selectedLogEntry;
private int _appVersionClickCount;
public IStorageProvider? StorageProvider
{
get => _storageProvider;
set => SetProperty(ref _storageProvider, value);
}
public MainWindowViewModel(
SerialService serialService,
ConfigurationService configurationService,
MetaUpdateService metaUpdateService,
MetaDefinitionService metaDefinitionService,
SerialLineDecoder serialLineDecoder,
GithubUpdateService githubUpdateService,
ILogger<MainWindowViewModel> logger)
{
_serialService = serialService ?? throw new ArgumentNullException(nameof(serialService));
_configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));
_metaUpdateService = metaUpdateService ?? throw new ArgumentNullException(nameof(metaUpdateService));
_metaDefinitionService = metaDefinitionService ?? throw new ArgumentNullException(nameof(metaDefinitionService));
_serialLineDecoder = serialLineDecoder ?? throw new ArgumentNullException(nameof(serialLineDecoder));
_githubUpdateService = githubUpdateService ?? throw new ArgumentNullException(nameof(githubUpdateService));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
// Get version from assembly
var version = Assembly.GetExecutingAssembly().GetName().Version;
AppVersion = version?.ToString() ?? "Unversioned";
// Initialize console models with only Xbox consoles
foreach (ConsoleType type in Enum.GetValues(typeof(ConsoleType)))
{
if (type.ToString().StartsWith("Xbox"))
{
ConsoleModels.Add(type);
}
}
SelectedConsoleModel = ConsoleModels.FirstOrDefault();
ShowTimestamps = _configurationService.Config.ShowTimestamps;
DescriptionDisplayMode = _configurationService.Config.DescriptionDisplayMode;
RefreshPorts();
_serialService.DataReceived += OnDataReceived;
_serialService.Disconnected += OnDisconnected;
_serialService.DeviceStateChanged += OnDeviceStateChanged;
_serialService.DeviceConfigChanged += OnDeviceConfigChanged;
}
private MessageBoxStandardParams MsgBoxHyperlink(string title, string text, string link)
{
return new MessageBoxStandardParams
{
ContentTitle = title,
ContentMessage = text,
ButtonDefinitions = ButtonEnum.Ok,
Icon = Icon.None,
WindowStartupLocation = WindowStartupLocation.CenterScreen,
SizeToContent = SizeToContent.WidthAndHeight,
HyperLinkParams = new HyperLinkParams
{
Text = link,
Action = new Action(() => GlobalActions.OpenHyperlinkAction(link)),
}
};
}
// Executed by code behind view
public async void OnLoaded()
{
var updateAvailable = await _metaUpdateService.CheckForMetaDefinitionUpdatesAsync();
if (updateAvailable)
{
var box = MessageBoxManager
.GetMessageBoxStandard(
Assets.Resources.NewMetadataAvailable,
Assets.Resources.NewMetadataAvailableInformation,
ButtonEnum.YesNo
);
var result = await box.ShowAsPopupAsync(GetParentWindow());
if (result.HasFlag(ButtonResult.Yes))
{
try
{
await _metaUpdateService.UpdateMetaDefinitionAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, Assets.Resources.FailedUpdateMetadata);
await MessageBoxManager
.GetMessageBoxStandard(Assets.Resources.Error, string.Format(Assets.Resources.FailedUpdateMetadataMessageBoxError, ex.Message), ButtonEnum.Ok)
.ShowAsPopupAsync(GetParentWindow());
}
}
}
// Update the metadata last update timestamp
MetadataLastUpdate = _metaUpdateService.LastUpdateTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? Assets.Resources.Never;
var success = await _metaUpdateService.TryLoadLocalDefinition();
if (!success)
{
_logger.LogWarning(Assets.Resources.FailedLoadLocalMetadata);
var box = MessageBoxManager
.GetMessageBoxStandard(Assets.Resources.Warning, Assets.Resources.FailedLoadLocalMetadataMessageBoxWarning,
ButtonEnum.Ok);
await box.ShowAsPopupAsync(GetParentWindow());
}
try
{
await _metaDefinitionService.RefreshMetaDefinitionsAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, Assets.Resources.FailedLoadLocalMetadata);
await MessageBoxManager
.GetMessageBoxStandard(Assets.Resources.Error, string.Format(Assets.Resources.FailedLoadLocalMetadataMessageBoxError, ex.Message),
ButtonEnum.Ok)
.ShowAsPopupAsync(GetParentWindow());
}
if (_configurationService.Config.CheckForAppUpdates)
{
updateAvailable = await _githubUpdateService.CheckForAppUpdatesAsync(AppVersion);
if (updateAvailable)
{
var box = MessageBoxManager
.GetMessageBoxStandard(MsgBoxHyperlink(
Assets.Resources.Warning,
Assets.Resources.NewAppReleaseAvailable,
"https://github.com/xboxoneresearch/XboxPostcodeMonitor/releases"
));
await box.ShowAsPopupAsync(GetParentWindow());
}
}
}
[RelayCommand]
private void ClearLog()
{
LogEntries.Clear();
RawLogEntries.Clear();
SelectedLogEntry = null;
}
[RelayCommand]
private void SelectLogEntry(LogEntry entry)
{
if (SelectedLogEntry == entry)
{
entry.IsSelected = false;
SelectedLogEntry = null;
return;
}
if (SelectedLogEntry != null)
SelectedLogEntry.IsSelected = false;
entry.IsSelected = true;
SelectedLogEntry = entry;
}
[RelayCommand]
private async Task SaveLogAsync()
{
if (_storageProvider == null)
return;
var timestamp = DateTime.Now.ToString("yyyyMMdd-HHmmss");
var defaultName = $"POST_{SelectedConsoleModel}_{timestamp}_{AppVersion}.log";
var file = await _storageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
{
Title = Assets.Resources.SaveLogFiles,
DefaultExtension = "log",
SuggestedFileName = defaultName,
FileTypeChoices = new[]
{
new FilePickerFileType(Assets.Resources.LogFiles)
{
Patterns = new[] { "*.log" }
}
}
});
if (file == null)
return;
var sb = new StringBuilder();
// Add metadata
sb.AppendLine("=== Metadata ===");
sb.AppendLine($"Console Type: {SelectedConsoleModel}");
sb.AppendLine($"Pico Firmware: {lastConnectedPicoFwVersion}");
sb.AppendLine($"Metadata Update: {MetadataLastUpdate}");
sb.AppendLine($"App Version: {AppVersion}");
sb.AppendLine();
// Add raw log
sb.AppendLine("=== Raw Log ===");
foreach (var entry in RawLogEntries)
{
sb.AppendLine(entry?.Trim());
}
sb.AppendLine();
// Add decoded log
sb.AppendLine("=== Decoded Log ===");
foreach (var entry in LogEntries.Where(e => e.DecodedCode != null))
{
sb.AppendLine(entry.FormattedWithTs);
}
try
{
await File.WriteAllTextAsync(file.Path.LocalPath, sb.ToString());
}
catch (Exception ex)
{
_logger.LogError(ex, Assets.Resources.ErrorSavingLogFile);
await MessageBoxManager
.GetMessageBoxStandard(Assets.Resources.Error, string.Format(Assets.Resources.ErrorSavingLogFileMessageBoxError, ex.Message),
ButtonEnum.Ok)
.ShowAsPopupAsync(GetParentWindow());
}
}
[RelayCommand]
private void RefreshPorts()
{
SerialPorts.Clear();
foreach (var port in _serialService.GetPortInfos())
SerialPorts.Add(port);
if (SerialPorts.Count > 0 && SelectedPort == null)
SelectedPort = SerialPorts.FirstOrDefault();
}
[RelayCommand]
private async Task ToggleConnectionAsync()
{
if (SelectedPort == null)
{
return;
}
try
{
if (IsConnected)
{
_serialService.Disconnect();
IsConnected = false;
}
else
{
await _serialService.ConnectAsync(SelectedPort.Name);
ClearLog();
IsConnected = true;
}
}
catch (Exception ex)
{
_logger.LogError(ex, Assets.Resources.ErrorConection);
await MessageBoxManager
.GetMessageBoxStandard(Assets.Resources.Error, string.Format(Assets.Resources.ErrorConectionMessageBoxError, ex.Message),
ButtonEnum.Ok)
.ShowAsPopupAsync(GetParentWindow());
}
if (IsConnected && _configurationService.Config.CheckForFwUpdates)
{
var updateAvailable = await _githubUpdateService.CheckForFirmwareUpdatesAsync(_serialService.FirmwareVersion);
if (updateAvailable)
{
var box = MessageBoxManager
.GetMessageBoxStandard(MsgBoxHyperlink(
Assets.Resources.Warning,
Assets.Resources.NewFirmwareReleaseAvailable,
"https://github.com/xboxoneresearch/PicoDurangoPOST/releases"
));
await box.ShowAsPopupAsync(GetParentWindow());
}
}
}
private void OnDataReceived(string line)
{
RawLogEntries.Add(line);
var decoded = _serialLineDecoder.DecodeLine(line, SelectedConsoleModel);
if (decoded != null)
{
LogEntries.Add(new LogEntry { DecodedCode = decoded });
}
}
private void OnDisconnected()
{
IsConnected = false;
FirmwareVersion = Assets.Resources.NotConnected;
BuildDate = string.Empty;
MirrorDisplay = false;
PortraitMode = false;
PrintTimestamps = false;
I2cScanOutput = Assets.Resources.ScanButtonText;
var prevSelectedPort = SelectedPort;
RefreshPorts();
if (prevSelectedPort != null && SerialPorts.Contains(prevSelectedPort)) {
SelectedPort = prevSelectedPort;
}
}
private void OnDeviceStateChanged()
{
FirmwareVersion = _serialService.FirmwareVersion;
BuildDate = _serialService.BuildDate;
// Retain this info even after disconnected, for saving the Log
lastConnectedPicoFwVersion = $"{FirmwareVersion} ({BuildDate})";
}
private void OnDeviceConfigChanged()
{
MirrorDisplay = _serialService.MirrorDisplay;
PortraitMode = _serialService.PortraitMode;
PrintTimestamps = _serialService.PrintTimestamps;
}
[RelayCommand]
private async Task ShowConfigurationAsync()
{
var dialog = new ConfigurationDialog
{
DataContext = new ConfigurationDialogViewModel(_configurationService)
};
await dialog.ShowDialog(GetParentWindow());
ShowTimestamps = _configurationService.Config.ShowTimestamps;
DescriptionDisplayMode = _configurationService.Config.DescriptionDisplayMode;
}
[RelayCommand]
private void AppVersionClicked()
{
if (DebugModeUnlocked)
return;
_appVersionClickCount++;
if (_appVersionClickCount >= 5)
DebugModeUnlocked = true;
}
[RelayCommand]
private async Task ShowDebugMenuAsync()
{
var dialog = new DebugDialog
{
DataContext = new DebugDialogViewModel(RawLogEntries, LogEntries, _serialLineDecoder, ConsoleModels)
};
await dialog.ShowDialog(GetParentWindow());
}
}