Пример #1
0
        public object GetData(string headerName)
        {
            if (!sdk.IsConnected())
            {
                return(null);
            }

            return(sdk.GetData(headerName));
        }
Пример #2
0
Файл: sdk.cs Проект: iDeeW/iFlag
        // 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();
            }
        }
Пример #3
0
        /// <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;
        }
Пример #4
0
 public Boolean isConnected()
 {
     if (sdk.IsConnected())
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Пример #5
0
        // 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();
                }
            }
        }
Пример #6
0
        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);
        }
Пример #7
0
        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;
            }
        }
Пример #8
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;
            }
        }
Пример #9
0
        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";
                }
            }
        }
Пример #10
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;
        }
Пример #11
0
        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();
        }
Пример #12
0
        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();
                }
            }
        }
Пример #13
0
        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);
            }
        }
Пример #14
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;
            }
        }