示例#1
0
        private static Task SetExchangeRates(string origdata)
        {
            try
            {
                dynamic message  = JsonConvert.DeserializeObject(origdata);
                string  data     = message.data.Value;
                var     exchange = JsonConvert.DeserializeObject <ExchangeRateJson>(data);
                if (exchange?.exchanges_fiat == null || exchange.exchanges == null)
                {
                    return(Task.CompletedTask);
                }
                double usdBtcRate = -1;
                foreach (var exchangePair in exchange.exchanges)
                {
                    if (!exchangePair.TryGetValue("coin", out var coin) || coin != "BTC" ||
                        !exchangePair.TryGetValue("USD", out var usd) ||
                        !double.TryParse(usd, NumberStyles.Float, CultureInfo.InvariantCulture, out var usdD))
                    {
                        continue;
                    }

                    usdBtcRate = usdD;
                    break;
                }
                BalanceAndExchangeRates.Instance.UpdateExchangesFiat(usdBtcRate, exchange.exchanges_fiat);
            }
            catch (Exception e)
            {
                NHLog.Error("NHWebSocket", $"SetExchangeRates error: {e.Message}");
            }
            return(Task.CompletedTask);
        }
示例#2
0
        // 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();
                }
            }
        }
示例#3
0
        // TODO copy pasted crap from NiceHashStats
        #region NonRpcMessages
        #region SMA
        private static void SetAlgorithmRates(JArray data)
        {
            try
            {
                var payingDict = new Dictionary <AlgorithmType, double>();
                if (data != null)
                {
                    foreach (var algo in data)
                    {
                        var algoKey = (AlgorithmType)algo[0].Value <int>();
                        payingDict[algoKey] = algo[1].Value <double>();
                    }
                }

                NHSmaData.UpdateSmaPaying(payingDict);
                // TODO new check crap
                foreach (var dev in AvailableDevices.Devices)
                {
                    dev.UpdateEstimatePaying(payingDict);
                }
            }
            catch (Exception e)
            {
                NHLog.Error("NHWebSocket", $"SetAlgorithmRates error: {e.Message}");
            }
        }
示例#4
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.CompletedTask);
 }
示例#5
0
        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)}");
            });
        }
示例#6
0
 private static Task SetBalance(string data)
 {
     try
     {
         dynamic message = JsonConvert.DeserializeObject(data);
         string  balance = message.value.Value;
         if (double.TryParse(balance, NumberStyles.Float, CultureInfo.InvariantCulture, out var btcBalance))
         {
             BalanceAndExchangeRates.Instance.BtcBalance = btcBalance;
         }
     }
     catch (Exception e)
     {
         NHLog.Error("NHWebSocket", $"SetBalance error: {e.Message}");
     }
     return(Task.CompletedTask);
 }
示例#7
0
        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");
            }
        }
示例#8
0
        private static Task HandleMarkets(string data)
        {
            try
            {
                var markets = JsonConvert.DeserializeObject <MarketsMessage>(data);
                var hasEU   = markets.data.Contains("EU");
                var hasUSA  = markets.data.Contains("USA");
#if !DEBUG_MARKETS
                StratumService.Instance.SetEnabled(hasEU, hasUSA);
#else
                changeDebugMarkets();
                StratumService.Instance.SetEnabled(debugEU, debugUSA);
#endif
            }
            catch (Exception e)
            {
                NHLog.Error("NHWebSocket", $"HandleMarkets error: {e.Message}");
            }
            return(Task.CompletedTask);
        }
示例#9
0
 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}");
     }
 }
示例#10
0
 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);
     }
 }
示例#11
0
        // 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);
        }
示例#12
0
        private static string CreateMinerStatusMessage(bool sendDeviceNames = false)
        {
            var devices   = AvailableDevices.Devices;
            var rigStatus = ApplicationStateManager.CalcRigStatusString();
            var paramList = new List <JToken>
            {
                rigStatus
            };

            var deviceList = new JArray();

            foreach (var device in devices)
            {
                try
                {
                    var array = new JArray
                    {
                        sendDeviceNames?device.Name : "",
                         device.B64Uuid // TODO
                    };
                    var status = DeviceReportStatus(device.DeviceType, device.State);
                    array.Add(status);

                    array.Add((int)Math.Round(device.Load));

                    var speedsJson = new JArray();
                    var speeds     = MiningDataStats.GetSpeedForDevice(device.Uuid);
                    if (speeds != null && device.State == DeviceState.Mining)
                    {
                        foreach (var kvp in speeds)
                        {
                            speedsJson.Add(new JArray((int)kvp.type, kvp.speed));
                        }
                    }
                    array.Add(speedsJson);

                    // Hardware monitoring
                    array.Add((int)Math.Round(device.Temp));
                    array.Add(device.FanSpeed);
                    array.Add((int)Math.Round(device.PowerUsage));

                    // Power mode
                    array.Add((int)device.TDPSimple);

                    // Intensity mode
                    array.Add(0);

                    deviceList.Add(array);
                }
                catch (Exception e)
                {
                    NHLog.Error("NHWebSocket", e.Message);
                }
            }

            paramList.Add(deviceList);

            var data = new MinerStatusMessage
            {
                param = paramList
            };
            var sendData = JsonConvert.SerializeObject(data);

            return(sendData);
        }
示例#13
0
 private static void Send(string data)
 {
     NHLog.Info("NHWebSocket", $"Sending data: {data}");
     _webSocket?.Send(data);
 }
示例#14
0
        // 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);
            }
        }
示例#15
0
        static private async Task HandleRpcMessage(string method, string data)
        {
            string       btc          = null;
            string       worker       = null;
            string       group        = null;
            int          rpcId        = -1;
            bool         executed     = false;
            bool         loginNeeded  = false;
            ExecutedCall executedCall = null;
            string       rpcAnswer    = "";

            try
            {
                _isInRPC.Value = true;
                dynamic message     = JsonConvert.DeserializeObject(data);
                int?    rpcIdOption = (int?)message.id;
                rpcId = rpcIdOption ?? -1;

                ThrowIfWeCannotHanldeRPC();
                switch (method)
                {
                case "mining.set.username":
                    btc      = (string)message.username;
                    executed = await miningSetUsername(btc);

                    loginNeeded = executed;
                    break;

                case "mining.set.worker":
                    worker      = (string)message.worker;
                    executed    = miningSetWorker(worker);
                    loginNeeded = executed;
                    break;

                case "mining.set.group":
                    group       = (string)message.group;
                    executed    = miningSetGroup(group);
                    loginNeeded = executed;
                    break;

                case "mining.enable":
                    executed = await SetDevicesEnabled((string)message.device, true);

                    break;

                case "mining.disable":
                    executed = await SetDevicesEnabled((string)message.device, false);

                    break;

                case "mining.start":
                    executed = await StartMining((string)message.device);

                    break;

                case "mining.stop":
                    executed = await StopMining((string)message.device);

                    break;

                case "mining.set.power_mode":
                    // TODO not supported atm
                    SetPowerMode((string)message.device, (TDPSimpleType)message.power_mode);
                    break;

                case "miner.reset":
                    rpcAnswer = MinerReset((string)message.level);
                    break;

                default:
                    throw new RpcException($"RpcMessage operation not supported for method '{method}'", ErrorCode.UnableToHandleRpc);
                }
                if (!string.IsNullOrEmpty(rpcAnswer))
                {
                    executedCall = new ExecutedCall(rpcId, 0, rpcAnswer);
                }
                else
                {
                    executedCall = new ExecutedCall(rpcId, 0, null);
                }
            }
            catch (RpcException rpcEx)
            {
                executedCall = new ExecutedCall(rpcId, rpcEx.Code, rpcEx.Message);
            }
            catch (Exception e)
            {
                NHLog.Error("NHWebSocket", $"Non RpcException - error: {e.Message}");
                // intenral nhm error
                if (executedCall == null)
                {
                    executedCall = new ExecutedCall(rpcId, 1, "Internal NiceHash Miner Error");
                }
            }
            finally
            {
                _isInRPC.Value = false;
                if (executedCall != null)
                {
                    // send miner status and send executed
                    var minerStatusMsg = CreateMinerStatusMessage();
                    Send(minerStatusMsg);
                    _lastSendMinerStatusTimestamp.Value = DateTime.UtcNow;
                    // Then executed
                    var rpcMessage = executedCall.Serialize();
                    Send(rpcMessage);
                    // Login if we have to
                    if (loginNeeded)
                    {
                        SetCredentials(btc, worker, group);
                    }
                }
            }
        }