/// <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; }
public object GetData(string headerName) { if (!sdk.IsConnected()) { return(null); } return(sdk.GetData(headerName)); }
public Boolean Connect() { sdk.Startup(); if (sdk.VarHeaders != null && sdk.VarHeaders.Count > 0 && (Double)sdk.GetData("SessionTime") > 0) { return(true); } else { return(false); } }
private static void UpdateDriverPositions(Dictionary <int, Driver> drivers) { float[] distPcts = (float[])sdk.GetData("CarIdxLapDistPct"); bool[] onPitRoad = (bool[])sdk.GetData("CarIdxOnPitRoad"); if (distPcts != null) { foreach (int carIdx in drivers.Keys) { Driver driver = drivers[carIdx]; driver.LapPct = distPcts[driver.Index]; driver.OnPitRoad = onPitRoad[driver.Index]; } } }
// 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(); } }
private static void ReplaySeek(Bookmark ev) { Int32 rewindFrames = (Int32)sdk.GetData("ReplayFrameNum") - (int)ev.ReplayPos - (ev.Rewind * 60); sdk.BroadcastMessage(iRSDKSharp.BroadcastMessageTypes.ReplaySetPlaySpeed, 0, 0); sdk.BroadcastMessage(iRSDKSharp.BroadcastMessageTypes.CamSwitchNum, ev.DriverIdx, ev.CamIdx); sdk.BroadcastMessage(iRSDKSharp.BroadcastMessageTypes.ReplaySetPlayPosition, (int)iRSDKSharp.ReplayPositionModeTypes.Begin, (int)(ev.ReplayPos - (ev.Rewind * 60))); Int32 curpos = (Int32)sdk.GetData("ReplayFrameNum"); DateTime timeout = DateTime.Now; // wait rewind to finish, but only 15 secs while (curpos != (int)(ev.ReplayPos - (ev.Rewind * 60)) && (DateTime.Now - timeout).TotalSeconds < 15) { Thread.Sleep(16); curpos = (Int32)sdk.GetData("ReplayFrameNum"); } SetPlaySpeed(ev.PlaySpeed); }
public TelemetryValue TelemetryValueByName(string name) { object data; TelemetryValue tv; switch (name) { case "SlipAngle": data = SlipAngle; break; case "Rumble": data = Rumble; break; case "RumbleHz": data = RumbleHz; break; default: if (_sdk.VarHeaders.ContainsKey(name)) { data = _sdk.GetData(name); } else { throw new UnknownTelemetryValueException(name); } break; } tv = new iR60TelemetryValue(name, data); object value = tv.Value; if (value == null) { throw new UnknownTelemetryValueException(name); } return(tv); }
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); }
public TelemetryValue TelemetryValueByName(string name) { object data; TelemetryValue tv; switch (name) { case "SlipAngle": data = SlipAngle; break; case "Rumble": data = Rumble; break; case "RumbleHz": data = RumbleHz; break; case "VertAccel": data = VertAccel; break; case "LongAccel": data = LongAccel; break; case "LatAccel": data = LatAccel; break; case "Pitch": data = RadianToDegree("Pitch") * -1; // invert Pitch break; case "Roll": data = RadianToDegree("Roll"); break; case "Yaw": data = RadianToDegree("Yaw"); break; case "PitchRate": data = RadianToDegree("PitchRate"); break; case "RollRate": data = RadianToDegree("RollRate"); break; case "YawRate": data = RadianToDegree("YawRate"); break; default: if (_sdk.VarHeaders.ContainsKey(name)) { data = _sdk.GetData(name); } else { throw new UnknownTelemetryValueException(name); } break; } tv = new iR60TelemetryValue(name, data); object value = tv.Value; if (value == null) { throw new UnknownTelemetryValueException(name); } return(tv); }
public iRacingData(iRacingSDK sdk, bool hasNewSessionData, bool isNewSession) { if (hasNewSessionData) { SessionInfo = new SessionInfo(sdk.GetSessionInfoString()).Yaml; } else { SessionInfo = ""; } SessionInfoUpdate = sdk.Header.SessionInfoUpdate; IsNewSession = isNewSession; SessionTime = (System.Double)sdk.GetData("SessionTime"); SessionTick = (System.Int32)sdk.GetData("SessionTick"); SessionNum = (System.Int32)sdk.GetData("SessionNum"); SessionState = (SessionStates)sdk.GetData("SessionState"); SessionFlags = (int)sdk.GetData("SessionFlags"); SessionTimeRemain = (System.Double)sdk.GetData("SessionTimeRemain"); SessionLapsRemain = (System.Int32)sdk.GetData("SessionLapsRemain"); SessionLapsRemainEx = (System.Int32)sdk.GetData("SessionLapsRemainEx"); DisplayUnits = (DisplayUnits)sdk.GetData("DisplayUnits"); DriverMarker = (System.Boolean)sdk.GetData("DriverMarker"); PushToPass = (System.Boolean)sdk.GetData("PushToPass"); IsOnTrack = (System.Boolean)sdk.GetData("IsOnTrack"); PlayerCarPosition = (System.Int32)sdk.GetData("PlayerCarPosition"); PlayerCarClassPosition = (System.Int32)sdk.GetData("PlayerCarClassPosition"); PlayerTrackSurface = (TrackSurfaces)sdk.GetData("PlayerTrackSurface"); PlayerTrackSurfaceMaterial = (TrackSurfaceMaterial)sdk.GetData("PlayerTrackSurfaceMaterial"); PlayerCarIdx = (System.Int32)sdk.GetData("PlayerCarIdx"); PlayerCarTeamIncidentCount = (System.Int32)sdk.GetData("PlayerCarTeamIncidentCount"); PlayerCarMyIncidentCount = (System.Int32)sdk.GetData("PlayerCarMyIncidentCount"); PlayerCarDriverIncidentCount = (System.Int32)sdk.GetData("PlayerCarDriverIncidentCount"); CarIdxLap = (System.Int32[])sdk.GetData("CarIdxLap"); CarIdxLapCompleted = (System.Int32[])sdk.GetData("CarIdxLapCompleted"); CarIdxLapDistPct = (System.Single[])sdk.GetData("CarIdxLapDistPct"); CarIdxTrackSurface = (TrackSurfaces[])sdk.GetData("CarIdxTrackSurface"); CarIdxTrackSurfaceMaterial = (TrackSurfaceMaterial[])sdk.GetData("CarIdxTrackSurfaceMaterial"); CarIdxOnPitRoad = (System.Boolean[])sdk.GetData("CarIdxOnPitRoad"); CarIdxPosition = (System.Int32[])sdk.GetData("CarIdxPosition"); CarIdxClassPosition = (System.Int32[])sdk.GetData("CarIdxClassPosition"); CarIdxF2Time = (System.Single[])sdk.GetData("CarIdxF2Time"); CarIdxEstTime = (System.Single[])sdk.GetData("CarIdxEstTime"); OnPitRoad = (System.Boolean)sdk.GetData("OnPitRoad"); CarIdxRPM = (System.Single[])sdk.GetData("CarIdxRPM"); CarIdxGear = (System.Int32[])sdk.GetData("CarIdxGear"); Throttle = (System.Single)sdk.GetData("Throttle"); Brake = (System.Single)sdk.GetData("Brake"); Clutch = (System.Single)sdk.GetData("Clutch"); Gear = (System.Int32)sdk.GetData("Gear"); RPM = (System.Single)sdk.GetData("RPM"); Lap = (System.Int32)sdk.GetData("Lap"); LapCompleted = (System.Int32)sdk.GetData("LapCompleted"); LapDist = (System.Single)sdk.GetData("LapDist"); LapDistPct = (System.Single)sdk.GetData("LapDistPct"); RaceLaps = (System.Int32)sdk.GetData("RaceLaps"); LapBestLap = (System.Int32)sdk.GetData("LapBestLap"); LapBestLapTime = (System.Single)sdk.GetData("LapBestLapTime"); LapLastLapTime = (System.Single)sdk.GetData("LapLastLapTime"); LapCurrentLapTime = (System.Single)sdk.GetData("LapCurrentLapTime"); TrackTemp = (System.Single)sdk.GetData("TrackTemp"); TrackTempCrew = (System.Single)sdk.GetData("TrackTempCrew"); AirTemp = (System.Single)sdk.GetData("AirTemp"); WeatherType = (WeatherType)sdk.GetData("WeatherType"); Skies = (Skies)sdk.GetData("Skies"); AirDensity = (System.Single)sdk.GetData("AirDensity"); AirPressure = (System.Single)sdk.GetData("AirPressure"); WindVel = (System.Single)sdk.GetData("WindVel"); WindDir = (System.Single)sdk.GetData("WindDir"); RelativeHumidity = (System.Single)sdk.GetData("RelativeHumidity"); CarLeftRight = (System.Int32)sdk.GetData("CarLeftRight"); PitRepairLeft = (System.Single)sdk.GetData("PitRepairLeft"); PitOptRepairLeft = (System.Single)sdk.GetData("PitOptRepairLeft"); IsOnTrackCar = (System.Boolean)sdk.GetData("IsOnTrackCar"); IsInGarage = (System.Boolean)sdk.GetData("IsInGarage"); EngineWarnings = (EngineWarnings)(int)sdk.GetData("EngineWarnings"); FuelLevel = (System.Single)sdk.GetData("FuelLevel"); FuelLevelPct = (System.Single)sdk.GetData("FuelLevelPct"); WaterTemp = (System.Single)sdk.GetData("WaterTemp"); WaterLevel = (System.Single)sdk.GetData("WaterLevel"); FuelPress = (System.Single)sdk.GetData("FuelPress"); FuelUsePerHour = (System.Single)sdk.GetData("FuelUsePerHour"); OilTemp = (System.Single)sdk.GetData("OilTemp"); OilPress = (System.Single)sdk.GetData("OilPress"); OilLevel = (System.Single)sdk.GetData("OilLevel"); Speed = (System.Single)sdk.GetData("Speed"); IsReplayPlaying = (System.Boolean)sdk.GetData("IsReplayPlaying"); RRcoldPressure = (System.Single)sdk.GetData("RRcoldPressure"); RRtempCL = (System.Single)sdk.GetData("RRtempCL"); RRtempCM = (System.Single)sdk.GetData("RRtempCM"); RRtempCR = (System.Single)sdk.GetData("RRtempCR"); RRwearL = (System.Single)sdk.GetData("RRwearL"); RRwearM = (System.Single)sdk.GetData("RRwearM"); RRwearR = (System.Single)sdk.GetData("RRwearR"); LRcoldPressure = (System.Single)sdk.GetData("LRcoldPressure"); LRtempCL = (System.Single)sdk.GetData("LRtempCL"); LRtempCM = (System.Single)sdk.GetData("LRtempCM"); LRtempCR = (System.Single)sdk.GetData("LRtempCR"); LRwearL = (System.Single)sdk.GetData("LRwearL"); LRwearM = (System.Single)sdk.GetData("LRwearM"); LRwearR = (System.Single)sdk.GetData("LRwearR"); RFcoldPressure = (System.Single)sdk.GetData("RFcoldPressure"); RFtempCL = (System.Single)sdk.GetData("RFtempCL"); RFtempCM = (System.Single)sdk.GetData("RFtempCM"); RFtempCR = (System.Single)sdk.GetData("RFtempCR"); RFwearL = (System.Single)sdk.GetData("RFwearL"); RFwearM = (System.Single)sdk.GetData("RFwearM"); RFwearR = (System.Single)sdk.GetData("RFwearR"); LFcoldPressure = (System.Single)sdk.GetData("LFcoldPressure"); LFtempCL = (System.Single)sdk.GetData("LFtempCL"); LFtempCM = (System.Single)sdk.GetData("LFtempCM"); LFtempCR = (System.Single)sdk.GetData("LFtempCR"); LFwearL = (System.Single)sdk.GetData("LFwearL"); LFwearM = (System.Single)sdk.GetData("LFwearM"); LFwearR = (System.Single)sdk.GetData("LFwearR"); Pitch = (System.Single)sdk.GetData("Pitch"); Yaw = (System.Single)sdk.GetData("Yaw"); Roll = (System.Single)sdk.GetData("Roll"); Voltage = (System.Single)sdk.GetData("Voltage"); }
public void fetch(TelemetryInfo telem, iRacingSDK sdk, double fuelVal, int brake, Boolean sendTimeReset, Boolean sendTime, double prevFuel) { Gear = telem.Gear.Value; Speed = telem.Speed.Value; RPM = Convert.ToInt16(telem.RPM.Value); Shift = telem.ShiftIndicatorPct.Value; Lap = telem.Lap.Value > 199 ? 199 : telem.Lap.Value; Engine = (byte)(Convert.ToString(telem.EngineWarnings.Value).Contains("PitSpeedLimiter") ? 1 : 0); DeltaNeg = 0; Mins = 0; if (fuelVal != 0) { double tmp = Math.Round(telem.FuelLevel.Value / fuelVal, 2); if (tmp > 99.9) { Fuel = Convert.ToInt16(Math.Round(tmp)); } else if (tmp > 9.99) { Fuel = Convert.ToInt16(Math.Round(tmp * 10)); Engine |= 1 << 1; } else { Fuel = Convert.ToInt16(Math.Round(tmp * 100)); Engine |= 2 << 1; } } else { Fuel = Convert.ToInt16(Math.Round(telem.FuelLevelPct.Value * 100)); Engine |= 3 << 1; } Engine |= (byte)(brake << 3); if (prevFuel != 0) { Engine |= (1 << 4); } if (sendTimeReset) { Engine |= (1 << 5); } if (sendTime) { Engine |= (1 << 6); float l = Convert.ToSingle(sdk.GetData("LapLastLapTime")); if (l > 0) { Mins = Convert.ToInt16(Math.Floor(l / 60)); int Secs = Convert.ToInt16(Math.Floor(l - (Mins * 60))); int mSecs = Convert.ToInt16(Math.Floor((l - (Secs + (Mins * 60))) * 1000)); Delta = (Secs << 9) | mSecs; } } else { Delta = (int)(Math.Round(Convert.ToSingle(sdk.GetData("LapDeltaToBestLap")) * 1000)); if (Delta <= 0) { DeltaNeg = 1; Delta = Delta * -1; } Delta = Delta > 9999 ? 9999 : Delta; } }
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"; } } }
public void initialize() { sdk = new iRacingSDK(); sdk.Startup(); // check connection if (sdk.IsConnected()) { String yaml = sdk.GetSessionInfo(); // caridx Int32 start = yaml.IndexOf("DriverCarIdx: ") + "DriverCarIdx: ".Length; Int32 end = yaml.IndexOf("\n", start); carIdx = Int32.Parse(yaml.Substring(start, end - start)); // carname start = yaml.IndexOf("CarIdx: " + carIdx.ToString(), start); start = yaml.IndexOf("CarPath: ", start) + "CarPath: ".Length; end = yaml.IndexOf("\n", start); if (start < 0) carname = "unknown"; else carname = yaml.Substring(start, end - start); // track name start = yaml.IndexOf("TrackName: ") + "TrackName: ".Length; end = yaml.IndexOf("\n", start); if (start < 0) trackname = "unknown"; else trackname = yaml.Substring(start, end - start); // track length start = yaml.IndexOf("TrackLength: ") + "TrackLength: ".Length; end = yaml.IndexOf("km\n", start); String dbg = yaml.Substring(start, end - start); trackLength = (Int32)(Single.Parse(yaml.Substring(start, end - start)) * 1000); // session types RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled; MatchCollection sessionNums, sessionTypes; Regex optionRegex = new Regex(@"SessionNum: (\d+)", options); // Get matches of pattern in yaml sessionNums = optionRegex.Matches(yaml); optionRegex = new Regex(@"SessionType: (\w+)", options); sessionTypes = optionRegex.Matches(yaml); Int32 currentSessionNum = (Int32)sdk.GetData("SessionNum"); // Iterate matches for (Int32 ctr = 0; ctr < Math.Min(sessionNums.Count, sessionTypes.Count); ctr++) { if (Int32.Parse(sessionNums[ctr].Value.Substring(12)) == currentSessionNum) { switch (sessionTypes[ctr].Value.Substring(13).Trim()) { case "Practice": sessiontype = iRacing.SessionTypes.practice; break; case "Qualify": sessiontype = iRacing.SessionTypes.qualify; break; case "Race": sessiontype = iRacing.SessionTypes.race; break; default: sessiontype = iRacing.SessionTypes.invalid; break; } } } // reset laptimes lapStartTime = (Double)sdk.GetData("ReplaySessionTime"); lapTimeValid = false; // fuel consumption, last 5 lap rolling fuelcons = new Single[fuelconslaps]; fuelconsPtr = 0; // init timedelta timedelta = new TimeDelta(trackLength); timedelta.SaveBestLap(carIdx); LoadBestLap(); init = true; } else // retry next tick { init = 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(); } } }
public void initialize() { sdk = new iRacingSDK(); sdk.Startup(); // check connection if (sdk.IsConnected()) { String yaml = sdk.GetSessionInfo(); // caridx Int32 start = yaml.IndexOf("DriverCarIdx: ") + "DriverCarIdx: ".Length; Int32 end = yaml.IndexOf("\n", start); carIdx = Int32.Parse(yaml.Substring(start, end - start)); // carname start = yaml.IndexOf("CarIdx: " + carIdx.ToString(), start); start = yaml.IndexOf("CarPath: ", start) + "CarPath: ".Length; end = yaml.IndexOf("\n", start); if (start < 0) { carname = "unknown"; } else { carname = yaml.Substring(start, end - start); } // track name start = yaml.IndexOf("TrackName: ") + "TrackName: ".Length; end = yaml.IndexOf("\n", start); if (start < 0) { trackname = "unknown"; } else { trackname = yaml.Substring(start, end - start); } // track length start = yaml.IndexOf("TrackLength: ") + "TrackLength: ".Length; end = yaml.IndexOf("km\n", start); String dbg = yaml.Substring(start, end - start); trackLength = (Int32)(Single.Parse(yaml.Substring(start, end - start)) * 1000); // session types RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled; MatchCollection sessionNums, sessionTypes; Regex optionRegex = new Regex(@"SessionNum: (\d+)", options); // Get matches of pattern in yaml sessionNums = optionRegex.Matches(yaml); optionRegex = new Regex(@"SessionType: (\w+)", options); sessionTypes = optionRegex.Matches(yaml); Int32 currentSessionNum = (Int32)sdk.GetData("SessionNum"); // Iterate matches for (Int32 ctr = 0; ctr < Math.Min(sessionNums.Count, sessionTypes.Count); ctr++) { if (Int32.Parse(sessionNums[ctr].Value.Substring(12)) == currentSessionNum) { switch (sessionTypes[ctr].Value.Substring(13).Trim()) { case "Practice": sessiontype = iRacing.SessionTypes.practice; break; case "Qualify": sessiontype = iRacing.SessionTypes.qualify; break; case "Race": sessiontype = iRacing.SessionTypes.race; break; default: sessiontype = iRacing.SessionTypes.invalid; break; } } } // reset laptimes lapStartTime = (Double)sdk.GetData("ReplaySessionTime"); lapTimeValid = false; // fuel consumption, last 5 lap rolling fuelcons = new Single[fuelconslaps]; fuelconsPtr = 0; // init timedelta timedelta = new TimeDelta(trackLength); timedelta.SaveBestLap(carIdx); LoadBestLap(); init = true; } else // retry next tick { init = false; } }
public void updateData() { // Check if the SDK is connected if (sdk.IsConnected()) { // telemetry gear = (Int32)sdk.GetData("Gear"); rpm = (Int32)(Single)sdk.GetData("RPM"); speed = (Int32)((Single)sdk.GetData("Speed") * 3.6); fuel = (Int32)((Single)sdk.GetData("FuelLevel")); shiftindicator = (Single)sdk.GetData("ShiftIndicatorPct"); Int32 enwarn = (Int32)sdk.GetData("EngineWarnings"); if (((Int32)sdk.GetData("EngineWarnings") & 0x10) > 0) { pitlimiter = true; } else { pitlimiter = false; } lap = (Int32)sdk.GetData("Lap"); lapsrem = (Int32)sdk.GetData("SessionLapsRemain"); Double sessionTime = new Double(); Boolean curontrack = (Boolean)sdk.GetData("IsOnTrack"); if (curontrack == false && ontrack == true) { SaveBestLap(); } ontrack = curontrack; if (ontrack) { sessionTime = (Double)sdk.GetData("SessionTime"); } else { sessionTime = (Double)sdk.GetData("ReplaySessionTime"); } if (carIdx >= 0) // skip things that require caridx if we don't have it { Int32[] driverLaps = new Int32[64]; driverLaps = (Int32[])sdk.GetData("CarIdxLap"); Single[] driverTrkPos = new Single[64]; driverTrkPos = (Single[])sdk.GetData("CarIdxLapDistPct"); Int32 lapPointer = (Int32)Math.Floor((driverTrkPos[carIdx] % 1) * (trackLength / 10)); timedelta.Update(sessionTime, driverTrkPos); if (driverTrkPos[carIdx] < 0.1 && lastTickTrackPos > 0.9) { Double distance = (1 - lastTickTrackPos) + driverTrkPos[carIdx]; Double time = sessionTime - lastTickTime; Double tickCorrection = (1 - lastTickTrackPos) / distance; // save lap time if (lapTimeValid) { Double laptime = (sessionTime - (1 - tickCorrection) * time) - lapStartTime; prevlap = new TimeSpan(0, 0, 0, (Int32)Math.Floor(laptime), (Int32)Math.Floor((laptime % 1) * 1000)); fuelcons[fuelconsPtr % fuelcons.Length] = (Single)sdk.GetData("FuelLevel"); // update fuel consumption after one full lap if (fuelconsPtr > 0) { if (fuelconsPtr >= fuelcons.Length) { Single[] consrate = new Single[fuelcons.Length - 1]; Int32 j = 0; for (int i = fuelconsPtr; i < fuelconsPtr + consrate.Length; i++) { consrate[j++] = fuelcons[(i + 1) % fuelcons.Length] - fuelcons[(i + 2) % fuelcons.Length]; } fuelneed = (Int32)(fuelcons[fuelconsPtr % fuelcons.Length] - (lapsrem * consrate.Average())); fuelconsumption = consrate.Average(); } else if (fuelconsPtr > 0) { fuelneed = (Int32)(fuelcons[fuelconsPtr % fuelcons.Length] - (lapsrem * fuelcons[(fuelconsPtr - 1) % fuelcons.Length])); fuelconsumption = fuelcons[(fuelconsPtr - 1) % fuelcons.Length] - fuelcons[fuelconsPtr % fuelcons.Length]; } } fuelconsPtr++; } // start new lap lapStartTime = sessionTime - (1 - tickCorrection) * time; lapTimeValid = true; } else if (Math.Abs(driverTrkPos[carIdx] - lastTickTrackPos) > 0.1) { // invalidate lap time if jumping too much lapTimeValid = false; } // reset fuel consumption when in pits TrackLocation[] trackSurface = (iRSDKSharp.TrackLocation[])sdk.GetData("CarIdxTrackSurface"); if (trackSurface[carIdx] == TrackLocation.irsdk_InPitStall) { fuelcons = new Single[fuelconslaps]; fuelconsPtr = 0; } lastTickTrackPos = driverTrkPos[carIdx]; // save for next tick lastTickTime = sessionTime; Int32[] driverCarIdx = new Int32[64]; if (sessiontype == SessionTypes.race) { // in race calculate who is infront using trackpct and lap number for (Int32 i = 0; i < 64; i++) { driverTrkPos[i] += (Single)driverLaps[i]; driverCarIdx[i] = i; } Array.Sort(driverTrkPos, driverCarIdx); Array.Reverse(driverCarIdx); position = (Int32)(Array.IndexOf(driverCarIdx, carIdx) + 1); delta = timedelta.GetDelta(carIdx, driverCarIdx[Math.Max(position - 2, 0)]); } else { if (sdk.Header.SessionInfoUpdate != lastSesInfoUpdate) { // parse position String yaml = sdk.GetSessionInfo(); Int32 sessionmatch = yaml.IndexOf(" - SessionNum: " + ((Int32)sdk.GetData("SessionNum")).ToString()); Int32 carmatch = yaml.IndexOf("CarIdx: " + carIdx.ToString(), sessionmatch); Int32 positionmatch = yaml.LastIndexOf("Position:", carmatch); if (positionmatch < 0) { position = 0; } else { position = Int32.Parse(yaml.Substring(positionmatch + "Position:".Length, 2)); } } delta = timedelta.GetBestLapDelta(driverTrkPos[carIdx] % 1); } } lastSesInfoUpdate = sdk.Header.SessionInfoUpdate; } else { init = false; } }
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; }