This repository has been archived by the owner on Dec 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFsSimConnect.cs
490 lines (420 loc) · 17.3 KB
/
FsSimConnect.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
namespace FSMosquitoClient
{
using Microsoft.Extensions.Logging;
using Microsoft.FlightSimulator.SimConnect;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Runtime.InteropServices;
using System.Timers;
/// <summary>
/// Represents a wrapper around SimConnect
/// </summary>
public sealed class FsSimConnect : IFsSimConnect
{
private const int PulseInterval = 750;
private const int RequestWaitInterval = 1000 * 5;
private static int s_subscriptionCount = 0;
private static int s_currentRequestId = 0;
private readonly ILogger<FsSimConnect> _logger;
private readonly Timer _pulseTimer = new Timer(PulseInterval);
private readonly Timer _reconnectTimer = new Timer(15 * 1000);
private readonly ConcurrentDictionary<string, SimConnectSubscription> _subscriptions = new ConcurrentDictionary<string, SimConnectSubscription>();
private readonly ConcurrentDictionary<int, SimConnectSubscription> _pendingSubscriptions = new ConcurrentDictionary<int, SimConnectSubscription>();
private IntPtr _lastHandle;
private SimConnect _simConnect;
public event EventHandler SimConnectOpened;
public event EventHandler SimConnectClosed;
public event EventHandler<(SimConnectTopic, uint, object)> TopicValueChanged;
public event EventHandler SimConnectDataReceived;
public event EventHandler SimConnectDataRequested;
public FsSimConnect(ILogger<FsSimConnect> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_pulseTimer.Elapsed += OnPulse_Elapsed;
_reconnectTimer.Elapsed += (sender, args) =>
{
if (IsConnected == false)
{
ConnectToSimConnect();
}
};
}
#region Properties
public bool IsConnected
{
get
{
return _simConnect != null;
}
}
public bool IsDisposed
{
get;
private set;
}
public bool IsOpen { get; private set; }
#endregion
public void Connect(IntPtr handle)
{
if (IsDisposed)
{
throw new InvalidOperationException("FsMqtt Is Disposed.");
}
if (IsConnected)
{
throw new InvalidOperationException("FsMqtt is already connected.");
}
_lastHandle = handle;
ConnectToSimConnect();
}
/// <summary>
/// Actually establishes the connection to SimConnect - try/catching the exception the contructor throws if FS isn't running.
/// </summary>
private void ConnectToSimConnect()
{
try
{
_simConnect = new SimConnect("FSMosquito", _lastHandle, Consts.WM_USER_SIMCONNECT, null, 0);
/// Listen to connect and quit msgs
_simConnect.OnRecvOpen += new SimConnect.RecvOpenEventHandler(SimConnect_OnRecvOpen);
_simConnect.OnRecvQuit += new SimConnect.RecvQuitEventHandler(SimConnect_OnRecvQuit);
// Listen to exceptions
_simConnect.OnRecvException += new SimConnect.RecvExceptionEventHandler(SimConnect_OnRecvException);
// Listen to simobject data request
_simConnect.OnRecvSimobjectDataBytype += new SimConnect.RecvSimobjectDataBytypeEventHandler(SimConnect_OnRecvSimObjectDataByType);
_reconnectTimer.Stop();
}
catch(Exception ex)
{
_simConnect = null;
_logger.LogError($"Unable to connect to SimConnect: {ex.Message}", ex);
_reconnectTimer.Start();
}
}
public void Disconnect()
{
if (IsDisposed)
{
throw new InvalidOperationException("FsMqtt Is Disposed.");
}
if (!IsConnected)
{
throw new InvalidOperationException("FsMqtt is not connected.");
}
OnSimConnect_Closed();
}
public void SignalReceiveSimConnectMessage()
{
if (IsDisposed || !IsConnected)
{
return;
}
try
{
lock (_simConnect)
{
_simConnect.ReceiveMessage();
}
}
catch(Exception ex)
{
_logger.LogError($"An error occurred while signaling to recieve a message: {ex.Message}", ex);
OnSimConnect_Closed();
_reconnectTimer.Start();
}
}
public void Set(string datumName, uint? objectId, object value)
{
if (objectId.HasValue == false)
{
objectId = 0;
}
if (!_subscriptions.ContainsKey(datumName))
{
_logger.LogInformation($"Skipping setting value of {datumName} to {value} on object {objectId} as the topic has not been previously registered.");
}
var subscription = _subscriptions[datumName];
var def = (Definition)Enum.ToObject(typeof(Definition), subscription.Id);
_simConnect.SetDataOnSimObject(def, objectId.Value, SIMCONNECT_DATA_SET_FLAG.DEFAULT, value);
// Cause the updated value to be re-transmitted next pulse.
subscription.LastValue = null;
}
public void Subscribe(SimConnectTopic topic)
{
if (_subscriptions.ContainsKey(topic.DatumName))
{
_logger.LogInformation($"Skipping {topic.DatumName} as it has already been registered.");
// This is verging on side-effect, but clear the last value so it will be re-transmitted next pulse.
var subscription = _subscriptions[topic.DatumName];
subscription.LastValue = null;
return;
}
SimConnectSubscription newSubscription;
switch(topic.Units)
{
case Consts.SimConnectStringV:
newSubscription = new SimConnectSubscription()
{
Id = System.Threading.Interlocked.Increment(ref s_subscriptionCount),
Topic = topic,
};
break;
default:
newSubscription = new SimConnectSubscription()
{
Id = System.Threading.Interlocked.Increment(ref s_subscriptionCount),
Topic = topic,
};
break;
}
if (_subscriptions.TryAdd(topic.DatumName, newSubscription) == false)
{
return;
}
_logger.LogInformation($"Registered subscription for {topic.DatumName} with {topic.Units}.");
}
/// <summary>
/// Registers a data definition/struct with SimConnect for the specified subscription.
/// </summary>
/// <param name="subscription"></param>
private void RegisterSubscriptionDataDefinition(SimConnectSubscription subscription)
{
if (subscription.IsRegistered)
{
return;
}
if (IsDisposed || !IsConnected)
{
return;
}
var def = (Definition)Enum.ToObject(typeof(Definition), subscription.Id);
var topic = subscription.Topic;
try
{
switch (topic.Units)
{
case Consts.SimConnectBool:
_simConnect.AddToDataDefinition(def, topic.DatumName, null, SIMCONNECT_DATATYPE.INT32, 0, SimConnect.SIMCONNECT_UNUSED);
_simConnect.RegisterDataDefineStruct<bool>(def);
break;
case Consts.SimConnectStringV:
_simConnect.AddToDataDefinition(def, topic.DatumName, null, SIMCONNECT_DATATYPE.STRINGV, 0, SimConnect.SIMCONNECT_UNUSED);
_simConnect.RegisterDataDefineStruct<StringStruct>(def);
break;
default:
/// Define a data structure
_simConnect.AddToDataDefinition(def, topic.DatumName, topic.Units, 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.
_simConnect.RegisterDataDefineStruct<double>(def);
break;
}
subscription.IsRegistered = true;
_logger.LogInformation($"Registered Data Definition for {topic.DatumName} with {topic.Units}. ({subscription.Id})");
}
catch(Exception ex)
{
_logger.LogError($"An exception occurred attempting to register a data definition {ex.Message}", ex);
}
}
#region Event Handlers
/// <summary>
/// Occurs when a connection is established to SimConnect.
/// </summary>
/// <param name="sender"></param>
/// <param name="data"></param>
private void SimConnect_OnRecvOpen(SimConnect sender, SIMCONNECT_RECV_OPEN data)
{
IsOpen = true;
_logger.LogInformation("SimConnect_OnRecvOpen");
_pulseTimer.Start();
OnSimConnect_Opened();
}
/// <summary>
/// Occurs when the user closes the game.
/// </summary>
/// <param name="sender"></param>
/// <param name="data"></param>
private void SimConnect_OnRecvQuit(SimConnect sender, SIMCONNECT_RECV data)
{
IsOpen = false;
_logger.LogInformation("SimConnect_OnRecvQuit");
OnSimConnect_Closed();
_reconnectTimer.Start();
}
/// <summary>
/// Occurs when an exception is raised by SimConnect.
/// </summary>
/// <param name="sender"></param>
/// <param name="data"></param>
private void SimConnect_OnRecvException(SimConnect sender, SIMCONNECT_RECV_EXCEPTION data)
{
var eException = (SIMCONNECT_EXCEPTION)data.dwException;
_logger.LogInformation("SimConnect_OnRecvException: " + eException.ToString());
OnSimConnect_Closed();
_reconnectTimer.Start();
}
/// <summary>
/// Occurs when SimConnect emits object data for a specific object type.
/// </summary>
/// <param name="sender"></param>
/// <param name="data"></param>
private void SimConnect_OnRecvSimObjectDataByType(SimConnect sender, SIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE data)
{
uint requestId = data.dwRequestID;
uint objectId = data.dwObjectID;
// ObjectID == 0 is the user object data. See SimConnect.SIMCONNECT_OBJECT_ID_USER;
// But it seems to return it as 1... ???
object currentValue;
if (_pendingSubscriptions.TryRemove((int)requestId, out SimConnectSubscription subscription))
{
switch (subscription.Topic.Units)
{
case Consts.SimConnectBool:
currentValue = (bool)data.dwData[0];
break;
case Consts.SimConnectStringV:
currentValue = ((StringStruct)data.dwData[0]).value;
break;
default:
currentValue = (double)data.dwData[0];
break;
}
subscription.PendingRequestId = null;
subscription.PendingRequestStartTimeStamp = null;
if (subscription.LastValue == null || subscription.LastValue.Equals(currentValue) == false)
{
if (subscription.LastValue != currentValue)
{
subscription.LastValue = currentValue;
OnTopicValue_Changed(subscription.Topic, objectId, currentValue);
}
}
}
OnSimConnectDataRecieved();
}
private void OnSimConnect_Opened()
{
if (SimConnectOpened != null)
{
SimConnectOpened.Invoke(this, EventArgs.Empty);
}
}
private void OnSimConnect_Closed()
{
_pulseTimer.Stop();
_simConnect.Dispose();
_simConnect = null;
// Since SimConnect is now closed, mark all subscriptions as not registered, and non-pending
// Also, clear out the last value so that subscribers recieve an updated value on re-acquisition of signal.
foreach(var subscription in _subscriptions.Values)
{
subscription.IsRegistered = false;
subscription.PendingRequestId = null;
subscription.LastValue = null;
}
// Raise the SimClosed event
if (SimConnectClosed != null)
{
SimConnectClosed.Invoke(this, EventArgs.Empty);
}
}
private void OnTopicValue_Changed(SimConnectTopic topic, uint objectId, object value)
{
if (TopicValueChanged != null)
{
TopicValueChanged.Invoke(this, (topic, objectId, value));
}
}
private void OnPulse_Elapsed(object sender, ElapsedEventArgs e)
{
if (_simConnect == null)
{
return;
}
// Reset all subscriptions that have waited beyond the wait timeout.
foreach(var subscription in _subscriptions.Values.Where(s => s.PendingRequestStartTimeStamp.HasValue && s.PendingRequestStartTimeStamp.Value.AddMilliseconds(RequestWaitInterval) < DateTime.Now))
{
subscription.PendingRequestId = null;
subscription.PendingRequestStartTimeStamp = null;
}
// Request data for all subscriptions which currently aren't waiting for data.
foreach(var subscription in _subscriptions.Values.Where(s => s.PendingRequestId.HasValue == false))
{
RegisterSubscriptionDataDefinition(subscription);
var nextRequestId = GetNextRequestId();
if (_pendingSubscriptions.TryAdd(nextRequestId, subscription) == false)
{
continue;
}
subscription.PendingRequestId = nextRequestId;
subscription.PendingRequestStartTimeStamp = DateTime.Now;
var req = (Request)Enum.ToObject(typeof(Request), subscription.PendingRequestId);
var def = (Definition)Enum.ToObject(typeof(Definition), subscription.Id);
_simConnect.RequestDataOnSimObjectType(req, def, 0, SIMCONNECT_SIMOBJECT_TYPE.USER);
OnSimConnectDataRequested();
}
}
private void OnSimConnectDataRecieved()
{
if (SimConnectDataReceived != null)
{
SimConnectDataReceived.Invoke(this, EventArgs.Empty);
}
}
private void OnSimConnectDataRequested()
{
if (SimConnectDataRequested != null)
{
SimConnectDataRequested.Invoke(this, EventArgs.Empty);
}
}
#endregion
#region IDisposable
private void Dispose(bool disposing)
{
if (!IsDisposed)
{
if (disposing)
{
if (null != _simConnect)
{
_pulseTimer.Stop();
_pulseTimer.Dispose();
_reconnectTimer.Stop();
_reconnectTimer.Dispose();
_simConnect.Dispose();
_simConnect = null;
}
}
IsDisposed = true;
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
#endregion
#region Structs
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
struct StringStruct
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
public string value;
};
#endregion
#region Static Methods
/// <summary>
/// Gets the next request id (threadsafe, non-overflowing... although if we get to int.maxvalue, that's a lot of seconds)
/// </summary>
/// <returns></returns>
private static int GetNextRequestId()
{
System.Threading.Interlocked.Increment(ref s_currentRequestId);
return System.Threading.Interlocked.CompareExchange(ref s_currentRequestId, 0, int.MaxValue - 1);
}
#endregion
}
}