public void ShouldWorkWhenCorrectFileIsGeiven()
        {
            var conf = YamlParser.Parse(Path.Combine(_testDataFolder, "simple-correct-example.yaml"));

            //sanity check
            Assert.True(true);
        }
示例#2
0
        public static string GetLatestReleaseVersion(string userRepo, out string updateInfo)
        {
            string urlInfo = giturl + userRepo + "/releases";
            string version = "";

            updateInfo = "";
            ReleaseUrl = "";
            StringBuilder sbVersionHistory = new StringBuilder();
            string        jsonData         = DownloadString(urlInfo);
            var           jsonINFO         = YamlParser.Parse(jsonData);

            foreach (var releaseInfo in jsonINFO.ChildItems)
            {
                var assets = releaseInfo.GetObject("assets");
                foreach (var assetInfo in assets.ChildItems)
                {
                    string url = assetInfo["browser_download_url"];
                    if ((ReleaseUrl.Length == 0) && url.EndsWith("HMSEditor.exe"))
                    {
                        version    = releaseInfo["tag_name"];
                        ReleaseUrl = url;
                    }
                }
                sbVersionHistory.AppendLine("### v" + releaseInfo["tag_name"]);
                sbVersionHistory.AppendLine(releaseInfo["body"] + "\r\n");
            }
            updateInfo = sbVersionHistory.ToString();
            updateInfo = MarkdownToHtml(updateInfo);
            return(version);
        }
示例#3
0
        public static string GetRepoUpdatedDate(string userRepo, out string info)
        {
            string lastDate = ""; info = ""; StringBuilder sb = new StringBuilder();
            string jsonInfo = DownloadString(giturl + userRepo);

            lastDate = regexUpdDate.Match(jsonInfo).Groups[1].Value;
            string     jsonCommitsData = DownloadString(giturl + userRepo + "/commits");
            YamlObject Commits         = YamlParser.Parse(jsonCommitsData);

            foreach (var commit in Commits.ChildItems)
            {
                string date = NormalizeDate(commit[@"commit\author\date"]);
                string msg  = commit[@"commit\message"];
                if (date.StartsWith("2015.10"))
                {
                    break;
                }
                if ((msg.IndexOf("README.md") > 0) || (msg.IndexOf("gitignore") > 0))
                {
                    continue;
                }
                sb.AppendLine("### " + date + "  \r\n" + msg + "\r\n");
            }
            info  = DownloadString("https://raw.githubusercontent.com/" + userRepo + "/master/README.md");
            info += "  \r\n## История обновлений и исправлений  \r\n" + sb.ToString();
            info  = MarkdownToHtml(info);
            return(lastDate);
        }
示例#4
0
 /// <summary>
 /// Gets a value from the session info YAML. May throw an exception. Use <see cref="TryGetValue"/> for safer operation.
 /// </summary>
 /// <param name="query">The YAML query path to the value.</param>
 public string GetValue(string query)
 {
     if (!this.IsValidYaml)
     {
         return(null);
     }
     return(YamlParser.Parse(_yaml, query));
 }
示例#5
0
    public void Test3()
    {
        var parser = new YamlParser();

        var sb = new StringBuilder()
                 .AppendLine("layout: 'default'")
                 .AppendLine("permalink: '/:year/:month/:day/:name:ext'")
                 .ToString();
        var result = parser.Parse <TempFileMetadata>(sb);
    }
示例#6
0
 /// <summary>
 /// Gets a value from the session info YAML, or null if there is an error.
 /// </summary>
 /// <param name="query">The YAML query path to the value.</param>
 public string TryGetValue(string query)
 {
     try
     {
         return(YamlParser.Parse(_yaml, query));
     }
     catch (Exception)
     {
         return(null);
     }
 }
示例#7
0
        void AssertSuccessRestored(object obj)
        {
            var yaml  = serializer.Serialize(obj);
            var nodes = parser.Parse(yaml);

            Assert.AreEqual(1, nodes.Count);
            var restored = constructor.NodeToObject(nodes[0], YamlNode.DefaultConfig);
            var yaml2    = serializer.Serialize(restored);

            Assert.AreEqual(yaml, yaml2);
        }
示例#8
0
        // Parse the YAML DriverInfo section that contains information such as driver id, name, license, car number, etc.
        private void ParseDrivers(string sessionInfo)
        {
            // This string is used for every property of the driver
            // {0} is replaced by the driver ID
            // {1} is replaced by the property key
            // The result is a string like:         DriverInfo:Drivers:CarIdx:{17}CarNumber:
            // which is the correct way to request the property 'CarNumber' from the driver with id 17.
            const string driverYamlPath = "DriverInfo:Drivers:CarIdx:{{{0}}}{1}:";

            int    id = 0;
            Driver driver;

            var newDrivers = new List <Driver>();

            // Loop through drivers until none are found
            do
            {
                driver = null;

                // Try to get the UserName of the driver (because its the first value given)
                // If the UserName value is not found (name == null) then we found all drivers
                string name = YamlParser.Parse(sessionInfo, string.Format(driverYamlPath, id, "UserName"));
                if (name != null)
                {
                    // Find this driver in the list
                    // This strange " => " syntax is called a lambda expression and is short for a loop through all drivers
                    // Read as: select the first driver 'd', if any, whose Name is equal to name.
                    driver = drivers.FirstOrDefault(d => d.Name == name);

                    if (driver == null)
                    {
                        // Or create a new Driver if we didn't find him before
                        driver                  = new Driver();
                        driver.Id               = id;
                        driver.Name             = name;
                        driver.CustomerId       = int.Parse(YamlParser.Parse(sessionInfo, string.Format(driverYamlPath, id, "UserID")));
                        driver.Number           = YamlParser.Parse(sessionInfo, string.Format(driverYamlPath, id, "CarNumber"));
                        driver.ClassId          = int.Parse(YamlParser.Parse(sessionInfo, string.Format(driverYamlPath, id, "CarClassID")));
                        driver.CarPath          = YamlParser.Parse(sessionInfo, string.Format(driverYamlPath, id, "CarPath"));
                        driver.CarClassRelSpeed = int.Parse(YamlParser.Parse(sessionInfo, string.Format(driverYamlPath, id, "CarClassRelSpeed")));
                        driver.Rating           = int.Parse(YamlParser.Parse(sessionInfo, string.Format(driverYamlPath, id, "IRating")));
                    }
                    newDrivers.Add(driver);

                    id++;
                }
            } while (driver != null);

            // Replace old list of drivers with new list of drivers and update the grid
            drivers.Clear();
            drivers.AddRange(newDrivers);

            this.UpdateDriversGrid();
        }
示例#9
0
        public void Parse_WholeValidSimpleSceneFromFile_ShouldCreateOneCameraOneLightOneSphere()
        {
            string     yamlString = File.ReadAllText("../../../Sphere.yaml");
            YamlParser yamlParser = new YamlParser(yamlString);

            yamlParser.Parse();

            Assert.Single(yamlParser.Lights);
            Assert.Single(yamlParser.Shapes);
            Assert.True(yamlParser.Shapes[0] is Sphere);
            Assert.IsType <Stripe>(yamlParser.Shapes[0].Material.Pattern);
        }
示例#10
0
 /// <summary>
 /// Gets a value from the session info YAML. Returns true if successfull, false if there is an error.
 /// </summary>
 /// <param name="query">The YAML query path to the value.</param>
 /// <param name="value">When this method returns, contains the requested value if the query was valid, or null if the query was invalid.</param>
 public bool TryGetValue(string query, out string value)
 {
     try
     {
         value = YamlParser.Parse(_yaml, query);
         return(true);
     }
     catch (Exception)
     {
         value = null;
         return(false);
     }
 }
示例#11
0
        /// <summary>
        /// Deserialize C# object(s) from a YAML text. Since a YAML text can contain multiple YAML documents, each of which
        /// represents a C# object, the result is returned as an array of <see cref="object"/>.
        /// </summary>
        /// <param name="yaml">A YAML text from which C# objects are deserialized.</param>
        /// <param name="types">Expected type(s) of the root object(s) in the YAML stream.</param>
        /// <returns>C# object(s) deserialized from YAML text.</returns>
        public object[] Deserialize(string yaml, params Type[] types)
        {
            var context = config.CreateContext();
            var parser  = new YamlParser();
            var nodes   = parser.Parse(yaml, config);
            var objects = new List <object>();

            for (int i = 0; i < nodes.Count; i++)
            {
                var node = nodes[i];
                objects.Add(Constructor.NodeToObject(node, i < types.Length ? types[i] : null, context));
            }
            return(objects.ToArray());
        }
示例#12
0
        public static Track FromSessionInfo(string sessionString)
        {
            var track = new Track();

            track.Id        = Parser.ParseInt(YamlParser.Parse(sessionString, "WeekendInfo:TrackID:"));
            track.Name      = YamlParser.Parse(sessionString, "WeekendInfo:TrackDisplayName:");
            track.CodeName  = YamlParser.Parse(sessionString, "WeekendInfo:TrackName:");
            track.Length    = Parser.ParseTrackLength(YamlParser.Parse(sessionString, "WeekendInfo:TrackLength:"));
            track.NightMode = YamlParser.Parse(sessionString, "WeekendInfo:NightMode:") == "1";
            track.Category  = YamlParser.Parse(sessionString, "WeekendInfo:Category:");
            track.IsOval    = track.Category.ToLower().Contains("oval");

            return(track);
        }
        void AssertSuccessRestored(object obj)
        {
            var yaml  = serializer.Serialize(obj);
            var nodes = parser.Parse(yaml);

            Assert.AreEqual(1, nodes.Count);
            var yamlConfig = new YamlConfig();

            yamlConfig.LookupAssemblies.Add(typeof(YamlConstructorTest).Assembly);
            var restored = constructor.NodeToObject(nodes[0], new SerializerContext(yamlConfig));
            var yaml2    = serializer.Serialize(restored);

            Assert.AreEqual(yaml, yaml2);
        }
示例#14
0
        // Parse the YAML SessionInfo section that contains information such as lap times, position, etc.
        private void ParseTimes(string sessionInfo)
        {
            // This string is used for every property of the driver
            // {0} is replaced by the current session number
            // {1} is replaced by the driver position
            // {2} is replaced by the property key
            // The result is a string like:         SessionInfo:Sessions:SessionNum:{1}ResultsPositions:Positin:{13}FastestTime:
            // which is the correct way to request the property 'FastestTime' from the driver in position 13.
            const string resultsYamlPath = "SessionInfo:Sessions:SessionNum:{{{0}}}ResultsPositions:Position:{{{1}}}{2}:";

            int    position = 1;
            Driver driver   = null;

            // Loop through positions starting at 1 until no more are found
            do
            {
                driver = null;

                // Find the car id belonging to the current position
                string idString = YamlParser.Parse(sessionInfo,
                                                   string.Format(resultsYamlPath, currentSessionNum, position, "CarIdx"));
                if (idString != null)
                {
                    int id = int.Parse(idString);

                    // Find the corresponding driver from the list
                    // This strange " => " syntax is called a lambda expression and is short for a loop through all drivers
                    // Read as: select the first driver 'd', if any, whose Id is equal to id.
                    driver = drivers.FirstOrDefault(d => d.Id == id);

                    if (driver != null)
                    {
                        driver.Position       = position;
                        driver.FastestLapTime =
                            float.Parse(
                                YamlParser.Parse(sessionInfo,
                                                 string.Format(resultsYamlPath, currentSessionNum, position,
                                                               "FastestTime")), CultureInfo.InvariantCulture);
                        driver.LastLapTime =
                            float.Parse(
                                YamlParser.Parse(sessionInfo,
                                                 string.Format(resultsYamlPath, currentSessionNum, position, "LastTime")),
                                CultureInfo.InvariantCulture);
                    }

                    position++;
                }
            } while (driver != null);
        }
示例#15
0
        //--- Methods ---
        public IParser Preprocess(string source)
        {
            var inputStream  = YamlParser.Parse(source);
            var outputStream = new YamlStream {
                Start     = inputStream.Start,
                Documents = inputStream.Documents
                            .Select(inputDocument => Preprocess(inputDocument))
                            .ToList(),
                End = inputStream.End
            };
            var parsingEvents = new List <ParsingEvent>();

            outputStream.AppendTo(parsingEvents);
            return(new YamlParsingEventsParser(parsingEvents));
        }
示例#16
0
 /// <summary>
 /// Gets a value from the session info YAML, or null if there is an error.
 /// </summary>
 /// <param name="query">The YAML query path to the value.</param>
 public string TryGetValue(string query)
 {
     if (!this.IsValidYaml)
     {
         return(null);
     }
     try
     {
         return(YamlParser.Parse(_yaml, query));
     }
     catch (Exception)
     {
         return(null);
     }
 }
示例#17
0
 public void ParseDynamicSessionInfo(string sessionInfo, bool isPlayerCar)
 {
     // Parse only session info that could have changed (driver dependent)
     this.Name              = ParseDriverYaml(sessionInfo, "UserName");
     this.CustId            = Parser.ParseInt(ParseDriverYaml(sessionInfo, "UserID"));
     this.IRating           = Parser.ParseInt(ParseDriverYaml(sessionInfo, "IRating"));
     this.LicensLevelString = ParseDriverYaml(sessionInfo, "LicString");
     this.licensLevel       = Parser.ParseLicens(LicensLevelString);
     this.IsSpectator       = Parser.ParseInt(ParseDriverYaml(sessionInfo, "IsSpectator")) == 1;
     if (isPlayerCar && (this.Car.DriverPitTrkPct <= 0 || this.Car.DriverCarMaxFuelPct <= 0 || this.Car.DriverCarFuelMaxLtr <= 0))
     {
         this.Car.DriverCarFuelMaxLtr = Parser.ParseFloat(YamlParser.Parse(sessionInfo, "DriverInfo:DriverCarFuelMaxLtr:"), -1.0f);
         this.Car.DriverCarMaxFuelPct = Parser.ParseFloat(YamlParser.Parse(sessionInfo, "DriverInfo:DriverCarMaxFuelPct:"), -1.0f);
         this.Car.DriverPitTrkPct     = Parser.ParseFloat(YamlParser.Parse(sessionInfo, "DriverInfo:DriverPitTrkPct:"), -1.0f);
     }
 }
示例#18
0
        public void ParseStaticSessionInfo(string sessionInfo, bool isPlayerCar)
        {
            this.TeamId               = Parser.ParseInt(ParseDriverYaml(sessionInfo, "TeamID"));
            this.TeamName             = ParseDriverYaml(sessionInfo, "TeamName");
            this.Car.CarId            = Parser.ParseInt(ParseDriverYaml(sessionInfo, "CarID"));
            this.Car.CarNumber        = ParseDriverYaml(sessionInfo, "CarNumberRaw");
            this.Car.CarClassId       = Parser.ParseInt(ParseDriverYaml(sessionInfo, "CarClassID"));
            this.Car.CarClassRelSpeed = Parser.ParseInt(ParseDriverYaml(sessionInfo, "CarClassRelSpeed"));
            if (isPlayerCar)
            {
                this.Car.DriverCarFuelMaxLtr = Parser.ParseFloat(YamlParser.Parse(sessionInfo, "DriverInfo:DriverCarFuelMaxLtr:"), -1.0f);
                this.Car.DriverCarMaxFuelPct = Parser.ParseFloat(YamlParser.Parse(sessionInfo, "DriverInfo:DriverCarMaxFuelPct:"), -1.0f);
                this.Car.DriverPitTrkPct     = Parser.ParseFloat(YamlParser.Parse(sessionInfo, "DriverInfo:DriverPitTrkPct:"), -1.0f);
            }
            bool isPaceCar = Parser.ParseInt(ParseDriverYaml(sessionInfo, "CarIsPaceCar")) == 1;

            this.IsPaceCar = this.CustId == -1 || isPaceCar;
        }
示例#19
0
        private static SceneBuilder ParseYamlFile(CommandLine cl)
        {
            string file = cl.Input;

            var parser = new YamlParser();

            if (parser.Parse(file))
            {
                Console.WriteLine("Parsed!");

                return(new SceneBuilder(parser.Root));
            }
            else
            {
                Console.WriteLine("Oh no!");
            }

            return(null);
        }
示例#20
0
        /// <summary>
        /// Deserialize C# object(s) from a YAML text. Since a YAML text can contain multiple YAML documents, each of which
        /// represents a C# object, the result is returned as an array of <see cref="object"/>.
        /// </summary>
        /// <param name="yaml">A YAML text from which C# objects are deserialized.</param>
        /// <param name="types">Expected type(s) of the root object(s) in the YAML stream.</param>
        /// <returns>C# object(s) deserialized from YAML text.</returns>
        public object[] Deserialize(string yaml, params Type[] types)
        {
            var c = config != null ? config : YamlNode.DefaultConfig;

            var parser  = new YamlParser();
            var nodes   = parser.Parse(yaml, c);
            var objects = new List <object>();

            for (int i = 0; i < nodes.Count; i++)
            {
                var node = nodes[i];
                if (i < types.Length)
                {
                    objects.Add(constructor.NodeToObject(node, types[i], c));
                }
                else
                {
                    objects.Add(constructor.NodeToObject(node, null, c));
                }
            }
            return(objects.ToArray());
        }
示例#21
0
        public void Parse_WholeValidSimpleSceneFromString_ShouldCreateOneCameraOneLightOneSphere()
        {
            string yamlString = @"
camera:
  from: [-5.0, 1.5, 0.0]
  to: [0.0, 0.0, 0.0]
  up: [0, 1, 0]

lights:
  - type: point
    position: [-4.9, 4.9, -1]
    color: [1, 1, 1]

shapes:
  - type: sphere
    transform:
      scale: [ 1.0, 1.0, 1.0 ]
      translate: [ 0.0, 0.0, 0.0 ]
    material:
      pattern:
        type: stripes
        colors:
          - [1, 1, 1]
          - [0, 0, 0]
      ambient: 0.2
      diffuse: 0.4
      specular: 0.9
      shininess: 50";

            YamlParser yamlParser = new YamlParser(yamlString);

            yamlParser.Parse();

            Assert.Single(yamlParser.Lights);
            Assert.Single(yamlParser.Shapes);
            Assert.True(yamlParser.Shapes[0] is Sphere);
            Assert.IsType <Stripe>(yamlParser.Shapes[0].Material.Pattern);
        }
        //--- Methods ---
        public ModuleNode Convert(string source, string selector)
        {
            // parse text into a pre-processed YAML token stream
            IParser yamlParser;

            try {
                _selector = ":" + (selector ?? "Default");
                var inputStream  = YamlParser.Parse(source);
                var outputStream = new YamlStream {
                    Start     = inputStream.Start,
                    Documents = inputStream.Documents
                                .Select(inputDocument => Preprocess(inputDocument))
                                .ToList(),
                    End = inputStream.End
                };
                var parsingEvents = new List <ParsingEvent>();
                outputStream.AppendTo(parsingEvents);
                yamlParser = new YamlParsingEventsParser(parsingEvents);
            } catch (Exception e) {
                LogError(e);
                return(null);
            }

            // parse YAML token stream into module AST
            try {
                return(new DeserializerBuilder()
                       .WithNamingConvention(new PascalCaseNamingConvention())
                       .WithNodeDeserializer(new CloudFormationFunctionNodeDeserializer())
                       .WithCloudFormationFunctions()
                       .Build()
                       .Deserialize <ModuleNode>(yamlParser));
            } catch (YamlDotNet.Core.YamlException e) {
                LogError($"parsing error near {e.Message}");
            } catch (Exception e) {
                LogError(e);
            }
            return(null);
        }
示例#23
0
        private AYamlValue Include(string filePath)
        {
            var sourceFile = Path.Combine(Path.GetDirectoryName(SourceFilename), filePath);

            // read include contents
            string contents = null;

            try {
                contents = File.ReadAllText(sourceFile);
            } catch (FileNotFoundException) {
                LogError($"could not find '{sourceFile}'");
            } catch (IOException) {
                LogError($"invalid !Include value '{sourceFile}'");
            } catch (ArgumentException) {
                LogError($"invalid !Include value '{sourceFile}'");
            }
            AYamlValue result = new YamlScalar(new Scalar("<BAD>"));

            if (contents != null)
            {
                // check if YAML conversion is required
                if (Path.GetExtension(sourceFile).ToLowerInvariant() != ".yml")
                {
                    return(new YamlScalar(new Scalar(contents)));
                }
                InSourceFile(sourceFile, () => {
                    try {
                        var includeStream = YamlParser.Parse(contents);
                        result            = Preprocess(includeStream.Documents.First()).Values.First();
                    } catch (YamlDotNet.Core.YamlException e) {
                        LogError($"parsing error near {e.Message}", e);
                    } catch (Exception e) {
                        LogError($"parse error: {e.Message}", e);
                    }
                });
            }
            return(result);
        }
示例#24
0
        public bool SdkOnSessionInfoUpdated(string sessionInfo, int sessionNumber, int driverId)
        {
            _DriverId = driverId;
            bool reloadDrivers = false;
            //also need
            int sessionId    = Parser.ParseInt(YamlParser.Parse(sessionInfo, "WeekendInfo:SessionID:"));
            int subSessionId = Parser.ParseInt(YamlParser.Parse(sessionInfo, "WeekendInfo:SubSessionID:"));

            if (_currentSessionNumber == null || (_currentSessionNumber != sessionNumber) || sessionId != _sessionId || subSessionId != _subSessionId)
            {
                // Session changed, reset session info
                reloadDrivers = true;
                _sessionData.Update(sessionInfo, sessionNumber);
                _sessionId          = sessionId;
                _subSessionId       = subSessionId;
                _isRaceOrQualifying = this.SessionData.SessionType == "Race" || this.SessionData.SessionType == "Open Qualify" || this.SessionData.SessionType == "Lone Qualify";
            }
            _currentSessionNumber = sessionNumber;
            // Update drivers
            this.UpdateDriverList(sessionInfo, reloadDrivers);

            return(reloadDrivers);
        }
示例#25
0
        public void Update(string sessionString, int sessionNumber)
        {
            this.Track               = Track.FromSessionInfo(sessionString);
            this.SubsessionId        = Parser.ParseInt(YamlParser.Parse(sessionString, "WeekendInfo:SubSessionID:"));
            this.SessionId           = Parser.ParseInt(YamlParser.Parse(sessionString, "WeekendInfo:SessionID:"));
            this.IsTeamRacing        = Parser.ParseInt(YamlParser.Parse(sessionString, "WeekendInfo:TeamRacing:")) == 1;
            this.NumCarClasses       = Parser.ParseInt(YamlParser.Parse(sessionString, "WeekendInfo:NumCarClasses:"));
            this.EventType           = YamlParser.Parse(sessionString, "WeekendInfo:EventType:");
            this.SessionType         = YamlParser.Parse(sessionString, string.Format(sessionInfoYamlPath, sessionNumber, "SessionType"));
            this.RaceLaps            = YamlParser.Parse(sessionString, string.Format(sessionInfoYamlPath, sessionNumber, "SessionLaps"));
            this.SessionTimeString   = YamlParser.Parse(sessionString, string.Format(sessionInfoYamlPath, sessionNumber, "SessionTime"));
            this.RaceTime            = Parser.ParseSec(SessionTimeString);
            this.IncidentLimitString = YamlParser.Parse(sessionString, "WeekendInfo:WeekendOptions:IncidentLimit:");
            this.StandingStart       = Parser.ParseInt(YamlParser.Parse(sessionString, "WeekendInfo:WeekendOptions:StandingStart:")) == 1;

            if (IsLimitedIncidents)
            {
                IncidentLimit = Parser.ParseInt(IncidentLimitString);
            }
            else
            {
                IncidentLimit = -1;
            }
        }
示例#26
0
        /// <summary>
        /// Deserialize C# object(s) from a YAML text. Since a YAML text can contain multiple YAML documents, each of which 
        /// represents a C# object, the result is returned as an array of <see cref="object"/>.
        /// </summary>
        /// <param name="yaml">A YAML text from which C# objects are deserialized.</param>
        /// <param name="types">Expected type(s) of the root object(s) in the YAML stream.</param>
        /// <returns>C# object(s) deserialized from YAML text.</returns>
        public object[] Deserialize(string yaml, params Type[] types)
        {
            var c = config != null ? config : YamlNode.DefaultConfig;

            var parser = new YamlParser();
            var nodes = parser.Parse(yaml, c);
            var objects = new List<object>();
            for ( int i = 0; i < nodes.Count; i++ ) {
                var node = nodes[i];
                if ( i < types.Length ) {
                    objects.Add(constructor.NodeToObject(node, types[i], c));
                } else {
                    objects.Add(constructor.NodeToObject(node, null, c));
                }
            }
            return objects.ToArray();
        }
        private void Loop()
        {
            int lastUpdate = -1;

            while (_IsRunning)
            {
                // Check if we can find the sim
                if (sdk.IsConnected())
                {
                    if (!_IsConnected)
                    {
                        // If this is the first time, raise the Connected event
                        this.RaiseEvent(OnConnected, EventArgs.Empty);
                    }

                    _IsConnected = true;

                    // Get the session info string
                    string sessionInfo = sdk.GetSessionInfo();

                    // Parse out your own driver Id
                    if (this.DriverId == -1)
                    {
                        _DriverId = int.Parse(YamlParser.Parse(sessionInfo, "DriverInfo:DriverCarIdx:"));
                    }

                    // Get the session time (in seconds) of this update
                    var time = (double)sdk.GetData("SessionTime");

                    // Is the session info updated?
                    int newUpdate = sdk.Header.SessionInfoUpdate;
                    if (newUpdate != lastUpdate)
                    {
                        lastUpdate = newUpdate;

                        // Raise the SessionInfoUpdated event and pass along the session info and session time.
                        var sessionArgs = new SessionInfoUpdatedEventArgs(sessionInfo, time);
                        this.RaiseEvent(OnSessionInfoUpdated, sessionArgs);
                    }

                    // Raise the TelemetryUpdated event and pass along the lap info and session time
                    var telArgs = new TelemetryUpdatedEventArgs(new TelemetryInfo(sdk), time);
                    this.RaiseEvent(OnTelemetryUpdated, telArgs);
                }
                else if (sdk.IsInitialized)
                {
                    // We have already been initialized before, so the sim is closing
                    this.RaiseEvent(OnDisconnected, EventArgs.Empty);

                    sdk.Shutdown();
                    _DriverId    = -1;
                    lastUpdate   = -1;
                    _IsConnected = false;
                }
                else
                {
                    _IsConnected = false;
                    _DriverId    = -1;

                    //Try to find the sim
                    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 a second
                    Thread.Sleep(1000);
                }
            }

            sdk.Shutdown();
            _DriverId    = -1;
            _IsConnected = false;
        }
示例#28
0
 private string ParseRaceResultsYaml(string sessionInfo, int sessionnumber, int position, string node)
 {
     return(YamlParser.Parse(sessionInfo, string.Format(driverResultYamlPath, sessionnumber, position, node)));
 }
示例#29
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);
            }
        }
示例#30
0
 /// <summary>
 /// Deserialize C# object(s) from a YAML text. Since a YAML text can contain multiple YAML documents, each of which 
 /// represents a C# object, the result is returned as an array of <see cref="object"/>.
 /// </summary>
 /// <param name="yaml">A YAML text from which C# objects are deserialized.</param>
 /// <param name="types">Expected type(s) of the root object(s) in the YAML stream.</param>
 /// <returns>C# object(s) deserialized from YAML text.</returns>
 public object[] Deserialize(string yaml, params Type[] types)
 {
     var context = config.CreateContext();
     var parser = new YamlParser();
     var nodes = parser.Parse(yaml, config);
     var objects = new List<object>();
     for ( int i = 0; i < nodes.Count; i++ ) {
         var node = nodes[i];
         objects.Add(Constructor.NodeToObject(node, i < types.Length ? types[i] : null, context));
     }
     return objects.ToArray();
 }
示例#31
0
        private void Loop()
        {
            int lastUpdate = -1;

            while (_IsRunning)
            {
                // Check if we can find the sim
                if (sdk.IsConnected())
                {
                    if (!_IsConnected)
                    {
                        // If this is the first time, raise the Connected event
                        this.RaiseEvent(OnConnected, EventArgs.Empty);
                    }

                    _hasConnected = true;
                    _IsConnected  = true;

                    readMutex.WaitOne(8);

                    int       attempts    = 0;
                    const int maxAttempts = 99;

                    object sessionnum = this.TryGetSessionNum();
                    while (sessionnum == null && attempts <= maxAttempts)
                    {
                        attempts++;
                        sessionnum = this.TryGetSessionNum();
                    }
                    if (attempts >= maxAttempts)
                    {
                        Debug.WriteLine("Session num too many attempts");
                        continue;
                    }

                    // Parse out your own driver Id
                    if (this.DriverId == -1)
                    {
                        string sessionInfoDriver = sdk.GetSessionInfo();
                        _DriverId = int.Parse(YamlParser.Parse(sessionInfoDriver, "DriverInfo:DriverCarIdx:"));
                    }

                    // Get the session time (in seconds) of this update
                    var time = (double)sdk.GetData("SessionTime");

                    // Raise the TelemetryUpdated event and pass along the lap info and session time
                    var telArgs = new TelemetryUpdatedEventArgs(new TelemetryInfo(sdk), time);
                    this.RaiseEvent(OnTelemetryUpdated, telArgs);

                    // Is the session info updated?
                    int newUpdate = sdk.Header.SessionInfoUpdate;
                    if (newUpdate != lastUpdate)
                    {
                        lastUpdate = newUpdate;

                        // Get the session info string
                        var sessionInfo = sdk.GetSessionInfo();

                        // Raise the SessionInfoUpdated event and pass along the session info and session time.
                        var sessionArgs = new SessionInfoUpdatedEventArgs(sessionInfo, time);
                        this.RaiseEvent(OnSessionInfoUpdated, sessionArgs);
                    }
                }
                else if (_hasConnected)
                {
                    // We have already been initialized before, so the sim is closing
                    this.RaiseEvent(OnDisconnected, EventArgs.Empty);

                    sdk.Shutdown();
                    _DriverId     = -1;
                    lastUpdate    = -1;
                    _IsConnected  = false;
                    _hasConnected = false;
                }
                else
                {
                    _IsConnected  = false;
                    _hasConnected = false;
                    _DriverId     = -1;

                    //Try to find the sim
                    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();
            _DriverId    = -1;
            _IsConnected = false;
        }
示例#32
0
 private string ParseDriverYaml(string sessionInfo, string Node)
 {
     return(YamlParser.Parse(sessionInfo, string.Format(driverYamlPath, this.Id, Node)));
 }