public void Operation() { using (var sleepHelper = new SleepHelper()) { var signal = new ManualResetEventSlim(); var listener = new Listener(); var done = false; var asyncToken = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromSeconds(1)); done = true; }); task.CompletesAsyncOperation(asyncToken); task.Start(); Wait(listener, signal); Assert.True(done, "The operation should have completed"); } }
public void QueuedOperation() { using (var sleepHelper = new SleepHelper()) { var signal = new ManualResetEventSlim(); var listener = new Listener(); var done = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken2 = listener.BeginAsyncOperation("Test"); var queuedTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); done = true; }); queuedTask.CompletesAsyncOperation(asyncToken2); queuedTask.Start(); }); task.CompletesAsyncOperation(asyncToken1); task.Start(); Wait(listener, signal); Assert.True(done, "Should have waited for the queued operation to finish!"); } }
public void IgnoredCancel() { using (var sleepHelper = new SleepHelper()) { var signal = new ManualResetEventSlim(); var listener = new Listener(); var done = false; var queuedFinished = false; var cancelledFinished = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { using (listener.BeginAsyncOperation("Test")) { var cancelledTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromSeconds(10)); cancelledFinished = true; }); signal.Set(); cancelledTask.Start(); } sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); // Now that we've cancelled the first request, queue another one to make sure we wait for it. var asyncToken2 = listener.BeginAsyncOperation("Test"); var queuedTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromSeconds(1)); queuedFinished = true; }); queuedTask.CompletesAsyncOperation(asyncToken2); queuedTask.Start(); done = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(); Wait(listener, signal); Assert.True(done, "Cancelling should have completed the current task."); Assert.True(queuedFinished, "Continued didn't run, but it was supposed to ignore the cancel."); Assert.False(cancelledFinished, "We waited for the cancelled task to finish."); } }
public void SecondCompletion() { using (var sleepHelper = new SleepHelper()) { var signal1 = new ManualResetEventSlim(); var signal2 = new ManualResetEventSlim(); var listener = new Listener(); var firstDone = false; var secondDone = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var firstTask = Task.Factory.StartNew(() => { signal1.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); firstDone = true; }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); firstTask.CompletesAsyncOperation(asyncToken1); firstTask.Wait(); var asyncToken2 = listener.BeginAsyncOperation("Test"); var secondTask = Task.Factory.StartNew(() => { signal2.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); secondDone = true; }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); secondTask.CompletesAsyncOperation(asyncToken2); // give it two signals since second one might not have started when WaitTask.Wait is called - race condition Wait(listener, signal1, signal2); Assert.True(firstDone, "First didn't finish"); Assert.True(secondDone, "Should have waited for the second task"); } }
public void Nested() { using (var sleepHelper = new SleepHelper()) { var signal = new ManualResetEventSlim(); var listener = new Listener(); var outerDone = false; var innerDone = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); using (listener.BeginAsyncOperation("Test")) { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); innerDone = true; } sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); outerDone = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(); Wait(listener, signal); Assert.True(innerDone, "Should have completed the inner task"); Assert.True(outerDone, "Should have completed the outer task"); } }
public void MultipleEnqueues() { using (var sleepHelper = new SleepHelper()) { var signal = new ManualResetEventSlim(); var listener = new Listener(); var outerDone = false; var firstQueuedDone = false; var secondQueuedDone = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken2 = listener.BeginAsyncOperation("Test"); var firstQueueTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken3 = listener.BeginAsyncOperation("Test"); var secondQueueTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); secondQueuedDone = true; }); secondQueueTask.CompletesAsyncOperation(asyncToken3); secondQueueTask.Start(); firstQueuedDone = true; }); firstQueueTask.CompletesAsyncOperation(asyncToken2); firstQueueTask.Start(); outerDone = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(); Wait(listener, signal); Assert.True(outerDone, "The outer task should have finished!"); Assert.True(firstQueuedDone, "The first queued task should have finished"); Assert.True(secondQueuedDone, "The second queued task should have finished"); } }
public static void Initialize(CQLog log) { if (!File.Exists("config.json")) { FileStream configFile = new FileStream("config.json", FileMode.OpenOrCreate); StreamReader reader = new StreamReader( System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("vip.popop.pcr.GHelper.Resources.default.json") ); StreamWriter writer = new StreamWriter(configFile); string defaultJson = reader.ReadToEnd(); writer.Write(defaultJson); Config = JsonConvert.DeserializeObject <Configuration>(defaultJson); reader.Close(); writer.Close(); configFile.Close(); } else { FileStream configFileO = new FileStream("config.json", FileMode.Open); StreamReader configReader = new StreamReader(configFileO); Config = JsonConvert.DeserializeObject <Configuration>(configReader.ReadToEnd()); configReader.Close(); configReader.Dispose(); configFileO.Close(); } Event_GroupMessage.ClearHandler(); Event_PrivateMessage.ClearHandler(); accountManager = new Account { logger = log }; accountManager.OnInitialize(); if (Config.IsPhonographEnabled) { phonograph = new Phonograph { Client = (Phonograph.ClientType)Enum.Parse(typeof(Phonograph.ClientType), Config.Phonograph.Platform), IsWithLink = Config.Phonograph.WithLink }; phonograph.OnInitialize(); } if (Config.IsRepeaterEnabled) { repeater = new Repeater { repeatChance = Config.Repeater.RepeatChance, cooldown = Config.Repeater.Cooldown, banWords = Config.Repeater.BanWords }; repeater.OnInitialize(); } if (Config.IsSleepHelperEnabled) { sleepHelper = new SleepHelper { }; sleepHelper.OnInitialize(); } if (Config.IsLinkGeneratorEnabled) { linkGenerator = new LinkGenerator { }; linkGenerator.OnInitialize(); } if (Config.IsSoloEnabled) { solo = new Solo { validSpan = Config.Solo.ValidSpan, checkTime = Config.Solo.CheckTime, maxStack = Config.Solo.MaxStack }; solo.OnInitialize(); } if (Config.IsForestEnabled) { forest = new Forest() { Logger = log }; forest.OnInitialize(); } //letTheyOut = new LetThemOut { //}; //letTheyOut.OnInitialize(); }
public void Cancel() { using (var sleepHelper = new SleepHelper()) { var signal = new ManualResetEventSlim(); var listener = new Listener(); var done = false; var continued = false; var asyncToken1 = listener.BeginAsyncOperation("Test"); var task = new Task(() => { signal.Set(); sleepHelper.Sleep(TimeSpan.FromMilliseconds(500)); var asyncToken2 = listener.BeginAsyncOperation("Test"); var queuedTask = new Task(() => { sleepHelper.Sleep(TimeSpan.FromSeconds(5)); continued = true; }); asyncToken2.Dispose(); queuedTask.Start(); done = true; }); task.CompletesAsyncOperation(asyncToken1); task.Start(); Wait(listener, signal); Assert.True(done, "Cancelling should have completed the current task."); Assert.False(continued, "Continued Task when it shouldn't have."); } }
static void Main(string[] args) { SleepHelper.PreventSleep(); if (args != null && args.Length > 0) { foreach (string arg in args) { if (arg.Contains(",")) { Logger.ColoredConsoleWrite(ConsoleColor.Green, $"Found coordinates in command line: {arg}"); if (File.Exists(lastcords)) { Logger.ColoredConsoleWrite(ConsoleColor.Yellow, "Last coords file exists, trying to delete it"); File.Delete(lastcords); } cmdCoords = arg; } } } if (args != null && args.Length > 0 && args[0].Contains("-nogui")) { Logger.ColoredConsoleWrite(ConsoleColor.Red, "You added -nogui! If you didnt setup correctly with the GUI. It wont work."); foreach (PokemonId pokemon in Enum.GetValues(typeof(PokemonId))) { if (pokemon.ToString() != "Missingno") { GUI.gerEng[StringUtils.getPokemonNameGer(pokemon)] = pokemon.ToString(); } } int i = 0; if (File.Exists(account)) { string[] lines = File.ReadAllLines(@account); foreach (string line in lines) { try { switch (i) { case 0: if (line == "Google") { Globals.acc = Enums.AuthType.Google; } else { Globals.acc = Enums.AuthType.Ptc; } break; case 1: Globals.username = line; break; case 2: Globals.password = line; break; case 3: if (line.Split('.').Length - 1 > 1) { // Coords in one line, comma-delimited. string[] crdParts = line.Split(','); Globals.latitute = double.Parse(crdParts[0].Replace(',', '.'), GUI.cords, System.Globalization.NumberFormatInfo.InvariantInfo); Globals.longitude = double.Parse(crdParts[1].Replace(',', '.'), GUI.cords, System.Globalization.NumberFormatInfo.InvariantInfo); i++; } else { Globals.latitute = double.Parse(line.Replace(',', '.'), GUI.cords, System.Globalization.NumberFormatInfo.InvariantInfo); } break; case 4: Globals.longitude = double.Parse(line.Replace(',', '.'), GUI.cords, System.Globalization.NumberFormatInfo.InvariantInfo); break; case 5: Globals.altitude = double.Parse(line.Replace(',', '.'), GUI.cords, System.Globalization.NumberFormatInfo.InvariantInfo); break; case 6: Globals.speed = double.Parse(line.Replace(',', '.'), GUI.cords, System.Globalization.NumberFormatInfo.InvariantInfo); break; case 7: Globals.radius = int.Parse(line); break; case 8: Globals.defLoc = bool.Parse(line); break; case 9: Globals.transfer = bool.Parse(line); break; case 10: Globals.duplicate = int.Parse(line); break; case 11: Globals.evolve = bool.Parse(line); break; case 12: Globals.maxCp = int.Parse(line); break; case 13: Globals.telAPI = line; break; case 14: Globals.telName = line; break; case 15: Globals.telDelay = int.Parse(line); break; case 16: //Globals.telDelay = int.Parse(line); // NavigationOption... break; case 17: Globals.useluckyegg = bool.Parse(line); break; case 18: Globals.gerNames = bool.Parse(line); break; case 19: Globals.useincense = bool.Parse(line); break; case 20: Globals.ivmaxpercent = int.Parse(line); break; case 21: Globals.pokeList = bool.Parse(line); break; case 22: Globals.keepPokemonsThatCanEvolve = bool.Parse(line); break; case 23: Globals.pokevision = bool.Parse(line); break; case 24: Globals.useluckyegg = bool.Parse(line); break; case 25: Globals.autoIncubate = bool.Parse(line); break; case 26: Globals.useBasicIncubators = bool.Parse(line); break; case 27: Globals.TransferFirstLowIV = bool.Parse(line); break; //case 28: // Globals.userazzberry = bool.Parse(line); // break; } } catch (Exception) { Logger.ColoredConsoleWrite(ConsoleColor.Red, $"Problem with value: {line} (line #{i})"); throw; } i++; } if (cmdCoords != string.Empty) { string[] crdParts = cmdCoords.Split(','); Globals.latitute = double.Parse(crdParts[0].Replace(',', '.'), GUI.cords, System.Globalization.NumberFormatInfo.InvariantInfo); Globals.longitude = double.Parse(crdParts[1].Replace(',', '.'), GUI.cords, System.Globalization.NumberFormatInfo.InvariantInfo); } Logger.ColoredConsoleWrite(ConsoleColor.Yellow, $"Starting at: {Globals.latitute},{Globals.longitude}"); } if (File.Exists(items)) { string[] lines = File.ReadAllLines(@items); i = 0; foreach (string line in lines) { switch (i) { case 0: Globals.pokeball = int.Parse(line); break; case 1: Globals.greatball = int.Parse(line); break; case 2: Globals.ultraball = int.Parse(line); break; case 3: Globals.masterball = int.Parse(line); break; case 4: Globals.revive = int.Parse(line); break; case 5: Globals.toprevive = int.Parse(line); break; case 6: Globals.potion = int.Parse(line); break; case 7: Globals.superpotion = int.Parse(line); break; case 8: Globals.hyperpotion = int.Parse(line); break; case 9: Globals.toppotion = int.Parse(line); break; case 10: Globals.berry = int.Parse(line); break; } i++; } } if (File.Exists(keep)) { string[] lines = System.IO.File.ReadAllLines(@keep); foreach (string line in lines) { if (line != string.Empty) { if (Globals.gerNames) { Globals.noTransfer.Add((PokemonId)Enum.Parse(typeof(PokemonId), GUI.gerEng[line])); } else { Globals.noTransfer.Add((PokemonId)Enum.Parse(typeof(PokemonId), line)); } } } } if (File.Exists(ignore)) { string[] lines = System.IO.File.ReadAllLines(@ignore); foreach (string line in lines) { if (line != string.Empty) { if (Globals.gerNames) { Globals.noCatch.Add((PokemonId)Enum.Parse(typeof(PokemonId), GUI.gerEng[line])); } else { Globals.noCatch.Add((PokemonId)Enum.Parse(typeof(PokemonId), line)); } } } } if (File.Exists(evolve)) { string[] lines = System.IO.File.ReadAllLines(@evolve); foreach (string line in lines) { if (line != string.Empty) { if (Globals.gerNames) { Globals.doEvolve.Add((PokemonId)Enum.Parse(typeof(PokemonId), GUI.gerEng[line])); } else { Globals.doEvolve.Add((PokemonId)Enum.Parse(typeof(PokemonId), line)); } } } } } else { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new GUI()); if (Globals.pokeList) { Task.Run(() => { Pokemons pokemonList = new Pokemons(); pokemonList.ShowDialog(); }); } } Logger.SetLogger(new Logging.ConsoleLogger(LogLevel.Info)); Globals.infoObservable.HandleNewHuntStats += SaveHuntStats; Task.Run(() => { CheckVersion(); try { new Logic.Logic(new Settings(), Globals.infoObservable).Execute().Wait(); } catch (PtcOfflineException) { Logger.ColoredConsoleWrite(ConsoleColor.Red, "PTC Servers are probably down OR you credentials are wrong.", LogLevel.Error); Logger.ColoredConsoleWrite(ConsoleColor.Red, "Trying again in 20 seconds..."); Thread.Sleep(20000); new Logic.Logic(new Settings(), Globals.infoObservable).Execute().Wait(); } catch (AccountNotVerifiedException) { Logger.ColoredConsoleWrite(ConsoleColor.Red, "Your PTC Account is not activated. Exiting in 10 Seconds."); Thread.Sleep(10000); Environment.Exit(0); } catch (Exception ex) { Logger.ColoredConsoleWrite(ConsoleColor.Red, $"Unhandled exception: {ex}", LogLevel.Error); Logger.Error("Restarting in 20 Seconds."); Thread.Sleep(20000); new Logic.Logic(new Settings(), Globals.infoObservable).Execute().Wait(); } }); System.Console.ReadLine(); SleepHelper.AllowSleep(); }
static void Main(string[] args) { var openGUI = true; Version version = new Version(); // Review & parse command line arguments if (args != null && args.Length > 0) { #region Parse Arguments foreach (string arg in args) { #region Argument -nogui if (arg.Contains("-nogui")) { openGUI = false; Profile selectedProfile = new Profile(); Logger.ColoredConsoleWrite(ConsoleColor.Cyan, "Argument: -nogui"); if (!arg.Contains(":")) // Load Default Profile { #region Read bot settings if (File.Exists(GlobalVars.FileForProfiles)) { var Profiles = Newtonsoft.Json.JsonConvert.DeserializeObject <Collection <Profile> >(File.ReadAllText(GlobalVars.FileForProfiles)); foreach (Profile _profile in Profiles) { if (_profile.IsDefault) { selectedProfile = _profile; break; } } if (selectedProfile != null) { GlobalVars.ProfileName = selectedProfile.ProfileName; selectedProfile.Settings = ProfileSettings.LoadFromFile(Path.Combine(GlobalVars.PathToConfigs, $"{selectedProfile.ProfileName}.json")); selectedProfile.Settings.SaveToGlobals(); } else { Logger.ColoredConsoleWrite(ConsoleColor.Red, "Default Profile not found! You didn't setup the bot correctly by running it with -nogui."); Environment.Exit(-1); } } else { Logger.ColoredConsoleWrite(ConsoleColor.Red, "You have not setup the bot yet. Run it without -nogui to Configure."); Environment.Exit(-1); } } else // Load selected profile { var givenProfile = arg.Split(':'); if (File.Exists(Path.Combine(GlobalVars.PathToConfigs, givenProfile[1] + ".json"))) { selectedProfile.ProfileName = givenProfile[1]; GlobalVars.ProfileName = selectedProfile.ProfileName; selectedProfile.Settings = ProfileSettings.LoadFromFile(Path.Combine(GlobalVars.PathToConfigs, givenProfile[1] + ".json")); selectedProfile.Settings.SaveToGlobals(); } else { Logger.ColoredConsoleWrite(ConsoleColor.Red, "Profile not found! You didn't setup the bot correctly by running it with -nogui."); Environment.Exit(-1); } } Logger.ColoredConsoleWrite(ConsoleColor.Cyan, "Argument: profile. Using " + GlobalVars.ProfileName + ". Check logs in this profile log folder."); CheckLogDirectories(Path.Combine(GlobalVars.PathToLogs, GlobalVars.ProfileName)); if (GlobalVars.UsePwdEncryption) { GlobalVars.Password = Encryption.Decrypt(GlobalVars.Password); } #endregion } #endregion #region Argument Coordinates if (arg.Contains(",")) { if (File.Exists(GlobalVars.FileForCoordinates)) { Logger.ColoredConsoleWrite(ConsoleColor.Yellow, "Last coords file exists, trying to delete it"); File.Delete(GlobalVars.FileForCoordinates); } string[] crdParts = arg.Split(','); GlobalVars.latitude = double.Parse(crdParts[0].Replace(',', '.'), ConfigWindow.cords, System.Globalization.NumberFormatInfo.InvariantInfo); GlobalVars.longitude = double.Parse(crdParts[1].Replace(',', '.'), ConfigWindow.cords, System.Globalization.NumberFormatInfo.InvariantInfo); Logger.ColoredConsoleWrite(ConsoleColor.Cyan, $"Argument: coordinates. Starting at: {GlobalVars.latitude},{GlobalVars.longitude},{GlobalVars.altitude}"); //we assume -nogui openGUI = false; } #endregion #region Argument -bypassversioncheck GlobalVars.BypassCheckCompatibilityVersion |= arg.ToLower().Contains("-bypassversioncheck"); #endregion #region Argument -bypasskillswitch GlobalVars.BypassKillSwitch |= arg.ToLower().Contains("-bypasskillswitch"); #endregion #region Argument -help if (arg.ToLower().Contains("-help")) { //Show Help System.Console.WriteLine($"Pokemon BOT C# v{Resources.BotVersion.ToString()} help" + Environment.NewLine); System.Console.WriteLine("Use:"); System.Console.WriteLine(" -nogui<:profile_name> <lat>,<long> Console mode only, starting on the indicated Profile , Latitude & Longitude "); System.Console.WriteLine(" -bypassversioncheck Do NOT check BOT & API compatibility (be careful with that option!)"); System.Console.WriteLine(" -bypasskillswitch Do NOT check the forced bot stop (this assures a more than probable ban of your account)"); System.Console.WriteLine(" -help This help" + Environment.NewLine); Environment.Exit(0); } #endregion } } #endregion // Checking if current BOT API implementation supports NIANTIC current API (unless there's an override command line switch) var currentAPIVersion = new CurrentAPIVersion(); Logger.ColoredConsoleWrite(ConsoleColor.DarkCyan, "_____________________________________________________________"); Logger.ColoredConsoleWrite(ConsoleColor.White, "Attention: NO BOT IS SAFE - YOUR ACCOUNT MIGHT BE BANNED !!!"); Logger.ColoredConsoleWrite(ConsoleColor.Gray, "----- You have been warned => Your decision, your risk -----"); Logger.ColoredConsoleWrite(ConsoleColor.DarkCyan, "_____________________________________________________________"); Logger.ColoredConsoleWrite(ConsoleColor.Gray, $" Supported API version: {Resources.BotApiSupportedVersion}"); Logger.ColoredConsoleWrite(ConsoleColor.Gray, $" Current API version: {currentAPIVersion.GetNianticAPIVersion()}"); Logger.ColoredConsoleWrite(ConsoleColor.DarkCyan, $"_____________________________________________________v{Resources.BotVersion}"); Resources.SetApiVars(currentAPIVersion.GetNianticAPIVersion()); // Check if a new version of BOT is available CheckForNewBotVersion(); if (!GlobalVars.BypassCheckCompatibilityVersion) { bool CurrentVersionsOK = currentAPIVersion.CheckAPIVersionCompatibility(GlobalVars.BotApiSupportedVersion); if (!CurrentVersionsOK) { Logger.ColoredConsoleWrite(ConsoleColor.Red, $"Atention, current API version is new and still not supported by Bot."); Logger.ColoredConsoleWrite(ConsoleColor.Red, $"Bot will now exit to keep your account safe."); Logger.ColoredConsoleWrite(ConsoleColor.Red, $"---------- PRESS ANY KEY TO CLOSE ----------"); Console.ReadKey(); Environment.Exit(-1); } } // Check if Bot is deactivated at server level if (!GlobalVars.BypassKillSwitch) { StringUtils.CheckKillSwitch(); } if (openGUI) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ConfigWindow()); Task.Run(() => { new Panels.SplashScreen().ShowDialog(); }); openGUI = GlobalVars.EnablePokeList; if (GlobalVars.EnableConsoleInTab) { Logger.type = 1; } // To open tabbed GUI to test programing /* * TabbedSystem.skipReadyToUse = true; * Application.Run( new TabbedSystem()); * Environment.Exit(0); */ } SleepHelper.PreventSleep(); // Ensure all log paths exists CheckLogDirectories(Path.Combine(GlobalVars.PathToLogs, GlobalVars.ProfileName)); GlobalVars.infoObservable.HandleNewHuntStats += SaveHuntStats; Task MainTask; MainTask = Task.Run(() => { do { try { DeviceSetup.SelectDevice(GlobalVars.DeviceTradeName, GlobalVars.DeviceID, GlobalVars.FileForDeviceData); new Logic.Logic(new Settings(), GlobalVars.infoObservable).Execute(); } catch (Exception ex) { Logger.Error($"Unhandled exception: {ex}"); } Logger.Error("Restarting in 20 Seconds."); Thread.Sleep(20000); }while (Logic.Logic.restartLogic); }); if (openGUI) { if (GlobalVars.simulatedPGO) { Application.Run(new GameAspectSimulator()); } else { if (GlobalVars.EnableConsoleInTab) { FreeConsole(); } Application.Run(new TabbedSystem()); } } MainTask.Wait(); SleepHelper.AllowSleep(); }
static void Main(string[] args) { if (args.Length > 0) { if (args[0].Contains("pokesniper2")) { SharePokesniperURI(args[0]); return; } } configureNBug(); SleepHelper.PreventSleep(); if (args != null && args.Length > 0) { foreach (string arg in args) { if (arg.Contains(",")) { Logger.ColoredConsoleWrite(ConsoleColor.Green, $"Found coordinates in command line: {arg}"); if (File.Exists(lastcords)) { Logger.ColoredConsoleWrite(ConsoleColor.Yellow, "Last coords file exists, trying to delete it"); File.Delete(lastcords); } cmdCoords = arg; } } } if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } if (!File.Exists(pokelog)) { File.Create(pokelog).Close(); } if (!File.Exists(manualTransferLog)) { File.Create(manualTransferLog).Close(); } if (!File.Exists(EvolveLog)) { File.Create(EvolveLog).Close(); } if (args != null && args.Length > 0 && args[0].Contains("-nogui")) { Logger.ColoredConsoleWrite(ConsoleColor.Red, "You added -nogui! If you didnt setup correctly with the GUI. It wont work."); int i = 1; //TODO Implement JSON Load if (Globals.usePwdEncryption) { Globals.password = Encryption.Decrypt(Globals.password); } if (cmdCoords != string.Empty) { string[] crdParts = cmdCoords.Split(','); Globals.latitute = double.Parse(crdParts[0].Replace(',', '.'), GUI.cords, System.Globalization.NumberFormatInfo.InvariantInfo); Globals.longitude = double.Parse(crdParts[1].Replace(',', '.'), GUI.cords, System.Globalization.NumberFormatInfo.InvariantInfo); } Logger.ColoredConsoleWrite(ConsoleColor.Yellow, $"Starting at: {Globals.latitute},{Globals.longitude}"); } else { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new GUI()); if (Globals.pokeList) { Task.Run(() => { if (Globals.simulatedPGO) { var pokemonList = new GameAspectSimulator(); pokemonList.ShowDialog(); } else { var pokemonList = new Pokemons(); pokemonList.ShowDialog(); } }); } } Logger.SetLogger(new Logging.ConsoleLogger(LogLevel.Info)); Globals.infoObservable.HandleNewHuntStats += SaveHuntStats; Task.Run(() => { CheckVersion(); try { new Logic.Logic(new Settings(), Globals.infoObservable).Execute().Wait(); } catch (PtcOfflineException) { Logger.ColoredConsoleWrite(ConsoleColor.Red, "PTC Servers are probably down OR you credentials are wrong.", LogLevel.Error); Logger.ColoredConsoleWrite(ConsoleColor.Red, "Trying again in 20 seconds..."); Thread.Sleep(20000); new Logic.Logic(new Settings(), Globals.infoObservable).Execute().Wait(); } catch (AccountNotVerifiedException) { Logger.ColoredConsoleWrite(ConsoleColor.Red, "Your PTC Account is not activated. Exiting in 10 Seconds."); Thread.Sleep(10000); Environment.Exit(0); } catch (Exception ex) { Logger.ColoredConsoleWrite(ConsoleColor.Red, $"Unhandled exception: {ex}", LogLevel.Error); Logger.Error("Restarting in 20 Seconds."); Thread.Sleep(20000); new Logic.Logic(new Settings(), Globals.infoObservable).Execute().Wait(); } }); System.Console.ReadLine(); SleepHelper.AllowSleep(); }
static void Main(string[] args) { var openGUI = false; // Review & parse command line arguments if (args != null && args.Length > 0) { #region Parse Arguments foreach (string arg in args) { // First of all. // We check if bot have called clicking in a pokesnimer URI: pokesniper2://PokemonName/latitude,longitude if (args[0].Contains("pokesniper2") || args[0].Contains("msniper")) { // If yes, We create a temporary file to share with main process, and close. SharePokesniperURI(args[0]); return; } #region Argument -nogui if (arg.Contains("-nogui")) { Logger.ColoredConsoleWrite(ConsoleColor.Red, "You added -nogui!"); #region Read bot settings if (File.Exists(Program.accountProfiles)) { string JSONstring = File.ReadAllText(accountProfiles); var Profiles = Newtonsoft.Json.JsonConvert.DeserializeObject <Collection <Profile> >(JSONstring); Profile selectedProfile = null; foreach (Profile _profile in Profiles) { if (_profile.IsDefault) { selectedProfile = _profile; break; } } if (selectedProfile != null) { var filenameProf = Path.Combine(path, $"{selectedProfile.ProfileName}.json"); selectedProfile.Settings = ProfileSettings.LoadFromFile(filenameProf); selectedProfile.Settings.SaveToGlobals(); } else { Logger.ColoredConsoleWrite(ConsoleColor.Red, "Default Profile not found! You didn't setup the bot correctly by running it with -nogui."); Environment.Exit(-1); } } else { Logger.ColoredConsoleWrite(ConsoleColor.Red, "You have not setup the bot yet. Run it without -nogui to Configure."); Environment.Exit(-1); } if (GlobalVars.UsePwdEncryption) { GlobalVars.Password = Encryption.Decrypt(GlobalVars.Password); } #endregion } #endregion #region Argument Coordinates if (arg.Contains(",")) { if (File.Exists(LastCoordsTXTFileName)) { Logger.ColoredConsoleWrite(ConsoleColor.Yellow, "Last coords file exists, trying to delete it"); File.Delete(LastCoordsTXTFileName); } string[] crdParts = arg.Split(','); GlobalVars.latitude = double.Parse(crdParts[0].Replace(',', '.'), GUI.cords, System.Globalization.NumberFormatInfo.InvariantInfo); GlobalVars.longitude = double.Parse(crdParts[1].Replace(',', '.'), GUI.cords, System.Globalization.NumberFormatInfo.InvariantInfo); Logger.ColoredConsoleWrite(ConsoleColor.Yellow, $"Found coordinates in command line. Starting at: {GlobalVars.latitude},{GlobalVars.longitude},{GlobalVars.altitude}"); } #endregion #region Argument -bypassversioncheck if (arg.ToLower().Contains("-bypassversioncheck")) { GlobalVars.BypassCheckCompatibilityVersion = true; } #endregion #region Argument -help if (arg.ToLower().Contains("-help")) { //Show Help System.Console.WriteLine($"Pokemon BOT C# v{Resources.BotVersion.ToString()} help" + Environment.NewLine); System.Console.WriteLine("Use:"); System.Console.WriteLine(" -nogui <lat>,<long> Console mode only, starting on the indicated Latitude & Longitude"); System.Console.WriteLine(" -bypassversioncheck Do NOT check BOT & API compatibility (be careful with that option!)"); System.Console.WriteLine(" -help This help" + Environment.NewLine); Environment.Exit(0); } #endregion } } else { openGUI = true; } #endregion // Checking if current BOT API implementation supports NIANTIC current API (unless there's an override command line switch) if (!GlobalVars.BypassCheckCompatibilityVersion) { Logger.ColoredConsoleWrite(ConsoleColor.DarkMagenta, $"Bot Current version: {Resources.BotVersion}"); Logger.ColoredConsoleWrite(ConsoleColor.DarkMagenta, $"Bot Supported API version: {Resources.BotApiSupportedVersion}"); Logger.ColoredConsoleWrite(ConsoleColor.DarkMagenta, $"Current API version: {new CurrentAPIVersion().GetNianticAPIVersion()}"); bool CurrentVersionsOK = new CurrentAPIVersion().CheckAPIVersionCompatibility(GlobalVars.BotApiSupportedVersion); if (!CurrentVersionsOK) { Logger.ColoredConsoleWrite(ConsoleColor.Red, $"Atention, current API version is new and still not supported by Bot."); Logger.ColoredConsoleWrite(ConsoleColor.Red, $"Bot will now exit to keep your account safe."); Logger.ColoredConsoleWrite(ConsoleColor.Red, $"---------- PRESS ANY KEY TO CLOSE ----------"); System.Console.ReadKey(); Environment.Exit(-1); } } // Check if Bot is deactivated at server level StringUtils.CheckKillSwitch(); // Check if a new version of BOT is available CheckVersion(); if (openGUI) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new GUI()); Task.Run(() => { new Panels.SplashScreen().ShowDialog(); }); openGUI = GlobalVars.EnablePokeList; if (GlobalVars.EnableConsoleInTab) { Logger.type = 1; } // To open tabbed GUI to test programing /* * Pokemons.skipReadyToUse = true; * Application.Run( new Pokemons()); * Environment.Exit(0); */ } SleepHelper.PreventSleep(); CreateLogDirectories(); GlobalVars.infoObservable.HandleNewHuntStats += SaveHuntStats; Task.Run(() => { do { try { DeviceSetup.SelectDevice(GlobalVars.DeviceTradeName, GlobalVars.DeviceID, deviceData); new Logic.Logic(new Settings(), GlobalVars.infoObservable).Execute(); } catch (Exception ex) { Logger.Error($"Unhandled exception: {ex}"); } Logger.Error("Restarting in 20 Seconds."); Thread.Sleep(20000); }while (Logic.Logic.restartLogic); }); if (openGUI) { if (GlobalVars.simulatedPGO) { Application.Run(new GameAspectSimulator()); } else { if (GlobalVars.EnableConsoleInTab) { FreeConsole(); } Application.Run(new TabbedSystem()); } } else { System.Console.ReadLine(); } SleepHelper.AllowSleep(); }
private void RePlayThread() { Task.Run(() => { double sendDelay = 0.000005; _signalJump = false; _signalEnd = false; if (_watch.IsRunning) { _watch.Restart(); } else { _watch.Reset(); } while (true) { var pkg = _reader.Get(); if (pkg == null) { if (_signalEnd || _signalJump) { if (_watch.IsRunning) { _watch.Restart(); } else { _watch.Reset(); } _signalJump = false; } SleepHelper.Delay(); continue; } //Logger.Debug.WriteLine(pkg.index); //int c = 0, d = 0; foreach (var msg in pkg.GetMessages()) { var sendTiming = (msg.header.time - pkg.time) / SpeedRate; while (_watch.Elapsed.TotalSeconds + _sleepDelay + sendDelay < sendTiming) { if (_signalJump) { RePlayThread(); return; } //if (_watch.Elapsed.TotalSeconds + _sleepDelay + sendDelay < sendTiming) //{ //c++; //var a = _watch.Elapsed.TotalSeconds + _sleepDelay + sendDelay - sendTiming; SleepHelper.Delay(); //if (_watch.Elapsed.TotalSeconds + _sleepDelay + sendDelay < sendTiming) //{ // var aa = _watch.Elapsed.TotalSeconds + _sleepDelay + sendDelay - sendTiming; // var aaa = a - aa; //} //} //else //{ // d++; //} } _map.TryGetValue(ConverToIP64(msg.header.ip, msg.header.port), out var point); if (point == null) { continue; } _msgForSend.Enqueue(new SendInfo() { bytes = msg.bytes, point = point }); //_sendHandler?.Invoke(msg.bytes.Span, point); } // 发送下一个 pkg 之前的延时 while (_watch.Elapsed.TotalSeconds + _sleepDelay < _reader.Interval / SpeedRate) { if (_signalJump) { RePlayThread(); return; } //if (_watch.Elapsed.TotalSeconds + _sleepDelay < _reader.Interval / SpeedRate) //{ SleepHelper.Delay(); //} } // Core 中不应该有直接输出 //Logger.Debug.WriteLine(pkg.index + " " + _watch.Elapsed.TotalSeconds); _infos.Enqueue(new ReplayInfo() { time = new DateTime((long)(pkg.time * 1e7)).AddYears(1970 - 1).AddDays(-1), index = pkg.index, pkgCostTime = _watch.Elapsed.TotalSeconds //pkgCostTime = (pkg.GetMessages().First().header.time - pkg.time) / SpeedRate }); // 播放完毕 if (pkg.index >= _reader.Count - 1) { _signalEnd = true; } else { _signalEnd = false; } // 需要在所有使用 pkg 的代码完成后再归还 // 缓解内存压力 _reader.Return(ref pkg); _watch.Restart(); } }); }