public static void loadSystemIndex(ref Elite.MessageBus messageBus) { string systemIndexFile = Path.Combine(Config.Path(), "ocellus_index.json"); if (!downloadIndex() && !File.Exists(systemIndexFile)) { Debug.Write("Error getting the system index - returning"); return; } try { JavaScriptSerializer serializer = new JavaScriptSerializer(); serializer.MaxJsonLength = 50000000; Dictionary <string, dynamic> systemIndex = new Dictionary <string, dynamic>(); string[] lines = File.ReadAllLines(systemIndexFile); systemIndex = serializer.Deserialize <Dictionary <string, dynamic> >(lines[0]); messageBus.systemIndex = systemIndex; messageBus.systemIndexLoaded = true; Debug.Write("Loaded " + systemIndex["systems"].Count.ToString() + " populated star systems from Index"); } catch (Exception ex) { Debug.Write(ex.ToString()); } }
public static void addSpeech(Elite.MessageBus messageBus, string text, string voice) { Elite.Speech newMessage = new Elite.Speech(); newMessage.text = text; newMessage.voice = voice; messageBus.spokenAnnouncements.Add(newMessage); }
public static void startupNotifications(Elite.MessageBus messageBus, int registryCheck) { // This returns null if the registry key is missing - that's ok if (registryCheck == 1) { addSpeech(messageBus, "Welcome to the Ocellus Assistant. Say configure plug in to begin.", null); } else if (registryCheck == 2 || registryCheck == 3) { addSpeech(messageBus, "New Configurations available. Say Configure Plug in to make modifications.", null); } else { string announcementType = PluginRegistry.getStringValue("startupNotification"); if (announcementType == "tts") { string voice = PluginRegistry.getStringValue("startupVoice"); addSpeech(messageBus, PluginRegistry.getStringValue("startupText"), voice); } else if (announcementType == "sound") { string file = PluginRegistry.getStringValue("startupSound"); playSound(file); } } if (Upgrade.needUpgrade()) { updateAnnouncement(messageBus); } }
public static void loadGrammar(Elite.MessageBus messageBus) { SpeechRecognitionEngine recognitionEngine = messageBus.recognitionEngine; recognitionEngine.SetInputToDefaultAudioDevice(); recognitionEngine.InitialSilenceTimeout = TimeSpan.FromSeconds(5); recognitionEngine.EndSilenceTimeout = TimeSpan.FromSeconds(1.5); recognitionEngine.BabbleTimeout = TimeSpan.FromSeconds(5); DateTime startTime = DateTime.Now; Debug.Write("Begin loading star system grammar"); bool grammarLoaded = true; int counter = 0; try { GrammarBuilder gb = new GrammarBuilder(); gb.Culture = messageBus.recognitionEngineLang; Choices systemChoice = new Choices(); foreach (string system in messageBus.systemIndex["systems"].Keys) { List <string> alternates = alternatePhonetics(system); foreach (string alternate in alternates) { counter += 1; GrammarBuilder systemBuilder = new GrammarBuilder(alternate); systemBuilder.Culture = messageBus.recognitionEngineLang; SemanticResultValue systemSemantic = new SemanticResultValue(systemBuilder, system); systemChoice.Add(new GrammarBuilder(systemSemantic)); } } gb.Append(systemChoice); Grammar grammar = new Grammar(gb); grammar.Name = "populated"; recognitionEngine.LoadGrammar(grammar); Debug.Write("Star system recognition engine rules loaded: " + counter); } catch (Exception ex) { Debug.Write(ex.ToString()); grammarLoaded = false; Debug.Write("Error: Unable to load grammar"); Announcements.errorAnnouncement(messageBus, "Unable to load star system recognition engine"); } if (grammarLoaded) { DateTime endTime = DateTime.Now; TimeSpan loadTime = endTime - startTime; Debug.Write("Finished loading star system grammar. Load time: " + loadTime.Seconds.ToString() + " seconds"); Debug.Write("Recognition Engine - Audio Level: " + recognitionEngine.AudioLevel.ToString()); Debug.Write("Recognition Engine - Audio Format: " + recognitionEngine.AudioFormat.ToString()); Debug.Write("Recognition Engine - Grammars Loaded: " + recognitionEngine.Grammars.Count.ToString()); Debug.Write("Recognition Engine - Recognizer Information: " + recognitionEngine.RecognizerInfo.Name.ToString()); Announcements.engineAnnouncement(messageBus); } messageBus.grammarLoaded = grammarLoaded; }
public static int calcDistanceFromHere(Elite.MessageBus messageBus, string toSystem) { double fromX; double fromY; double fromZ; double toX; double toY; double toZ; if (messageBus.currentSystem == "" || messageBus.currentSystem == null) { Debug.Write("Error: calcDistance - fromSystem not specified"); return(-1); } if (toSystem == "" || toSystem == null) { Debug.Write("Error: calcDistance - toSystem not specified"); return(-1); } if (messageBus.currentSystem == toSystem) { return(0); } if (messageBus.haveSystemCoords) { Debug.Write("Using coords from netlog"); fromX = messageBus.currentX; fromY = messageBus.currentY; fromZ = messageBus.currentZ; } else if (messageBus.systemIndex["systems"].ContainsKey(messageBus.currentSystem)) { Debug.Write("Using coords from Index"); fromX = Convert.ToDouble(messageBus.systemIndex["systems"][messageBus.currentSystem]["x"]); fromY = Convert.ToDouble(messageBus.systemIndex["systems"][messageBus.currentSystem]["y"]); fromZ = Convert.ToDouble(messageBus.systemIndex["systems"][messageBus.currentSystem]["z"]); } else { Debug.Write("Error: Unable to determine your current coordinates in system '" + messageBus.currentSystem + "'"); return(-1); } if (messageBus.systemIndex["systems"].ContainsKey(toSystem)) { toX = Convert.ToDouble(messageBus.systemIndex["systems"][toSystem]["x"]); toY = Convert.ToDouble(messageBus.systemIndex["systems"][toSystem]["y"]); toZ = Convert.ToDouble(messageBus.systemIndex["systems"][toSystem]["z"]); } else { Debug.Write("Error: Dest system '" + toSystem + "' is not in the EDDN database"); return(-1); } int distance = (int)(Math.Sqrt(Math.Pow((fromX - toX), 2) + Math.Pow((fromY - toY), 2) + Math.Pow((fromZ - toZ), 2)) + .5); return(distance); }
public static void engineAnnouncement(Elite.MessageBus messageBus) { string announcementType = PluginRegistry.getStringValue("engineNotification"); if (announcementType == "tts") { string voice = PluginRegistry.getStringValue("engineVoice"); addSpeech(messageBus, PluginRegistry.getStringValue("engineText"), voice); } else if (announcementType == "sound") { string file = PluginRegistry.getStringValue("engineSound"); playSound(file); } }
public static void speak(Elite.MessageBus messageBus) { SpeechSynthesizer reader = new SpeechSynthesizer(); while (true) { if (messageBus.spokenAnnouncements.Count > 0) { try { Elite.Speech message = messageBus.spokenAnnouncements[0]; messageBus.spokenAnnouncements.RemoveAt(0); if (message.voice != null && message.voice != "") { try { reader.SelectVoice(message.voice); } catch { Debug.Write("Error: Unable to set voice: " + message.voice); } } reader.SetOutputToDefaultAudioDevice(); reader.Speak(message.text); Thread.Sleep(1500); } catch (Exception ex) { Debug.Write(ex.ToString()); } } else { Thread.Sleep(250); } } }
public static EliteBinds getBinds(ref Dictionary <string, object> state, ref Dictionary <string, string> textValues, ref Dictionary <string, bool?> booleanValues, Elite.MessageBus messageBus) { EliteBinds eliteBinds = null; if (needsBindsReload(ref state, ref textValues, ref booleanValues) == true) { Tuple <string, string> tResponse = Elite.getBindsFilename(); string bindsPreset = tResponse.Item1; string bindsFile = tResponse.Item2; if (bindsPreset != null && bindsFile != null) { Debug.Write("Current Binds file: " + bindsFile); var bindsTree = XElement.Load(bindsFile); state["VAEDbindsFile"] = bindsFile; state["VAEDbindsPreset"] = bindsPreset; state["VAEDlastPresetTimestamp"] = File.GetLastWriteTime(bindsPreset); state["VAEDlastBindsTimestamp"] = File.GetLastWriteTime(bindsFile); XElement keyboardLayout = bindsTree.Element("KeyboardLayout"); string lang = keyboardLayout.Value.ToString(); Debug.Write("Elite key bindings language set to: " + lang); state["VAEDbindsLanguage"] = lang; eliteBinds = new EliteBinds(bindsTree, lang); state["VAEDeliteBinds"] = eliteBinds; } } else { eliteBinds = (EliteBinds)state["VAEDeliteBinds"]; } return(eliteBinds); }
public static Dictionary <string, dynamic> getProfile(Elite.MessageBus messageBus) { string htmlData = ""; // Load debug companion JSON if it is present. string debugJson = Path.Combine(Config.Path(), "debug_companion.json"); if (File.Exists(debugJson)) { Debug.Write("-------------- Loading debug companion json --------------"); htmlData = File.ReadAllText(debugJson); } else { if (messageBus.profileLastUpdate != null) { int secondsAgo = -60; DateTime lastRun = messageBus.profileLastUpdate; DateTime compareTime = DateTime.Now.AddSeconds(secondsAgo); double diffSeconds = (lastRun - compareTime).TotalSeconds; if (diffSeconds > 0) { Debug.Write("Companion API cooldown in progress. " + diffSeconds.ToString() + " seconds remaining."); return(messageBus.companion); } } messageBus.profileLastUpdate = DateTime.Now; Debug.Write("Downloading Profile from Frontier Companion API"); Tuple <bool, string, CookieContainer, string> tRespon = Web.sendRequest(profileURL, messageBus.cookies); messageBus.cookies = tRespon.Item3; Web.WriteCookiesToDisk(Config.CookiePath(), tRespon.Item3); htmlData = tRespon.Item4; if (htmlData.Contains("Please correct the following") || htmlData == "") { messageBus.loggedinState = "error"; return(null); } } string companionFile = Path.Combine(Config.Path(), "companion.json"); using (StreamWriter outputFile = new StreamWriter(companionFile)) { outputFile.Write(htmlData); } JavaScriptSerializer serializer = new JavaScriptSerializer(); Dictionary <string, dynamic> result = new Dictionary <string, dynamic>(); try { result = serializer.Deserialize <Dictionary <string, dynamic> >(htmlData); } catch { // Something's not right with the data Debug.Write("ERROR: Unable to deserialize Companion API output"); return(null); } messageBus.companion = result; return(result); }
public static bool updateProfile(Elite.MessageBus messageBus, ref Dictionary <string, object> state, ref Dictionary <string, Int16?> shortIntValues, ref Dictionary <string, string> textValues, ref Dictionary <string, int?> intValues, ref Dictionary <string, decimal?> decimalValues, ref Dictionary <string, bool?> booleanValues) { Dictionary <string, dynamic> result = getProfile(messageBus); if (result == null) { textValues["VAEDprofileStatus"] = "error"; return(false); } bool currentlyDocked = false; try { textValues["VAEDprofileStatus"] = "ok"; state["VAEDcompanionDict"] = result; string cmdr = result["commander"]["name"]; int credits = result["commander"]["credits"]; int debt = result["commander"]["debt"]; int shipId = result["commander"]["currentShipId"]; string currentShipId = shipId.ToString(); currentlyDocked = result["commander"]["docked"]; string combatRank = Elite.combatRankToString(result["commander"]["rank"]["combat"]); string tradeRank = Elite.tradeRankToString(result["commander"]["rank"]["trade"]); string exploreRank = Elite.exploreRankToString(result["commander"]["rank"]["explore"]); string cqcRank = Elite.cqcRankToString(result["commander"]["rank"]["cqc"]); string federationRank = Elite.federationRankToString(result["commander"]["rank"]["federation"]); string empireRank = Elite.empireRankToString(result["commander"]["rank"]["empire"]); string powerPlayRank = Elite.powerPlayRankToString(result["commander"]["rank"]["power"]); string currentShip = ""; Dictionary <string, dynamic> allShips = new Dictionary <string, dynamic>(); if (result["ships"].GetType() == typeof(System.Collections.ArrayList)) { for (int counter = 0; counter < result["ships"].Count; counter += 1) { string id = result["ships"][counter]["id"].ToString(); allShips.Add(id, result["ships"][counter]); if (id == currentShipId) { currentShip = result["ships"][counter]["name"]; } } } else { allShips = result["ships"]; currentShip = result["ships"][currentShipId]["name"]; } int howManyShips = allShips.Count; int cargoCapacity = result["ship"]["cargo"]["capacity"]; int quantityInCargo = result["ship"]["cargo"]["qty"]; //Set current System textValues["VAEDcurrentSystem"] = null; if (result.ContainsKey("lastSystem") && result["lastSystem"].ContainsKey("name")) { textValues["VAEDcurrentSystem"] = result["lastSystem"]["name"]; if (messageBus.currentSystem != result["lastSystem"]["name"]) { messageBus.currentSystem = result["lastSystem"]["name"]; if (messageBus.systemIndex["systems"].ContainsKey(messageBus.currentSystem)) { messageBus.currentX = (double)messageBus.systemIndex["Systems"][messageBus.currentSystem]["x"]; messageBus.currentY = (double)messageBus.systemIndex["Systems"][messageBus.currentSystem]["y"]; messageBus.currentZ = (double)messageBus.systemIndex["Systems"][messageBus.currentSystem]["z"]; messageBus.haveSystemCoords = true; } else { messageBus.haveSystemCoords = false; } } } else { Debug.Write("ERROR: Companion API doesn't have current location "); textValues["VAEDprofileStatus"] = "error"; return(false); } // Null out ship locations string[] listOfShips = Elite.listOfShipVariableNames(); foreach (string ship in listOfShips) { textValues["VAEDship-" + ship + "-1"] = null; intValues["VAEDshipCounter-" + ship] = 0; } List <string> keys = new List <string>(allShips.Keys); Dictionary <string, dynamic> theShips = new Dictionary <string, dynamic>(); foreach (string key in keys) { string tempShip = allShips[key]["name"]; string tempSystem = null; if (allShips[key].ContainsKey("starsystem")) { tempSystem = allShips[key]["starsystem"]["name"]; } int currDistance = -1; if (tempSystem != null) { currDistance = Atlas.calcDistanceFromHere(messageBus, tempSystem); } } foreach (string key in keys) { string tempShip = allShips[key]["name"]; string tempSystem = null; if (allShips[key].ContainsKey("starsystem")) { tempSystem = allShips[key]["starsystem"]["name"]; } string variableShipName = Elite.frontierShipToVariable(tempShip); string shipCounterString = "VAEDshipCounter-" + variableShipName; intValues[shipCounterString]++; int counterInt = (int)intValues[shipCounterString]; string counterStr = counterInt.ToString(); textValues["VAEDship-" + variableShipName + "-" + counterStr] = tempSystem; } //Setup ambiguous ship variables textValues["VAEDambiguousViper"] = null; textValues["VAEDambiguousCobra"] = null; textValues["VAEDambiguousDiamondback"] = null; textValues["VAEDambiguousAsp"] = null; textValues["VAEDambiguousEagle"] = null; if ((intValues["VAEDshipCounter-ViperMkIII"] + intValues["VAEDshipCounter-ViperMkIV"]) == 1) { if (textValues["VAEDship-ViperMkIII-1"] != null) { textValues["VAEDambiguousViper"] = textValues["VAEDship-ViperMkIII-1"]; } else { textValues["VAEDambiguousViper"] = textValues["VAEDship-ViperMkIV-1"]; } } if ((intValues["VAEDshipCounter-CobraMkIII"] + intValues["VAEDshipCounter-CobraMkIV"]) == 1) { if (textValues["VAEDship-CobraMkIII-1"] != null) { textValues["VAEDambiguousCobra"] = textValues["VAEDship-CobraMkIII-1"]; } else { textValues["VAEDambiguousCobra"] = textValues["VAEDship-CobraMkIV-1"]; } } if ((intValues["VAEDshipCounter-DiamondbackExplorer"] + intValues["VAEDshipCounter-DiamondbackScout"]) == 1) { if (textValues["VAEDship-DiamondbackScout-1"] != null) { textValues["VAEDambiguousDiamondback"] = textValues["VAEDship-DiamondbackScout-1"]; } else { textValues["VAEDambiguousDiamondback"] = textValues["VAEDship-DiamondBackExplorer-1"]; } } if ((intValues["VAEDshipCounter-AspExplorer"] + intValues["VAEDshipCounter-AspScout"]) == 1) { if (textValues["VAEDship-AspExplorer-1"] != null) { textValues["VAEDambiguousAsp"] = textValues["VAEDship-AspExplorer-1"]; } else { textValues["VAEDambiguousAsp"] = textValues["VAEDship-AspScout-1"]; } } if ((intValues["VAEDshipCounter-Eagle"] + intValues["VAEDshipCounter-ImperialEagle"]) == 1) { if (textValues["VAEDship-Eagle-1"] != null) { textValues["VAEDambiguousEagle"] = textValues["VAEDship-Eagle-1"]; } else { textValues["VAEDambiguousEagle"] = textValues["VAEDship-ImperialEagle-1"]; } } intValues["VAEDnumberOfShips"] = howManyShips; textValues["VAEDcmdr"] = cmdr; intValues["VAEDcredits"] = credits; intValues["VAEDloan"] = debt; booleanValues["VAEDcurrentlyDocked"] = currentlyDocked; textValues["VAEDcombatRank"] = combatRank; textValues["VAEDexploreRank"] = exploreRank; textValues["VAEDtradeRank"] = tradeRank; textValues["VAEDcqcRank"] = cqcRank; textValues["VAEDfederationRank"] = federationRank; textValues["VAEDempireRank"] = empireRank; textValues["VAEDcurrentShip"] = Elite.frontierShipToPretty(currentShip); textValues["VAEDphoneticShip"] = Elite.frontierShipToPhonetic(currentShip).ToLower(); intValues["VAEDcargoCapacity"] = cargoCapacity; intValues["VAEDquantityInCargo"] = quantityInCargo; Ship.Components shipObj = Ship.decode(result); state["VAEDshipObj"] = shipObj; booleanValues["VAEDshipHasCargoScanner"] = shipObj.attributes.hasCargoScanner; booleanValues["VAEDshipHasFrameShiftWakeScanner"] = shipObj.attributes.hasFrameShiftWakeScanner; booleanValues["VAEDshipHasKillWarrantScanner"] = shipObj.attributes.hasKillWarrantScanner; booleanValues["VAEDshipHasShieldBooster"] = shipObj.attributes.hasShieldBooster; booleanValues["VAEDshipHasChaffLauncher"] = shipObj.attributes.hasChaffLauncher; booleanValues["VAEDshipHasElectronicCountermeasures"] = shipObj.attributes.hasElectronicCountermeasures; booleanValues["VAEDshipHasHeatSinkLauncher"] = shipObj.attributes.hasHeatSinkLauncher; booleanValues["VAEDshipHasPointDefence"] = shipObj.attributes.hasPointDefence; textValues["VAEDshipBulkheads"] = shipObj.standard.bulkheads; intValues["VAEDshipPowerPlantClass"] = shipObj.standard.powerPlant.@class; textValues["VAEDshipPowerPlantRating"] = shipObj.standard.powerPlant.rating; textValues["VAEDshipThrustersRating"] = shipObj.standard.thrusters.rating; intValues["VAEDshipThrustersClass"] = shipObj.standard.thrusters.@class; textValues["VAEDshipFrameShiftDriveRating"] = shipObj.standard.frameShiftDrive.rating; intValues["VAEDshipFrameShiftDriveClass"] = shipObj.standard.frameShiftDrive.@class; textValues["VAEDshipLifeSupportRating"] = shipObj.standard.lifeSupport.rating; intValues["VAEDshipLifeSupportClass"] = shipObj.standard.lifeSupport.@class; textValues["VAEDshipPowerDistributorRating"] = shipObj.standard.powerDistributor.rating; intValues["VAEDshipPowerDistributorClass"] = shipObj.standard.powerDistributor.@class; textValues["VAEDshipSensorsRating"] = shipObj.standard.sensors.rating; intValues["VAEDshipSensorsClass"] = shipObj.standard.sensors.@class; textValues["VAEDshipFuelTankRating"] = shipObj.standard.fuelTank.rating; intValues["VAEDshipFuelTankClass"] = shipObj.standard.fuelTank.@class; } catch (Exception ex) { Debug.Write("ERROR: Unable to parse Companion API output " + ex.ToString()); textValues["VAEDprofileStatus"] = "error"; return(false); } try { textValues["VAEDeddbStarportId"] = null; textValues["VAEDcurrentStarport"] = null; textValues["VAEDeddbSystemId"] = null; if (currentlyDocked) { TrackSystems.Add(ref state, result["lastSystem"]["name"]); if (result.ContainsKey("lastStarport") && result["lastStarport"].ContainsKey("name")) { textValues["VAEDcurrentStarport"] = result["lastStarport"]["name"]; } //Set Station Services booleanValues["VAEDstarportCommodities"] = false; booleanValues["VAEDstarportShipyard"] = false; booleanValues["VAEDstarportOutfitting"] = false; if (result["lastStarport"].ContainsKey("commodities")) { booleanValues["VAEDstarportCommodities"] = true; } if (result["lastStarport"].ContainsKey("ships") && result["lastStarport"]["ships"].ContainsKey("shipyard_list")) { booleanValues["VAEDstarportShipyard"] = true; } if (result["lastStarport"].ContainsKey("ships") && result["lastStarport"].ContainsKey("modules")) { booleanValues["VAEDstarportOutfitting"] = true; } Task.Run(() => Eddn.updateEddn(messageBus)); } else { Debug.Write("Not docked, skipping EDDN update"); } if (messageBus.systemIndexLoaded) { if (textValues["VAEDcurrentSystem"] != null && messageBus.systemIndex["systems"].ContainsKey(textValues["VAEDcurrentSystem"])) { textValues["VAEDeddbSystemId"] = messageBus.systemIndex["systems"][textValues["VAEDcurrentSystem"]]["id"].ToString(); if (textValues["VAEDcurrentStarport"] != null && messageBus.systemIndex["systems"][textValues["VAEDcurrentSystem"]]["stations"].ContainsKey(textValues["VAEDcurrentStarport"])) { textValues["VAEDeddbStarportId"] = messageBus.systemIndex["systems"][textValues["VAEDcurrentSystem"]]["stations"][textValues["VAEDcurrentStarport"]].ToString(); } } } } catch (Exception ex) { Debug.Write(ex.ToString()); textValues["VAEDprofileStatus"] = "error"; return(false); } return(true); }
public static void errorAnnouncement(Elite.MessageBus messageBus, string error) { string voice = PluginRegistry.getStringValue("errorVoice"); addSpeech(messageBus, error, voice); }
public static void VA_Init1(ref Dictionary <string, object> state, ref Dictionary <string, Int16?> shortIntValues, ref Dictionary <string, string> textValues, ref Dictionary <string, int?> intValues, ref Dictionary <string, decimal?> decimalValues, ref Dictionary <string, bool?> booleanValues, ref Dictionary <string, object> extendedValues) { try { Debug.Write("---------------------- Ocellus Plugin " + pluginVersion + " Initializing ----------------------"); string configPath = Config.Path(); string drive = configPath.Substring(0, 2); Debug.Write("Current culture set to: " + Thread.CurrentThread.CurrentCulture.ToString()); // Cleanup string oldGrammar = Path.Combine(configPath, "systems_grammar.xml"); if (File.Exists(oldGrammar)) { File.Delete(oldGrammar); } string oldEddb = Path.Combine(configPath, "eddb_index.txt"); if (File.Exists(oldEddb)) { File.Delete(oldEddb); } string oldAtlas = Path.Combine(configPath, "atlas_index.txt"); if (File.Exists(oldAtlas)) { File.Delete(oldAtlas); } Utilities.ReportFreeSpace(drive); Elite.MessageBus messageBus = new Elite.MessageBus(); int registryCheck = PluginRegistry.checkRegistry(); // Load System Index into memory SystemIndex.loadSystemIndex(ref messageBus); // Spin up Speech announcer thread Task.Run(() => Announcements.speak(messageBus)); // Setup Speech engine try { CultureInfo currCulture = Thread.CurrentThread.CurrentCulture; SpeechRecognitionEngine recognitionEngine = new SpeechRecognitionEngine(currCulture); messageBus.recognitionEngine = recognitionEngine; messageBus.recognitionEngineLang = currCulture; } catch { messageBus.recognitionEngineLang = new CultureInfo("en-US"); SpeechRecognitionEngine recognitionEngine = new SpeechRecognitionEngine(messageBus.recognitionEngineLang); messageBus.recognitionEngine = recognitionEngine; Debug.Write("Warning: Falling back to default language for recognition engine"); } Task.Run(() => EliteGrammar.loadGrammar(messageBus)); // Setup plugin storage directory - used for cookies and debug logs string appPath = Config.Path(); string cookieFile = Config.CookiePath(); string debugFile = Config.DebugPath(); textValues["VAEDdebugPath"] = debugFile; // Determine Elite Dangerous directories string gameStartString = PluginRegistry.getStringValue("startPath"); string gameStartParams = PluginRegistry.getStringValue("startParams"); textValues["VAEDgameStartString"] = gameStartString; textValues["VAEDgameStartParams"] = gameStartParams; // Load Tracked Systems into memory TrackSystems.Load(ref state); CookieContainer cookieJar = new CookieContainer(); if (File.Exists(cookieFile)) { // If we have cookies then we are likely already logged in cookieJar = Web.ReadCookiesFromDisk(cookieFile); Tuple <CookieContainer, string> tAuthentication = Companion.loginToAPI(cookieJar); if (tAuthentication.Item2 == "ok") { cookieJar = tAuthentication.Item1; state["VAEDcookieContainer"] = cookieJar; state["VAEDloggedIn"] = "ok"; } else { state.Add("VAEDloggedIn", "no"); } } else { state.Add("VAEDloggedIn", "no"); } EliteBinds.getBinds(ref state, ref textValues, ref booleanValues, messageBus); messageBus.cookies = cookieJar; messageBus.loggedinState = (string)state["VAEDloggedIn"]; state["VAEDmessageBus"] = messageBus; Task.Run(() => Announcements.startupNotifications(messageBus, registryCheck)); //Watch the netlog for docked and system change information Task.Run(() => Elite.tailNetLog(messageBus)); } catch (Exception ex) { Debug.Write(ex.ToString()); } }
public static void VA_Invoke1(String context, ref Dictionary <string, object> state, ref Dictionary <string, Int16?> shortIntValues, ref Dictionary <string, string> textValues, ref Dictionary <string, int?> intValues, ref Dictionary <string, decimal?> decimalValues, ref Dictionary <string, bool?> booleanValues, ref Dictionary <string, object> extendedValues) { try { Elite.MessageBus messageBus = (Elite.MessageBus)state["VAEDmessageBus"]; messageBus.loggedinState = (string)state["VAEDloggedIn"]; if (state.ContainsKey("VAEDcookieContainer")) { messageBus.cookies = (CookieContainer)state["VAEDcookieContainer"]; } Debug.Write("COMMAND: " + context); switch (context.ToLower()) { case "check for upgrade": if (Upgrade.needUpgradeWithCooldown(ref state)) { booleanValues["VAEDupgradeAvailable"] = true; state["VAEDupgradeAvailable"] = true; } else { booleanValues["VAEDupgradeAvailable"] = false; state["VAEDupgradeAvailable"] = false; } break; case "distance from here": string currentSystem = messageBus.currentSystem; if (currentSystem == null) // If we don't have it from netlog then go get it from the profile { Dictionary <string, dynamic> companion = Companion.getProfile((messageBus)); if (companion.ContainsKey("lastSystem") && companion["lastSystem"].ContainsKey("name")) { currentSystem = currentSystem = companion["lastSystem"]["name"]; messageBus.currentSystem = currentSystem; // We didn't have current system from netlog, so erase out x,y,z messageBus.haveSystemCoords = false; } } decimalValues["VAEDdecimalDistance"] = null; decimalValues["VAEDintDistance"] = null; if (currentSystem != null) { int distance = Atlas.calcDistanceFromHere(messageBus, textValues["VAEDtargetSystem"]); if (distance < 0) { //Cound not find destination system Debug.Write("Error: Could not determine distance to target system"); booleanValues["VAEDerrorTargetSystem"] = true; break; } // Found the system - return distance intValues["VAEDintDistance"] = distance; booleanValues["VAEDerrorTargetSystem"] = false; booleanValues["VAEDerrorSourceSystem"] = false; break; } //Can't find the System Debug.Write("Error: Could not determine current location for command 'distance from here'"); booleanValues["VAEDerrorSourceSystem"] = true; booleanValues["VAEDerrorDestinationSystem"] = false; break; case "dictate system": booleanValues["VAEDrecognitionNotLoaded"] = false; if (messageBus.grammarLoaded) { SpeechRecognitionEngine recognitionEngine = messageBus.recognitionEngine; Tuple <string, string> tSystemNames = EliteGrammar.dictateSystem(recognitionEngine, (List <String>)state["VAEDtrackedSystems"]); textValues["VAEDdictateSystem"] = tSystemNames.Item1; textValues["VAEDdictateSystemPhonetic"] = tSystemNames.Item2; break; } else { booleanValues["VAEDrecognitionNotLoaded"] = true; Debug.Write("Error: Speech Engine not yet Initialized. (Possibly still loading)"); } textValues["VAEDdictateSystem"] = null; textValues["VAEDdictateSystemPhonetic"] = null; break; case "press key bind": // If the Binds file changes then reload the binds. string[] parts = textValues["VAEDkeyBinding"].Split(new char[] { ':' }, 2); EliteBinds eliteBinds = EliteBinds.getBinds(ref state, ref textValues, ref booleanValues, messageBus); if (eliteBinds != null) { string keyboardLanguage; if (state.ContainsKey("VAEDbindsLanguage")) { keyboardLanguage = (string)state["VAEDbindsLanguage"]; } else { keyboardLanguage = "en-US"; } List <uint> scanCodeExs = KeyMouse.MapVkToScanCodeExs(eliteBinds.GetCodes(parts[1], keyboardLanguage)); if (scanCodeExs.Count == 0) { Debug.Write("Warning: No key binding found for: " + textValues["VAEDkeyBinding"]); booleanValues["VAEDkeyBindingError"] = true; break; } switch (parts[0]) { // For now we only "best effort" focus the game before keypressing. Igorning the setFocus return code. case "KEYPRESS": Debug.Write("Key Press " + parts[1]); User32.setFocus(eliteWindowTitle); KeyMouse.KeyPress(scanCodeExs); booleanValues["VAEDkeyBindingError"] = false; break; case "KEYUP": Debug.Write("Key up " + parts[1]); User32.setFocus(eliteWindowTitle); KeyMouse.KeyUp(scanCodeExs); booleanValues["VAEDkeyBindingError"] = false; break; case "KEYDOWN": Debug.Write("Key down " + parts[1]); User32.setFocus(eliteWindowTitle); KeyMouse.KeyDown(scanCodeExs); booleanValues["VAEDkeyBindingError"] = false; break; default: booleanValues["VAEDkeyBindingError"] = true; break; } } else { Debug.Write("Error: Binds not loaded, unable to perform keypress"); } break; case "clear debug": Debug.Clear(); break; case "get debug": string tempDebug = Debug.Path(); textValues["VAEDdebugFile"] = tempDebug; break; case "export for ed shipyard": Companion.updateProfile(messageBus, ref state, ref shortIntValues, ref textValues, ref intValues, ref decimalValues, ref booleanValues); if (state.ContainsKey("VAEDshipObj")) { Ship.Components shipObj = (Ship.Components)state["VAEDshipObj"]; StringBuilder export = EDShipyard.export(shipObj); if (export != null) { booleanValues["VAEDexportEDShipyardError"] = false; Clipboard.SetText(export.ToString()); break; } } Debug.Write("Error: Unable to form ED Shipyard.com Export"); Clipboard.Clear(); booleanValues["VAEDexportEDShipyuardError"] = true; break; case "export for coriolis": Companion.updateProfile(messageBus, ref state, ref shortIntValues, ref textValues, ref intValues, ref decimalValues, ref booleanValues); if (state.ContainsKey("VAEDshipObj")) { Ship.Components shipObj = (Ship.Components)state["VAEDshipObj"]; string json = Coriolis.export(shipObj); if (json != null) { booleanValues["VAEDexportCoriolisError"] = false; Clipboard.SetText(json); break; } } Debug.Write("Error: Unable to form Coriolis.io JSON"); Clipboard.Clear(); booleanValues["VAEDexportCoriolisError"] = true; break; case "edit web variable sources": bool foundWindow = false; foreach (Form form in Application.OpenForms) { if (form.GetType().Name == "EditWebVars") { Debug.Write("Edit Web Variable Sources window is already open"); foundWindow = true; } } if (!foundWindow) { var webVarsForm = new WebVars.EditWebVars(); webVarsForm.ShowDialog(); } break; case "get web variables": GetWebVars.readWebVars(ref state, ref textValues, ref intValues, ref booleanValues); break; case "get file variables": FileVar.readFileVars(ref state, ref textValues, ref intValues, ref booleanValues); break; case "get clipboard": if (Clipboard.ContainsText(TextDataFormat.Text)) { textValues.Add("VAEDclipboard", Clipboard.GetText()); } break; case "get frontier credentials": var configureForm = new ConfigureForm.Configuration((string)state["VAEDloggedIn"]); configureForm.ShowDialog(); CookieContainer loginCookies = configureForm.Cookie; state["VAEDcookieContainer"] = loginCookies; string loginResponse = configureForm.LoginResponse; Debug.Write("Frontier Login Response: " + loginResponse); textValues["VAEDloggedIn"] = loginResponse; break; case "get frontier verification": CookieContainer verifyCookies = new CookieContainer(); if (state.ContainsKey("VAEDcookieContainer")) { verifyCookies = (CookieContainer)state["VAEDcookieContainer"]; } var verificationForm = new VerificationCode.Validate(); verificationForm.Cookie = verifyCookies; verificationForm.ShowDialog(); verifyCookies = verificationForm.Cookie; string verifyResponse = verificationForm.VerifyResponse; state["VAEDloggedIn"] = verifyResponse; state["VAEDcookieContainer"] = verifyCookies; textValues["VAEDloggedIn"] = verifyResponse; if (verifyResponse == "ok") { Web.WriteCookiesToDisk(Config.CookiePath(), verifyCookies); } break; case "update profile and eddn": if (state["VAEDloggedIn"].ToString() == "ok" && state.ContainsKey("VAEDcookieContainer")) { Companion.updateProfile(messageBus, ref state, ref shortIntValues, ref textValues, ref intValues, ref decimalValues, ref booleanValues); } else // Not logged in { textValues["VAEDprofileStatus"] = "credentials"; } break; default: Debug.Write("ERROR: unknown command"); break; } } catch (Exception ex) { Debug.Write(ex.ToString()); } }