static public async Task Start(string address, CancellationToken token) { var random = new Random(); _address = address; NHLog.Info("NHWebSocket-WD", "Starting nhmws watchdog"); NHSmaData.InitializeIfNeeded(); // TODO use this or just use the application exit source while (!token.IsCancellationRequested) { try { await NewConnection(token); } catch (Exception e) { NHLog.Error("NHWebSocket-WD", $"Error occured: {e.Message}"); } // 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 Task.Delay(delaySeconds * 1000, token); } else if (_isNhmwsRestart && !token.IsCancellationRequested) { NHLog.Info("NHWebSocket-WD", $"Restarting nhmws SESSION"); } } NHLog.Info("NHWebSocket-WD", "Ending nhmws watchdog"); }
// 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}"); } }
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); }
private static Task HandleMarkets(string data) { try { } catch (Exception e) { NHLog.Error("NHWebSocket", $"HandleMarkets error: {e.Message}"); } return(Task.CompletedTask); }
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)); }
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 bal)) { ApplicationStateManager.OnBalanceUpdate(bal); } } catch (Exception e) { NHLog.Error("NHWebSocket", $"SetBalance error: {e.Message}"); } return(Task.Delay(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); }
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"); } }
private static Task HandleMarkets(string data) { try { var markets = JsonConvert.DeserializeObject <MarketsMessage>(data); #if !DEBUG_MARKETS StratumService.Instance.SetEnabledMarkets(markets.data); #else changeDebugMarkets(); StratumService.Instance.SetEnabledMarkets(debugEU, debugUSA); #endif } catch (Exception e) { NHLog.Error("NHWebSocket", $"HandleMarkets error: {e.Message}"); } return(Task.CompletedTask); }
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.SetEnabled(hasEU, hasUSA); #else changeDebugMarkets(); StratumService.SetEnabled(debugEU, debugUSA); #endif } catch (Exception e) { NHLog.Error("NHWebSocket", $"HandleMarkets error: {e.Message}"); } return(Task.Delay(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}"); } }
private static Task SetExchangeRates(string origdata) { var completed = Task.Delay(0); 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(completed); } 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; } ExchangeRateApi.UsdBtcRate = usdD; break; } ExchangeRateApi.UpdateExchangesFiat(exchange.exchanges_fiat); // TODO check where and why we have this ApplicationStateManager.OnExchangeUpdated(); } catch (Exception e) { NHLog.Error("NHWebSocket", $"SetExchangeRates error: {e.Message}"); } return(completed); }
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 = MiningStats.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); }
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; 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": MinerReset((string)message.level); break; default: throw new RpcException($"RpcMessage operation not supported for method '{method}'", ErrorCode.UnableToHandleRpc); } 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); } } } }