-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathMainViewModel.cs
399 lines (328 loc) · 13.4 KB
/
MainViewModel.cs
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
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Threading;
using fs2ff.Models;
using fs2ff.SimConnect;
#pragma warning disable 67
namespace fs2ff
{
[SuppressMessage("ReSharper", "NotAccessedField.Local", Justification = "DispatcherTimer field is kept to prevent premature GC")]
public class MainViewModel : INotifyPropertyChanged, ISimConnectMessageHandler
{
private readonly DataSender _dataSender;
private readonly SimConnectAdapter _simConnect;
private readonly IpDetectionService _ipDetectionService;
private readonly DispatcherTimer _ipHintTimer;
private readonly DispatcherTimer _autoConnectTimer;
private uint _attitudeFrequency = Preferences.Default.att_freq.AdjustToBounds(AttitudeFrequencyMin, AttitudeFrequencyMax);
private bool _autoDetectIpEnabled = Preferences.Default.ip_detection_enabled;
private bool _autoConnectEnabled = Preferences.Default.auto_connect_enabled;
private bool _dataAttitudeEnabled = Preferences.Default.att_enabled;
private bool _dataPositionEnabled = Preferences.Default.pos_enabled;
private bool _dataTrafficEnabled = Preferences.Default.tfk_enabled;
private bool _errorOccurred;
private IntPtr _hwnd = IntPtr.Zero;
private IPAddress? _ipAddress;
private uint _ipHintMinutesLeft = Preferences.Default.ip_hint_time;
public MainViewModel(DataSender dataSender, SimConnectAdapter simConnect, IpDetectionService ipDetectionService)
{
_dataSender = dataSender;
_simConnect = simConnect;
_simConnect.StateChanged += SimConnectStateChanged;
_simConnect.PositionReceived += SimConnectPositionReceived;
_simConnect.AttitudeReceived += SimConnectAttitudeReceived;
_simConnect.TrafficReceived += SimConnectTrafficReceived;
_ipDetectionService = ipDetectionService;
_ipDetectionService.NewIpDetected += IpDetectionService_NewIpDetected;
OpenSettingsCommand = new ActionCommand(OpenSettings);
DismissSettingsPaneCommand = new ActionCommand(DismissSettingsPane);
GotoNewReleaseCommand = new ActionCommand(GotoReleaseNotesPage);
ToggleConnectCommand = new ActionCommand(ToggleConnect, CanConnect);
ToggleSettingsPaneCommand = new ActionCommand(ToggleSettingsPane);
_ipAddress = IPAddress.TryParse(Preferences.Default.ip_address, out var ip) ? ip : null;
_ipHintTimer = new DispatcherTimer(TimeSpan.FromMinutes(1), DispatcherPriority.Normal, IpHintCallback, Dispatcher.CurrentDispatcher);
_autoConnectTimer = new DispatcherTimer(TimeSpan.FromSeconds(5), DispatcherPriority.Normal, AutoConnectCallback, Dispatcher.CurrentDispatcher);
ManageAutoConnect();
CheckForUpdates();
UpdateVisualState();
}
public event PropertyChangedEventHandler? PropertyChanged;
[SuppressMessage("ReSharper", "UnusedMember.Local", Justification = "Unknown is not supposed to be used")]
private enum FlightSimState
{
Unknown,
Connected,
Disconnected,
ErrorOccurred,
AutoConnecting
}
public static string WindowTitle => $"fs2ff - {App.InformationalVersion}";
public uint AttitudeFrequency
{
get => _attitudeFrequency;
set
{
_attitudeFrequency = value.AdjustToBounds(AttitudeFrequencyMin, AttitudeFrequencyMax);
_simConnect.SetAttitudeFrequency(_attitudeFrequency);
Preferences.Default.att_freq = value;
Preferences.Default.Save();
}
}
public static uint AttitudeFrequencyMax => 10;
public static uint AttitudeFrequencyMin => 4;
public bool AutoConnectEnabled
{
get => _autoConnectEnabled;
set
{
if (value != _autoConnectEnabled)
{
_autoConnectEnabled = value;
Preferences.Default.auto_connect_enabled = value;
Preferences.Default.Save();
// If auto connect was running and the sim wasn't then there is likely
// an error flagged. Clear it whenever AutoConnectEnabled changes state
// so in the event auto connect is disabled the window won't show
// a meaningless connection error to the user.
_errorOccurred = false;
ManageAutoConnect();
UpdateVisualState();
}
}
}
public bool AutoConnectLabelVisible { get; private set; }
public bool AutoDetectIpEnabled
{
get => _autoDetectIpEnabled;
set
{
if (value != _autoDetectIpEnabled)
{
_autoDetectIpEnabled = value;
Preferences.Default.ip_detection_enabled = value;
Preferences.Default.Save();
}
}
}
public bool ConnectButtonEnabled { get => !_autoConnectEnabled; }
public string? ConnectButtonText { get; private set; }
public bool ConnectedLabelVisible { get; private set; }
public bool DataAttitudeEnabled
{
get => _dataAttitudeEnabled;
set
{
if (value != _dataAttitudeEnabled)
{
_dataAttitudeEnabled = value;
Preferences.Default.att_enabled = value;
Preferences.Default.Save();
}
}
}
public bool DataPositionEnabled
{
get => _dataPositionEnabled;
set
{
if (value != _dataPositionEnabled)
{
_dataPositionEnabled = value;
Preferences.Default.pos_enabled = value;
Preferences.Default.Save();
}
}
}
public bool DataTrafficEnabled
{
get => _dataTrafficEnabled;
set
{
if (value != _dataTrafficEnabled)
{
_dataTrafficEnabled = value;
Preferences.Default.tfk_enabled = value;
Preferences.Default.Save();
}
}
}
public ICommand DismissSettingsPaneCommand { get; }
public bool ErrorLabelVisible { get; private set; }
public ICommand GotoNewReleaseCommand { get; }
public bool IndicatorVisible { get; private set; }
public IPAddress? IpAddress
{
get => _ipAddress;
set
{
if (!Equals(value, _ipAddress))
{
_ipAddress = value;
Preferences.Default.ip_address = value?.ToString() ?? "";
Preferences.Default.Save();
if (value != null)
{
ResetIpHintMinutesLeft();
}
ResetDataSenderConnection();
}
}
}
public bool IpHintVisible => IpAddress == null && IpHintMinutesLeft == 0;
public bool NotLabelVisible { get; private set; }
public ICommand OpenSettingsCommand { get; }
public bool SettingsPaneVisible { get; set; }
public ActionCommand ToggleConnectCommand { get; }
public ICommand ToggleSettingsPaneCommand { get; }
public bool UpdateMsgVisible => UpdateInfo != null && !SettingsPaneVisible;
public IntPtr WindowHandle
{
get => _hwnd;
set
{
_hwnd = value;
ToggleConnectCommand.TriggerCanExecuteChanged();
}
}
private FlightSimState CurrentFlightSimState =>
_simConnect.Connected ? FlightSimState.Connected :
AutoConnectEnabled ? FlightSimState.AutoConnecting :
_errorOccurred ? FlightSimState.ErrorOccurred :
FlightSimState.Disconnected;
private uint IpHintMinutesLeft
{
get => _ipHintMinutesLeft;
set
{
if (value != _ipHintMinutesLeft)
{
_ipHintMinutesLeft = value;
Preferences.Default.ip_hint_time = value;
Preferences.Default.Save();
}
}
}
private UpdateInformation? UpdateInfo { get; set; }
public void Dispose()
{
_ipDetectionService.NewIpDetected -= IpDetectionService_NewIpDetected;
_simConnect.TrafficReceived -= SimConnectTrafficReceived;
_simConnect.AttitudeReceived -= SimConnectAttitudeReceived;
_simConnect.PositionReceived -= SimConnectPositionReceived;
_simConnect.StateChanged -= SimConnectStateChanged;
_simConnect.Dispose();
_dataSender.Dispose();
}
public void ReceiveFlightSimMessage() => _simConnect.ReceiveMessage();
private void AutoConnectCallback(object? sender, EventArgs e) => Connect();
private bool CanConnect() => WindowHandle != IntPtr.Zero;
private void CheckForUpdates()
{
UpdateChecker.Check().ContinueWith(task => UpdateInfo = task.Result, TaskScheduler.FromCurrentSynchronizationContext());
}
private void Connect() => _simConnect.Connect(WindowHandle, AttitudeFrequency);
private void Disconnect() => _simConnect.Disconnect();
private void DismissSettingsPane() => SettingsPaneVisible = false;
private void GotoReleaseNotesPage()
{
if (UpdateInfo != null)
{
Process.Start("explorer.exe", UpdateInfo.DownloadLink.ToString());
}
}
private void IpDetectionService_NewIpDetected(IPAddress ip)
{
if (AutoDetectIpEnabled)
{
IpAddress = ip;
}
}
private void IpHintCallback(object? sender, EventArgs e)
{
if (IpHintMinutesLeft > 0 && IpAddress == null && _simConnect.Connected)
{
IpHintMinutesLeft--;
}
}
private void ManageAutoConnect()
{
if (!AutoConnectEnabled || CurrentFlightSimState == FlightSimState.Connected)
{
_autoConnectTimer.Stop();
}
else
{
_autoConnectTimer.Start();
}
}
private void OpenSettings() => SettingsPaneVisible = true;
private void ResetDataSenderConnection()
{
if (CurrentFlightSimState == FlightSimState.Connected)
{
_dataSender.Connect(IpAddress);
}
else
{
_dataSender.Disconnect();
}
}
private void ResetIpHintMinutesLeft()
{
Preferences.Default.PropertyValues["ip_hint_time"].SerializedValue = Preferences.Default.Properties["ip_hint_time"].DefaultValue;
Preferences.Default.PropertyValues["ip_hint_time"].Deserialized = false;
IpHintMinutesLeft = Preferences.Default.ip_hint_time;
}
private async Task SimConnectAttitudeReceived(Attitude att)
{
if (DataAttitudeEnabled)
{
await _dataSender.Send(att).ConfigureAwait(false);
}
}
private async Task SimConnectPositionReceived(Position pos)
{
if (DataPositionEnabled && (pos.Latitude != 0d || pos.Longitude != 0d))
{
await _dataSender.Send(pos).ConfigureAwait(false);
}
}
private void SimConnectStateChanged(bool failure)
{
_errorOccurred = failure;
ManageAutoConnect();
ResetDataSenderConnection();
UpdateVisualState();
}
private async Task SimConnectTrafficReceived(Traffic tfk, uint id)
{
// Ignore traffic with id=1, that's our own aircraft
if (DataTrafficEnabled && id != 1)
{
await _dataSender.Send(tfk, id).ConfigureAwait(false);
}
}
private void ToggleConnect()
{
if (_simConnect.Connected) Disconnect();
else Connect();
}
private void ToggleSettingsPane() => SettingsPaneVisible = !SettingsPaneVisible;
private void UpdateVisualState()
{
(IndicatorVisible, AutoConnectLabelVisible, NotLabelVisible, ErrorLabelVisible, ConnectedLabelVisible, ConnectButtonText) = CurrentFlightSimState switch
{
FlightSimState.AutoConnecting => (false, true, false, false, false, "Connect"),
FlightSimState.Connected => (true, false, false, false, true, "Disconnect"),
FlightSimState.Disconnected => (false, false, true, false, true, "Connect"),
FlightSimState.ErrorOccurred => (false, false, false, true, false, "Connect"),
_ => (false, false, true, false, true, "Connect")
};
}
}
}