-
Notifications
You must be signed in to change notification settings - Fork 3
/
IRacingSdk.cs
538 lines (411 loc) · 13.6 KB
/
IRacingSdk.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
using System;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
namespace IRSDKSharper
{
public class IRacingSdk
{
private const string SimulatorMemoryMappedFileName = "Local\\IRSDKMemMapFileName";
private const string SimulatorDataValidEventName = "Local\\IRSDKDataValidEvent";
private const string SimulatorBroadcastMessageName = "IRSDK_BROADCASTMSG";
public readonly IRacingSdkData Data;
public bool IsStarted { get; private set; } = false;
public bool IsConnected { get; private set; } = false;
public int UpdateInterval { get; set; } = 1;
public EventSystem EventSystem { get; private set; }
public event Action<Exception> OnException = null;
public event Action OnConnected = null;
public event Action OnDisconnected = null;
public event Action OnSessionInfo = null;
public event Action OnTelemetryData = null;
public event Action OnEventSystemDataReset = null;
public event Action OnEventSystemDataLoaded = null;
public event Action OnStopped = null;
public event Action<string> OnDebugLog = null;
private int keepThreadsAlive = 0;
private bool connectionLoopRunning = false;
private bool telemetryDataLoopRunning = false;
private bool sessionInfoLoopRunning = false;
private MemoryMappedFile simulatorMemoryMappedFile = null;
private MemoryMappedViewAccessor simulatorMemoryMappedFileViewAccessor = null;
private AutoResetEvent simulatorAutoResetEvent = null;
private AutoResetEvent sessionInfoAutoResetEvent = null;
private int lastTelemetryDataUpdate = -1;
private int lastSessionInfoUpdate = 0;
private int sessionInfoUpdateReady = 0;
private readonly uint simulatorBroadcastWindowMessage = WinApi.RegisterWindowMessage( SimulatorBroadcastMessageName );
/// <summary>
/// <para>Welcome to IRSDKSharper!</para>
/// This is the basic process to start it up:
/// <code>
/// var irsdk = new IRacingSDK();
///
/// irsdk.OnException += OnException;
/// irsdk.OnConnected += OnConnected;
/// irsdk.OnDisconnected += OnDisconnected;
/// irsdk.OnSessionInfo += OnSessionInfo;
/// irsdk.OnTelemetryData += OnTelemetryData;
/// irsdk.OnStopped += OnStopped;
///
/// irsdk.Start();
/// </code>
/// </summary>
/// <param name="throwYamlExceptions">Set this to true to throw exceptions when our IRacingSdkSessionInfo class is missing properties that exist in the YAML data string.</param>
public IRacingSdk( bool throwYamlExceptions = false )
{
Data = new IRacingSdkData( throwYamlExceptions );
EventSystem = new EventSystem( this );
}
public void Start()
{
if ( Interlocked.Exchange( ref keepThreadsAlive, 1 ) == 1 )
{
Log( "IRSDKSharper has already been started or is starting." );
}
else
{
Log( "IRSDKSharper is starting." );
Task.Run( ConnectionLoop );
IsStarted = true;
Log( "IRSDKSharper has been started." );
}
}
public void Stop()
{
if ( Interlocked.Exchange( ref keepThreadsAlive, 0 ) == 0 )
{
Log( "IRSDKSharper has already been stopped or is stopping." );
}
else
{
Log( "IRSDKSharper is stopping." );
Task.Run( () =>
{
if ( sessionInfoLoopRunning )
{
Log( "Waiting for session info loop to stop." );
sessionInfoAutoResetEvent?.Set();
while ( sessionInfoLoopRunning )
{
Thread.Sleep( 0 );
}
}
if ( telemetryDataLoopRunning )
{
Log( "Waiting for telemetry data loop to stop." );
while ( telemetryDataLoopRunning )
{
Thread.Sleep( 0 );
}
}
Data.Reset();
if ( connectionLoopRunning )
{
Log( "Waiting for connection loop to stop." );
while ( connectionLoopRunning )
{
Thread.Sleep( 0 );
}
}
IsStarted = false;
IsConnected = false;
simulatorMemoryMappedFile = null;
simulatorMemoryMappedFileViewAccessor = null;
simulatorAutoResetEvent = null;
sessionInfoAutoResetEvent = null;
lastTelemetryDataUpdate = -1;
lastSessionInfoUpdate = 0;
sessionInfoUpdateReady = 0;
EventSystem.Reset();
Log( "IRSDKSharper has been stopped." );
OnStopped?.Invoke();
} );
}
}
/// <summary>
/// This event system feature is currently experimental.
/// </summary>
public void EnableEventSystem( string directory )
{
EventSystem.SetDirectory( directory ?? string.Empty );
}
public void FireOnEventSystemDataReset()
{
OnEventSystemDataReset?.Invoke();
}
public void FireOnEventSystemDataLoaded()
{
OnEventSystemDataLoaded?.Invoke();
}
#region simulator remote control
public void CamSwitchPos( IRacingSdkEnum.CamSwitchMode camSwitchMode, int carPosition, int group, int camera )
{
if ( camSwitchMode != IRacingSdkEnum.CamSwitchMode.FocusAtDriver )
{
carPosition = (int) camSwitchMode;
}
BroadcastMessage( IRacingSdkEnum.BroadcastMsg.CamSwitchPos, (short) carPosition, (short) group, (short) camera );
}
public void CamSwitchNum( IRacingSdkEnum.CamSwitchMode camSwitchMode, int carNumberRaw, int group, int camera )
{
if ( camSwitchMode != IRacingSdkEnum.CamSwitchMode.FocusAtDriver )
{
carNumberRaw = (int) camSwitchMode;
}
BroadcastMessage( IRacingSdkEnum.BroadcastMsg.CamSwitchNum, (short) carNumberRaw, (short) group, (short) camera );
}
public void CamSetState( IRacingSdkEnum.CameraState cameraState )
{
BroadcastMessage( IRacingSdkEnum.BroadcastMsg.CamSetState, (short) cameraState );
}
public void ReplaySetPlaySpeed( int speed, bool slowMotion )
{
BroadcastMessage( IRacingSdkEnum.BroadcastMsg.ReplaySetPlaySpeed, (short) speed, slowMotion ? 1 : 0 );
}
public void ReplaySetPlayPosition( IRacingSdkEnum.RpyPosMode rpyPosMode, int frameNumber )
{
BroadcastMessage( IRacingSdkEnum.BroadcastMsg.ReplaySetPlayPosition, (short) rpyPosMode, frameNumber );
}
public void ReplaySearch( IRacingSdkEnum.RpySrchMode rpySrchMode )
{
BroadcastMessage( IRacingSdkEnum.BroadcastMsg.ReplaySearch, (short) rpySrchMode );
}
public void ReplaySetState( IRacingSdkEnum.RpyStateMode rpyStateMode )
{
BroadcastMessage( IRacingSdkEnum.BroadcastMsg.ReplaySetState, (short) rpyStateMode );
}
public void ReloadTextures( IRacingSdkEnum.ReloadTexturesMode reloadTexturesMode, int carIdx )
{
BroadcastMessage( IRacingSdkEnum.BroadcastMsg.ReloadTextures, (short) reloadTexturesMode, carIdx );
}
public void ChatComand( IRacingSdkEnum.ChatCommandMode chatCommandMode, int subCommand )
{
BroadcastMessage( IRacingSdkEnum.BroadcastMsg.ChatComand, (short) chatCommandMode, subCommand );
}
public void PitCommand( IRacingSdkEnum.PitCommandMode pitCommandMode, int parameter )
{
BroadcastMessage( IRacingSdkEnum.BroadcastMsg.PitCommand, (short) pitCommandMode, parameter );
}
public void TelemCommand( IRacingSdkEnum.TelemCommandMode telemCommandMode )
{
BroadcastMessage( IRacingSdkEnum.BroadcastMsg.TelemCommand, (short) telemCommandMode );
}
public void FFBCommand( IRacingSdkEnum.FFBCommandMode ffbCommandMode, float value )
{
BroadcastMessage( IRacingSdkEnum.BroadcastMsg.FFBCommand, (short) ffbCommandMode, value );
}
public void ReplaySearchSessionTime( int sessionNum, int sessionTimeMS )
{
BroadcastMessage( IRacingSdkEnum.BroadcastMsg.ReplaySearchSessionTime, (short) sessionNum, sessionTimeMS );
}
public void VideoCapture( IRacingSdkEnum.VideoCaptureMode videoCaptureMode )
{
BroadcastMessage( IRacingSdkEnum.BroadcastMsg.VideoCapture, (short) videoCaptureMode );
}
#endregion
#region broadcast message functions
private void BroadcastMessage( IRacingSdkEnum.BroadcastMsg msg, short var1, int var2 = 0 )
{
if ( !WinApi.PostMessage( (IntPtr) 0xFFFF, simulatorBroadcastWindowMessage, WinApi.MakeLong( (short) msg, var1 ), (IntPtr) var2 ) )
{
var errorCode = Marshal.GetLastWin32Error();
Marshal.ThrowExceptionForHR( errorCode, IntPtr.Zero );
}
}
private void BroadcastMessage( IRacingSdkEnum.BroadcastMsg msg, short var1, float var2 )
{
if ( !WinApi.PostMessage( (IntPtr) 0xFFFF, simulatorBroadcastWindowMessage, WinApi.MakeLong( (short) msg, var1 ), (IntPtr) ( var2 * 65536.0f ) ) )
{
var errorCode = Marshal.GetLastWin32Error();
Marshal.ThrowExceptionForHR( errorCode, IntPtr.Zero );
}
}
private void BroadcastMessage( IRacingSdkEnum.BroadcastMsg msg, short var1, short var2, short var3 )
{
if ( !WinApi.PostMessage( (IntPtr) 0xFFFF, simulatorBroadcastWindowMessage, WinApi.MakeLong( (short) msg, var1 ), WinApi.MakeLong( var2, var3 ) ) )
{
var errorCode = Marshal.GetLastWin32Error();
Marshal.ThrowExceptionForHR( errorCode, IntPtr.Zero );
}
}
#endregion
#region background tasks
private void ConnectionLoop()
{
Log( "Connection loop has been started." );
try
{
connectionLoopRunning = true;
while ( keepThreadsAlive == 1 )
{
if ( simulatorMemoryMappedFile == null )
{
try
{
simulatorMemoryMappedFile = MemoryMappedFile.OpenExisting( SimulatorMemoryMappedFileName );
}
catch ( FileNotFoundException )
{
}
}
if ( simulatorMemoryMappedFile != null )
{
Log( "simulatorMemoryMappedFile != null" );
if ( simulatorMemoryMappedFileViewAccessor == null )
{
simulatorMemoryMappedFileViewAccessor = simulatorMemoryMappedFile.CreateViewAccessor();
if ( simulatorMemoryMappedFileViewAccessor == null )
{
throw new Exception( "Failed to create memory mapped view accessor." );
}
else
{
Data.SetMemoryMappedViewAccessor( simulatorMemoryMappedFileViewAccessor );
}
}
}
if ( simulatorMemoryMappedFileViewAccessor != null )
{
Log( "simulatorMemoryMappedFileViewAccessor != null" );
var simulatorDataValidEventHandle = WinApi.OpenEvent( WinApi.EVENT_ALL_ACCESS, false, SimulatorDataValidEventName );
if ( simulatorDataValidEventHandle == (IntPtr) null )
{
var errorCode = Marshal.GetLastWin32Error();
if ( errorCode != WinApi.ERROR_FILE_NOT_FOUND )
{
Marshal.ThrowExceptionForHR( errorCode, IntPtr.Zero );
}
}
else
{
Log( "hSimulatorDataValidEvent != null" );
simulatorAutoResetEvent = new AutoResetEvent( false )
{
SafeWaitHandle = new SafeWaitHandle( simulatorDataValidEventHandle, true )
};
sessionInfoAutoResetEvent = new AutoResetEvent( false );
Task.Run( SessionInfoLoop );
Task.Run( TelemetryDataLoop );
break;
}
}
Thread.Sleep( 2000 );
}
connectionLoopRunning = false;
}
catch ( Exception exception )
{
Log( "Exception caught inside the connection loop." );
connectionLoopRunning = false;
OnException?.Invoke( exception );
}
Log( "Connection loop has been stopped." );
}
private void SessionInfoLoop()
{
Log( "Session info loop has been started." );
try
{
sessionInfoLoopRunning = true;
while ( keepThreadsAlive == 1 )
{
// Debug.Log( "Waiting for session info event." );
sessionInfoAutoResetEvent?.WaitOne();
if ( ( keepThreadsAlive == 1 ) && IsConnected )
{
// Debug.Log( "Updating session info." );
if ( Data.UpdateSessionInfo() )
{
sessionInfoUpdateReady = 1;
}
}
}
sessionInfoLoopRunning = false;
}
catch ( Exception exception )
{
Log( "Exception caught inside the session info loop." );
sessionInfoLoopRunning = false;
OnException?.Invoke( exception );
}
Log( "Session info loop has been stopped." );
}
private void TelemetryDataLoop()
{
Log( "Telemetry data loop has been started." );
try
{
telemetryDataLoopRunning = true;
while ( keepThreadsAlive == 1 )
{
var signalReceived = simulatorAutoResetEvent?.WaitOne( 250 ) ?? false;
if ( signalReceived )
{
if ( !IsConnected )
{
Log( "The iRacing simulator is running." );
IsConnected = true;
lastTelemetryDataUpdate = -1;
lastSessionInfoUpdate = 0;
sessionInfoUpdateReady = 0;
OnConnected?.Invoke();
}
Data.Update();
if ( ( lastSessionInfoUpdate != Data.SessionInfoUpdate ) || ( Data.TickCount >= Data.retryUpdateSessionInfoAfterTickCount ) )
{
// Debug.Log( "Data.SessionInfoUpdate has changed." );
lastSessionInfoUpdate = Data.SessionInfoUpdate;
Data.retryUpdateSessionInfoAfterTickCount = int.MaxValue;
sessionInfoAutoResetEvent?.Set();
}
EventSystem.Update( Data );
if ( Interlocked.Exchange( ref sessionInfoUpdateReady, 0 ) == 1 )
{
// Debug.Log( "Invoking OnSessionInfo." );
OnSessionInfo?.Invoke();
}
if ( ( Data.TickCount - lastTelemetryDataUpdate ) >= UpdateInterval )
{
lastTelemetryDataUpdate = Data.TickCount;
OnTelemetryData?.Invoke();
}
}
else
{
if ( IsConnected )
{
Log( "The iRacing simulator is no longer running." );
IsConnected = false;
Log( "Invoking OnDisconnected." );
OnDisconnected?.Invoke();
Data.Reset();
EventSystem.Reset();
}
}
}
telemetryDataLoopRunning = false;
}
catch ( Exception exception )
{
Log( "Exception caught inside the telemetry data loop." );
telemetryDataLoopRunning = false;
OnException?.Invoke( exception );
}
Log( "Telemetry data loop has been stopped." );
}
#endregion
#region Debug logging
[Conditional( "DEBUG" )]
public void Log( string message )
{
OnDebugLog?.Invoke( message );
}
#endregion
}
}