/// <summary> /// Handles all speech results. /// This should be called in a thread that doesn't mind blocking for a long time. /// </summary> /// <param name="result"></param> public void DefaultInput_Handler(RecognitionResult result) { AerRecognitionResult input = BuildAerRecognition(result); if (input.Confidence < input.RequiredConfidence) { return; } if (input.Command != null) { if (_EventRegistry.ContainsKey(input.Command)) { if (!_Squelched) { _EventRegistry[input.Command](input); } else if (input.Command.Equals("StartListening")) { _EventRegistry[input.Command](input); } } else { AerDebug.LogError(@"Recieved command that didn't have a handler, '" + result.Text + "', command=" + input.Command); } } else { AerDebug.LogError(@"Recieved Recognition Result that didn't have a command semantic, '" + result.Text + "'"); } }
public AerRSS(string rssURL) { _xmlDoc = new XmlDocument(); _webClient = new WebClient(); Entries = new List <RSSItem>(); Loaded = false; try { StreamReader rssFeed = new StreamReader(_webClient.OpenRead(rssURL)); _xmlDoc.Load(new XmlTextReader(rssFeed)); XmlNode rootRss = _xmlDoc.SelectSingleNode("rss"); XmlNodeList channels = rootRss.ChildNodes; foreach (XmlNode channelNode in channels) { XmlNodeList items = channelNode.SelectNodes("item"); foreach (XmlNode itemNode in items) { string title = itemNode.SelectSingleNode("title").InnerText; string description = itemNode.SelectSingleNode("description").InnerText; Entries.Add(new RSSItem(title, description)); } } Loaded = true; } catch (Exception e) { AerDebug.LogError("Problems loading RSS. " + e.Message); } }
/// <summary> /// Returns a List of strings from a EDDB Json Array. /// JsonReader MUST currently point to the StartArray token for the string Array. /// Used to pull Economies out of the economy list in station data. /// </summary> /// <param name="jsonReader">JsonReader populated with the string Array</param> /// <returns>List of strings that define the station economies</returns> private List <string> _ParseJsonEconomies(JsonTextReader jsonReader) { List <string> econs = new List <string>(); if (jsonReader.TokenType != JsonToken.StartArray) { AerDebug.LogError("_ParseJsonEconomies must be called at the start of an Array"); return(null); } while (jsonReader.TokenType != JsonToken.EndArray) { jsonReader.Read(); switch (jsonReader.TokenType) { case JsonToken.String: econs.Add(jsonReader.Value.ToString()); break; case JsonToken.EndArray: break; default: AerDebug.LogError("Unknown token type in economies list, " + jsonReader.TokenType); break; } } return(econs); }
/// <summary> /// Populates the Commodity Registry with data from the eddb json string /// </summary> /// <param name="json">Json string of EDDB commodities.json data</param> private void _ParseCommodities(string json) { AerDebug.Log("Loading Commodities..."); Stopwatch timer = new Stopwatch(); timer.Start(); JArray ja = JArray.Parse(json); foreach (JObject jo in ja) { EliteCommodity ec = new EliteCommodity(); ec.Name = jo["name"].ToString(); try { ec.AveragePrice = int.Parse(jo["average_price"].ToString()); } catch (FormatException e) { AerDebug.LogError(@"Error formatting Average Price for " + ec.Name + ", " + e.Message); ec.AveragePrice = -1; } ec.id = int.Parse(jo["id"].ToString()); _CommodityRegistry.Add(ec.id, ec); _CommodityNameRegistry.Add(ec.Name.ToLower(), ec.id); } timer.Stop(); }
public string Query(string title) { try { XmlDocument xmlDoc = new XmlDocument(); WebClient webClient = new WebClient(); StreamReader wikiXml = new StreamReader(webClient.OpenRead(wikiURL + title)); xmlDoc.Load(new XmlTextReader(wikiXml)); XmlNode extractNode = xmlDoc.SelectSingleNode("api/query/pages/page/extract"); if (extractNode != null) { return(extractNode.InnerText); } else { return("No Results Found"); } } catch (Exception e) { AerDebug.LogError("Problem querying wikipedia, " + e.Message); return("Error"); } }
public AerDB(string systemsJson, string stationsJson, string commoditiesJson) { _SystemRegistry = new Dictionary <int, EliteSystem>(); _SystemNameRegistry = new Dictionary <string, int>(); _CommodityRegistry = new Dictionary <int, EliteCommodity>(); _CommodityNameRegistry = new Dictionary <string, int>(); if (File.Exists(systemsJson) && File.Exists(commoditiesJson) && File.Exists(stationsJson)) { try { _ParseSystems(File.ReadAllText(systemsJson)); _ParseCommodities(File.ReadAllText(commoditiesJson)); _ParseStations(File.ReadAllText(stationsJson)); } catch (Exception e) { AerDebug.LogError("Encountered a problem parsing EDDB json files"); AerDebug.LogException(e); } } else { AerDebug.LogError("Could not find JSON files!"); } Loaded = true; }
/// <summary> /// Handles input form the AerHandler /// </summary> /// <param name="input"></param> public void RecognizedInput(AerRecognitionResult input) { if (input.Confidence < input.RequiredConfidence) { AerDebug.LogSpeech(input.Text, input.Confidence, false); return; } AerDebug.LogSpeech(input.Text, input.Confidence, true); if (input.Command != null) { if (_EventRegistry.ContainsKey(input.Command)) { //If we haven't said 'stop listening' if (!_Squelched) { TimeSpan elapsed = DateTime.UtcNow.Subtract(_LastQueryTime); if (input.Command.Equals("AerEndQuery")) { //Do nothing until Aer is addressed again... //This makes (_LastQueryTime + elapsed time) > _StopListeningTime _LastQueryTime = DateTime.UtcNow.Subtract(new TimeSpan(0, 0, _StopListeningTime)); _EventRegistry[input.Command](input); } else if (elapsed.TotalSeconds < _StopListeningTime) { _LastQueryTime = DateTime.UtcNow; _EventRegistry[input.Command](input); } else if (input.Command.Equals("AerQuery")) { _LastQueryTime = DateTime.UtcNow; _EventRegistry[input.Command](input); } //If require query is turned off... else if (!_ReqQuery) { _EventRegistry[input.Command](input); } } else { //If we said 'start listening' to end squelch state if (input.Command.Equals("StartListening")) { _EventRegistry[input.Command](input); } } } else { AerDebug.LogError(@"Recieved command that didn't have a handler, command=" + input.Command); } } else { AerDebug.LogError(@"Recieved Recognition Result that didn't have a command semantic, '" + input.ToString() + "'"); } }
/// <summary> /// Returns a List of EliteCommodity objects from a EDDB Json Array. /// JsonReader MUST currently point to the StartArray token for the Commodity Array. /// Pulls Commodity Data out of the CommodityRegistry /// Used for import/export/prohibited commodity lists /// </summary> /// <param name="jsonReader">JsonReader populated with the Commodity Array</param> /// <returns>List of populated EliteCommodity Data</returns> private List <EliteCommodity> _ParseJsonCommodities(JsonTextReader jsonReader) { List <EliteCommodity> commodities = new List <EliteCommodity>(); if (jsonReader.TokenType != JsonToken.StartArray) { AerDebug.LogError("_ParseJsonCommodities must be called at the start of an Array"); return(null); } while (jsonReader.TokenType != JsonToken.EndArray) { jsonReader.Read(); switch (jsonReader.TokenType) { case JsonToken.String: commodities.Add(GetCommodity(jsonReader.Value.ToString())); break; case JsonToken.EndArray: break; default: AerDebug.LogError("Unknown token type in commodities list, " + jsonReader.TokenType); break; } } return(commodities); }
/// <summary> /// Registers a new handler for a command /// </summary> /// <param name="Command"></param> /// <param name="handler"></param> public void RegisterHandler(string Command, AerInputHandler handler) { if (!_EventRegistry.ContainsKey(Command)) { _EventRegistry.Add(Command, handler); } else { AerDebug.LogError("Re-registered command to new handler, command=" + Command); _EventRegistry[Command] = handler; //Maybe it should just be thrown away? } }
public void ClearField() { for (int i = 0; i < 60; i++) { if (ScanCodes.ContainsKey('\b')) { _Keyboard.SendKey(ScanCodes['\b'], DXInputEmulate.KEYEVENTF_KEYDOWN); Thread.Sleep(_InputDelay); _Keyboard.SendKey(ScanCodes['\b'], DXInputEmulate.KEYEVENTF_KEYUP); } else { AerDebug.LogError("ScanCode for backspace character does not exists in dictionary"); } } }
public void Type(string typeMe) { char[] characters = typeMe.ToUpper().ToCharArray(); foreach (char c in characters) { if (ScanCodes.ContainsKey(c)) { _Keyboard.SendKey(ScanCodes[c], DXInputEmulate.KEYEVENTF_KEYDOWN); Thread.Sleep(_InputDelay); _Keyboard.SendKey(ScanCodes[c], DXInputEmulate.KEYEVENTF_KEYUP); } else { AerDebug.LogError("ScanCode for character '" + c + "' does not exists in dictionary"); } } }
/// <summary> /// Populates the Station Data with data from the eddb json string /// </summary> /// <param name="json">Json string of EDDB stations.json data</param> private void _ParseStations(string json) { JsonTextReader jsonReader = new JsonTextReader(new StringReader(json)); int arrayDepth = 0; while (jsonReader.Read()) { switch (jsonReader.TokenType) { case JsonToken.StartArray: arrayDepth++; break; case JsonToken.StartObject: try { EliteStation es = _ParseJsonStation(jsonReader); es.System.Stations.Add(es); } catch (Exception e) { AerDebug.LogError("Encountered a problem parsing stations."); AerDebug.LogException(e); } break; case JsonToken.EndArray: arrayDepth--; break; default: AerDebug.LogError("Unknown JSON TokenType: " + jsonReader.TokenType); break; } } if (arrayDepth != 0) { AerDebug.LogError("Malformed JSON parsing - arrayDepth == " + arrayDepth + " at end of parse"); } }
//I know that GrammarLoaded is bad, but there's no good way to get the delegate surfaced out of AerInput in to AerTalk yet. // This could be solved with a service registry, but I haven't thought that through yet. // It could also be solved by using RecognitionEngine.LoadGrammar() instead of the Async version again, but // I rather like the async version. public AerInput(string pathToGrammar = @"Grammars\", EventHandler <LoadGrammarCompletedEventArgs> GrammarLoaded = null) { LoadSettings(); try { RecognitionEngine = new SpeechRecognitionEngine(new CultureInfo(_CultureInfo)); } catch (ArgumentException e) { AerDebug.LogError("Could not load speech recognizer with the current Culture settings (" + _CultureInfo + "), using default"); RecognitionEngine = new SpeechRecognitionEngine(); } RecognitionEngine.SetInputToDefaultAudioDevice(); LoadGrammar(pathToGrammar, GrammarLoaded); RecognitionEngine.SpeechRecognized += this.SpeechRecognized_Handler; RecognitionEngine.UpdateRecognizerSetting("ResponseSpeed", _ResponseSpeed); NewInput = false; RecognitionEngine.RecognizeAsync(RecognizeMode.Multiple); }
//This is getting out of hand for the AerDB file, perhaps a static AerJSON should be created // As a container for all of these darn utility methods //TODO: Make AerEddb or AerJSON and create an interface between AerDB and it. -SingularTier //WARNING: THE CODE IN THE JSON PARSING REGION WILL MAKE YOU VOMIT. #region JSON Parsing /// <summary> /// Populates the System Registry with data from the eddb json string /// </summary> /// <param name="json">Json string of EDDB systems.json data</param> private void _ParseSystems(string json) { AerDebug.Log("Loading Systems..."); Stopwatch timer = new Stopwatch(); timer.Start(); JArray ja = JArray.Parse(json); foreach (JObject jo in ja) { try { EliteSystem es = new EliteSystem(); es.Name = jo["name"].ToString(); es.id = int.Parse(jo["id"].ToString()); es.x = float.Parse(jo["x"].ToString()); es.y = float.Parse(jo["y"].ToString()); es.z = float.Parse(jo["z"].ToString()); es.Faction = jo["faction"].ToString(); es.Population = jo["population"].ToString(); es.Government = jo["government"].ToString(); es.Allegiance = jo["allegiance"].ToString(); es.State = jo["state"].ToString(); es.Security = jo["security"].ToString(); es.PrimaryEconomy = jo["primary_economy"].ToString(); string permit = jo["needs_permit"].ToString(); es.PermitRequired = permit.Equals("1"); _SystemRegistry.Add(es.id, es); _SystemNameRegistry.Add(es.Name.ToLower(), es.id); } catch (FormatException e) { AerDebug.LogError("Malformed/Unexpected System JSON data, " + e.Message); } } timer.Stop(); }
public EliteStation GetStation(EliteSystem es, string stationName) { List <EliteStation> matchingStations; var est = from station in es.Stations where station.Name.Equals(stationName) select station; matchingStations = est.ToList <EliteStation>(); if (matchingStations.Count > 1) { AerDebug.LogError(@"Found " + matchingStations.Count + " stations with the name '" + stationName + "' in system '" + es.Name + "'"); } if (matchingStations.Count > 0) { return(matchingStations[0]); } else { return(null); } }
/// <summary> /// Pulls data out of the settings file /// </summary> protected virtual void LoadSettings() { string rspSpeed = Settings.Load(Settings.RESPONSE_SPEED_NODE, "750"); if (rspSpeed == null) { AerDebug.LogError("Could not load ResponseSpeed from settings file!"); rspSpeed = "750"; } try { _ResponseSpeed = int.Parse(rspSpeed); } catch (Exception e) { AerDebug.LogError("Invalid ResponseSpeed in settings file!"); AerDebug.LogException(e); _ResponseSpeed = 750; //Default if it breaks. } _CultureInfo = Settings.Load(Settings.CULTURE_NODE, "en-US"); }
public AerRecognitionResult BuildAerRecognition(RecognitionResult input) { int numberOfSemantics = 0; AerRecognitionResult output = new AerRecognitionResult(); output.Confidence = input.Confidence; try { if (input.Semantics.ContainsKey("Command") && input.Semantics["Command"] != null) { output.Command = input.Semantics["Command"].Value.ToString(); numberOfSemantics++; } if (input.Semantics.ContainsKey("Data") && input.Semantics["Data"] != null) { output.Data = input.Semantics["Data"].Value.ToString(); numberOfSemantics++; } if (input.Semantics.ContainsKey("CommodityId") && input.Semantics["CommodityId"] != null) { int commodityId = int.Parse(input.Semantics["CommodityId"].Value.ToString()); output.Commodity = _Eddb.GetCommodity(commodityId); numberOfSemantics++; } if (input.Semantics.ContainsKey("SystemName") && input.Semantics["SystemName"] != null) { string systemName = input.Semantics["SystemName"].Value.ToString(); if (systemName.Equals("__last__")) { output.System = _LastSystem; } else { if (systemName.Equals("__local__")) { output.System = LocalSystem; } else { output.System = _Eddb.GetSystem(systemName); } } _LastSystem = output.System; numberOfSemantics++; } if (input.Semantics.ContainsKey("FromSystem") && input.Semantics["FromSystem"] != null) { string systemName = input.Semantics["FromSystem"].Value.ToString(); if (systemName.Equals("__last__")) { output.FromSystem = _LastSystem; } else { if (systemName.Equals("__local__")) { output.FromSystem = LocalSystem; } else { output.FromSystem = _Eddb.GetSystem(systemName); } } numberOfSemantics++; } if (input.Semantics.ContainsKey("ToSystem") && input.Semantics["ToSystem"] != null) { string systemName = input.Semantics["ToSystem"].Value.ToString(); if (systemName.Equals("__last__")) { output.ToSystem = _LastSystem; } else { if (systemName.Equals("__local__")) { output.ToSystem = LocalSystem; } else { output.ToSystem = _Eddb.GetSystem(systemName); } } numberOfSemantics++; } if (input.Semantics.ContainsKey("StationName") && input.Semantics["StationName"] != null) { string station = input.Semantics["StationName"].Value.ToString(); if (station.Equals("__last__")) { output.Station = _LastStation; } if (output.System != null) { output.Station = _Eddb.GetStation(output.System, station); _LastStation = output.Station; } numberOfSemantics++; } } catch (Exception e) { AerDebug.LogError("Could not parse grammar semantics, " + e.Message); AerDebug.LogException(e); } output.RequiredConfidence = 0.92f - 0.02 * (numberOfSemantics * numberOfSemantics); return(output); }
/// <summary> /// Returns a List of EliteListing objects from a EDDB Json Array. /// JsonReader MUST currently point to the StartArray token for the Listing Array. /// </summary> /// <param name="jsonReader">JsonReader populated with the Listing Array</param> /// <returns>List of populated EliteListing Data</returns> private List <EliteListing> _ParseJsonListing(JsonTextReader jsonReader) { List <EliteListing> listings = new List <EliteListing>(); if (jsonReader.TokenType != JsonToken.StartArray) { AerDebug.LogError("_ParseJsonListing must be called at the start of an Array"); return(null); } EliteListing currentListing = null; while (jsonReader.TokenType != JsonToken.EndArray) { jsonReader.Read(); switch (jsonReader.TokenType) { case JsonToken.StartObject: currentListing = new EliteListing(); break; case JsonToken.EndObject: listings.Add(currentListing); break; case JsonToken.PropertyName: switch (jsonReader.Value.ToString()) { case "id": currentListing.id = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "station_id": currentListing.StationId = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "commodity_id": currentListing.Commodity = GetCommodity(jsonReader.ReadAsInt32().GetValueOrDefault()); break; case "supply": currentListing.Supply = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "buy_price": currentListing.BuyPrice = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "sell_price": currentListing.SellPrice = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "demand": currentListing.Demand = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "collected_at": currentListing.UpdatedAt = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "update_count": currentListing.UpdateCount = jsonReader.ReadAsInt32().GetValueOrDefault(); break; default: AerDebug.LogError("Unknown JSON property name: " + jsonReader.Value.ToString()); break; } break; case JsonToken.EndArray: break; default: AerDebug.LogError("Unknown token type in listing list, " + jsonReader.TokenType); break; } } return(listings); }
/// <summary> /// Returns an EliteStation from a EDDB Json Object. /// JsonReader MUST currently point to the StartObject token for the Station object. /// </summary> /// <param name="jsonReader">JsonReader populated with the Station Object</param> /// <returns>Populated EliteStation data</returns> private EliteStation _ParseJsonStation(JsonTextReader jsonReader) { EliteStation es = new EliteStation(); if (jsonReader.TokenType != JsonToken.StartObject) { AerDebug.LogError("Malformed JSON parsing - _ParseJsonStation must be called on a StartObject token"); } while (jsonReader.TokenType != JsonToken.EndObject) { jsonReader.Read(); switch (jsonReader.TokenType) { case JsonToken.PropertyName: switch (jsonReader.Value.ToString()) { case "id": es.id = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "name": es.Name = jsonReader.ReadAsString(); break; case "system_id": es.System = GetSystem(jsonReader.ReadAsInt32().GetValueOrDefault()); break; case "max_landing_pad_size": es.MaxPadSize = jsonReader.ReadAsString(); break; case "distance_to_star": es.DistanceFromStar = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "faction": es.Faction = jsonReader.ReadAsString(); break; case "government": es.Government = jsonReader.ReadAsString(); break; case "allegiance": es.Allegiance = jsonReader.ReadAsString(); break; case "state": es.State = jsonReader.ReadAsString(); break; case "type": es.StarportType = jsonReader.ReadAsString(); break; case "has_blackmarket": es.HasBlackmarket = (jsonReader.ReadAsInt32().GetValueOrDefault() == 1); break; case "has_commodities": es.HasCommodities = (jsonReader.ReadAsInt32().GetValueOrDefault() == 1); break; case "has_refuel": es.HasRefuel = (jsonReader.ReadAsInt32().GetValueOrDefault() == 1); break; case "has_repear": es.HasRepair = (jsonReader.ReadAsInt32().GetValueOrDefault() == 1); break; case "has_rearm": es.HasRearm = (jsonReader.ReadAsInt32().GetValueOrDefault() == 1); break; case "has_outfitting": es.HasOutfitting = (jsonReader.ReadAsInt32().GetValueOrDefault() == 1); break; case "has_shipyard": es.HasShipyard = (jsonReader.ReadAsInt32().GetValueOrDefault() == 1); break; case "import_commodities": jsonReader.Read(); es.Imports = _ParseJsonCommodities(jsonReader); break; case "export_commodities": jsonReader.Read(); es.Exports = _ParseJsonCommodities(jsonReader); break; case "prohibited_commodities": jsonReader.Read(); es.Prohibited = _ParseJsonCommodities(jsonReader); break; case "economies": jsonReader.Read(); es.Economies = _ParseJsonEconomies(jsonReader); break; case "updated_at": es.UpdatedAt = jsonReader.ReadAsInt32().GetValueOrDefault(); break; case "listings": jsonReader.Read(); es.Listings = _ParseJsonListing(jsonReader); break; default: break; } break; case JsonToken.EndObject: break; } } return(es); }