示例#1
0
        // TODO validator can be outside from setting
        private void TextBoxWorkerName_TextChanged(object sender, TextChangedEventArgs e)
        {
            var trimmedWorkerNameText = textBoxWorkerName.Text.Trim();
            var result = ApplicationStateManager.SetWorkerIfValidOrDifferent(trimmedWorkerNameText);

            ValidateWorkername();
        }
示例#2
0
        public static async Task DownloadUpdaterAsync(Progress <int> downloadProgress)
        {
            try
            {
                var url = ApplicationStateManager.GetNewVersionUpdaterUrl();
                var downloadRootPath = Path.Combine(Paths.Root, "updaters");
                if (!Directory.Exists(downloadRootPath))
                {
                    Directory.CreateDirectory(downloadRootPath);
                }
                var(success, downloadedFilePath) = await MinersDownloadManager.DownloadFileWebClientAsync(url, downloadRootPath, $"nhm_windows_updater_{ApplicationStateManager.OnlineVersion}", downloadProgress, ApplicationStateManager.ExitApplication.Token);

                if (!success || ApplicationStateManager.ExitApplication.Token.IsCancellationRequested)
                {
                    return;
                }

                // stop devices
                ApplicationStateManager.StopAllDevice();

                using (var updater = new Process())
                {
                    updater.StartInfo.UseShellExecute = false;
                    updater.StartInfo.FileName        = downloadedFilePath;
                    updater.Start();
                }
            } catch (Exception ex)
            {
                Logger.Error("UpdateHelpers", $"Updating failed: {ex.Message}");
            }
        }
示例#3
0
        private async void TextBoxBitcoinAddress_TextChanged(object sender, TextChangedEventArgs e)
        {
            var trimmedBtcText = textBoxBTCAddress.Text.Trim();
            var result         = await ApplicationStateManager.SetBTCIfValidOrDifferent(trimmedBtcText);

            ValidateBTCAddr();
        }
示例#4
0
        private void SettingsButton_Click(object sender, RoutedEventArgs e)
        {
            ApplicationStateManager.CurrentForm = ApplicationStateManager.CurrentFormState.Settings;

            using (var settings = new SettingsWindow())
            {
                settings.ShowDialog();

                if (settings.RestartRequired)
                {
                    if (!settings.DefaultsSet)
                    {
                        MessageBox.Show(
                            Translations.Tr("Settings change requires {0} to restart.", NHMProductInfo.Name),
                            Translations.Tr("Restart Notice"),
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                    ApplicationStateManager.RestartProgram();
                    Close();
                }
            }

            ApplicationStateManager.CurrentForm = ApplicationStateManager.CurrentFormState.Main;
        }
示例#5
0
        private async Task ProcessQRCode()
        {
            stopWatch = new Stopwatch();
            stopWatch.Start();

            var rigID = ApplicationStateManager.RigID();

            var requestBody = "{\"qrId\":\"" + _uuid + "\", \"rigId\":\"" + rigID + "\"}";
            var content     = new StringContent(requestBody, Encoding.UTF8, "application/json");

            using (var client = new HttpClient())
            {
                var response = await client.PostAsync("https://api2.nicehash.com/api/v2/organization/nhmqr", content);

                // create qr code
                rect_qrCode.Fill = QrCodeHelpers.GetQRCode(_uuid, GUISettings.Instance.DisplayTheme == "Light");

                while (true)
                {
                    await Task.Delay(5000);

                    if (stopWatch.ElapsedMilliseconds >= (1000 * 60 * 10))
                    {
                        lbl_qr_status.Visibility = Visibility.Visible;
                        btn_gen_qr.Visibility    = Visibility.Visible;
                        lbl_qr_status.Content    = "QR Code timeout. Please generate new one.";
                        return;
                    }
                }
            }
        }
        public static async Task MinerStatsCheck()
        {
            await _semaphore.WaitAsync();

            try
            {
                foreach (var m in _runningMiners.Values)
                {
                    // skip if not running or if await already in progress
                    if (!m.IsRunning || m.IsUpdatingApi)
                    {
                        continue;
                    }
                    var ad = m.GetSummaryAsync();
                }
                // Update GUI
                ApplicationStateManager.RefreshRates();
                // now we shoud have new global/total rate display it
                var kwhPriceInBtc = ExchangeRateApi.GetKwhPriceInBtc();
                var profitInBTC   = MiningStats.GetProfit(kwhPriceInBtc);
                ApplicationStateManager.DisplayTotalRate(profitInBTC);
            }
            catch (Exception e)
            {
                Logger.Error(Tag, $"Error occured while getting mining stats: {e.Message}");
            }
            finally
            {
                _semaphore.Release();
            }
            // TODO put this somewhere else maybe
            await RestartStagnatedMiners();
        }
示例#7
0
 public void SetNoDeviceAction()
 {
     ApplicationStateManager.NoDeviceAction = () =>
     {
         this.Dispatcher.Invoke(() =>
         {
             var nhmNoDeviceDialog = new CustomDialog()
             {
                 Title            = Translations.Tr("No Supported Devices"),
                 Description      = Translations.Tr("No supported devices are found. Select the OK button for help or cancel to continue."),
                 OkText           = Translations.Tr("OK"),
                 CancelText       = Translations.Tr("Cancel"),
                 AnimationVisible = Visibility.Collapsed
             };
             nhmNoDeviceDialog.OKClick += (s, e) =>
             {
                 Process.Start(Links.NhmNoDevHelp);
             };
             nhmNoDeviceDialog.OnExit += (s, e) =>
             {
                 ApplicationStateManager.ExecuteApplicationExit();
             };
             ShowContentAsModalDialog(nhmNoDeviceDialog);
         });
     };
 }
        private void OnAcceptOrDecline(object sender, RoutedEventArgs e)
        {
            _pluginsToAccept--;
            if (_pluginsToAccept == 0)
            {
                CustomDialogManager.HideCurrentModal();
                var nhmRestartDialog = new CustomDialog()
                {
                    Title            = Tr("Restart NiceHash Miner"),
                    Description      = Tr("NiceHash Miner restart is required."),
                    OkText           = Tr("Restart"),
                    AnimationVisible = Visibility.Collapsed,
                    CancelVisible    = Visibility.Collapsed,
                    ExitVisible      = Visibility.Collapsed,
                };
                nhmRestartDialog.OKClick += (s, e1) => {
                    Task.Run(() => ApplicationStateManager.RestartProgram());
                };
                CustomDialogManager.ShowModalDialog(nhmRestartDialog);

                var nhmRestartingDialog = new CustomDialog()
                {
                    Title            = Tr("NiceHash Miner Restarting"),
                    Description      = Tr("NiceHash Miner restart in progress."),
                    CancelVisible    = Visibility.Collapsed,
                    OkVisible        = Visibility.Collapsed,
                    AnimationVisible = Visibility.Visible,
                    ExitVisible      = Visibility.Collapsed
                };
                CustomDialogManager.ShowModalDialog(nhmRestartingDialog);
            }
        }
示例#9
0
        private async Task InitQRCode()
        {
            // this is vaild for 10 minutes
            _uuid      = Guid.NewGuid().ToString();
            _gotQRCode = await QrCodeGenerator.RequestNew_QR_Code(_uuid, ApplicationStateManager.RigID());

            if (_gotQRCode)
            {
                // create qr code
                var(image, ok) = QrCodeImageGenerator.GetQRCodeImage(_uuid);
                if (ok)
                {
                    rect_qrCode.Fill          = image;
                    ScanLabel.Content         = "Scan with official NiceHash mobile application";
                    ScanConfirmButton.Content = "Confirm scan";
                }
                else
                {
                    ScanLabel.Content            = "QR Code image generation failed";
                    ScanConfirmButton.Visibility = Visibility.Collapsed;
                }
            }
            else
            {
                ScanConfirmButton.Visibility = Visibility.Collapsed;
                ScanLabel.Content            = "Unable to retreive QR Code";
                //ScanConfirmButton.Content = "Retry QR code";
            }
        }
示例#10
0
        private static Task SetVersion(string data)
        {
            dynamic message = JsonConvert.DeserializeObject(data);
            string  version = message.v3.Value;

            ApplicationStateManager.OnVersionUpdate(version);
            return(Task.Delay(0));
        }
示例#11
0
 private void StatsHyperlink_OnClick(object sender, RoutedEventArgs e)
 {
     if (ConfigManager.CredentialsSettings.IsCredentialsValid == false)
     {
         return;
     }
     ApplicationStateManager.VisitMiningStatsPage();
 }
 static public ApplicationStateManager GetInstance()
 {
     if (m_instance == null)
     {
         m_instance = new ApplicationStateManager();
     }
     return(m_instance);
 }
示例#13
0
        void GameplayStateUpdate(SinglePlayerInputs _p1Inputs, SinglePlayerInputs _p2Inputs, bool skipRender = false)
        {
            //1.1 Check for pause? todo
            if (CurrentSplashState.CurrentState == SplashState.State.GameOver)
            {
                //check if any button is pressed to start a new game
                if (_p1Inputs.A || _p1Inputs.B || _p1Inputs.C || _p1Inputs.Start ||
                    _p2Inputs.A || _p2Inputs.B || _p2Inputs.C || _p2Inputs.Start)
                {
                    ApplicationStateManager.GetInstance().SetCharacterSelectScreen(m_setData);
                }
            }
            else if (UpdateSplashScreen())
            {
            }
            else if (m_previousState.RemainingHitstop > 0)
            {
                m_previousState.RemainingHitstop--;
            }
            else
            {
                //2. Sees if the inputs can be applied to current action
                GameState currentState = UpdateGameStateWithInputs(_p1Inputs, _p2Inputs, m_previousState);
                m_p1LastInputs = _p1Inputs;
                m_p2LastInputs = _p2Inputs;

                //3. Resolves actions
                MatchOutcome outcome = ResolveActions(_p1Inputs, _p2Inputs, currentState);



                //4. Checks if the match is over
                if (outcome.IsEnd())
                {
                    //Extra render on game end?
                    GameplayRendererObject.RenderScene(m_previousState, Match, CurrentSplashState);
                    HandleOutcome(outcome);
                    CurrentSplashState.CurrentState    = SplashState.State.RoundOver_ShowResult;
                    CurrentSplashState.FramesRemaining = GameplayConstants.FRAMES_END_ROUND_SPLASH;


                    //camera tests
                    //isPanning = true;
                    isRotating = true;
                }
                --currentState.RemainingTime;
                m_previousStates.Add(currentState);
            }
            if (!skipRender)
            {
                //5. Render Scene
                GameplayRendererObject.RenderScene(m_previousState, Match, CurrentSplashState);

                //6. Camera Tests
                CameraMoveTest(Match);
            }
        }
        public static void InitializeConfig()
        {
            // init defaults
            GeneralConfig.SetDefaults();
            ToSSetings.Instance.Hwid = ApplicationStateManager.RigID();

            var asmVersion = new Version(Application.ProductVersion);

            // load file if it exist
            var fromFile = InternalConfigs.ReadFileSettings <GeneralConfig>(GeneralConfigPath);

            if (fromFile != null)
            {
                if (fromFile.ConfigFileVersion != null && asmVersion.CompareTo(fromFile.ConfigFileVersion) != 0)
                {
                    IsVersionChanged = true;
                    Logger.Info(Tag, "Config file differs from version of NiceHashMiner... Creating backup archive");
                    CreateBackupArchive(fromFile.ConfigFileVersion);
                    if (RestoreBackupArchive(asmVersion))//check if we have backup version
                    {
                        fromFile = InternalConfigs.ReadFileSettings <GeneralConfig>(GeneralConfigPath);
                    }
                }
                if (fromFile?.ConfigFileVersion != null)
                {
                    GeneralConfig = fromFile;
                    GeneralConfig.FixSettingBounds();
                    // TODO temp
                    GeneralConfig.PropertyChanged += BalanceAndExchangeRates.Instance.GeneralConfig_PropertyChanged;
                }
                else
                {
                    Logger.Info(Tag, "Loaded Config file no version detected falling back to defaults.");
                }
            }
            else
            {
                GeneralConfigFileCommit();
            }

            //Init Blacklist plugins
            var blacklistFile = InternalConfigs.ReadFileSettings <BlacklistedPlugins>(BlacklistedPluginsPath);

            if (blacklistFile != null)
            {
                if (blacklistFile?.BlacklistedPluginUUIDs != null)
                {
                    BlacklistedPlugins.Instance.BlacklistedPluginUUIDs = blacklistFile.BlacklistedPluginUUIDs;
                }
            }
            else
            {
                BlacklistPluginsCommit();
            }
        }
示例#15
0
        public static void CreateMissingMinersInfo()
        {
            var notification = new Notification(NotificationsType.Error, NotificationsGroup.MissingMiners, Tr("Missing miner files"), Tr("There are missing files from last Miners Initialization. Please make sure that the file is accessible and that your anti-virus is not blocking the application. NiceHash Miner might not work properly without missing files. Please check the following blog post: {0}", Links.AVHelp));

            notification.Action = new NotificationAction
            {
                Info   = Tr("Restart NiceHash Miner"),
                Action = () => { _ = ApplicationStateManager.RestartProgram(); }
            };
            NotificationsManager.Instance.AddNotificationToList(notification);
        }
        public override ValidationResult Validate(string value, CultureInfo cultureInfo)
        {
            var result = ApplicationStateManager.SetWorkerIfValidOrDifferent(value);

            if (result == ApplicationStateManager.SetResult.INVALID)
            {
                return(new ValidationResult(false, Translations.Tr("Invalid workername!\n\nPlease enter a valid workername (Aa-Zz, 0-9, up to 15 character long).")));
            }

            return(ValidationResult.ValidResult);
        }
        public override ValidationResult Validate(string value, CultureInfo cultureInfo)
        {
            var result = ApplicationStateManager.SetBTCIfValidOrDifferent(value);

            if (result == ApplicationStateManager.SetResult.INVALID)
            {
                return(new ValidationResult(false, Translations.Tr("Invalid Bitcoin address! {0} will start mining in DEMO mode. In the DEMO mode, you can test run the miner and be able see how much you can earn using your computer. Would you like to continue in DEMO mode?\n\nDISCLAIMER: YOU WILL NOT EARN ANYTHING DURING DEMO MODE!", NHMProductInfo.Name)));
            }

            return(ValidationResult.ValidResult);
        }
示例#18
0
    void OnGUI()
    {
        GUIStyle style = new GUIStyle();

        style.fontSize = 26;
        string currentGameStatus = ApplicationStateManager.GetCurrentStateName();

        int halfScreenWidth    = Screen.width / 2;
        int quarterScreenWidth = Screen.width / 4;


        GUI.TextArea(new Rect(halfScreenWidth - quarterScreenWidth, 10, halfScreenWidth + quarterScreenWidth, Screen.height / 2), currentGameStatus, style);
    }
示例#19
0
 private static Task HandleBurn(string data)
 {
     try
     {
         dynamic message = JsonConvert.DeserializeObject(data);
         ApplicationStateManager.Burn(message.message.Value);
     }
     catch (Exception e)
     {
         NHLog.Error("NHWebSocket", $"SetBalance error: {e.Message}");
     }
     return(Task.Delay(0));
 }
示例#20
0
        private async Task ProcessQRCode()
        {
            var rigID = ApplicationStateManager.RigID();

            var requestBody = "{\"qrId\":\"" + _uuid + "\", \"rigId\":\"" + rigID + "\"}";
            var content     = new StringContent(requestBody, Encoding.UTF8, "application/json");

            using (var client = new HttpClient())
            {
                var response = await client.PostAsync("https://api2.nicehash.com/api/v2/organization/nhmqr", content);
            }
            // create qr code
            rect_qrCode.Fill = QrCodeHelpers.GetQRCode(_uuid);
        }
示例#21
0
 private static void SetBalance(string balance)
 {
     try
     {
         if (double.TryParse(balance, NumberStyles.Float, CultureInfo.InvariantCulture, out var bal))
         {
             ApplicationStateManager.OnBalanceUpdate(bal);
         }
     }
     catch (Exception e)
     {
         NHM.Common.Logger.Error("SOCKET", $"SetBalance error: {e.Message}");
     }
 }
示例#22
0
        private static void stopMiningAllDevices()
        {
            var allDisabled = AvailableDevices.Devices.All(dev => dev.IsDisabled);

            if (allDisabled)
            {
                throw new RpcException("All devices are disabled cannot stop", ErrorCode.DisabledDevice);
            }
            var(success, msg) = ApplicationStateManager.StopAllDevice();
            if (!success)
            {
                throw new RpcException(msg, ErrorCode.RedundantRpc);
            }
        }
示例#23
0
        private async Task ProcessQRCode()
        {
            var rigID = ApplicationStateManager.RigID();

            var requestBody = "{\"qrId\":\"" + _uuid + "\", \"rigId\":\"" + rigID + "\"}";
            var content     = new StringContent(requestBody, Encoding.UTF8, "application/json");

            using (var client = new HttpClient())
            {
                var response = await client.PostAsync("https://api2.nicehash.com/api/v2/organization/nhmqr", content);
            }
            // create qr code
            rect_qrCode.Fill = QrCodeHelpers.GetQRCode(_uuid);

            //if all ok start timer to poll
            while (true)
            {
                await Task.Delay(2000);

                try
                {
                    using (var client = new HttpClient())
                    {
                        var resp = await client.GetAsync($"https://api2.nicehash.com/api/v2/organization/nhmqr/{_uuid}");

                        if (resp.IsSuccessStatusCode)
                        {
                            var contentString = await resp.Content.ReadAsStringAsync();

                            if (!string.IsNullOrEmpty(contentString))
                            {
                                var btcResp = JsonConvert.DeserializeObject <BtcResponse>(contentString);
                                if (btcResp.btc != null)
                                {
                                    if (CredentialValidators.ValidateBitcoinAddress(btcResp.btc))
                                    {
                                        CredentialsSettings.Instance.SetBitcoinAddress(btcResp.btc);
                                        Close();
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
        private static void SocketOnOnDataReceived(object sender, MessageEventArgs e)
        {
            try
            {
                if (e.IsText)
                {
                    NiceHashMinerLegacy.Common.Logger.Info("SOCKET", "Received: " + e.Data);
                    dynamic message = JsonConvert.DeserializeObject(e.Data);
                    switch (message.method.Value)
                    {
                    case "sma":
                    {
                        // Try in case stable is not sent, we still get updated paying rates
                        try
                        {
                            var stable = JsonConvert.DeserializeObject(message.stable.Value);
                            SetStableAlgorithms(stable);
                        } catch
                        { }
                        SetAlgorithmRates(message.data);
                        break;
                    }

                    case "markets":
                        HandleMarkets(e.Data);
                        break;

                    case "balance":
                        SetBalance(message.value.Value);
                        break;

                    case "versions":
                        SetVersion(message.legacy.Value);
                        break;

                    case "burn":
                        ApplicationStateManager.Burn(message.message.Value);
                        break;

                    case "exchange_rates":
                        SetExchangeRates(message.data.Value);
                        break;
                    }
                }
            } catch (Exception er)
            {
                NiceHashMinerLegacy.Common.Logger.Error("SOCKET", er.ToString());
            }
        }
        private static async Task GracefulShutdown()
        {
            try
            {
                Logger.Info(Tag, "Installer/uninstaller is running, attempting NHM shutdown");
                await ApplicationStateManager.BeforeExit();

                ApplicationStateManager.ExecuteApplicationExit();
                Logger.Info(Tag, "NHM closed successfully due to installer/uninstaller.");
            }
            catch (Exception ex)
            {
                Logger.Error(Tag, $"GracefulShutdown: {ex.Message}");
            }
        }
        private static void throwIfWeCannotHanldeRPC()
        {
            var rigStatusPending = ApplicationStateManager.CalcRigStatus() == RigStatus.Pending;
            var formState        = ApplicationStateManager.IsInBenchmarkForm() ? ". Rig is in benchmarks form" : "";

            if (ApplicationStateManager.IsInSettingsForm())
            {
                formState = ". Rig is in settings form";
            }
            // throw if pending
            if (rigStatusPending)
            {
                throw new RpcException($"Cannot handle RPC call Rig is in PENDING state{formState}", ErrorCode.UnableToHandleRpc);
            }
        }
示例#27
0
        protected override void HandleMenuResult(MenuResult _result)
        {
            if (_result == MenuResult.Continue)
            {
                MatchInitializationData matchInitData = new MatchInitializationData();
                matchInitData.P1_Character = DetermineSelectedCharacter(P1);
                matchInitData.P2_Character = DetermineSelectedCharacter(P2);
                m_currentSetData.SetMatchInitData(matchInitData);

                ApplicationStateManager.GetInstance().SetGameplayState(m_currentSetData);
            }
            else if (_result == MenuResult.Back)
            {
                ApplicationStateManager.GetInstance().SetMainMenu();//go to main menu
            }
        }
示例#28
0
        private static async Task <bool> startMiningAllDevices()
        {
            var allDisabled = AvailableDevices.Devices.All(dev => dev.IsDisabled);

            if (allDisabled)
            {
                throw new RpcException("All devices are disabled cannot start", ErrorCode.DisabledDevice);
            }
            var(success, msg) = await ApplicationStateManager.StartAllAvailableDevicesTask();

            if (!success)
            {
                throw new RpcException(msg, ErrorCode.RedundantRpc);
            }
            return(true);
        }
示例#29
0
        private static bool CheckIfShouldMine(double currentProfit, bool log = true)
        {
            var isProfitable = CheckIfProfitable(currentProfit, log);

            ApplicationStateManager.SetProfitableState(isProfitable);
            ApplicationStateManager.DisplayNoInternetConnection(!_isConnectedToInternet);

            if (!_isConnectedToInternet && log)
            {
                Logger.Info(Tag, $"No internet connection! Not able to mine.");
            }

            // if profitable and connected to internet mine
            var shouldMine = isProfitable && _isConnectedToInternet;

            return(shouldMine);
        }
示例#30
0
 static public void UnsubscribeAllControls(Control c)
 {
     if (c is IDataVisualizer dv)
     {
         ApplicationStateManager.UnsubscribeStateDisplayer(dv);
     }
     // setters
     if (c is IEnabledDeviceStateSetter setter)
     {
         setter.SetDeviceEnabledState -= ApplicationStateManager.SetDeviceEnabledState;
     }
     // call on all controls
     foreach (Control childC in c.Controls)
     {
         SubscribeAllControls(childC);
     }
 }