// TODO this has nothing to do with Mian_Form private async void IdleCheck(object sender, IdleChangedEventArgs e) { if (!ConfigManager.GeneralConfig.StartMiningWhenIdle || _isManuallyStarted) { return; } // TODO set is mining here if (MiningState.Instance.IsCurrentlyMining) { if (!e.IsIdle) { await ApplicationStateManager.StopAllDevice(); Logger.Info("NICEHASH", "Resumed from idling"); } } else if (ApplicationStateManager.CurrentForm == ApplicationStateManager.CurrentFormState.Main && e.IsIdle) { Logger.Info("NICEHASH", "Entering idling state"); if (StartMining(false) != StartMiningReturnType.StartMining) { await ApplicationStateManager.StopAllDevice(); } } }
private void UpdateExchange(object sender, EventArgs e) { FormHelpers.SafeInvoke(this, () => { var br = ExchangeRateApi.GetUsdExchangeRate(); var currencyRate = Tr("N/A"); if (br > 0) { currencyRate = ExchangeRateApi.ConvertToActiveCurrency(br).ToString("F2"); } toolTip1.SetToolTip(statusStrip1, $"1 BTC = {currencyRate} {ExchangeRateApi.ActiveDisplayCurrency}"); Logger.Info("NICEHASH", $"Current Bitcoin rate: {br.ToString("F2", CultureInfo.InvariantCulture)}"); }); }
static public async Task Start(string address, CancellationToken token) { try { var random = new Random(); _address = address; NHLog.Info("NHWebSocket-WD", "Starting nhmws watchdog"); // TODO use this or just use the application exit source while (!token.IsCancellationRequested) { try { await NewConnection(token); // after each connection is completed check if we should re-connect or exit the watchdog // if we didn't initialize the restart delay reconnect if (!_isNhmwsRestart && !token.IsCancellationRequested) { // delays re-connect 10 to 30 seconds var delaySeconds = 10 + random.Next(0, 20); NHLog.Info("NHWebSocket-WD", $"Attempting reconnect in {delaySeconds} seconds"); await TaskHelpers.TryDelay(TimeSpan.FromSeconds(delaySeconds), token); } else if (_isNhmwsRestart && !token.IsCancellationRequested) { NHLog.Info("NHWebSocket-WD", $"Restarting nhmws SESSION"); } } catch (TaskCanceledException e) { NHLog.Debug("NHWebSocket-WD", $"TaskCanceledException {e.Message}"); return; } catch (Exception e) { NHLog.Error("NHWebSocket-WD", $"Error occured: {e.Message}"); } } } finally { NHLog.Info("NHWebSocket-WD", "Ending nhmws watchdog"); } }
static private async Task HandleMessage(MessageEventArgs e) { try { if (e.IsText) { NHLog.Info("NHWebSocket", $"Received: {e.Data}"); var method = GetMethod(e.Data); if (IsRpcMethod(method)) { await HandleRpcMessage(method, e.Data); } else { await HandleNonRpcMessage(method, e.Data); } } } catch (Exception ex) { NHLog.Error("NHWebSocket", $"HandleMessage {ex.Message}"); } }
static private void Login(object sender, EventArgs e) { NHLog.Info("NHWebSocket", "Connected"); ApplicationStateManager.SetNhmwsConnectionChanged(true); try { // always send login var loginJson = JsonConvert.SerializeObject(_login); var sendMessages = new List <NHSendMessage> { new NHSendMessage(MessageType.SEND_MESSAGE, loginJson) }; if (CredentialValidators.ValidateBitcoinAddress(_login.btc)) { var minerStatusJsonStr = CreateMinerStatusMessage(true); sendMessages.Add(new NHSendMessage(MessageType.SEND_MESSAGE_STATUS, minerStatusJsonStr)); } _sendQueue.Enqueue(sendMessages); } catch (Exception er) { NHLog.Info("NHWebSocket", er.Message); } }
// TODO this thing needs to be completely removed // TODO this will be moved outside of GUI code, replace textBoxBTCAddress.Text with ConfigManager.GeneralConfig.BitcoinAddress private StartMiningReturnType StartMining(bool showWarnings) { //if (ConfigManager.GeneralConfig.BitcoinAddress.Equals("")) //{ // if (showWarnings) // { // var result = MessageBox.Show(Tr("You have not entered a 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!"), // Tr("Start mining in DEMO mode?"), // MessageBoxButtons.YesNo, MessageBoxIcon.Warning); // if (result == DialogResult.Yes) // { // _demoMode = true; // //labelDemoMode.Visible = true; // } // else // { // return StartMiningReturnType.IgnoreMsg; // } // } // else // { // return StartMiningReturnType.IgnoreMsg; // } //} ////else if (!VerifyMiningAddress(true)) return StartMiningReturnType.IgnoreMsg; // TODO this whole shitty thing var hasData = NHSmaData.HasData; if (!showWarnings) { for (var i = 0; i < 10; i++) { if (hasData) { break; } Thread.Sleep(1000); hasData = NHSmaData.HasData; Logger.Info("NICEHASH", $"After {i}s has data: {hasData}"); } } if (!hasData) { Logger.Debug("NICEHASH", "No data received within timeout"); if (showWarnings) { MessageBox.Show(Tr("Unable to get NiceHash profitability data. If you are connected to internet, try again later."), Tr("Error!"), MessageBoxButtons.OK, MessageBoxIcon.Error); } return(StartMiningReturnType.IgnoreMsg); } var isMining = true; ApplicationStateManager.StartAllAvailableDevices(); return(isMining ? StartMiningReturnType.StartMining : StartMiningReturnType.ShowNoMining); }
private static void Send(string data) { NHLog.Info("NHWebSocket", $"Sending data: {data}"); _webSocket?.Send(data); }
// TODO add cancelation token static private async Task NewConnection(CancellationToken stop) { NHLog.Info("NHWebSocket", "STARTING nhmws SESSION"); try { // TODO think if we might want to dump prev data???? // on each new connection clear the ConcurrentQueues, _recieveQueue = new ConcurrentQueue <MessageEventArgs>(); _sendQueue = new ConcurrentQueue <IEnumerable <NHSendMessage> >(); _isNhmwsRestart = false; _notifyMinerStatusAfter.Value = null; NHLog.Info("NHWebSocket", "Creating socket"); using (_webSocket = new WebSocket(_address)) { _webSocket.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12; //stop.Register(() => _webSocket.Close(CloseStatusCode.Normal, "Closing CancellationToken")); _webSocket.OnOpen += Login; _webSocket.OnMessage += (s, eMsg) => _recieveQueue.Enqueue(eMsg); _webSocket.OnError += (s, e) => NHLog.Info("NHWebSocket", $"Error occured: {e.Message}"); _webSocket.OnClose += (s, e) => NHLog.Info("NHWebSocket", $"Connection closed code {e.Code}: {e.Reason}");; _webSocket.Log.Level = LogLevel.Debug; _webSocket.Log.Output = (data, s) => NHLog.Info("NHWebSocket", data.ToString()); _webSocket.EnableRedirection = true; NHLog.Info("NHWebSocket", "Connecting"); _webSocket.Connect(); const int minerStatusTickSeconds = 45; var checkWaitTime = TimeSpan.FromMilliseconds(50); var skipMinerStatus = !CredentialValidators.ValidateBitcoinAddress(_login.btc); NHLog.Info("NHWebSocket", "Starting Loop"); while (IsWsAlive && !stop.IsCancellationRequested) { if (IsWsAlive) { HandleSendMessage(); } if (IsWsAlive) { await HandleReceiveMessage(); } // TODO add here the last miner status send check if (IsWsAlive) { await TaskHelpers.TryDelay(checkWaitTime, stop); } if (skipMinerStatus) { continue; } var elapsedTime = DateTime.UtcNow - _lastSendMinerStatusTimestamp.Value; if (elapsedTime.TotalSeconds > minerStatusTickSeconds) { var minerStatusJsonStr = CreateMinerStatusMessage(); var minerStatus = new NHSendMessage(MessageType.SEND_MESSAGE_STATUS, minerStatusJsonStr); _sendQueue.Enqueue(new NHSendMessage[1] { minerStatus }); } if (_notifyMinerStatusAfter.Value.HasValue && DateTime.UtcNow >= _notifyMinerStatusAfter.Value.Value) { _notifyMinerStatusAfter.Value = null; var minerStatusJsonStr = CreateMinerStatusMessage(); var minerStatus = new NHSendMessage(MessageType.SEND_MESSAGE_STATUS, minerStatusJsonStr); _sendQueue.Enqueue(new NHSendMessage[1] { minerStatus }); } } // Ws closed NHLog.Info("NHWebSocket", "Exited Loop"); } } catch (TaskCanceledException e) { NHLog.Debug("NHWebSocket", $"TaskCanceledException {e.Message}"); } finally { NHLog.Info("NHWebSocket", "ENDING nhmws SESSION"); ApplicationStateManager.SetNhmwsConnectionChanged(false); } }