protected override Boolean InitialiseInternal() { lock (this) { if (!initialised) { try { if (sdk == null) { sdk = new iRacingSDK(); } sdk.Shutdown(); if (!sdk.IsInitialized) { sdk.Startup(); } if (sdk.IsConnected()) { initialised = true; if (dumpToFile) { dataToDump = new List <iRacingStructDumpWrapper>(); } ; int attempts = 0; const int maxAttempts = 99; object sessionnum = this.TryGetSessionNum(); while (sessionnum == null && attempts <= maxAttempts) { attempts++; sessionnum = this.TryGetSessionNum(); } if (attempts >= maxAttempts) { Console.WriteLine("Session num too many attempts"); } Console.WriteLine("Initialised iRacing shared memory"); } } catch (Exception) { initialised = false; } } return(initialised); } }
// Takes care of detecting a live iRacing session // private void detectSDK() { try { if (sdk.IsConnected() && sdk.VarHeaders.Count > 0) { // Check the availability of data retrieval // before eventualy declaring the sim as connected // to eliminate rare null pointer reference exceptions // int tick = (int)sdk.GetData("SessionTick"); indicateSimConnected(true); // Escape here when really ready // return; } } catch {} indicateSimConnected(false); if (sdk.IsInitialized) { sdk.Shutdown(); } else { sdk.Startup(); } }
/// <summary> /// The thread funktion to poll the telemetry data and send TelemetryUpdated events. /// </summary> private void Run() { int _lastSessionTick = 0; iRacingSDK sdk = new iRacingSDK(); Session session = new Session(); Stopwatch sw = new Stopwatch(); sw.Start(); while (!isStopped) { try { // check if the SDK is connected if (sdk.IsConnected()) { IsConnected = true; // check if car is on track and if we got new data if ((bool)sdk.GetData("IsOnTrack") && _lastSessionTick != (int)sdk.GetData("SessionTick")) { IsRunning = true; _lastSessionTick = (int)sdk.GetData("SessionTick"); sw.Restart(); TelemetryEventArgs args = new TelemetryEventArgs(new iR60TelemetryInfo(sdk, session)); RaiseEvent(OnTelemetryUpdate, args); } else if (sw.ElapsedMilliseconds > 500) { IsRunning = false; } } else { sdk.Startup(); IsRunning = false; } Thread.Sleep(SamplePeriod); } catch (Exception e) { LogError("iR60TelemetryProvider Exception while processing data", e); IsConnected = false; IsRunning = false; Thread.Sleep(1000); } } sdk.Shutdown(); IsConnected = false; IsRunning = false; }
// Takes care of detecting a live iRacing session // private void detectSDK() { if (sdk.IsConnected() && sdk.VarHeaders.Count > 0) { indicateSimConnected(true); } else { indicateSimConnected(false); if (sdk.IsInitialized) { sdk.Shutdown(); } else { sdk.Startup(); } } }
internal bool UpdateData(ref iRacingSDK sdk, Simulation sim) { if (!sdk.IsInitialized) { return(false); } if (!sdk.IsConnected()) { sdk.Shutdown(); return(false); } if (sdk.GetData("SessionNum") == null) { sdk = new iRacingSDK(); return(true); } Update(sdk, sim); return(true); }
private void tmr_Tick(object sender, EventArgs e) { double fanSpeedPercent = Convert.ToDouble(maxFanSpeed.Value); double manualSpeed = Convert.ToDouble(numericUpDownManualSpeed.Value) * 2.55; // remap manual speed percentage to 0-255 if ((fanSpeedPercent < 0) || (fanSpeedPercent > 100)) { fanSpeedPercent = 100; } if ((manualSpeed < 0) || (manualSpeed > 255)) { manualSpeed = 255; } // show progress bar if manual speed adjustment is selected if (checkBoxManualSpeed.Checked) { fanProgressBar.Visible = true; } else { fanProgressBar.Visible = false; } if (Process.GetProcesses().Any(p => p.ProcessName.Contains("iRacingService"))) { lbliracingStatus.BackColor = Color.Yellow; if (Process.GetProcesses().Any(p => p.ProcessName.Contains("iRacingSim"))) { sdk.Startup(); } } else { lblConn.Text = "iRacing NOT running"; lbliracingStatus.BackColor = Color.Red; sdk.Shutdown(); } if (sdk.IsConnected()) { lblConn.Text = "iRacing SDK is connected"; lbliracingStatus.BackColor = Color.LimeGreen; } else if (sdk.IsInitialized) { lblConn.Text = "iRacing SDK is initialized"; lbliracingStatus.BackColor = Color.Yellow; } if (sdk.IsConnected()) { //MPH if (this.radioButtonMph.Checked) { Speed = Convert.ToDouble(sdk.GetData("Speed")) * 2.23693629; carTopSpeedb = Speed; } //KPH else { Speed = Convert.ToDouble(sdk.GetData("Speed")) * 3.6; carTopSpeedb = Speed; } carTopSpeeda = Convert.ToDouble(carTopSpeed.Value); lblSpeed.Text = "Current car speed: " + Math.Round(Speed, 0); if (Speed >= carTopSpeeda) { carTopSpeeda = Speed; //If user has allowed top speed auto update and not defined a constant fan speed if ((chkAutoTopSpeed.Checked) && (!checkBoxManualSpeed.Checked)) { carTopSpeed.Value = Convert.ToDecimal(carTopSpeedb); } } if (checkBoxManualSpeed.Checked) // manual fan speed { Speed = manualSpeed; fanProgressBar.Value = (int)Math.Round(Speed, 0); } else // remap car speed to 0-255 range, and then scale by max fan speed % { if (Convert.ToDouble(sdk.GetData("VelocityX")) < 0) { Speed = 0; // User is going in reverse, stop the fans... } Speed = Speed * (255 / carTopSpeeda) * (fanSpeedPercent / 100); if (Speed > 255) { Speed = 255; //Fan speed cannot exceed 255 (byte limit) } } lblFanSpeed.Text = "Fan Speed (PWM): " + Math.Round(Speed, 0); // update GUI with current fan speed writeSerialPort(Speed, e); // write speed to arduino serial port } else //iRacing not connected { if (checkBoxManualSpeed.Checked) { lblFanSpeed.Text = "Fan speed (PWM): " + Math.Round(manualSpeed, 0); fanProgressBar.Value = (int)Math.Round(manualSpeed, 0); writeSerialPort(manualSpeed, e); } else { writeSerialPort(0, e); lblFanSpeed.Text = "Fan speed (PWM): 0"; } } }
private void Loop(CancellationToken cancellationToken) { int lastUpdate = -1; bool hasConnected = false; while (!cancellationToken.IsCancellationRequested) { // Check if we can find the sim if (sdk.IsConnected()) { if (!IsConnected) { // If this is the first time, raise the Connected event RaiseEvent(OnStarted, EventArgs.Empty); connectionSource.TrySetResult(); } hasConnected = true; IsConnected = true; readMutex.WaitOne(8); // Update telemetry info TelemetryData = new TelemetryData(sdk); // Update session info int newUpdate = sdk.Header.SessionInfoUpdate; if (newUpdate != lastUpdate) { RawSessionData = sdk.GetSessionInfo(); SessionData = deserializer.Deserialize <SessionData>(RawSessionData); var args = new SessionInfoChangedEventArgs(SessionData, (double)sdk.GetData("SessionTime")); RaiseEvent(OnSessionInfoChanged, args); if (lastUpdate == -1) { firstDataSource.TrySetResult(); } lastUpdate = newUpdate; } // Send telemetry event now to make sure both data is updated when either event is thrown var telArgs = new TelemetryInfoChangedEventArgs(TelemetryData, (double)sdk.GetData("SessionTime")); RaiseEvent(OnTelemetryInfoChanged, telArgs); } else if (hasConnected) { // We have already been initialized before, so the sim is closing RaiseEvent(OnStopped, EventArgs.Empty); SessionData = null; TelemetryData = null; sdk.Shutdown(); lastUpdate = -1; IsConnected = false; hasConnected = false; } else { // Have not been initialized before and there is no connection. Try to find the sim. IsConnected = false; hasConnected = false; sdk.Startup(); } // Sleep for a short amount of time until the next update is available if (IsConnected) { if (waitTime <= 0 || waitTime > 1000) { waitTime = 15; } Thread.Sleep(waitTime); } else { // Not connected yet, no need to check every 16 ms, let's try again in some time Thread.Sleep(ConnectSleepTime); } } sdk.Shutdown(); IsConnected = false; }
static void Main(string[] args) { if (args.Length < 1) { return; } Bookmarks myBookmarks = new Bookmarks();; Bookmark thisEvent = null; int currentIndex = 0; int CurrentFrame = 0; bool run = true; using (StreamReader sw = new StreamReader(args[0], Encoding.UTF8)) { System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(myBookmarks.GetType()); myBookmarks = x.Deserialize(sw) as Bookmarks; } Console.WriteLine("Waiting for iRacing to come up ...."); sdk = new iRacingSDK(); while (!Console.KeyAvailable && run) { //Check if the SDK is connected if (sdk.IsConnected()) { while (sdk.GetData("SessionNum") == null) { Console.WriteLine("Waiting for Session..."); Thread.Sleep(200); // Allow other windows to initialize more faster } thisEvent = myBookmarks.List[currentIndex]; switch (thisEvent.BookmarkType) { case BookmarkType.Start: ReplaySeek(thisEvent); currentIndex++; break; case BookmarkType.Play: CurrentFrame = (Int32)sdk.GetData("ReplayFrameNum"); if (CurrentFrame < thisEvent.ReplayPos) { continue; } sdk.BroadcastMessage(iRSDKSharp.BroadcastMessageTypes.CamSwitchNum, thisEvent.DriverIdx, thisEvent.CamIdx); SetPlaySpeed(thisEvent.PlaySpeed); currentIndex++; break; case BookmarkType.Stop: CurrentFrame = (Int32)sdk.GetData("ReplayFrameNum"); if (CurrentFrame < thisEvent.ReplayPos) { continue; } sdk.BroadcastMessage(iRSDKSharp.BroadcastMessageTypes.ReplaySetPlaySpeed, 0, 0); Console.WriteLine("End"); run = false; break; default: run = false; break; } } else { if (sdk.Startup()) { Console.WriteLine("iRacing up and running."); } else { Thread.Sleep(2000); } } } sdk.Shutdown(); }
private void tmr_Tick(object sender, EventArgs e) { if (chkDebug.Checked == true) { lblConn.Text = "Debug mode active!"; lblColor.BackColor = Color.FromArgb(255, 129, 0); Gear = trkGear.Value; Speed = randnum.Next(0, 255); RPM = randnum.Next(4253, 17954); Fuel = trkFuel.Value; Shift = trkShift.Value; if (chkPit.Checked == true) { Engine = 0x10; } else { Engine = 0x00; } iRPM = Convert.ToInt16(RPM); iFuel = Convert.ToByte(Math.Round(Fuel)); iShift = Convert.ToByte(Math.Round((Shift * 16) / 100)); Console.Out.WriteLine("iRPM: " + iRPM); int c = (iRPM >> 8) & 0x00FF; serialdata[0] = 255; serialdata[1] = Convert.ToByte(Gear + 1); serialdata[2] = Convert.ToByte(Speed); serialdata[3] = Convert.ToByte((iRPM >> 8) & 0x00FF); serialdata[4] = Convert.ToByte(iRPM & 0x00FF); serialdata[5] = Convert.ToByte(iFuel); serialdata[6] = Convert.ToByte(iShift); serialdata[7] = Engine; SP.Write(serialdata, 0, 8); } else { if (sdk.IsConnected()) { lblConn.Text = "Connected to iRacing API"; lblColor.BackColor = Color.FromArgb(0, 200, 0); Gear = Convert.ToInt32(sdk.GetData("Gear")); Speed = Convert.ToDouble(sdk.GetData("Speed")) * 2.23693629; RPM = Convert.ToDouble(sdk.GetData("RPM")); Fuel = Convert.ToDouble(sdk.GetData("FuelLevelPct")); Shift = Convert.ToDouble(sdk.GetData("ShiftIndicatorPct")); Engine = Convert.ToByte(sdk.GetData("EngineWarnings")); this.Text = Shift.ToString(); iRPM = Convert.ToInt16(RPM); iFuel = Convert.ToByte(Math.Round(Fuel * 100)); iShift = Convert.ToByte(Math.Round((Shift * 100 * 16) / 100)); serialdata[0] = 255; serialdata[1] = Convert.ToByte(Gear + 1); serialdata[2] = Convert.ToByte(Speed); serialdata[3] = Convert.ToByte((iRPM >> 8) & 0x00FF); serialdata[4] = Convert.ToByte(iRPM & 0x00FF); serialdata[5] = Convert.ToByte(iFuel); serialdata[6] = Convert.ToByte(iShift); serialdata[7] = Engine; SP.Write(serialdata, 0, 8); } else if (sdk.IsInitialized) { lblConn.Text = "No connection with iRacing API"; lblColor.BackColor = Color.FromArgb(200, 0, 0); sdk.Shutdown(); } else { lblConn.Text = "No connection with iRacing API"; lblColor.BackColor = Color.FromArgb(200, 0, 0); sdk.Startup(); } } }
private static string callbackCamera = "TV1"; // camera group to switch to when the client requests it static void Main(string[] args) { sdk = new iRacingSDK(); int lastUpdate = -1; //setup WebSocketServer var allSockets = new List <IWebSocketConnection>(); var server = new WebSocketServer("ws://localhost:8181"); server.Start(socket => { socket.OnOpen = () => { Console.WriteLine("Client Connected"); allSockets.Add(socket); }; socket.OnClose = () => { Console.WriteLine("Client Disconnected"); allSockets.Remove(socket); }; socket.OnMessage = message => { Console.WriteLine("Received -> " + message); int groupNum = cameras[callbackCamera]; sdk.BroadcastMessage(BroadcastMessageTypes.CamSwitchNum, Convert.ToInt32(message), groupNum, 0); }; }); while (true) { if (sdk.IsConnected()) { //If it is connected then see if the Session Info has been updated int newUpdate = sdk.Header.SessionInfoUpdate; if (telemData.getTrackId() == 0) { telemData.setTrackId(Convert.ToInt32(YamlParser.Parse(sdk.GetSessionInfo(), "WeekendInfo:TrackID:"))); DiscoverCameras(); } if (newUpdate != lastUpdate) { // Session Info updated (e.g. perhaps a client has connected/disconnected) lastUpdate = newUpdate; // Update the current Driver list string yaml = sdk.GetSessionInfo(); length = yaml.Length; start = yaml.IndexOf("DriverInfo:\n", 0, length); end = yaml.IndexOf("\n\n", start, length - start); string DriverInfo = yaml.Substring(start, end - start); ParseDrivers(DriverInfo); } UpdateDriverPositions(drivers); foreach (var socket in allSockets.ToList()) { Console.WriteLine("Broadcast sent..."); Console.WriteLine(telemData.toJson()); socket.Send(telemData.toJson()); } } else if (sdk.IsInitialized) { drivers.Clear(); cameras.Clear(); telemData.setTrackId(0); sdk.Shutdown(); lastUpdate = -1; } else { drivers.Clear(); cameras.Clear(); telemData.setTrackId(0); Console.WriteLine("NOT CONNECTED!"); sdk.Startup(); } System.Threading.Thread.Sleep(1000); } }