-
Notifications
You must be signed in to change notification settings - Fork 9
/
SimvarsViewModel.cs
656 lines (536 loc) · 22.5 KB
/
SimvarsViewModel.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
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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using Microsoft.FlightSimulator.SimConnect;
using Sentry;
using Serilog;
using Serilog.Core;
using Simvars.Emum;
using Simvars.Model;
using Simvars.Struct;
using Simvars.Util;
namespace Simvars
{
public enum Definition
{
Dummy = 0
}
public enum Request
{
Dummy = 0
}
// String properties must be packed inside of a struct
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
internal struct Struct1
{
// this is how you declare a fixed size string
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string sValue;
// other definitions can be added to this struct ...
}
public class SimvarRequest : ObservableObject
{
private bool _mBStillPending;
private double _mDValue;
private string _mSValue;
public bool BPending = true;
public Definition EDef = Definition.Dummy;
public Request ERequest = Request.Dummy;
public string sName { get; set; }
public bool bIsString { get; set; }
public double dValue
{
get => _mDValue;
set => SetProperty(ref _mDValue, value);
}
public string sValue
{
get => _mSValue;
set => SetProperty(ref _mSValue, value);
}
public string sUnits { get; set; }
public bool bStillPending
{
get => _mBStillPending;
set => SetProperty(ref _mBStillPending, value);
}
}
public class SimvarsViewModel : BaseViewModel, IBaseSimConnectWrapper
{
#region Real time
private readonly DispatcherTimer _mOTimer = new();
#endregion Real time
private bool _clicked;
private Timer _dataTimer;
private LiveTrafficHandler _liveTrafficHandler;
private PlayerAircraft _plane;
public ObservableCollection<Aircraft> spawnedPlanes { get; set; } = new();
public SimvarsViewModel()
{
Logger log = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Hour)
.CreateLogger();
Log.Logger = log;
Log.Information($"Application started");
using (SentrySdk.Init(o =>
{
o.Dsn = "https://[email protected]/5846102";
// When configuring for the first time, to see what the SDK is doing:
o.Debug = true;
// Set traces_sample_rate to 1.0 to capture 100% of transactions for performance
// monitoring. We recommend adjusting this value in production.
o.TracesSampleRate = 1.0;
}))
{
lObjectIDs = new ObservableCollection<uint> { 1 };
lSimvarRequests = new ObservableCollection<SimvarRequest>();
lErrorMessages = new ObservableCollection<string>();
cmdToggleConnect = new BaseCommand(p => { ToggleConnect(); });
cmdAddRequest = new BaseCommand(p =>
{
AddRequest(_mIIndexRequest == 0 ? _mSSimvarRequest : _mSSimvarRequest + ":" + _mIIndexRequest,
sUnitRequest, bIsString);
});
cmdLoadFiles = new BaseCommand(p => { ChangeWayPoint(); });
_mOTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);
_mOTimer.Tick += OnTick;
AddonScanner.ScanAddons();
}
}
private void ChangeWayPoint()
{
_liveTrafficHandler?.LiveTrafficAircraft?.ForEach(item =>
{
Log.Information("Setting waypoint manual objectId " + item.objectId);
if (!_clicked)
{
Log.Information(@"Going to eindhoven");
var wp = new SIMCONNECT_DATA_WAYPOINT[3];
wp[0].Flags = (uint)(SIMCONNECT_WAYPOINT_FLAGS.SPEED_REQUESTED);
wp[0].Altitude = 0;
wp[0].Latitude = 51.460557;
wp[0].Longitude = 5.386274;
wp[0].ktsSpeed = 15;
wp[1].Flags = (uint)(SIMCONNECT_WAYPOINT_FLAGS.SPEED_REQUESTED
);
wp[1].Altitude = 0;
wp[1].Latitude = 51.456122;
wp[1].Longitude = 5.381370;
wp[1].ktsSpeed = 15;
wp[2].Flags = (uint)(SIMCONNECT_WAYPOINT_FLAGS.SPEED_REQUESTED);
wp[2].Altitude = 0;
wp[2].Latitude = 51.455226;
wp[2].Longitude = 5.383666;
wp[2].ktsSpeed = 0;
var obj = new object[wp.Length];
wp.CopyTo(obj, 0);
_mOSimConnect.SetDataOnSimObject(SimConnectDataDefinition.PlaneWaypoints, item.objectId,
SIMCONNECT_DATA_SET_FLAG.DEFAULT, obj);
}
else
{
Log.Information(@"Going to Live Location");
var wp = new SIMCONNECT_DATA_WAYPOINT[1];
wp[0].Flags = (uint)(SIMCONNECT_WAYPOINT_FLAGS.SPEED_REQUESTED |
SIMCONNECT_WAYPOINT_FLAGS.ALTITUDE_IS_AGL);
wp[0].Altitude = item.altimeter;
wp[0].Latitude = item.latitude;
wp[0].Longitude = item.longitude;
wp[0].ktsSpeed = item.speed;
var obj = new object[wp.Length];
wp.CopyTo(obj, 0);
_mOSimConnect.SetDataOnSimObject(SimConnectDataDefinition.PlaneWaypoints, item.objectId,
SIMCONNECT_DATA_SET_FLAG.DEFAULT, obj);
}
});
// _clicked = !_clicked;
}
private void Connect()
{
Log.Information(@"Connect");
_plane = new PlayerAircraft();
try
{
/// The constructor is similar to SimConnect_Open in the native API
_mOSimConnect = new SimConnect("Simconnect - Enhanced Live Traffic", _mHWnd, WM_USER_SIMCONNECT, null,
0);
/// Listen to connect and quit msgs
_mOSimConnect.OnRecvOpen += SimConnect_OnRecvOpen;
_mOSimConnect.OnRecvQuit += SimConnect_OnRecvQuit;
_mOSimConnect.OnRecvAssignedObjectId +=
SimConnect_OnRecvAssignedObjectId;
/// Listen to exceptions
_mOSimConnect.OnRecvException += SimConnect_OnRecvException;
/// Catch a simobject data request
_mOSimConnect.OnRecvSimobjectDataBytype += SimConnect_OnRecvSimobjectDataBytype;
_mOSimConnect.OnRecvSimobjectData += simconnect_OnRecvSimobjectData;
_liveTrafficHandler = new LiveTrafficHandler(_mOSimConnect);
}
catch (COMException ex)
{
Log.Error(@"Connection to KH failed: " + ex.Message);
}
}
private void DataTimerCallback(object? state)
{
_liveTrafficHandler.FetchNewData(_plane);
try
{
Application.Current.Dispatcher.Invoke(delegate // <--- HERE
{
spawnedPlanes.Clear();
_liveTrafficHandler.LiveTrafficAircraft.ForEach(plane => { spawnedPlanes.Add(plane); });
});
}
catch (Exception ex)
{
Log.Error($"Failed to update plane list, {ex.Message}");
}
}
private void SimConnect_OnRecvAssignedObjectId(SimConnect sender, SIMCONNECT_RECV_ASSIGNED_OBJECT_ID data)
{
Log.Information(@"Recieved object ID " + data.dwObjectID + @" from request: " + data.dwRequestID);
_liveTrafficHandler.SetObjectId(data.dwRequestID, data.dwObjectID);
}
private void SimConnect_OnRecvOpen(SimConnect sender, SIMCONNECT_RECV_OPEN data)
{
Log.Information(@"SimConnect_OnRecvOpen");
Log.Information(@"Connected to KH");
_dataTimer = new Timer(DataTimerCallback, null, 0, 1000 * 10);
sConnectButtonLabel = "Disconnect";
bConnected = true;
// Register pending requests
foreach (var oSimvarRequest in lSimvarRequests)
if (oSimvarRequest.BPending)
{
oSimvarRequest.BPending = !RegisterToSimConnect(oSimvarRequest);
oSimvarRequest.bStillPending = oSimvarRequest.BPending;
}
_mOSimConnect.AddToDataDefinition(SimConnectDataDefinition.PlaneLocation, "Plane Longitude", "degrees",
SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
_mOSimConnect.AddToDataDefinition(SimConnectDataDefinition.PlaneLocation, "Plane Latitude", "degrees",
SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
_mOSimConnect.AddToDataDefinition(SimConnectDataDefinition.PlaneLocation, "Plane Altitude", "meters",
SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
_mOSimConnect.AddToDataDefinition(SimConnectDataDefinition.PlaneLocation, "Plane Pitch Degrees", "degrees",
SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
_mOSimConnect.AddToDataDefinition(SimConnectDataDefinition.PlaneLocation, "Plane Bank Degrees", "degrees",
SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
_mOSimConnect.AddToDataDefinition(SimConnectDataDefinition.PlaneLocation, "Plane Heading Degrees True", "degrees",
SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
_mOSimConnect.AddToDataDefinition(SimConnectDataDefinition.PlaneLocation, "AIRSPEED TRUE", "knots",
SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
_mOSimConnect.AddToDataDefinition(SimConnectDataDefinition.PlaneWaypoints, "AI WAYPOINT LIST", "number",
SIMCONNECT_DATATYPE.WAYPOINT, 0.0f, SimConnect.SIMCONNECT_UNUSED);
_mOSimConnect.RegisterDataDefineStruct<PlayerAircraftStruct>(SimConnectDataDefinition.PlaneLocation);
_mOSimConnect.RequestDataOnSimObject(DataRequests.REQUEST_1, SimConnectDataDefinition.PlaneLocation,
SimConnect.SIMCONNECT_OBJECT_ID_USER, SIMCONNECT_PERIOD.SECOND, 0, 0, 0, 0);
_mOTimer.Start();
bOddTick = false;
}
/// The case where the user closes game
private void SimConnect_OnRecvQuit(SimConnect sender, SIMCONNECT_RECV data)
{
Log.Information(@"SimConnect_OnRecvQuit");
Log.Information(@"KH has exited");
Disconnect();
}
private void SimConnect_OnRecvException(SimConnect sender, SIMCONNECT_RECV_EXCEPTION data)
{
var eException = (SIMCONNECT_EXCEPTION)data.dwException;
Log.Error($"SimConnect_OnRecvException: {eException}, this could be related to a request above.");
lErrorMessages.Add("@" + DateTime.Now.ToString("HH:mm:ss") + ": " + eException);
}
private void simconnect_OnRecvSimobjectData(SimConnect sender, SIMCONNECT_RECV_SIMOBJECT_DATA data)
{
var planeStructure = (PlayerAircraftStruct)data.dwData[0];
_plane.Update(planeStructure);
}
private void SimConnect_OnRecvSimobjectDataBytype(SimConnect sender, SIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE data)
{
Log.Information(@"SimConnect_OnRecvSimobjectDataBytype");
var iRequest = data.dwRequestID;
var iObject = data.dwObjectID;
if (!lObjectIDs.Contains(iObject)) lObjectIDs.Add(iObject);
foreach (var oSimvarRequest in lSimvarRequests)
if (iRequest == (uint)oSimvarRequest.ERequest &&
(!bObjectIdSelectionEnabled || iObject == _mIObjectIdRequest))
{
if (oSimvarRequest.bIsString)
{
var result = (Struct1)data.dwData[0];
oSimvarRequest.dValue = 0;
oSimvarRequest.sValue = result.sValue;
}
else
{
var dValue = (double)data.dwData[0];
oSimvarRequest.dValue = dValue;
oSimvarRequest.sValue = dValue.ToString("F9");
}
oSimvarRequest.BPending = false;
oSimvarRequest.bStillPending = false;
}
}
// May not be the best way to achive regular requests. See SimConnect.RequestDataOnSimObject
private void OnTick(object sender, EventArgs e)
{
bOddTick = !bOddTick;
foreach (var oSimvarRequest in lSimvarRequests)
if (!oSimvarRequest.BPending)
{
_mOSimConnect?.RequestDataOnSimObjectType(oSimvarRequest.ERequest, oSimvarRequest.EDef, 0,
_mESimObjectType);
oSimvarRequest.BPending = true;
}
else
{
oSimvarRequest.bStillPending = true;
}
}
private void ToggleConnect()
{
if (_mOSimConnect == null)
try
{
Connect();
}
catch (COMException ex)
{
Log.Error("Unable to connect to KH: " + ex.Message);
}
else
Disconnect();
}
private bool RegisterToSimConnect(SimvarRequest oSimvarRequest)
{
if (_mOSimConnect != null)
{
if (oSimvarRequest.bIsString)
{
/// Define a data structure containing string value
_mOSimConnect.AddToDataDefinition(oSimvarRequest.EDef, oSimvarRequest.sName, "",
SIMCONNECT_DATATYPE.STRING256, 0.0f, SimConnect.SIMCONNECT_UNUSED);
/// IMPORTANT: Register it with the simconnect managed wrapper marshaller If you
/// skip this step, you will only receive a uint in the .dwData field.
_mOSimConnect.RegisterDataDefineStruct<Struct1>(oSimvarRequest.EDef);
}
else
{
/// Define a data structure containing numerical value
_mOSimConnect.AddToDataDefinition(oSimvarRequest.EDef, oSimvarRequest.sName, oSimvarRequest.sUnits,
SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
/// IMPORTANT: Register it with the simconnect managed wrapper marshaller If you
/// skip this step, you will only receive a uint in the .dwData field.
_mOSimConnect.RegisterDataDefineStruct<double>(oSimvarRequest.EDef);
}
return true;
}
return false;
}
private void AddRequest(string sNewSimvarRequest, string sNewUnitRequest, bool bIsString)
{
Log.Information(@"AddRequest");
//string sNewSimvarRequest = _sOverrideSimvarRequest != null ? _sOverrideSimvarRequest : ((m_iIndexRequest == 0) ? m_sSimvarRequest : (m_sSimvarRequest + ":" + m_iIndexRequest));
//string sNewUnitRequest = _sOverrideUnitRequest != null ? _sOverrideUnitRequest : m_sUnitRequest;
var oSimvarRequest = new SimvarRequest
{
EDef = (Definition)_mICurrentDefinition,
ERequest = (Request)_mICurrentRequest,
sName = sNewSimvarRequest,
bIsString = bIsString,
sUnits = bIsString ? null : sNewUnitRequest
};
oSimvarRequest.BPending = !RegisterToSimConnect(oSimvarRequest);
oSimvarRequest.bStillPending = oSimvarRequest.BPending;
lSimvarRequests.Add(oSimvarRequest);
++_mICurrentDefinition;
++_mICurrentRequest;
}
#region IBaseSimConnectWrapper implementation
/// User-defined win32 event
public const int WM_USER_SIMCONNECT = 0x0402;
/// Window handle
private IntPtr _mHWnd = new(0);
/// SimConnect object
private SimConnect _mOSimConnect;
public bool bConnected
{
get => _mBConnected;
private set => SetProperty(ref _mBConnected, value);
}
private bool _mBConnected;
private uint _mICurrentDefinition;
private uint _mICurrentRequest;
public int GetUserSimConnectWinEvent()
{
return WM_USER_SIMCONNECT;
}
public void ReceiveSimConnectMessage()
{
_mOSimConnect?.ReceiveMessage();
}
public void SetWindowHandle(IntPtr hWnd)
{
_mHWnd = hWnd;
}
public void Disconnect()
{
_dataTimer.Dispose();
Log.Information(@"Disconnect");
_mOTimer.Stop();
bOddTick = false;
if (_mOSimConnect != null)
{
/// Dispose serves the same purpose as SimConnect_Close()
_mOSimConnect.Dispose();
_mOSimConnect = null;
}
sConnectButtonLabel = "Connect";
bConnected = false;
// Set all requests as pending
foreach (var oSimvarRequest in lSimvarRequests)
{
oSimvarRequest.BPending = true;
oSimvarRequest.bStillPending = true;
}
}
#endregion IBaseSimConnectWrapper implementation
#region UI bindings
public string sConnectButtonLabel
{
get => _mSConnectButtonLabel;
private set => SetProperty(ref _mSConnectButtonLabel, value);
}
private string _mSConnectButtonLabel = "Connect";
public bool bObjectIdSelectionEnabled
{
get => _mBObjectIdSelectionEnabled;
set => SetProperty(ref _mBObjectIdSelectionEnabled, value);
}
private bool _mBObjectIdSelectionEnabled;
private readonly SIMCONNECT_SIMOBJECT_TYPE _mESimObjectType = SIMCONNECT_SIMOBJECT_TYPE.USER;
public ObservableCollection<uint> lObjectIDs { get; }
private uint _mIObjectIdRequest;
private string _mSSimvarRequest;
public string sUnitRequest
{
get => _mSUnitRequest;
set => SetProperty(ref _mSUnitRequest, value);
}
private string _mSUnitRequest;
private string _mSSetValue;
public ObservableCollection<SimvarRequest> lSimvarRequests { get; }
private SimvarRequest _mOSelectedSimvarRequest;
private uint _mIIndexRequest;
private bool _mBSaveValues = true;
//Exclude Traffic Checkboxhandling
//================================
public bool bGaTraffic
{
get => _mbGaTraffic;
set
{
SetProperty(ref _mbGaTraffic, value);
_liveTrafficHandler.ExclGaTraffic = value;
}
}
private bool _mbGaTraffic;
public bool bGlidTraffic
{
get => _mbGlidTraffic;
set
{
SetProperty(ref _mbGlidTraffic, value);
_liveTrafficHandler.ExclGlidTraffic = value;
}
}
private bool _mbGlidTraffic;
public bool bAirlTraffic
{
get => _mbAirlTraffic;
set
{
SetProperty(ref _mbAirlTraffic, value);
_liveTrafficHandler.ExclAirlTraffic = value;
}
}
private bool _mbAirlTraffic;
public bool bGroundTraffic
{
get => _mbGroundTraffic;
set
{
SetProperty(ref _mbGroundTraffic, value);
_liveTrafficHandler.ExclGroundTraffic = value;
}
}
private bool _mbGroundTraffic;
public bool bLowAltTraffic
{
get => _mbLowAltTraffic;
set
{
SetProperty(ref _mbLowAltTraffic, value);
_liveTrafficHandler.ExclLowAltTraffic = value;
}
}
private bool _mbLowAltTraffic;
public bool bMidAltTraffic
{
get => _mbMidAltTraffic;
set
{
SetProperty(ref _mbMidAltTraffic, value);
_liveTrafficHandler.ExclMidAltTraffic = value;
}
}
private bool _mbMidAltTraffic;
public bool bHigAltTraffic
{
get => _mbHigAltTraffic;
set
{
SetProperty(ref _mbHigAltTraffic, value);
_liveTrafficHandler.ExclHigAltTraffic = value;
}
}
private bool _mbHigAltTraffic;
public bool bHigAltTrafficMode
{
get => _mbHigAltTrafficMode;
set
{
SetProperty(ref _mbHigAltTrafficMode, value);
_liveTrafficHandler.HighAltitudeTraffic = value;
}
}
private bool _mbHigAltTrafficMode;
//================================
public bool bIsString
{
get => _mBIsString;
set => SetProperty(ref _mBIsString, value);
}
private bool _mBIsString;
public bool bOddTick
{
get => _mBOddTick;
set => SetProperty(ref _mBOddTick, value);
}
private bool _mBOddTick;
public ObservableCollection<string> lErrorMessages { get; }
public BaseCommand cmdToggleConnect { get; }
public BaseCommand cmdAddRequest { get; }
public BaseCommand cmdRemoveSelectedRequest { get; private set; }
public BaseCommand cmdTrySetValue { get; private set; }
public BaseCommand cmdLoadFiles { get; }
#endregion UI bindings
}
}