-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMainWindowViewModel.cs
More file actions
370 lines (315 loc) · 12.4 KB
/
MainWindowViewModel.cs
File metadata and controls
370 lines (315 loc) · 12.4 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
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 MsBox.Avalonia;
using MsBox.Avalonia.Enums;
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 IStorageProvider? _storageProvider;
public ObservableCollection<string> 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]
private string? selectedPort;
[ObservableProperty]
private bool isConnected;
[ObservableProperty]
private int selectedTabIndex;
[ObservableProperty]
private bool mirrorDisplay;
[ObservableProperty]
private bool portraitMode;
[ObservableProperty]
private bool printTimestamps;
[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;
public IStorageProvider? StorageProvider
{
get => _storageProvider;
set => SetProperty(ref _storageProvider, value);
}
public MainWindowViewModel(
SerialService serialService,
ConfigurationService configurationService,
MetaUpdateService metaUpdateService,
MetaDefinitionService metaDefinitionService,
SerialLineDecoder serialLineDecoder,
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));
_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();
RefreshPorts();
_serialService.DataReceived += OnDataReceived;
_serialService.Disconnected += OnDisconnected;
_serialService.DeviceStateChanged += OnDeviceStateChanged;
_serialService.DeviceConfigChanged += OnDeviceConfigChanged;
}
// 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.ShowAsync();
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)
.ShowAsync();
}
}
}
// 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.ShowAsync();
}
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)
.ShowAsync();
}
if (_configurationService.Config.CheckForAppUpdates)
{
updateAvailable = await _metaUpdateService.CheckForAppUpdatesAsync(AppVersion);
if (updateAvailable)
{
var box = MessageBoxManager
.GetMessageBoxStandard(Assets.Resources.Warning,
string.Format(Assets.Resources.NewAppReleaseAvailable, "https://github.com/xboxoneresearch/XboxPostcodeMonitor/releases"), ButtonEnum.Ok);
await box.ShowAsync();
}
}
}
[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);
}
sb.AppendLine();
// Add decoded log
sb.AppendLine("=== Decoded Log ===");
foreach (var entry in LogEntries.Where(e => e.DecodedCode != null))
{
sb.AppendLine(entry.FormattedText);
}
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)
.ShowAsync();
}
}
[RelayCommand]
private void RefreshPorts()
{
SerialPorts.Clear();
foreach (var port in _serialService.GetPortNames())
SerialPorts.Add(port);
if (SerialPorts.Count > 0 && SelectedPort == null)
SelectedPort = SerialPorts.FirstOrDefault();
}
[RelayCommand]
private async Task ConnectAsync()
{
if (SelectedPort != null)
{
try
{
await _serialService.ConnectAsync(SelectedPort);
RawLogEntries?.Clear();
LogEntries?.Clear();
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)
.ShowAsync();
}
if (IsConnected && _configurationService.Config.CheckForFwUpdates)
{
var updateAvailable = await _metaUpdateService.CheckForFirmwareUpdatesAsync(_serialService.FirmwareVersion);
if (updateAvailable)
{
var box = MessageBoxManager
.GetMessageBoxStandard(Assets.Resources.Warning,
string.Format(Assets.Resources.NewFirmwareReleaseAvailable, "https://github.com/xboxoneresearch/PicoDurangoPOST/releases"), ButtonEnum.Ok);
await box.ShowAsync();
}
}
}
}
[RelayCommand]
private void Disconnect()
{
_serialService.Disconnect();
IsConnected = false;
}
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());
}
private Window GetParentWindow()
{
if (Avalonia.Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
return desktop?.MainWindow ?? throw new Exception(Assets.Resources.FailedGetMainWindow);
else
throw new Exception(Assets.Resources.FailedGetApplicationLifetime);
}
}