Beispiel #1
0
 public App()
 {
     if ((NTMinerRegistry.GetIsAutoStart() || CommandLineArgs.IsAutoStart) && NTMinerRegistry.GetIsNoUi())
     {
         NTMinerConsole.Disable();
     }
     VirtualRoot.SetOut(NotiCenterWindowViewModel.Instance);
     Logger.SetDir(MinerClientTempPath.TempLogsDirFullName);
     WpfUtil.Init();
     AppUtil.Init(this);
     AppUtil.IsHotKeyEnabled = true;
     InitializeComponent();
 }
Beispiel #2
0
        protected override void OnStartup(StartupEventArgs e)
        {
            RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
            // 通过群控升级挖矿端的时候升级器可能不存在所以需要下载,下载的时候需要用到下载器所以下载器需要提前注册
            VirtualRoot.Window <ShowFileDownloaderCommand>(LogEnum.DevConsole,
                                                           action: message => {
                UIThread.Execute(() => {
                    FileDownloader.ShowWindow(message.DownloadFileUrl, message.FileTitle, message.DownloadComplete);
                });
            });
            VirtualRoot.Window <UpgradeCommand>(LogEnum.DevConsole,
                                                action: message => {
                AppStatic.Upgrade(message.FileName, message.Callback);
            });
            if (!string.IsNullOrEmpty(CommandLineArgs.Upgrade))
            {
                VirtualRoot.Execute(new UpgradeCommand(CommandLineArgs.Upgrade, () => {
                    UIThread.Execute(() => { Environment.Exit(0); });
                }));
            }
            else
            {
                try {
                    appMutex = new Mutex(true, s_appPipName, out createdNew);
                }
                catch (Exception) {
                    createdNew = false;
                }
                if (createdNew)
                {
                    Logger.InfoDebugLine($"==================NTMiner.exe {NTMinerRoot.CurrentVersion.ToString()}==================");
                    if (!NTMiner.Windows.WMI.IsWmiEnabled)
                    {
                        DialogWindow.ShowDialog(message: "开源矿工无法运行所需的组件,因为本机未开启WMI服务,开源矿工需要使用WMI服务检测windows的内存、显卡等信息,请先手动开启WMI。", title: "提醒", icon: "Icon_Error");
                        Shutdown();
                        Environment.Exit(0);
                    }
                    NTMinerOverClockUtil.ExtractResource();

                    VirtualRoot.SetIsMinerClient(true);
                    NotiCenterWindowViewModel.IsHotKeyEnabled = true;
                    Window splashWindow = _appViewFactory.CreateSplashWindow();
                    splashWindow.Show();
                    NotiCenterWindow.Instance.Show();
                    if (DevMode.IsDevMode)
                    {
                        HandlerIdsWindow window = new HandlerIdsWindow();
                        window.Show();
                    }
                    if (!NTMiner.Windows.Role.IsAdministrator)
                    {
                        NotiCenterWindowViewModel.Instance.Manager
                        .CreateMessage()
                        .Warning("请以管理员身份运行。")
                        .WithButton("点击以管理员身份运行", button => {
                            Wpf.Util.RunAsAdministrator();
                        })
                        .Dismiss().WithButton("忽略", button => {
                        }).Queue();
                    }
                    VirtualRoot.On <StartingMineFailedEvent>("开始挖矿失败", LogEnum.DevConsole,
                                                             action: message => {
                        AppContext.Instance.MinerProfileVm.IsMining = false;
                        Write.UserFail(message.Message);
                    });
                    NTMinerRoot.Instance.Init(() => {
                        _appViewFactory.Link();
                        if (NTMinerRoot.Instance.GpuSet.Count == 0)
                        {
                            NotiCenterWindowViewModel.Instance.Manager.ShowErrorMessage("没有矿卡或矿卡未驱动。");
                        }
                        UIThread.Execute(() => {
                            if (NTMinerRoot.GetIsNoUi() && NTMinerRegistry.GetIsAutoStart())
                            {
                                MainWindow = NotiCenterWindow.Instance;
                                NotiCenterWindowViewModel.Instance.Manager.ShowSuccessMessage("已切换为无界面模式运行,可在选项页调整设置", "开源矿工");
                            }
                            else
                            {
                                _appViewFactory.ShowMainWindow(isToggle: false);
                            }
                            AppContext.NotifyIcon = ExtendedNotifyIcon.Create("开源矿工", isMinerStudio: false);
                            splashWindow?.Close();
                        });
                        #region 处理显示主界面命令
                        VirtualRoot.Window <ShowMainWindowCommand>("处理显示主界面命令", LogEnum.DevConsole,
                                                                   action: message => {
                            ShowMainWindow(message.IsToggle);
                        });
                        #endregion
                        Task.Factory.StartNew(() => {
                            try {
                                HttpServer.Start($"http://localhost:{Consts.MinerClientPort}");
                                NTMinerRoot.Instance.Start();
                                Daemon.DaemonUtil.RunNTMinerDaemon();
                            }
                            catch (Exception ex) {
                                Logger.ErrorDebugLine(ex);
                            }
                        });
                    });
                    Link();
                }
                else
                {
                    try {
                        _appViewFactory.ShowMainWindow(this, MinerServer.NTMinerAppType.MinerClient);
                    }
                    catch (Exception) {
                        DialogWindow.ShowDialog(message: "另一个NTMiner正在运行,请手动结束正在运行的NTMiner进程后再次尝试。", title: "提醒", icon: "Icon_Error");
                        Process currentProcess = Process.GetCurrentProcess();
                        NTMiner.Windows.TaskKill.KillOtherProcess(currentProcess);
                    }
                }
            }
            base.OnStartup(e);
        }
Beispiel #3
0
        public static SpeedData CreateSpeedData()
        {
            INTMinerRoot root = NTMinerRoot.Instance;
            SpeedData    data = new SpeedData {
                KernelSelfRestartCount = 0,
                IsAutoBoot             = NTMinerRegistry.GetIsAutoBoot(),
                IsAutoStart            = NTMinerRegistry.GetIsAutoStart(),
                Version       = NTMinerRoot.CurrentVersion.ToString(4),
                BootOn        = root.CreatedOn,
                MineStartedOn = null,
                IsMining      = root.IsMining,
                MineWorkId    = root.MinerProfile.MineWork != null?root.MinerProfile.MineWork.GetId() : Guid.Empty,
                                    MinerName           = root.MinerProfile.MinerName,
                                    GpuInfo             = root.GpuSetInfo,
                                    ClientId            = VirtualRoot.Id,
                                    MainCoinCode        = string.Empty,
                                    MainCoinWallet      = string.Empty,
                                    MainCoinTotalShare  = 0,
                                    MainCoinRejectShare = 0,
                                    MainCoinSpeed       = 0,
                                    DualCoinCode        = string.Empty,
                                    DualCoinTotalShare  = 0,
                                    DualCoinRejectShare = 0,
                                    DualCoinSpeed       = 0,
                                    DualCoinPool        = string.Empty,
                                    DualCoinWallet      = string.Empty,
                                    IsDualCoinEnabled   = false,
                                    Kernel                       = string.Empty,
                                    MainCoinPool                 = string.Empty,
                                    OSName                       = Windows.OS.Instance.WindowsEdition,
                                    GpuDriver                    = root.GpuSet.DriverVersion,
                                    GpuType                      = root.GpuSet.GpuType,
                                    OSVirtualMemoryMb            = NTMinerRoot.OSVirtualMemoryMb,
                                    KernelCommandLine            = NTMinerRoot.UserKernelCommandLine,
                                    DiskSpace                    = NTMinerRoot.DiskSpace,
                                    IsAutoRestartKernel          = root.MinerProfile.IsAutoRestartKernel,
                                    IsNoShareRestartKernel       = root.MinerProfile.IsNoShareRestartKernel,
                                    IsPeriodicRestartComputer    = root.MinerProfile.IsPeriodicRestartComputer,
                                    IsPeriodicRestartKernel      = root.MinerProfile.IsPeriodicRestartKernel,
                                    NoShareRestartKernelMinutes  = root.MinerProfile.NoShareRestartKernelMinutes,
                                    PeriodicRestartComputerHours = root.MinerProfile.PeriodicRestartComputerHours,
                                    PeriodicRestartKernelHours   = root.MinerProfile.PeriodicRestartKernelHours,
                                    GpuTable                     = root.GpusSpeed.Where(a => a.Gpu.Index != NTMinerRoot.GpuAllId).Select(a => new GpuSpeedData {
                    Index            = a.Gpu.Index,
                    Name             = a.Gpu.Name,
                    TotalMemory      = a.Gpu.TotalMemory,
                    MainCoinSpeed    = a.MainCoinSpeed.Value,
                    DualCoinSpeed    = a.DualCoinSpeed.Value,
                    FanSpeed         = a.Gpu.FanSpeed,
                    Temperature      = a.Gpu.Temperature,
                    PowerUsage       = a.Gpu.PowerUsage,
                    Cool             = a.Gpu.Cool,
                    PowerCapacity    = a.Gpu.PowerCapacity,
                    CoreClockDelta   = a.Gpu.CoreClockDelta,
                    MemoryClockDelta = a.Gpu.MemoryClockDelta,
                    TempLimit        = a.Gpu.TempLimit
                }).ToArray()
            };

            #region 当前选中的币种是什么
            if (root.CoinSet.TryGetCoin(root.MinerProfile.CoinId, out ICoin mainCoin))
            {
                data.MainCoinCode = mainCoin.Code;
                ICoinProfile coinProfile = root.MinerProfile.GetCoinProfile(mainCoin.GetId());
                data.MainCoinWallet = coinProfile.Wallet;
                if (root.PoolSet.TryGetPool(coinProfile.PoolId, out IPool mainCoinPool))
                {
                    data.MainCoinPool = mainCoinPool.Server;
                    if (mainCoinPool.IsUserMode)
                    {
                        IPoolProfile mainCoinPoolProfile = root.MinerProfile.GetPoolProfile(coinProfile.PoolId);
                        data.MainCoinWallet = mainCoinPoolProfile.UserName;
                    }
                }
                else
                {
                    data.MainCoinPool = string.Empty;
                }
                if (root.CoinKernelSet.TryGetCoinKernel(coinProfile.CoinKernelId, out ICoinKernel coinKernel))
                {
                    if (root.KernelSet.TryGetKernel(coinKernel.KernelId, out IKernel kernel))
                    {
                        data.Kernel = kernel.GetFullName();
                        ICoinKernelProfile coinKernelProfile = root.MinerProfile.GetCoinKernelProfile(coinProfile.CoinKernelId);
                        data.IsDualCoinEnabled = coinKernelProfile.IsDualCoinEnabled;
                        if (coinKernelProfile.IsDualCoinEnabled)
                        {
                            if (root.CoinSet.TryGetCoin(coinKernelProfile.DualCoinId, out ICoin dualCoin))
                            {
                                data.DualCoinCode = dualCoin.Code;
                                ICoinProfile dualCoinProfile = root.MinerProfile.GetCoinProfile(dualCoin.GetId());
                                data.DualCoinWallet = dualCoinProfile.DualCoinWallet;
                                if (root.PoolSet.TryGetPool(dualCoinProfile.DualCoinPoolId, out IPool dualCoinPool))
                                {
                                    data.DualCoinPool = dualCoinPool.Server;
                                    if (dualCoinPool.IsUserMode)
                                    {
                                        IPoolProfile dualCoinPoolProfile = root.MinerProfile.GetPoolProfile(dualCoinProfile.DualCoinPoolId);
                                        data.DualCoinWallet = dualCoinPoolProfile.UserName;
                                    }
                                }
                                else
                                {
                                    data.DualCoinPool = string.Empty;
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            if (root.IsMining)
            {
                var mineContext = root.CurrentMineContext;
                if (mineContext != null)
                {
                    data.KernelSelfRestartCount = mineContext.KernelSelfRestartCount;
                    data.MineStartedOn          = mineContext.CreatedOn;
                    data.KernelCommandLine      = mineContext.CommandLine;
                }
                // 判断上次报告的算力币种和本次报告的是否相同,否则说明刚刚切换了币种默认第一次报告0算力
                if (_sLastSpeedMainCoin == null || _sLastSpeedMainCoin == root.CurrentMineContext.MainCoin)
                {
                    _sLastSpeedMainCoin = root.CurrentMineContext.MainCoin;
                    Guid       coinId     = root.CurrentMineContext.MainCoin.GetId();
                    IGpusSpeed gpuSpeeds  = NTMinerRoot.Instance.GpusSpeed;
                    IGpuSpeed  totalSpeed = gpuSpeeds.CurrentSpeed(NTMinerRoot.GpuAllId);
                    data.MainCoinSpeed = totalSpeed.MainCoinSpeed.Value;
                    ICoinShare share = root.CoinShareSet.GetOrCreate(coinId);
                    data.MainCoinTotalShare  = share.TotalShareCount;
                    data.MainCoinRejectShare = share.RejectShareCount;
                }
                else
                {
                    _sLastSpeedMainCoin = root.CurrentMineContext.MainCoin;
                }
                if (root.CurrentMineContext is IDualMineContext dualMineContext)
                {
                    // 判断上次报告的算力币种和本次报告的是否相同,否则说明刚刚切换了币种默认第一次报告0算力
                    if (_sLastSpeedDualCoin == null || _sLastSpeedDualCoin == dualMineContext.DualCoin)
                    {
                        _sLastSpeedDualCoin = dualMineContext.DualCoin;
                        Guid       coinId     = dualMineContext.DualCoin.GetId();
                        IGpusSpeed gpuSpeeds  = NTMinerRoot.Instance.GpusSpeed;
                        IGpuSpeed  totalSpeed = gpuSpeeds.CurrentSpeed(NTMinerRoot.GpuAllId);
                        data.DualCoinSpeed = totalSpeed.DualCoinSpeed.Value;
                        ICoinShare share = root.CoinShareSet.GetOrCreate(coinId);
                        data.DualCoinTotalShare  = share.TotalShareCount;
                        data.DualCoinRejectShare = share.RejectShareCount;
                    }
                    else
                    {
                        _sLastSpeedDualCoin = dualMineContext.DualCoin;
                    }
                }
            }
            return(data);
        }
Beispiel #4
0
 private void DoRun()
 {
     if (AppUtil.GetMutex(NTKeyword.MinerClientAppMutex))
     {
         NotiCenterWindow.ShowWindow();
         Logger.InfoDebugLine($"==================NTMiner.exe {EntryAssemblyInfo.CurrentVersionStr}==================");
         // 在另一个UI线程运行欢迎界面以确保欢迎界面的响应不被耗时的主界面初始化过程阻塞
         // 注意:必须确保SplashWindow没有用到任何其它界面用到的依赖对象
         SplashWindow splashWindow = null;
         SplashWindow.ShowWindowAsync(window => {
             splashWindow = window;
         });
         if (!NTMiner.Windows.WMI.IsWmiEnabled)
         {
             DialogWindow.ShowHardDialog(new DialogWindowViewModel(
                                             message: "开源矿工无法运行所需的组件,因为本机未开启WMI服务,开源矿工需要使用WMI服务检测windows的内存、显卡等信息,请先手动开启WMI。",
                                             title: "提醒",
                                             icon: "Icon_Error"));
             Shutdown();
             Environment.Exit(0);
         }
         if (!NTMiner.Windows.Role.IsAdministrator)
         {
             NotiCenterWindowViewModel.Instance.Manager
             .CreateMessage()
             .Warning("提示", "请以管理员身份运行。")
             .WithButton("点击以管理员身份运行", button => {
                 WpfUtil.RunAsAdministrator();
             })
             .Dismiss().WithButton("忽略", button => {
             }).Queue();
         }
         BuildPaths();
         NTMinerContext.Instance.Init(() => {
             _appViewFactory.BuildPaths();
             if (VirtualRoot.IsLTWin10)
             {
                 VirtualRoot.ThisLocalWarn(nameof(App), AppRoot.LowWinMessage, toConsole: true);
             }
             if (NTMinerContext.Instance.GpuSet.Count == 0)
             {
                 VirtualRoot.ThisLocalError(nameof(App), "没有矿卡或矿卡未驱动。", toConsole: true);
             }
             if (NTMinerContext.WorkType != WorkType.None && NTMinerContext.Instance.ServerContext.CoinSet.Count == 0)
             {
                 VirtualRoot.ThisLocalError(nameof(App), "访问阿里云失败,请尝试更换本机dns解决此问题。", toConsole: true);
             }
             UIThread.Execute(() => {
                 Window mainWindow  = null;
                 AppRoot.NotifyIcon = ExtendedNotifyIcon.Create("开源矿工", isMinerStudio: false);
                 if (NTMinerRegistry.GetIsNoUi() && NTMinerRegistry.GetIsAutoStart())
                 {
                     ConsoleWindow.Instance.Hide();
                     VirtualRoot.Out.ShowSuccess("以无界面模式启动,可在选项页调整设置", header: "开源矿工");
                 }
                 else
                 {
                     _appViewFactory.ShowMainWindow(isToggle: false, out mainWindow);
                 }
                 // 主窗口显式后退出SplashWindow
                 splashWindow?.Dispatcher.Invoke((Action) delegate() {
                     splashWindow?.OkClose();
                 });
                 // 启动时Windows状态栏显式的是SplashWindow的任务栏图标,SplashWindow关闭后激活主窗口的Windows任务栏图标
                 mainWindow?.Activate();
                 StartStopMineButtonViewModel.Instance.AutoStart();
                 // 注意:因为推迟到这里才启动的计时器,所以别忘了在Upgrade、和Action情况时启动计时器
                 VirtualRoot.StartTimer(new WpfTimingEventProducer());
                 if (CommandLineArgs.Action.TryParse(out MinerClientActionType resourceType))
                 {
                     VirtualRoot.Execute(new MinerClientActionCommand(resourceType));
                 }
             });
             Task.Factory.StartNew(() => {
                 var minerProfile = NTMinerContext.Instance.MinerProfile;
                 if (minerProfile.IsDisableUAC)
                 {
                     NTMiner.Windows.UAC.DisableUAC();
                 }
                 if (minerProfile.IsAutoDisableWindowsFirewall)
                 {
                     Firewall.DisableFirewall();
                 }
                 if (minerProfile.IsDisableWAU)
                 {
                     NTMiner.Windows.WAU.DisableWAUAsync();
                 }
                 if (minerProfile.IsDisableAntiSpyware)
                 {
                     NTMiner.Windows.Defender.DisableAntiSpyware();
                 }
                 if (!Firewall.IsMinerClientRuleExists())
                 {
                     Firewall.AddMinerClientRule();
                 }
                 try {
                     HttpServer.Start($"http://{NTKeyword.Localhost}:{NTKeyword.MinerClientPort.ToString()}");
                     Daemon.DaemonUtil.RunNTMinerDaemon();
                     NoDevFee.NoDevFeeUtil.RunNTMinerNoDevFee();
                 }
                 catch (Exception ex) {
                     Logger.ErrorDebugLine(ex);
                 }
             });
         });
     }
     else
     {
         try {
             _appViewFactory.ShowMainWindow(this, NTMinerAppType.MinerClient);
         }
         catch (Exception) {
             DialogWindow.ShowSoftDialog(new DialogWindowViewModel(
                                             message: "另一个开源矿工正在运行但唤醒失败,请重试。",
                                             title: "错误",
                                             icon: "Icon_Error"));
             Process currentProcess = Process.GetCurrentProcess();
             NTMiner.Windows.TaskKill.KillOtherProcess(currentProcess);
         }
     }
 }
Beispiel #5
0
        private void Link()
        {
            VirtualRoot.Window <RegCmdHereCommand>("处理注册右键打开windows命令行菜单命令", LogEnum.DevConsole,
                                                   action: message => {
                try {
                    RegCmdHere();
                    VirtualRoot.Happened(new RegCmdHereEvent(true, "windows右键命令行添加成功"));
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                    VirtualRoot.Happened(new RegCmdHereEvent(false, "windows右键命令行添加失败"));
                }
            });
            #region 挖矿开始时将无份额内核重启份额计数置0
            int      shareCount = 0;
            DateTime shareOn    = DateTime.Now;
            VirtualRoot.On <MineStartedEvent>("挖矿开始后将无份额内核重启份额计数置0", LogEnum.DevConsole,
                                              action: message => {
                // 将无份额内核重启份额计数置0
                shareCount = 0;
                if (!message.MineContext.IsRestart)
                {
                    shareOn = DateTime.Now;
                }
            });
            #endregion
            #region 每20秒钟检查是否需要重启
            VirtualRoot.On <Per20SecondEvent>("每20秒钟检查是否需要重启", LogEnum.None,
                                              action: message => {
                #region 重启电脑
                try {
                    if (MinerProfile.IsPeriodicRestartComputer)
                    {
                        if ((DateTime.Now - this.CreatedOn).TotalMinutes > 60 * MinerProfile.PeriodicRestartComputerHours + MinerProfile.PeriodicRestartComputerMinutes)
                        {
                            Logger.WarnWriteLine($"每运行{MinerProfile.PeriodicRestartKernelHours}小时{MinerProfile.PeriodicRestartComputerMinutes}分钟重启电脑");
                            Windows.Power.Restart(60);
                            VirtualRoot.Execute(new CloseNTMinerCommand());
                            return;    // 退出
                        }
                    }
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                }
                #endregion

                #region 周期重启内核
                try {
                    if (IsMining && MinerProfile.IsPeriodicRestartKernel)
                    {
                        if ((DateTime.Now - CurrentMineContext.CreatedOn).TotalMinutes > 60 * MinerProfile.PeriodicRestartKernelHours + MinerProfile.PeriodicRestartKernelMinutes)
                        {
                            Logger.WarnWriteLine($"每运行{MinerProfile.PeriodicRestartKernelHours}小时{MinerProfile.PeriodicRestartKernelMinutes}分钟重启内核");
                            RestartMine();
                            return;    // 退出
                        }
                    }
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                }
                #endregion

                #region 收益没有增加重启内核
                try {
                    if (IsMining && this.CurrentMineContext.MainCoin != null)
                    {
                        int totalShare       = 0;
                        bool restartComputer = MinerProfile.IsNoShareRestartComputer && (DateTime.Now - shareOn).TotalMinutes > MinerProfile.NoShareRestartComputerMinutes;
                        bool restartKernel   = MinerProfile.IsNoShareRestartKernel && (DateTime.Now - shareOn).TotalMinutes > MinerProfile.NoShareRestartKernelMinutes;
                        if (restartComputer || restartKernel)
                        {
                            ICoinShare mainCoinShare = this.CoinShareSet.GetOrCreate(this.CurrentMineContext.MainCoin.GetId());
                            totalShare = mainCoinShare.TotalShareCount;
                            if ((this.CurrentMineContext is IDualMineContext dualMineContext) && dualMineContext.DualCoin != null)
                            {
                                ICoinShare dualCoinShare = this.CoinShareSet.GetOrCreate(dualMineContext.DualCoin.GetId());
                                totalShare += dualCoinShare.TotalShareCount;
                            }
                            // 如果份额没有增加
                            if (shareCount == totalShare)
                            {
                                if (restartComputer)
                                {
                                    if (!NTMinerRegistry.GetIsAutoBoot())
                                    {
                                        NTMinerRegistry.SetIsAutoBoot(true);
                                    }
                                    if (!NTMinerRegistry.GetIsAutoStart())
                                    {
                                        NTMinerRegistry.SetIsAutoStart(true);
                                    }
                                    Logger.WarnWriteLine($"{MinerProfile.NoShareRestartComputerMinutes}分钟收益没有增加重启电脑");
                                    Windows.Power.Restart(60);
                                    VirtualRoot.Execute(new CloseNTMinerCommand());
                                    return;    // 退出
                                }
                                // 产生过份额或者已经两倍重启内核时间了
                                if (restartKernel && (totalShare > 0 || (DateTime.Now - shareOn).TotalMinutes > 2 * MinerProfile.NoShareRestartKernelMinutes))
                                {
                                    Logger.WarnWriteLine($"{MinerProfile.NoShareRestartKernelMinutes}分钟收益没有增加重启内核");
                                    RestartMine();
                                    return;    // 退出
                                }
                            }
                            if (totalShare > shareCount)
                            {
                                shareCount = totalShare;
                                shareOn    = DateTime.Now;
                            }
                        }
Beispiel #6
0
        private void Link()
        {
            VirtualRoot.BuildCmdPath <RegCmdHereCommand>(path: message => {
                try {
                    Windows.Cmd.RegCmdHere();
                    VirtualRoot.ThisLocalInfo(nameof(NTMinerContext), "添加windows右键命令行成功");
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                    VirtualRoot.ThisLocalError(nameof(NTMinerContext), "添加windows右键命令行失败", OutEnum.Warn);
                }
            }, location: this.GetType());
            VirtualRoot.BuildCmdPath <UnRegCmdHereCommand>(path: message => {
                try {
                    Windows.Cmd.UnRegCmdHere();
                    VirtualRoot.ThisLocalInfo(nameof(NTMinerContext), "移除windows右键命令行成功");
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                    VirtualRoot.ThisLocalError(nameof(NTMinerContext), "移除windows右键命令行失败", OutEnum.Warn);
                }
            }, location: this.GetType());
            VirtualRoot.BuildEventPath <Per1MinuteEvent>("每1分钟阻止系统休眠", LogEnum.None,
                                                         path: message => {
                Power.PreventSleep(MinerProfile.IsPreventDisplaySleep);
            }, location: this.GetType());
            #region 挖矿开始时将无份额内核重启份额计数置0
            int      shareCount   = 0;
            DateTime shareOn      = DateTime.Now;
            DateTime hightSpeedOn = DateTime.Now;
            VirtualRoot.BuildEventPath <MineStartedEvent>("挖矿开始后将无份额内核重启份额计数置0", LogEnum.DevConsole,
                                                          path: message => {
                // 将无份额内核重启份额计数置0
                shareCount   = 0;
                hightSpeedOn = DateTime.Now;
                if (!message.MineContext.IsRestart)
                {
                    // 当不是内核重启时更新shareOn,如果是内核重启不用更新shareOn从而给不干扰无内核矿机重启的逻辑
                    shareOn = DateTime.Now;
                }
            }, location: this.GetType());
            #endregion
            #region 每20秒钟检查是否需要重启
            VirtualRoot.BuildEventPath <Per20SecondEvent>("每20秒钟检查是否需要重启", LogEnum.None,
                                                          path: message => {
                #region 低算力重启电脑
                if (IsMining && LockedMineContext.ProcessCreatedOn != DateTime.MinValue)
                {
                    var coinProfile = MinerProfile.GetCoinProfile(MinerProfile.CoinId);
                    if (coinProfile.IsLowSpeedRestartComputer && coinProfile.LowSpeed != 0 && coinProfile.LowSpeedRestartComputerMinutes > 0)
                    {
                        IGpuSpeed totalSpeed = GpusSpeed.CurrentSpeed(GpuAllId);
                        if (totalSpeed.MainCoinSpeed.SpeedOn.AddMinutes(coinProfile.LowSpeedRestartComputerMinutes) >= message.BornOn)
                        {
                            if (totalSpeed.MainCoinSpeed.Value.ToNearSpeed(coinProfile.LowSpeed) >= coinProfile.LowSpeed)
                            {
                                hightSpeedOn = message.BornOn;
                            }
                        }
                        if (hightSpeedOn.AddMinutes(coinProfile.LowSpeedRestartComputerMinutes) < message.BornOn)
                        {
                            string coinCode = string.Empty;
                            if (ServerContext.CoinSet.TryGetCoin(MinerProfile.CoinId, out ICoin coin))
                            {
                                coinCode = coin.Code;
                            }
                            VirtualRoot.ThisLocalWarn(nameof(NTMinerContext), $"{coinCode}总算力持续{coinProfile.LowSpeedRestartComputerMinutes}分钟低于{coinProfile.LowSpeed}重启电脑", toConsole: true);
                            VirtualRoot.Execute(new ShowRestartWindowsCommand(countDownSeconds: 10));
                            if (!MinerProfile.IsAutoBoot || !NTMinerRegistry.GetIsAutoStart())
                            {
                                VirtualRoot.Execute(new SetAutoStartCommand(true, true));
                            }
                            return;
                        }
                    }
                    else
                    {
                        hightSpeedOn = message.BornOn;
                    }
                }
                #endregion

                #region 周期重启电脑
                try {
                    if (MinerProfile.IsPeriodicRestartComputer)
                    {
                        if ((DateTime.Now - this.CreatedOn).TotalMinutes > 60 * MinerProfile.PeriodicRestartComputerHours + MinerProfile.PeriodicRestartComputerMinutes)
                        {
                            string content = $"每运行{MinerProfile.PeriodicRestartKernelHours.ToString()}小时{MinerProfile.PeriodicRestartComputerMinutes.ToString()}分钟重启电脑";
                            VirtualRoot.ThisLocalWarn(nameof(NTMinerContext), content, toConsole: true);
                            VirtualRoot.Execute(new ShowRestartWindowsCommand(countDownSeconds: 10));
                            if (!MinerProfile.IsAutoBoot || !NTMinerRegistry.GetIsAutoStart())
                            {
                                VirtualRoot.Execute(new SetAutoStartCommand(true, true));
                            }
                            return;    // 退出
                        }
                    }
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                }
                #endregion

                #region 周期重启内核
                try {
                    if (IsMining && MinerProfile.IsPeriodicRestartKernel && LockedMineContext.MineStartedOn != DateTime.MinValue)
                    {
                        if ((DateTime.Now - LockedMineContext.MineStartedOn).TotalMinutes > 60 * MinerProfile.PeriodicRestartKernelHours + MinerProfile.PeriodicRestartKernelMinutes)
                        {
                            VirtualRoot.ThisLocalWarn(nameof(NTMinerContext), $"每运行{MinerProfile.PeriodicRestartKernelHours.ToString()}小时{MinerProfile.PeriodicRestartKernelMinutes.ToString()}分钟重启内核", toConsole: true);
                            RestartMine();
                            return;    // 退出
                        }
                    }
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                }
                #endregion

                #region 无份额重启内核
                try {
                    if (IsMining && this.LockedMineContext.MainCoin != null)
                    {
                        int totalShare       = 0;
                        bool restartComputer = MinerProfile.NoShareRestartComputerMinutes > 0 && MinerProfile.IsNoShareRestartComputer && (DateTime.Now - shareOn).TotalMinutes > MinerProfile.NoShareRestartComputerMinutes;
                        bool restartKernel   = MinerProfile.NoShareRestartKernelMinutes > 0 && MinerProfile.IsNoShareRestartKernel && (DateTime.Now - shareOn).TotalMinutes > MinerProfile.NoShareRestartKernelMinutes;
                        if (restartComputer || restartKernel)
                        {
                            ICoinShare mainCoinShare = this.CoinShareSet.GetOrCreate(this.LockedMineContext.MainCoin.GetId());
                            totalShare = mainCoinShare.TotalShareCount;
                            if ((this.LockedMineContext is IDualMineContext dualMineContext) && dualMineContext.DualCoin != null)
                            {
                                ICoinShare dualCoinShare = this.CoinShareSet.GetOrCreate(dualMineContext.DualCoin.GetId());
                                totalShare += dualCoinShare.TotalShareCount;
                            }
                            // 如果份额没有增加
                            if (shareCount == totalShare)
                            {
                                bool isMineStartedARestartComputerMinutes = (DateTime.Now - this.LockedMineContext.MineStartedOn).TotalMinutes > MinerProfile.NoShareRestartComputerMinutes;
                                if (restartComputer && isMineStartedARestartComputerMinutes)
                                {
                                    if (!MinerProfile.IsAutoBoot || !NTMinerRegistry.GetIsAutoStart())
                                    {
                                        VirtualRoot.Execute(new SetAutoStartCommand(true, true));
                                    }
                                    string content = $"{MinerProfile.NoShareRestartComputerMinutes.ToString()}分钟无份额重启电脑";
                                    VirtualRoot.ThisLocalWarn(nameof(NTMinerContext), content, toConsole: true);
                                    VirtualRoot.Execute(new ShowRestartWindowsCommand(countDownSeconds: 10));
                                    return;    // 退出
                                }
                                bool isMineStartedARestartKernelMinutes = (DateTime.Now - this.LockedMineContext.MineStartedOn).TotalMinutes > MinerProfile.NoShareRestartKernelMinutes;
                                if (restartKernel && isMineStartedARestartKernelMinutes)
                                {
                                    VirtualRoot.ThisLocalWarn(nameof(NTMinerContext), $"{MinerProfile.NoShareRestartKernelMinutes.ToString()}分钟无份额重启内核", toConsole: true);
                                    RestartMine();
                                    return;    // 退出
                                }
                            }
                            if (totalShare > shareCount)
                            {
                                shareCount = totalShare;
                                shareOn    = DateTime.Now;
                            }
                        }
Beispiel #7
0
        protected override void OnStartup(StartupEventArgs e)
        {
            RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
            if (!string.IsNullOrEmpty(CommandLineArgs.Upgrade))
            {
                AppStatic.Upgrade(CommandLineArgs.Upgrade, () => {
                    Environment.Exit(0);
                });
            }
            else
            {
                try {
                    appMutex = new Mutex(true, s_appPipName, out createdNew);
                }
                catch (Exception) {
                    createdNew = false;
                }
                if (createdNew)
                {
                    if (!NTMiner.Windows.WMI.IsWmiEnabled)
                    {
                        DialogWindow.ShowDialog(message: "开源矿工无法运行所需的组件,因为本机未开机WMI服务,开源矿工需要使用WMI服务检测windows的内存、显卡等信息,请先手动开启WMI。", title: "提醒", icon: "Icon_Error");
                        Shutdown();
                        Environment.Exit(0);
                    }
                    NTMinerOverClockUtil.ExtractResource();

                    AppStatic.SetIsMinerClient(true);
                    NotiCenterWindowViewModel.IsHotKeyEnabled = true;
                    SplashWindow splashWindow = new SplashWindow();
                    splashWindow.Show();
                    NotiCenterWindow.Instance.Show();
                    NTMinerRoot.Instance.Init(() => {
                        NTMinerRoot.KernelDownloader = new KernelDownloader();
                        UIThread.Execute(() => {
                            if (!NTMinerRegistry.GetIsNoUi() || !NTMinerRegistry.GetIsAutoStart())
                            {
                                Views.MainWindow.ShowMainWindow();
                            }
                            else
                            {
                                NotiCenterWindowViewModel.Instance.Manager.ShowSuccessMessage("已切换为无界面模式运行", "开源矿工");
                            }
                            System.Drawing.Icon icon = new System.Drawing.Icon(GetResourceStream(new Uri("pack://application:,,,/NTMiner;component/logo.ico")).Stream);
                            AppHelper.NotifyIcon     = ExtendedNotifyIcon.Create(icon, "开源矿工", isMinerStudio: false);
                            #region 处理显示主界面命令
                            VirtualRoot.Window <ShowMainWindowCommand>("处理显示主界面命令", LogEnum.None,
                                                                       action: message => {
                                UIThread.Execute(() => {
                                    MainWindow mainWindow = this.MainWindow as MainWindow;
                                    if (mainWindow == null)
                                    {
                                        AppContext.Enable();
                                        Views.MainWindow.ShowMainWindow();
                                        // 使状态栏显示显示最新状态
                                        if (NTMinerRoot.Instance.IsMining)
                                        {
                                            var coinShare = NTMinerRoot.Instance.CoinShareSet.GetOrCreate(NTMinerRoot.Instance.CurrentMineContext.MainCoin.GetId());
                                            VirtualRoot.Happened(new ShareChangedEvent(coinShare));
                                            if (NTMinerRoot.Instance.CurrentMineContext is IDualMineContext dualMineContext)
                                            {
                                                coinShare = NTMinerRoot.Instance.CoinShareSet.GetOrCreate(dualMineContext.DualCoin.GetId());
                                                VirtualRoot.Happened(new ShareChangedEvent(coinShare));
                                            }
                                            AppContext.Instance.GpuSpeedVms.Refresh();
                                        }
                                    }
                                    else
                                    {
                                        mainWindow.ShowThisWindow(message.IsToggle);
                                    }
                                });
                            });
                            #endregion
                            splashWindow?.Close();
                            Task.Factory.StartNew(() => {
                                try {
                                    HttpServer.Start($"http://localhost:{WebApiConst.MinerClientPort}");
                                    NTMinerRoot.Instance.Start();
                                }
                                catch (Exception ex) {
                                    Logger.ErrorDebugLine(ex.Message, ex);
                                }
                            });
                        });
                    });
                    Link();
                }
                else
                {
                    try {
                        AppHelper.ShowMainWindow(this, MinerServer.NTMinerAppType.MinerClient);
                    }
                    catch (Exception) {
                        DialogWindow.ShowDialog(message: "另一个NTMiner正在运行,请手动结束正在运行的NTMiner进程后再次尝试。", title: "提醒", icon: "Icon_Error");
                        Process currentProcess = Process.GetCurrentProcess();
                        NTMiner.Windows.TaskKill.KillOtherProcess(currentProcess);
                    }
                }
            }
            base.OnStartup(e);
        }