private void frmMain_Load(object sender, EventArgs e) { String[] ports = SerialPort.GetPortNames(); numericUpDownManualSpeed.Value = Convert.ToDecimal(Properties.Settings.Default.ManualFanSpeed); checkBoxManualSpeed.Checked = Properties.Settings.Default.EnableManualSpeed; carTopSpeed.Value = Convert.ToDecimal(Properties.Settings.Default.TopSpeed); maxFanSpeed.Value = Convert.ToDecimal(Properties.Settings.Default.MaxFanSpeed); chkAutoTopSpeed.Checked = Properties.Settings.Default.AutoTopSpeed; if (ports.Length > 0) { cboPorts.Items.AddRange(ports); preferredPort = Properties.Settings.Default.Port.ToString(); } else { label1.Text = "No Arduino's found"; btnSave.Enabled = false; } lblConn.Text = "No connection with iRacing API"; sdk.Startup(); tmr.Enabled = true; }
// 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; }
public Boolean Connect() { sdk.Startup(); if (sdk.VarHeaders != null && sdk.VarHeaders.Count > 0 && (Double)sdk.GetData("SessionTime") > 0) { return(true); } else { return(false); } }
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() { if (sdk.IsConnected() && sdk.VarHeaders.Count > 0) { indicateSimConnected(true); } else { indicateSimConnected(false); if (sdk.IsInitialized) { sdk.Shutdown(); } else { 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; } }
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); } }
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; } }