public double GetCurrentHashrate(DeviceConfig deviceConfig)
        {
            double gpuHashrate = 0;

            try
            {
                var json = GetApiDataAsync(_port, "{\"id\":0,\"jsonrpc\":\"2.0\",\"method\":\"miner_getstat1\"}\n").Result;

                var    jResults  = JToken.Parse(json)["result"].Value <JArray>();
                string hashrates = jResults[3].Value <string>();
                if (hashrates.Contains(";", StringComparison.OrdinalIgnoreCase))
                {
                    string[] splitHashrates = hashrates.Split(';');
                    int      index          = DeviceConfigs.OrderBy(dc => dc.DeviceId).ToList().IndexOf(deviceConfig);
                    double   hashrateInKh   = double.Parse(splitHashrates[index], NumberStyles.None, CultureInfo.InvariantCulture);
                    return(hashrateInKh * 1000);
                }
                else
                {
                    double hashrateInKh = double.Parse(hashrates, NumberStyles.None, CultureInfo.InvariantCulture);
                    return(hashrateInKh * 1000);
                }
            }
            catch (Exception ex)
            {
                Log.Debug("Couldn't get current hashrate: " + ex.Message);
            }

            return(gpuHashrate);
        }
        public void StartMiner(bool minimized)
        {
            _minimized = minimized;
            _process   = new Process();
            DeviceConfig firstDeviceConfig = DeviceConfigs.First();
            string       minerPath         = Helpers.ResolveToFullPath(firstDeviceConfig.MinerPath, Helpers.GetApplicationRoot());
            string       minerFolderPath   = Path.GetDirectoryName(minerPath);

            _process.StartInfo.FileName = "cmd";
            List <string> userDefindedArgs = new List <string>();

            if (!String.IsNullOrEmpty(firstDeviceConfig.MinerArguments))
            {
                userDefindedArgs.AddRange(firstDeviceConfig.MinerArguments.Split(" "));
            }

            if (!String.IsNullOrEmpty(firstDeviceConfig.MinerDeviceSpecificArguments))
            {
                userDefindedArgs.AddRange(firstDeviceConfig.MinerDeviceSpecificArguments.Split(" "));
            }

            string args  = "";
            string space = "";

            if (!userDefindedArgs.Contains("-o"))
            {
                string address = Pool.PoolUrl.StartsWith("stratum+tcp://", StringComparison.OrdinalIgnoreCase) ? Pool.PoolUrl : "stratum+tcp://" + Pool.PoolUrl;
                args  = $"{space}-o {address}";
                space = " ";
            }

            if (!userDefindedArgs.Contains("-u"))
            {
                args += $"{space}-u {Pool.PoolUser}";
                space = " ";
            }

            if (!userDefindedArgs.Contains("-p"))
            {
                args += $"{space}-p {Pool.PoolPassword}";
                space = " ";
            }

            if (!userDefindedArgs.Contains("-d"))
            {
                string devicesString = string.Join(',', DeviceConfigs.Select(dc => dc.DeviceId));
                args += $"{space}-d {devicesString}";
                space = " ";
            }

            _port = firstDeviceConfig.MinerApiPort > 0 ? firstDeviceConfig.MinerApiPort : Helpers.GetAvailablePort();
            if (!userDefindedArgs.Any(a => a.StartsWith("--api_listen={", StringComparison.OrdinalIgnoreCase)))
            {
                args += $"{space}--api_listen={_port}";
                space = " ";
            }

            if (!String.IsNullOrEmpty(firstDeviceConfig.MinerArguments))
            {
                args += space + firstDeviceConfig.MinerArguments;
            }

            if (DeviceConfigs.Any(dc => !string.IsNullOrEmpty(dc.MinerDeviceSpecificArguments)))
            {
                Dictionary <string, List <string> > combinedArgumentsDictionary = new Dictionary <string, List <string> >();
                foreach (DeviceConfig deviceConfig in DeviceConfigs)
                {
                    var splittedArguments = deviceConfig.MinerDeviceSpecificArguments.Split(" ");
                    foreach (string splittedArgument in splittedArguments)
                    {
                        const string cnConfigArgmument = "--cn_config=";
                        if (splittedArgument.StartsWith(cnConfigArgmument, StringComparison.OrdinalIgnoreCase))
                        {
                            AddToListInDictionary(combinedArgumentsDictionary, cnConfigArgmument, splittedArgument.Substring(cnConfigArgmument.Length));
                        }
                        const string ethConfigArgmument = "--eth_config=";
                        if (splittedArgument.StartsWith(ethConfigArgmument, StringComparison.OrdinalIgnoreCase))
                        {
                            AddToListInDictionary(combinedArgumentsDictionary, ethConfigArgmument, splittedArgument.Substring(ethConfigArgmument.Length));
                        }
                    }
                }
                StringBuilder argumentsBuilder = new StringBuilder();
                bool          first            = true;
                foreach (var combinedArgument in combinedArgumentsDictionary)
                {
                    if (!first)
                    {
                        argumentsBuilder.Append(" ");
                    }

                    first = false;
                    argumentsBuilder.Append(combinedArgument.Key);
                    argumentsBuilder.Append(string.Join(',', combinedArgument.Value));
                }
                args += space + argumentsBuilder;
            }

            _process.EnableRaisingEvents = true;
            _process.Exited += ProcessOnExited;
            _process.StartInfo.Arguments              = $"/c \"{Path.GetFileName(minerPath)} {args}\"";
            _process.StartInfo.UseShellExecute        = true;
            _process.StartInfo.CreateNoWindow         = false;
            _process.StartInfo.RedirectStandardOutput = false;
            _process.StartInfo.WorkingDirectory       = minerFolderPath;
            _process.StartInfo.WindowStyle            = minimized ? ProcessWindowStyle.Minimized : ProcessWindowStyle.Normal;
            Log.Debug($"Miner Start Info: \"{_process.StartInfo.FileName}\" {_process.StartInfo.Arguments}");
            _process.Start();
        }
        public void StartMiner(bool minimized)
        {
            _minimized = minimized;
            _process   = new Process();
            DeviceConfig firstDevice = DeviceConfigs.First();
            string       minerPath   = Helpers.ResolveToFullPath(firstDevice.MinerPath, Helpers.GetApplicationRoot());

            _port = firstDevice.MinerApiPort > 0 ? firstDevice.MinerApiPort : Helpers.GetAvailablePort();

            string minerFolderPath = Path.GetDirectoryName(minerPath);

            _process.StartInfo.FileName = minerPath;

            List <string> userDefindedArgs = new List <string>();

            if (!String.IsNullOrEmpty(firstDevice.MinerArguments))
            {
                userDefindedArgs.AddRange(firstDevice.MinerArguments.Split(" "));
            }

            string args  = "";
            string space = "";

            if (!userDefindedArgs.Contains("-o"))
            {
                args  = $"{space}-o {Pool.PoolUrl}";
                space = " ";
            }
            if (!userDefindedArgs.Contains("-u"))
            {
                args += $"{space}-u {Pool.PoolUser}";
                space = " ";
            }
            if (!userDefindedArgs.Contains("-p"))
            {
                args += $"{space}-p {Pool.PoolPassword}";
                space = " ";
            }

            if (DeviceConfigs.All(dc => dc.DeviceType != DeviceType.CPU))
            {
                if (!userDefindedArgs.Contains("--no-cpu"))
                {
                    args += $"{space}--no-cpu";
                    space = " ";
                }
            }

            if (DeviceConfigs.Any(dc => dc.DeviceType == DeviceType.AMD))
            {
                if (!userDefindedArgs.Contains("--opencl"))
                {
                    args += $"{space}--opencl";
                    space = " ";
                }
                if (!userDefindedArgs.Any(a => a.StartsWith("--opencl-devices=", StringComparison.OrdinalIgnoreCase)))
                {
                    args += $"{space}--opencl-devices={string.Join(',', DeviceConfigs.Where(dc => dc.DeviceType == DeviceType.AMD).Select(dc => dc.DeviceId))}";
                    space = " ";
                }
            }

            if (DeviceConfigs.Any(dc => dc.DeviceType == DeviceType.NVIDIA))
            {
                if (!userDefindedArgs.Contains("--cuda"))
                {
                    args += $"{space}--cuda";
                    space = " ";
                }
                if (!userDefindedArgs.Any(a => a.StartsWith("--opencl-devices=", StringComparison.OrdinalIgnoreCase)))
                {
                    args += $"{space}--cuda-devices={string.Join(',', DeviceConfigs.Where(dc => dc.DeviceType == DeviceType.NVIDIA).Select(dc => dc.DeviceId))}";
                    space = " ";
                }
            }

            args += $"{space}--http-port={_port}";
            space = " ";


            if (!String.IsNullOrEmpty(firstDevice.MinerArguments))
            {
                args += space + firstDevice.MinerArguments;
            }

            _process.EnableRaisingEvents = true;
            _process.Exited += ProcessOnExited;
            _process.StartInfo.Arguments              = args;
            _process.StartInfo.UseShellExecute        = true;
            _process.StartInfo.CreateNoWindow         = false;
            _process.StartInfo.RedirectStandardOutput = false;
            _process.StartInfo.WorkingDirectory       = minerFolderPath;
            _process.StartInfo.WindowStyle            = minimized ? ProcessWindowStyle.Minimized : ProcessWindowStyle.Normal;
            Log.Debug($"Miner Start Info: \"{_process.StartInfo.FileName}\" {_process.StartInfo.Arguments}");
            _process.Start();
        }
        public void StartMiner(bool minimized)
        {
            _minimized = minimized;
            _process   = new Process();
            DeviceConfig firstDeviceConfig = DeviceConfigs.First();
            string       minerPath         = Helpers.ResolveToFullPath(firstDeviceConfig.MinerPath, Helpers.GetApplicationRoot());
            string       minerFolderPath   = Path.GetDirectoryName(minerPath);

            _process.StartInfo.FileName = "cmd";
            List <string> userDefindedArgs = new List <string>();

            if (!String.IsNullOrEmpty(firstDeviceConfig.MinerArguments))
            {
                userDefindedArgs.AddRange(firstDeviceConfig.MinerArguments.Split(" "));
            }

            if (!String.IsNullOrEmpty(firstDeviceConfig.MinerDeviceSpecificArguments))
            {
                userDefindedArgs.AddRange(firstDeviceConfig.MinerDeviceSpecificArguments.Split(" "));
            }

            string args  = "";
            string space = "";

            if (!userDefindedArgs.Contains("-epool"))
            {
                args  = $"{space}-epool {Pool.PoolUrl}";
                space = " ";
            }

            if (!userDefindedArgs.Contains("-ewal"))
            {
                args += $"{space}-ewal {Pool.PoolUser}";
                space = " ";
            }

            if (!userDefindedArgs.Contains("-epsw"))
            {
                args += $"{space}-epsw {Pool.PoolPassword}";
                space = " ";
            }

            if (!userDefindedArgs.Contains("-di"))
            {
                string devicesString = string.Join("", DeviceConfigs.Select(dc => dc.DeviceId));
                args += $"{space}-di {devicesString}";
                space = " ";
            }

            _port = firstDeviceConfig.MinerApiPort > 0 ? firstDeviceConfig.MinerApiPort : Helpers.GetAvailablePort();
            if (!userDefindedArgs.Contains("-mport"))
            {
                args += $"{space}-mport -{_port}";
                space = " ";
            }

            if (!String.IsNullOrEmpty(firstDeviceConfig.MinerArguments))
            {
                args += space + firstDeviceConfig.MinerArguments;
            }

            if (DeviceConfigs.Any(dc => !string.IsNullOrEmpty(dc.MinerDeviceSpecificArguments)))
            {
                Dictionary <string, List <string> > combinedArgumentsDictionary = new Dictionary <string, List <string> >();
                foreach (DeviceConfig deviceConfig in DeviceConfigs)
                {
                    var splittedArguments = deviceConfig.MinerDeviceSpecificArguments.Split(" ");
                    for (var index = 0; index + 1 < splittedArguments.Length; index += 2)
                    {
                        AddToListInDictionary(combinedArgumentsDictionary, splittedArguments[index], splittedArguments[index + 1]);
                    }
                }
                StringBuilder argumentsBuilder = new StringBuilder();
                bool          first            = true;
                foreach (var combinedArgument in combinedArgumentsDictionary)
                {
                    if (!first)
                    {
                        argumentsBuilder.Append(" ");
                    }

                    first = false;
                    argumentsBuilder.Append(combinedArgument.Key);
                    argumentsBuilder.Append(" ");
                    argumentsBuilder.Append(string.Join(',', combinedArgument.Value));
                }
                args += space + argumentsBuilder;
            }

            _process.EnableRaisingEvents = true;
            _process.Exited += ProcessOnExited;
            _process.StartInfo.Arguments              = $"/c \"{Path.GetFileName(minerPath)} {args}\"";
            _process.StartInfo.UseShellExecute        = true;
            _process.StartInfo.CreateNoWindow         = false;
            _process.StartInfo.RedirectStandardOutput = false;
            _process.StartInfo.WorkingDirectory       = minerFolderPath;
            _process.StartInfo.WindowStyle            = minimized ? ProcessWindowStyle.Minimized : ProcessWindowStyle.Normal;
            Log.Debug($"Miner Start Info: \"{_process.StartInfo.FileName}\" {_process.StartInfo.Arguments}");
            _process.Start();
        }
 public ChumgHsinConnectionUserControl(ChungHsin_MySqlComponent chungHsin_MySqlComponent)
 {
     ChungHsin_MySqlComponent = chungHsin_MySqlComponent;
     CaseSettings             = chungHsin_MySqlComponent.CaseSettings;
     ReceiveSettings          = chungHsin_MySqlComponent.ReceiveSettings;
     DeviceConfigs            = chungHsin_MySqlComponent.DeviceConfigs;
     InitializeComponent();
     #region Receive斷線資訊
     AigridControl.DataSource           = ReceiveSettings;
     gridView1.OptionsBehavior.Editable = false;
     gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
     for (int i = 0; i < gridView1.Columns.Count; i++)
     {
         gridView1.Columns[i].BestFit();
     }
     gridView1.Columns["PK"].Visible             = false;
     gridView1.Columns["NotifyFlag"].Visible     = false;
     gridView1.Columns["DeviceTypeEnum"].Caption = "設備類型";
     gridView1.Columns["CaseNo"].Caption         = "案場名稱";
     gridView1.Columns["ReceiveNo"].Caption      = "Receive編號";
     gridView1.Columns["ReceiveName"].Caption    = "Receive名稱";
     gridView1.Columns["NotifyFlag"].Visible     = false;
     gridView1.Columns["HTimeoutSpan"].Visible   = false;
     gridView1.Columns["MTimeoutSpan"].Visible   = false;
     gridView1.Columns["SendTime"].Visible       = false;
     gridView1.Columns["ConnectionFlag"].Caption = "連線狀態";
     #region 案場名稱顯示功能
     gridView1.CustomColumnDisplayText += (s, e) =>
     {
         if (e.Column.FieldName.ToString() == "CaseNo")
         {
             string cellValue = e.Value.ToString();
             var    data      = CaseSettings.SingleOrDefault(g => g.CaseNo == cellValue);
             if (data != null)
             {
                 e.DisplayText = data.TitleName;
             }
         }
         else if (e.Column.FieldName.ToString() == "DeviceTypeEnum")
         {
             int cellValue = Convert.ToInt32(e.Value);
             var data      = DeviceConfigs.SingleOrDefault(g => g.DeviceTypeEnum == cellValue);
             if (data != null)
             {
                 e.DisplayText = data.DeviceName;
             }
         }
     };
     #endregion
     #region 斷線燈號顯示功能
     gridView1.CustomDrawCell += (s, e) =>
     {
         e.Appearance.TextOptions.HAlignment = HorzAlignment.Center;
         e.Appearance.Options.UseTextOptions = true;
         e.DefaultDraw();
         if (e.Column.FieldName == "ConnectionFlag")
         {
             Color  color;
             string cellValue = e.CellValue.ToString();
             if (cellValue == "不使用")
             {
                 color = normalPriority;
             }
             else if (cellValue == "斷線")
             {
                 color = highPriority;
             }
             else
             {
                 color = lowPriority;
             }
             e.Cache.FillEllipse(e.Bounds.X + 150, e.Bounds.Y + 1, markWidth, markWidth, color);
         }
     };
     #endregion
     #endregion
 }