示例#1
0
        protected async Task <APIData <T> > GetAsync <T>(string url)
            where T : new()
        {
            APIData <T> result = new APIData <T>();

            try
            {
                using (HttpClient httpClient = CreateHttpClient())
                {
                    using (var readContent = await httpClient.GetAsync(Endpoint + url))
                    {
                        string data = await readContent.Content.ReadAsStringAsync();

                        result.Data = await Task.Run(() => JsonConvert.DeserializeObject <T>(data));

                        var headers = readContent.Headers.Concat(readContent.Content.Headers).FirstOrDefault(d => d.Key == "X-Pagination").Value;
                        if (headers != null)
                        {
                            result.Header = await Task.Run(() => JsonConvert.DeserializeObject <APIHeader>(headers.FirstOrDefault()));
                        }
                        return(result);
                    }
                }
            }
            catch
            {
                result = null;
            }

            return(result);
        }
示例#2
0
        static void Main(string[] args)
        {
            var fooAPIData = new APIData()
            {
                Id   = 777,
                Name = "VulcanSource",
            };
            var foo = JsonPutAsync(fooAPIData).Result;

            Console.WriteLine($"使用 JSON 格式與使用 Put 方法呼叫 Web API 的結果");
            Console.WriteLine($"結果狀態 : {foo.Success}");
            Console.WriteLine($"結果訊息 : {foo.Message}");
            Console.WriteLine($"Payload : {foo.Payload}");
            Console.WriteLine($"");

            Console.WriteLine($"Press any key to Exist...{Environment.NewLine}");
            Console.ReadKey();

            fooAPIData = new APIData()
            {
                Id   = 123,
                Name = "VulcanSource",
            };
            foo = JsonPutAsync(fooAPIData).Result;
            Console.WriteLine($"使用 JSON 格式與使用 Put 方法呼叫 Web API 的結果");
            Console.WriteLine($"結果狀態 : {foo.Success}");
            Console.WriteLine($"結果訊息 : {foo.Message}");
            Console.WriteLine($"Payload : {foo.Payload}");
            Console.WriteLine($"");

            Console.WriteLine($"Press any key to Exist...{Environment.NewLine}");
            Console.ReadKey();
        }
示例#3
0
        public override APIData GetSummary()
        {
            APIData ad = new APIData(MiningSetup.CurrentAlgorithmType);

            bool ismining;
            var getSpeedStatus = GetSpeed(out ismining, out ad.Speed);
            if (GetSpeedStatus.GOT == getSpeedStatus) {
                // fix MH/s
                ad.Speed *= 1000 * 1000;
                _currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
                // check if speed zero
                if (ad.Speed == 0) _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;
                return ad;
            } else if (GetSpeedStatus.NONE == getSpeedStatus) {
                ad.Speed = 0;
                _currentMinerReadStatus = MinerAPIReadStatus.NONE;
                return ad;
            }
            // else if (GetSpeedStatus.EXCEPTION == getSpeedStatus) {
            // we don't restart unles not responding for long time check cooldown logic in Miner
            //Helpers.ConsolePrint(MinerTAG(), "ethminer is not running.. restarting..");
            //IsRunning = false;
            _currentMinerReadStatus = MinerAPIReadStatus.NONE;
            return null;
        }
示例#4
0
        public override APIData GetSummary()
        {
            APIData ad = new APIData(MiningSetup.CurrentAlgorithmType);

            if (database == null)
            {
                try {
                    database = new ProspectorDatabase(WorkingDirectory + "info.db");
                } catch (Exception e) { Helpers.ConsolePrint(MinerTAG(), e.ToString()); }
            }
            else
            {
                foreach (var pair in MiningSetup.MiningPairs)
                {
                    if (database != null)
                    {
                        ad.Speed += database.QueryLastSpeed(deviceIDString(pair.Device.ID, pair.Device.DeviceType));
                    }
                }
            }
            // check if speed zero
            if (ad.Speed == 0)
            {
                _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;
            }

            return(ad);
        }
        public APIResult QueryStringGet([FromQuery] APIData value)
        {
            APIResult foo;

            if (value.Id == 777)
            {
                foo = new APIResult()
                {
                    Success = true,
                    Message = "透過 Get 方法,接收到 Id=777",
                    Payload = new List <APIData>()
                    {
                        new APIData()
                        {
                            Id   = 777,
                            Name = "Vulcan by QueryStringGet"
                        }
                    }
                };
            }
            else
            {
                foo = new APIResult()
                {
                    Success = false,
                    Message = "無法發現到指定的 ID",
                    Payload = null
                };
            }
            return(foo);
        }
示例#6
0
        public override APIData GetSummary()
        {
            _currentMinerReadStatus = MinerAPIReadStatus.NONE;
            APIData ad = new APIData(MiningSetup.CurrentAlgorithmType);

            TcpClient       client = null;
            JsonApiResponse resp   = null;

            try {
                byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes("status\n");
                client = new TcpClient("127.0.0.1", APIPort);
                NetworkStream nwStream = client.GetStream();
                nwStream.Write(bytesToSend, 0, bytesToSend.Length);
                byte[] bytesToRead = new byte[client.ReceiveBufferSize];
                int    bytesRead   = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
                string respStr     = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
                resp = JsonConvert.DeserializeObject <JsonApiResponse>(respStr, Globals.JsonSettings);
                client.Close();
            } catch (Exception ex) {
                Helpers.ConsolePrint("ERROR", ex.Message);
            }

            if (resp != null && resp.error == null)
            {
                ad.Speed = resp.result.speed_sps;
                _currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
                if (ad.Speed == 0)
                {
                    _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;
                }
            }

            return(ad);
        }
示例#7
0
        public override async Task <APIData> GetSummaryAsync()
        {
            _currentMinerReadStatus = MinerAPIReadStatus.NONE;
            APIData         ad     = new APIData(MiningSetup.CurrentAlgorithmType);
            TcpClient       client = null;
            JsonApiResponse resp   = null;

            try {
                byte[] bytesToSend = Encoding.ASCII.GetBytes("{\"method\":\"getstat\"}\n");
                client = new TcpClient("127.0.0.1", APIPort);
                NetworkStream nwStream = client.GetStream();
                await nwStream.WriteAsync(bytesToSend, 0, bytesToSend.Length);

                byte[] bytesToRead = new byte[client.ReceiveBufferSize];
                int    bytesRead   = await nwStream.ReadAsync(bytesToRead, 0, client.ReceiveBufferSize);

                string respStr = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
                resp = JsonConvert.DeserializeObject <JsonApiResponse>(respStr, Globals.JsonSettings);
                client.Close();
            } catch (Exception ex) {
                Helpers.ConsolePrint(MinerTAG(), ex.Message);
            }

            if (resp != null && resp.error == null)
            {
                ad.Speed = resp.result.Aggregate <Result, uint>(0, (current, t1) => current + t1.speed_sps);
                _currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
                if (ad.Speed == 0)
                {
                    _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;
                }
            }

            return(ad);
        }
示例#8
0
 private static void SaveData(APIData data)
 {
     if (data != null)
     {
         SaveData(data.formData, data.url);
     }
 }
示例#9
0
    private static void SaveData(Dictionary <string, string> formData, string url)
    {
        try
        {
            Debug.Log("APIManager - SaveData - Starting saving");
            string          dataName = "data_" + String.Format("{0:yyyyMMdd_HHmmss}", DateTime.Now);
            BinaryFormatter bf       = new BinaryFormatter();
            if (!Directory.Exists(Application.persistentDataPath + "/apiData"))
            {
                Directory.CreateDirectory(Application.persistentDataPath + "/apiData");
            }
            FileStream stream = new FileStream(Application.persistentDataPath + "/apiData/" + dataName + ".hhs", FileMode.Create);

            APIData data = new APIData();
            data.formData = formData;
            data.url      = url;

            bf.Serialize(stream, data);
            stream.Close();
            Debug.Log("APIManager - SaveData - Finished saving");
        }
        catch (Exception ex)
        {
            Debug.LogError("APIManager - SaveData" + ex.Message);
        }
    }
示例#10
0
        public override APIData GetSummary()
        {
            APIData ad = new APIData();

            FillAlgorithm("daggerhashimoto", ref ad);
            bool ismining;
            var  getSpeedStatus = GetSpeed(out ismining, out ad.Speed);

            if (GetSpeedStatus.GOT == getSpeedStatus)
            {
                // fix MH/s
                ad.Speed *= 1000 * 1000;
                _currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
                // check if speed zero
                if (ad.Speed == 0)
                {
                    _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;
                }
                return(ad);
            }
            else if (GetSpeedStatus.NONE == getSpeedStatus)
            {
                ad.Speed = 0;
                _currentMinerReadStatus = MinerAPIReadStatus.NONE;
                return(ad);
            }
            // else if (GetSpeedStatus.EXCEPTION == getSpeedStatus) {
            // we don't restart unles not responding for long time check cooldown logic in Miner
            //Helpers.ConsolePrint(MinerTAG(), "ethminer is not running.. restarting..");
            //IsRunning = false;
            _currentMinerReadStatus = MinerAPIReadStatus.NONE;
            return(null);
        }
示例#11
0
    private static IEnumerator PostData(Dictionary <string, string> formData, string ApiURL, System.Action <int> callback = null, bool SaveOnFail = false)
    {
        Debug.Log("APIManager - PostData - starting post data to " + ApiURL);

        APIData apiData = new APIData();

        apiData.saveOnFail = SaveOnFail;
        apiData.formData   = formData;
        apiData.url        = ApiURL;

        string url = UnityEngine.RemoteSettings.GetString(ApiURL, "");

        if (url == "")
        {
            if (ApiURL == "ApiLogURL")
            {
                url = "https://api.surewash.net/api/log/";
            }
            if (ApiURL == "ApiSessionsURL")
            {
                url = "https://api.surewash.net/api/sessions/";
            }
            if (ApiURL == "ApiGoalCompleteURL")
            {
                url = "https://api.surewash.net/api/goals/";
            }
            if (ApiURL == "ApiHandyMDOpenedURL")
            {
                url = "https://api.surewash.net/api/handymdopened";
            }
            if (ApiURL == "ApiHandyMDLevelURL")
            {
                url = "https://api.surewash.net/api/handymdlevel";
            }
        }

        if (PlayerPrefs.GetInt("AnonymousLogin", 1) == 1 && UnityEngine.RemoteSettings.GetInt("APISendAnomousData", 0) == 0)
        {
            if (callback != null)
            {
                callback(-4);
            }
            if (SaveOnFail)
            {
                SaveData(apiData);
            }
            yield break;
        }
        else
        {
            WWWForm form = new WWWForm();

            foreach (KeyValuePair <string, string> entry in formData)
            {
                form.AddField(entry.Key, entry.Value);
            }

            yield return(ProcessAPIRequest <System.Action <int> >(url, false, form, FinishPostData, callback, apiData));
        }
    }
示例#12
0
        public override APIData GetSummary()
        {
            _currentMinerReadStatus = MinerAPIReadStatus.NONE;
            APIData ad = new APIData(MiningSetup.CurrentAlgorithmType);

            TcpClient client = null;
            JsonApiResponse resp = null;
            try {
                byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes("status\n");
                client = new TcpClient("127.0.0.1", APIPort);
                NetworkStream nwStream = client.GetStream();
                nwStream.Write(bytesToSend, 0, bytesToSend.Length);
                byte[] bytesToRead = new byte[client.ReceiveBufferSize];
                int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
                string respStr = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
                resp = JsonConvert.DeserializeObject<JsonApiResponse>(respStr, Globals.JsonSettings);
                client.Close();
            } catch (Exception ex) {
                Helpers.ConsolePrint("ERROR", ex.Message);
            }

            if (resp != null && resp.error == null) {
                ad.Speed = resp.result.speed_sps;
                _currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
                if (ad.Speed == 0) {
                    _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;
                }
            }

            return ad;
        }
        /// <summary>
        /// The GetSummaryAsync
        /// </summary>
        /// <returns>The <see cref="Task{APIData}"/></returns>
        public override Task <APIData> GetSummaryAsync()
        {
            APIData ad = new APIData(MiningSetup.CurrentAlgorithmType);

            var getSpeedStatus = GetSpeed(out bool ismining, out ad.Speed);

            if (GetSpeedStatus.GOT == getSpeedStatus)
            {
                // fix MH/s
                ad.Speed *= 1000 * 1000;
                _currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
                // check if speed zero
                if (ad.Speed == 0)
                {
                    _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;
                }
                return(Task.FromResult(ad));
            }
            else if (GetSpeedStatus.NONE == getSpeedStatus)
            {
                ad.Speed = 0;
                _currentMinerReadStatus = MinerAPIReadStatus.NONE;
                return(Task.FromResult(ad));
            }
            // else if (GetSpeedStatus.EXCEPTION == getSpeedStatus) {
            // we don't restart unles not responding for long time check cooldown logic in Miner
            //Helpers.ConsolePrint(MinerTAG(), "ethminer is not running.. restarting..");
            //IsRunning = false;
            _currentMinerReadStatus = MinerAPIReadStatus.NONE;
            return(Task.FromResult <APIData>(null));
        }
示例#14
0
        public override APIData GetSummary()
        {
            _currentMinerReadStatus = MinerAPIReadStatus.NONE;
            APIData ad = new APIData(MiningSetup.CurrentAlgorithmType);

            TcpClient       client = null;
            JsonApiResponse resp   = null;

            try {
                byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes("{\"id\":0,\"jsonrpc\":\"2.0\",\"method\":\"miner_getstat1\"}n");
                client = new TcpClient("127.0.0.1", APIPort);
                NetworkStream nwStream = client.GetStream();
                nwStream.Write(bytesToSend, 0, bytesToSend.Length);
                byte[] bytesToRead = new byte[client.ReceiveBufferSize];
                int    bytesRead   = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
                string respStr     = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
                resp = JsonConvert.DeserializeObject <JsonApiResponse>(respStr, Globals.JsonSettings);
                client.Close();
                //Helpers.ConsolePrint("ClaymoreZcashMiner API back:", respStr);
            } catch (Exception ex) {
                Helpers.ConsolePrint(this.MinerTAG(), "GetSummary exception: " + ex.Message);
            }

            if (resp != null && resp.error == null)
            {
                //Helpers.ConsolePrint("ClaymoreZcashMiner API back:", "resp != null && resp.error == null");
                if (resp.result != null && resp.result.Count > 4)
                {
                    //Helpers.ConsolePrint("ClaymoreZcashMiner API back:", "resp.result != null && resp.result.Count > 4");
                    var speeds = resp.result[3].Split(';');
                    ad.Speed = 0;
                    foreach (var speed in speeds)
                    {
                        //Helpers.ConsolePrint("ClaymoreZcashMiner API back:", "foreach (var speed in speeds) {");
                        double tmpSpeed = 0;
                        try {
                            tmpSpeed = Double.Parse(speed, CultureInfo.InvariantCulture);
                        } catch {
                            tmpSpeed = 0;
                        }
                        ad.Speed += tmpSpeed;
                    }
                    ad.Speed *= api_read_mult;
                    _currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
                }
                if (ad.Speed == 0)
                {
                    _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;
                }
                // some clayomre miners have this issue reporting negative speeds in that case restart miner
                if (ad.Speed < 0)
                {
                    Helpers.ConsolePrint(this.MinerTAG(), "Reporting negative speeds will restart...");
                    this.Restart();
                }
            }

            return(ad);
        }
示例#15
0
            /// <summary>
            /// Create APIData object directly from a JSON string.
            /// </summary>
            /// <returns>The deserialized data packet.</returns>
            /// <param name="json">JSON string representing the data.</param>
            public static APIData FromJSON(string json)
            {
                APIData data = new APIData();

                APIData.PopulateFromJSON(json, data);

                return(data);
            }
示例#16
0
    public void GetJsonData()
    {
        // 初始化 APIData 对象,把自己传过去,用来回调
        APIData data = new APIData(this);

        // 调用函数发起请求
        data.GetSphericalLayoutData();
        data.GetHierarchyLayoutData();
    }
示例#17
0
        public override async Task <APIData> GetSummaryAsync()
        {
            _currentMinerReadStatus = MinerAPIReadStatus.NONE;
            APIData ad = new APIData(MiningSetup.CurrentAlgorithmType);

            if (_skipAPICheck == false)
            {
                JsonApiResponse resp = null;
                try
                {
                    string DataToSend = GetHttpRequestNHMAgentStrin("");
                    string respStr    = await GetAPIDataAsync(APIPort, DataToSend, true);

                    if (respStr != null && respStr.Contains("{"))
                    {
                        int start = respStr.IndexOf("{");
                        if (start > -1)
                        {
                            string respStrJSON = respStr.Substring(start);
                            resp = JsonConvert.DeserializeObject <JsonApiResponse>(respStrJSON.Trim(), Globals.JsonSettings);
                        }
                    }
                    //Helpers.ConsolePrint("OptiminerZcashMiner API back:", respStr);
                }
                catch (Exception ex)
                {
                    Helpers.ConsolePrint("OptiminerZcashMiner", "GetSummary exception: " + ex.Message);
                }

                if (resp != null && resp.solution_rate != null)
                {
                    //Helpers.ConsolePrint("OptiminerZcashMiner API back:", "resp != null && resp.error == null");
                    const string total_key = "Total";
                    const string _5s_key   = "5s";
                    if (resp.solution_rate.ContainsKey(total_key))
                    {
                        var total_solution_rate_dict = resp.solution_rate[total_key];
                        if (total_solution_rate_dict != null && total_solution_rate_dict.ContainsKey(_5s_key))
                        {
                            ad.Speed = total_solution_rate_dict[_5s_key];
                            _currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
                        }
                    }
                    if (ad.Speed == 0)
                    {
                        _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;
                    }
                }
            }
            else if (_skipAPICheck && _startAPI.Elapsed.TotalSeconds > waitSeconds)
            {
                _startAPI.Stop();
                _skipAPICheck = false;
            }

            return(ad);
        }
示例#18
0
        public void MinerStatsCheck(Dictionary <AlgorithmType, NiceHashSMA> NiceHashData)
        {
            double CurrentProfit = 0.0d;

            _mainFormRatesComunication.ClearRates(_currentAllGroupedDevices.Count);
            foreach (var group in _currentAllGroupedDevices)
            {
                var   groupMiners = _groupedDevicesMiners[CalcGroupedDevicesKey(group)];
                Miner m           = groupMiners.CurrentWorkingMiner;

                // skip if not running
                if (!m.IsRunning)
                {
                    continue;
                }

                APIData AD = m.GetSummary();
                if (AD == null)
                {
                    Helpers.ConsolePrint(m.MinerTAG(), "GetSummary returned null..");
                }
                // set rates
                if (NiceHashData != null && AD != null)
                {
                    m.CurrentRate = NiceHashData[AD.AlgorithmID].paying * AD.Speed * 0.000000001;
                }
                else
                {
                    m.CurrentRate = 0;
                    // set empty
                    AD = new APIData()
                    {
                        AlgorithmID   = m.CurrentAlgorithmType,
                        AlgorithmName = AlgorithmNiceHashNames.GetName(m.CurrentAlgorithmType),
                        Speed         = 0.0d
                    };
                }
                CurrentProfit += m.CurrentRate;
                // Update GUI
                _mainFormRatesComunication.AddRateInfo(m.MinerTAG(), groupMiners.DevicesInfoString, AD, m.CurrentRate, m.IsAPIReadException);
            }
            // check if profitabile
            if (CheckStatus && !IsMiningRegardlesOfProfit)
            {
                CheckStatus = false;
                if (IsProfitable)
                {
                    // check current profit
                    CheckIfShouldMine(CurrentProfit, true);
                }
                else if (!IsProfitable)
                {
                    // recalculate and switch
                    SwichMostProfitableGroupUpMethod(NiceHashData, true);
                }
            }
        }
示例#19
0
        public override async Task <APIData> GetSummaryAsync()
        {
            _currentMinerReadStatus = MinerAPIReadStatus.NONE;
            var    ad   = new APIData(MiningSetup.CurrentAlgorithmType, MiningSetup.CurrentSecondaryAlgorithmType);
            string resp = null;

            try
            {
                var bytesToSend = Encoding.ASCII.GetBytes("summary\r\n");
                var client      = new TcpClient("127.0.0.1", APIPort);
                var nwStream    = client.GetStream();
                await nwStream.WriteAsync(bytesToSend, 0, bytesToSend.Length);

                var bytesToRead = new byte[client.ReceiveBufferSize];
                var bytesRead   = await nwStream.ReadAsync(bytesToRead, 0, client.ReceiveBufferSize);

                var respStr = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);

                client.Close();
                resp = respStr;
                //Helpers.ConsolePrint(MinerTag(), "API: " + respStr);
            }
            catch (Exception ex)
            {
                Helpers.ConsolePrint(MinerTAG(), "GetSummary exception: " + ex.Message);
            }

            if (resp != null)
            {
                var    st    = resp.IndexOf(";KHS=");
                var    e     = resp.IndexOf(";SOLV=");
                var    parse = resp.Substring(st + 5, e - st - 5).Trim();
                double tmp   = Double.Parse(parse, CultureInfo.InvariantCulture);
                ad.Speed = tmp * 1000;



                if (ad.Speed == 0)
                {
                    _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;
                }
                else
                {
                    _currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
                }

                // some clayomre miners have this issue reporting negative speeds in that case restart miner
                if (ad.Speed < 0)
                {
                    Helpers.ConsolePrint(MinerTAG(), "Reporting negative speeds will restart...");
                    Restart();
                }
            }

            return(ad);
        }
        public override async Task <APIData> GetSummaryAsync()
        {
            APIData ad = new APIData(MiningSetup.CurrentAlgorithmType);

            try {
                _currentMinerReadStatus = MinerAPIReadStatus.WAIT;
                string dataToSend = GetHttpRequestNHMAgentStrin("api.json");
                string respStr    = await GetAPIDataAsync(APIPort, dataToSend);

                if (respStr.IndexOf("HTTP/1.1 200 OK") > -1)
                {
                    respStr = respStr.Substring(respStr.IndexOf(HTTPHeaderDelimiter) + HTTPHeaderDelimiter.Length);
                }
                else if (String.IsNullOrEmpty(respStr))
                {
                    _currentMinerReadStatus = MinerAPIReadStatus.NETWORK_EXCEPTION;
                    throw new Exception("Response is empty!");
                }
                else
                {
                    throw new Exception("Response not HTTP formed! " + respStr);
                }

                dynamic resp = JsonConvert.DeserializeObject(respStr);

                if (resp != null)
                {
                    JArray totals = resp.hashrate.total;
                    foreach (var total in totals)
                    {
                        if (total.Value <string>() == null)
                        {
                            continue;
                        }
                        ad.Speed = total.Value <double>();
                        break;
                    }
                    if (ad.Speed == 0)
                    {
                        _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;
                    }
                    else
                    {
                        _currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
                    }
                }
                else
                {
                    throw new Exception("Response does not contain speed data");
                }
            } catch (Exception ex) {
                Helpers.ConsolePrint(MinerTAG(), ex.Message);
            }

            return(ad);
        }
示例#21
0
            /// <summary>
            /// Populate APIData object from a JSON string.
            /// </summary>
            /// <param name="json">JSON string representing the data.</param>
            /// <param name="dataObject">The object to populate.</param>
            public static void PopulateFromJSON(string json, APIData dataObject)
            {
                dataObject.AssignedData = false;

                using (var sr = new StringReader(json))
                    using (var reader = new JsonTextReader(sr))
                    {
                        // Use buffer
                        reader.ArrayPool = JSONArrayPool.Instance;

                        while (reader.Read())
                        {
                            if ((reader.TokenType == JsonToken.PropertyName) && (reader.Depth == 1))
                            {
                                switch (reader.Value.ToString())
                                {
                                case "action":
                                    dataObject.Action = reader.ReadAsString();
                                    break;

                                case "device_id":
                                case "from":
                                    dataObject.DeviceId = reader.ReadAsInt32();
                                    break;

                                case "uid":
                                    dataObject.StringData = reader.ReadAsString();
                                    break;

                                case "ad_was_shown":
                                    dataObject.StateData = reader.ReadAsBoolean();
                                    break;

                                default:
                                    // Reset StringBuilder
                                    dataObject.Data.Length = 0;

                                    using (var sw = new StringWriter(dataObject.Data))
                                        using (var writer = new JsonTextWriter(sw))
                                        {
                                            // Use buffer
                                            writer.ArrayPool = JSONArrayPool.Instance;

                                            reader.Read();
                                            writer.WriteToken(reader);
                                        }

                                    dataObject.AssignedData = true;
                                    break;
                                }
                            }
                        } // while(reader.Read())
                    }// using StringReader / JsonTextReader - Dispose
            }             // PopulateFromJSON()
示例#22
0
#pragma warning disable CS1998 // This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
        /// <summary>
        /// The GetSummaryAsync
        /// </summary>
        /// <returns>The <see cref="Task{APIData}"/></returns>
        public override async Task <APIData> GetSummaryAsync()
#pragma warning restore CS1998 // This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
        {
            // cryptonight does not have api bind port
            APIData hsrData = new APIData(MiningSetup.CurrentAlgorithmType)
            {
                Speed = 0
            };

            if (IsAPIReadException)
            {
                // check if running
                if (ProcessHandle == null)
                {
                    //_currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from hsrminer Proccess is null");
                    return(null);
                }
                try
                {
                    var runningProcess = Process.GetProcessById(ProcessHandle.Id);
                }
                catch (ArgumentException ex)
                {
                    //_currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from hsrminer reason: " + ex.Message);
                    return(null); // will restart outside
                }
                catch (InvalidOperationException ex)
                {
                    //_currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from hsrminer reason: " + ex.Message);
                    return(null); // will restart outside
                }

                var totalSpeed = 0.0d;

                /*foreach (var miningPair in MiningSetup.MiningPairs)
                 * {
                 *  var algo = miningPair.Device.GetAlgorithm(MinerBaseType.Palgin_Neoscrypt, AlgorithmType.NeoScrypt, AlgorithmType.NONE);
                 *  if (algo != null)
                 *  {
                 *      totalSpeed += algo.BenchmarkSpeed;
                 *      //Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from hsrminer. Used benchmark hashrate");
                 *  }
                 * }*/

                hsrData.Speed = totalSpeed;
                return(hsrData);
            }

            //  return await GetSummaryCPU_Palgin_NeoscryptAsync();
            return(hsrData);
        }
示例#23
0
        //Process once a day services
        public void Process_DailyService()
        {
            DataTable tbl = null;

            tbl = ServicesData.GetAllSellerIds();
            foreach (DataRow row in tbl.Rows)
            {
                String custmid = Convert.ToString(row["stp_custId"]);
                StripeServices.UpdateBillingPeriod(custmid);//when webhooks don't work
            }
            APIData.SetOldReportDatesData();
        }
示例#24
0
        /// <summary>
        /// The GetSummaryAsync
        /// </summary>
        /// <returns>The <see cref="Task{APIData}"/></returns>
        public override async Task <APIData> GetSummaryAsync()
        {
            // cryptonight does not have api bind port
            if (IsAPIReadException)
            {
                // check if running
                if (ProcessHandle == null)
                {
                    _currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from cryptonight Proccess is null");
                    return(null);
                }
                try
                {
                    var runningProcess = Process.GetProcessById(ProcessHandle.Id);
                }
                catch (ArgumentException ex)
                {
                    _currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from cryptonight reason: " + ex.Message);
                    return(null); // will restart outside
                }
                catch (InvalidOperationException ex)
                {
                    _currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from cryptonight reason: " + ex.Message);
                    return(null); // will restart outside
                }

                var totalSpeed = 0.0d;
                foreach (var miningPair in MiningSetup.MiningPairs)
                {
                    var algo = miningPair.Device.GetAlgorithm(MinerBaseType.ccminer, AlgorithmType.cryptonight, AlgorithmType.NONE);
                    if (algo != null)
                    {
                        totalSpeed += algo.BenchmarkSpeed;
                    }
                }

                APIData cryptonightData = new APIData(MiningSetup.CurrentAlgorithmType)
                {
                    Speed = totalSpeed
                };
                _currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
                // check if speed zero
                if (cryptonightData.Speed == 0)
                {
                    _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;
                }
                return(cryptonightData);
            }
            return(await GetSummaryCPU_CCMINERAsync());
        }
        public JsonResult RunCampaigns(List <CampaignStatus> Camplist)
        {
            String    res = "";
            DataTable dt  = new DataTable();

            dt.Columns.AddRange(new DataColumn[2] {
                new DataColumn("RecordID", typeof(String)),
                new DataColumn("Status", typeof(bool))
            });

            foreach (var row in Camplist)
            {
                dt.Rows.Add();
                dt.Rows[dt.Rows.Count - 1][0] = row.RecordID;
                dt.Rows[dt.Rows.Count - 1][1] = row.Status;
            }

            if (dt.Rows.Count > 0)
            {
                var      profile       = APIData.GetUserProfileForSkuData(SessionData.UserID);
                DataRow  dr            = profile.Rows[0];
                String   ProfileId     = Convert.ToString(dr["ProfileId"]);
                DateTime LastUpdatedOn = Convert.ToDateTime(dr["AccessTokenUpdatedOn"]);

                var Auth = new AuthorizationModel()
                {
                    access_token  = Convert.ToString(dr["AccessToken"]),
                    refresh_token = Convert.ToString(dr["RefreshToken"]),
                    token_type    = Convert.ToString(dr["TokenType"]),
                    expires_in    = Convert.ToInt32(dr["TokenExpiresIn"])
                };
                var msg        = string.Empty;
                var campaignId = dt.AsEnumerable().Select(r => Convert.ToInt64(r.Field <string>("RecordID"))).ToArray();

                ReportsAPI api = new ReportsAPI();
                api.GetUserProductAdsCount(SessionData.UserID, ProfileId, LastUpdatedOn, Auth, out msg, Camplist);
                res = optimizeData.RunCampaignData(dt, SessionData.UserID);
            }
            else
            {
                res = "Something went wrong!";
            }

            if (res == "")
            {
                SessionData.FormulaAccess = 1;
            }
            return(new JsonResult()
            {
                Data = res, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
示例#26
0
        public override async Task <APIData> GetSummaryAsync()
        {
            // CryptoNight does not have api bind port
            APIData hsrData = new APIData(MiningSetup.CurrentAlgorithmType)
            {
                Speed = 0
            };

            if (IsAPIReadException)
            {
                // check if running
                if (ProcessHandle == null)
                {
                    //_currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from hsrminer Proccess is null");
                    return(null);
                }
                try
                {
                    var runningProcess = Process.GetProcessById(ProcessHandle.Id);
                }
                catch (ArgumentException ex)
                {
                    //_currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from hsrminer reason: " + ex.Message);
                    return(null); // will restart outside
                }
                catch (InvalidOperationException ex)
                {
                    //_currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from hsrminer reason: " + ex.Message);
                    return(null); // will restart outside
                }

                var totalSpeed = 0.0d;
                foreach (var miningPair in MiningSetup.MiningPairs)
                {
                    var algo = miningPair.Device.GetAlgorithm(MinerBaseType.hsrneoscrypt, AlgorithmType.NeoScrypt, AlgorithmType.NONE);
                    if (algo != null)
                    {
                        totalSpeed += algo.BenchmarkSpeed;
                        Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from hsrminer. Used benchmark hashrate");
                    }
                }

                hsrData.Speed = totalSpeed;
                return(hsrData);
            }

            //  return await GetSummaryCPU_hsrneoscryptAsync();
            return(hsrData);
        }
示例#27
0
 public static bool TryParse <T>(this CachedSession oSession, out APIData <T> result)
 {
     try
     {
         result = oSession.Parse <T>();
         return(result.IsSuccess);
     }
     catch
     {
         result = null;
         return(false);
     }
 }
 static void Main(string[] args)
 {
     //var request = new
     //{
     //    Method = "update",
     //    Path = "/api/categories/1",
     //    Date = "03/09/19",
     //    Body = (new { cid = 1, name = "BeveragesTesting" }).ToJson()
     //};
     //Console.WriteLine(request.Method);
     var apiDate   = new APIData();
     var tcpServer = new TcpServer();
 }
示例#29
0
        public void 傳入錯誤字串__應回傳APIData空物件()
        {
            //arrange
            var json = "aaaa";

            var expected = new APIData <Product, int>();

            //act
            var actual = A01_Generics_Demo.Demo(json);

            //assert
            actual.ShouldBeEquivalentTo(expected);
        }
示例#30
0
        public override APIData GetSummary()
        {
            // CryptoNight does not have api bind port
            if (CurrentAlgorithmType == AlgorithmType.CryptoNight)
            {
                // check if running
                if (ProcessHandle == null)
                {
                    _currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from CryptoNight Proccess is null");
                    return(null);
                }
                try {
                    var runningProcess = Process.GetProcessById(ProcessHandle.Id);
                } catch (ArgumentException ex) {
                    _currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from CryptoNight");
                    return(null); // will restart outside
                } catch (InvalidOperationException ex) {
                    _currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from CryptoNight");
                    return(null); // will restart outside
                }
                // extra check
                if (CurrentMiningAlgorithm == null)
                {
                    _currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from CryptoNight Proccess CurrentMiningAlgorithm is NULL");
                    return(null);
                }

                var totalSpeed = 0.0d;
                foreach (var cdev in CDevs)
                {
                    totalSpeed += cdev.DeviceBenchmarkConfig.AlgorithmSettings[AlgorithmType.CryptoNight].BenchmarkSpeed;
                }

                APIData CryptoNightData = new APIData();
                CryptoNightData.AlgorithmID   = AlgorithmType.CryptoNight;
                CryptoNightData.AlgorithmName = "cryptonight";
                CryptoNightData.Speed         = totalSpeed;
                _currentMinerReadStatus       = MinerAPIReadStatus.GOT_READ;
                // check if speed zero
                if (CryptoNightData.Speed == 0)
                {
                    _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;
                }
                return(CryptoNightData);
            }
            return(GetSummaryCPU_CCMINER());
        }
示例#31
0
        public object Post(APIData JsonObj) //Request DataBinding to APIDataObj
        {
            //Get Target Method
            var func = this.GetType().GetMethod(JsonObj.FunctionName, BindingFlags.NonPublic | BindingFlags.Instance);

            if (func == null)
            {
                JsonObj.returncode    = "01";
                JsonObj.returnmessage = "Function Name Not Found!!";
                JsonObj.FunctionType  = "R";
                return(JsonObj);
            }
            return(func.Invoke(this, new object[] { JsonObj }));
        }
示例#32
0
        public async Task MinerStatsCheck(Dictionary <AlgorithmType, NiceHashSMA> NiceHashData)
        {
            double CurrentProfit = 0.0d;

            _mainFormRatesComunication.ClearRates(_runningGroupMiners.Count);
            var checks = new List <GroupMiner>(_runningGroupMiners.Values);

            try
            {
                foreach (var groupMiners in checks)
                {
                    Miner m = groupMiners.Miner;

                    // skip if not running or if await already in progress
                    if (!m.IsRunning || m.IsUpdatingAPI)
                    {
                        continue;
                    }

                    m.IsUpdatingAPI = true;
                    APIData AD = await m.GetSummaryAsync();

                    m.IsUpdatingAPI = false;
                    if (AD == null)
                    {
                        Helpers.ConsolePrint(m.MinerTAG(), "GetSummary returned null..");
                    }
                    // set rates
                    if (NiceHashData != null && AD != null)
                    {
                        groupMiners.CurrentRate = NiceHashData[AD.AlgorithmID].paying * AD.Speed * 0.000000001;
                        if (NiceHashData.ContainsKey(AD.SecondaryAlgorithmID))
                        {
                            groupMiners.CurrentRate += NiceHashData[AD.SecondaryAlgorithmID].paying * AD.SecondarySpeed * 0.000000001;
                        }
                    }
                    else
                    {
                        groupMiners.CurrentRate = 0;
                        // set empty
                        AD = new APIData(groupMiners.AlgorithmType);
                    }
                    CurrentProfit += groupMiners.CurrentRate;
                    // Update GUI
                    _mainFormRatesComunication.AddRateInfo(m.MinerTAG(), groupMiners.DevicesInfoString, AD, groupMiners.CurrentRate, m.IsAPIReadException);
                }
            }
            catch (Exception e) { Helpers.ConsolePrint(TAG, e.Message); }
        }
示例#33
0
        public override APIData GetSummary()
        {
            // CryptoNight does not have api bind port
            if (CurrentAlgorithmType == AlgorithmType.CryptoNight) {
                // check if running
                if (ProcessHandle == null) {
                    _currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from CryptoNight Proccess is null");
                    return null;
                }
                try {
                    var runningProcess = Process.GetProcessById(ProcessHandle.Id);
                } catch (ArgumentException ex) {
                    _currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from CryptoNight");
                    return null; // will restart outside
                } catch (InvalidOperationException ex) {
                    _currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from CryptoNight");
                    return null; // will restart outside
                }
                // extra check
                if (CurrentMiningAlgorithm == null) {
                    _currentMinerReadStatus = MinerAPIReadStatus.RESTART;
                    Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Could not read data from CryptoNight Proccess CurrentMiningAlgorithm is NULL");
                    return null;
                }

                var totalSpeed = 0.0d;
                foreach (var cdev in CDevs) {
                    totalSpeed += cdev.DeviceBenchmarkConfig.AlgorithmSettings[AlgorithmType.CryptoNight].BenchmarkSpeed;
                }

                APIData CryptoNightData = new APIData();
                CryptoNightData.AlgorithmID = AlgorithmType.CryptoNight;
                CryptoNightData.AlgorithmName = "cryptonight";
                CryptoNightData.Speed = totalSpeed;
                _currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
                // check if speed zero
                if (CryptoNightData.Speed == 0) _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;
                return CryptoNightData;
            }
            return GetSummaryCPU_CCMINER();
        }
示例#34
0
        public void MinerStatsCheck(Dictionary<AlgorithmType, NiceHashSMA> NiceHashData)
        {
            double CurrentProfit = 0.0d;
            _mainFormRatesComunication.ClearRates(_runningGroupMiners.Count);
            foreach (var groupMiners in _runningGroupMiners.Values) {
                Miner m = groupMiners.Miner;

                // skip if not running
                if (!m.IsRunning) continue;

                APIData AD = m.GetSummary();
                if (AD == null) {
                    Helpers.ConsolePrint(m.MinerTAG(), "GetSummary returned null..");
                }
                // set rates
                if (NiceHashData != null && AD != null) {
                    groupMiners.CurrentRate = NiceHashData[AD.AlgorithmID].paying * AD.Speed * 0.000000001;
                } else {
                    groupMiners.CurrentRate = 0;
                    // set empty
                    AD = new APIData(groupMiners.AlgorithmType);
                }
                CurrentProfit += groupMiners.CurrentRate;
                // Update GUI
                _mainFormRatesComunication.AddRateInfo(m.MinerTAG(), groupMiners.DevicesInfoString, AD, groupMiners.CurrentRate, m.IsAPIReadException);
            }
            //// check if profitabile
            //if (CheckStatus && !IsMiningRegardlesOfProfit) {
            //    CheckStatus = false;
            //    if (IsProfitable) {
            //        // check current profit
            //        CheckIfShouldMine(CurrentProfit, true);
            //    } else if (!IsProfitable) {
            //        // recalculate and switch
            //        SwichMostProfitableGroupUpMethod(NiceHashData, true);
            //    }
            //}
        }
示例#35
0
        // TODO _currentMinerReadStatus
        public override APIData GetSummary()
        {
            string resp;
            APIData ad = new APIData(MiningSetup.CurrentAlgorithmType);

            resp = GetAPIData(APIPort, "summary");
            if (resp == null) {
                _currentMinerReadStatus = MinerAPIReadStatus.NONE;
                return null;
            }

            try {
                // Checks if all the GPUs are Alive first
                string resp2 = GetAPIData(APIPort, "devs");
                if (resp2 == null) {
                    _currentMinerReadStatus = MinerAPIReadStatus.NONE;
                    return null;
                }

                string[] checkGPUStatus = resp2.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                for (int i = 1; i < checkGPUStatus.Length - 1; i++) {
                    if (!checkGPUStatus[i].Contains("Status=Alive")) {
                        Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " GPU " + i + ": Sick/Dead/NoStart/Initialising/Disabled/Rejecting/Unknown");
                        _currentMinerReadStatus = MinerAPIReadStatus.WAIT;
                        return null;
                    }
                }

                string[] resps = resp.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                if (resps[1].Contains("SUMMARY")) {
                    string[] data = resps[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    // Get miner's current total speed
                    string[] speed = data[4].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                    // Get miner's current total MH
                    double total_mh = Double.Parse(data[18].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries)[1], new CultureInfo("en-US"));

                    ad.Speed = Double.Parse(speed[1]) * 1000;

                    if (total_mh <= PreviousTotalMH) {
                        Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " SGMiner might be stuck as no new hashes are being produced");
                        Helpers.ConsolePrint(MinerTAG(), ProcessTag() + " Prev Total MH: " + PreviousTotalMH + " .. Current Total MH: " + total_mh);
                        _currentMinerReadStatus = MinerAPIReadStatus.NONE;
                        return null;
                    }

                    PreviousTotalMH = total_mh;
                } else {
                    ad.Speed = 0;
                }
            } catch {
                _currentMinerReadStatus = MinerAPIReadStatus.NONE;
                return null;
            }

            _currentMinerReadStatus = MinerAPIReadStatus.GOT_READ;
            // check if speed zero
            if (ad.Speed == 0) _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO;

            return ad;
        }