Exemple #1
0
 private static void SwitchRadeonGpuMode(bool on)
 {
     SwitchRadeonGpu.SwitchRadeonGpu.Run(on, (isSuccess, e) => {
         if (isSuccess)
         {
             if (on)
             {
                 VirtualRoot.ThisWorkerInfo(nameof(App), "开启A卡计算模式成功", OutEnum.Success);
             }
             else
             {
                 VirtualRoot.ThisWorkerInfo(nameof(App), "关闭A卡计算模式成功", OutEnum.Success);
             }
         }
         else if (e != null)
         {
             VirtualRoot.Out.ShowError(e.Message, delaySeconds: 4);
         }
         else
         {
             if (on)
             {
                 VirtualRoot.ThisWorkerError(nameof(App), "开启A卡计算模式失败", OutEnum.Warn);
             }
             else
             {
                 VirtualRoot.ThisWorkerError(nameof(App), "关闭A卡计算模式失败", OutEnum.Warn);
             }
         }
     });
 }
Exemple #2
0
        protected override void OnStartup(StartupEventArgs e)
        {
            RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
            // 通过群控升级挖矿端的时候升级器可能不存在所以需要下载,下载的时候需要用到下载器所以下载器需要提前注册
            VirtualRoot.BuildCmdPath <ShowFileDownloaderCommand>(action: message => {
                UIThread.Execute(() => {
                    FileDownloader.ShowWindow(message.DownloadFileUrl, message.FileTitle, message.DownloadComplete);
                });
            });
            VirtualRoot.BuildCmdPath <UpgradeCommand>(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 {MainAssemblyInfo.CurrentVersion.ToString()}==================");
                    if (!NTMiner.Windows.WMI.IsWmiEnabled)
                    {
                        DialogWindow.ShowDialog(new DialogWindowViewModel(
                                                    message: "开源矿工无法运行所需的组件,因为本机未开启WMI服务,开源矿工需要使用WMI服务检测windows的内存、显卡等信息,请先手动开启WMI。",
                                                    title: "提醒",
                                                    icon: "Icon_Error"));
                        Shutdown();
                        Environment.Exit(0);
                    }

                    NotiCenterWindowViewModel.IsHotKeyEnabled = true;
                    ConsoleWindow.Instance.Show();
                    NotiCenterWindow.Instance.Show();
                    if (!NTMiner.Windows.Role.IsAdministrator)
                    {
                        NotiCenterWindowViewModel.Instance.Manager
                        .CreateMessage()
                        .Warning("请以管理员身份运行。")
                        .WithButton("点击以管理员身份运行", button => {
                            WpfUtil.RunAsAdministrator();
                        })
                        .Dismiss().WithButton("忽略", button => {
                        }).Queue();
                    }
                    VirtualRoot.BuildEventPath <StartingMineFailedEvent>("开始挖矿失败", LogEnum.DevConsole,
                                                                         action: message => {
                        AppContext.Instance.MinerProfileVm.IsMining = false;
                        VirtualRoot.Out.ShowError(message.Message);
                    });
                    NTMinerRoot.Instance.Init(() => {
                        _appViewFactory.Link();
                        if (VirtualRoot.IsLTWin10)
                        {
                            VirtualRoot.ThisWorkerWarn(nameof(App), AppStatic.LowWinMessage, toConsole: true);
                        }
                        if (NTMinerRoot.Instance.GpuSet.Count == 0)
                        {
                            VirtualRoot.ThisWorkerError(nameof(App), "没有矿卡或矿卡未驱动。", toConsole: true);
                        }
                        if (NTMinerRoot.Instance.CoinSet.Count == 0)
                        {
                            VirtualRoot.ThisWorkerError(nameof(App), "访问阿里云失败,请尝试更换本机dns解决此问题。", toConsole: true);
                        }
                        UIThread.Execute(() => {
                            if (NTMinerRoot.Instance.MinerProfile.IsNoUi && NTMinerRoot.Instance.MinerProfile.IsAutoStart)
                            {
                                ConsoleWindow.Instance.Hide();
                                VirtualRoot.Out.ShowSuccess("已切换为无界面模式运行,可在选项页调整设置", "开源矿工");
                            }
                            else
                            {
                                _appViewFactory.ShowMainWindow(isToggle: false);
                            }
                            StartStopMineButtonViewModel.Instance.AutoStart();
                            AppContext.NotifyIcon = ExtendedNotifyIcon.Create("开源矿工", isMinerStudio: false);
                            ConsoleWindow.Instance.HideSplash();
                        });
                        #region 处理显示主界面命令
                        VirtualRoot.BuildCmdPath <ShowMainWindowCommand>(action: message => {
                            ShowMainWindow(message.IsToggle);
                        });
                        #endregion
                        Task.Factory.StartNew(() => {
                            try {
                                HttpServer.Start($"http://localhost:{VirtualRoot.MinerClientPort}");
                                Daemon.DaemonUtil.RunNTMinerDaemon();
                            }
                            catch (Exception ex) {
                                Logger.ErrorDebugLine(ex);
                            }
                        });
                    });
                    Link();
                }
                else
                {
                    try {
                        _appViewFactory.ShowMainWindow(this, MinerServer.NTMinerAppType.MinerClient);
                    }
                    catch (Exception) {
                        DialogWindow.ShowDialog(new DialogWindowViewModel(
                                                    message: "另一个NTMiner正在运行,请手动结束正在运行的NTMiner进程后再次尝试。",
                                                    title: "提醒",
                                                    icon: "Icon_Error"));
                        Process currentProcess = Process.GetCurrentProcess();
                        NTMiner.Windows.TaskKill.KillOtherProcess(currentProcess);
                    }
                }
            }
            base.OnStartup(e);
        }
Exemple #3
0
        private void Link()
        {
            VirtualRoot.BuildCmdPath <RegCmdHereCommand>(action: message => {
                try {
                    RegCmdHere(); VirtualRoot.ThisWorkerInfo(nameof(NTMinerRoot), "windows右键命令行添加成功", OutEnum.Success);
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                    RegCmdHere(); VirtualRoot.ThisWorkerError(nameof(NTMinerRoot), "windows右键命令行添加失败", OutEnum.Warn);
                }
            });
            VirtualRoot.BuildEventPath <Per1MinuteEvent>("每1分钟阻止系统休眠", LogEnum.None,
                                                         action: message => {
                Windows.Power.PreventSleep();
            });
            #region 挖矿开始时将无份额内核重启份额计数置0
            int      shareCount = 0;
            DateTime shareOn    = DateTime.Now;
            VirtualRoot.BuildEventPath <MineStartedEvent>("挖矿开始后将无份额内核重启份额计数置0", LogEnum.DevConsole,
                                                          action: message => {
                // 将无份额内核重启份额计数置0
                shareCount = 0;
                if (!message.MineContext.IsRestart)
                {
                    shareOn = DateTime.Now;
                }
            });
            #endregion
            #region 每20秒钟检查是否需要重启
            VirtualRoot.BuildEventPath <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 (!MinerProfile.IsAutoBoot || !MinerProfile.IsAutoStart)
                                    {
                                        VirtualRoot.Execute(new SetAutoStartCommand(true, 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;
                            }
                        }
Exemple #4
0
 public void Init(Action callback)
 {
     Task.Factory.StartNew(() => {
         bool isWork = Environment.GetCommandLineArgs().Contains("--work", StringComparer.OrdinalIgnoreCase);
         if (isWork)   // 是作业
         {
             DoInit(isWork, callback);
             if (VirtualRoot.IsMinerClient)
             {
                 NTMinerRegistry.SetIsLastIsWork(true);
             }
         }
         else   // 不是作业
         {
             if (VirtualRoot.IsMinerClient)
             {
                 NTMinerRegistry.SetIsLastIsWork(false);
             }
             // 如果是Debug模式且不是群控客户端则使用本地数据库初始化
             bool useLocalDb = DevMode.IsDebugMode && !VirtualRoot.IsMinerStudio;
             if (useLocalDb)
             {
                 DoInit(isWork: false, callback: callback);
             }
             else
             {
                 Logger.InfoDebugLine("开始下载server.json");
                 GetAliyunServerJson((data) => {
                     // 如果server.json未下载成功则不覆写本地server.json
                     if (data != null && data.Length != 0)
                     {
                         Logger.InfoDebugLine("GetAliyunServerJson下载成功");
                         var serverJson = Encoding.UTF8.GetString(data);
                         if (!string.IsNullOrEmpty(serverJson))
                         {
                             SpecialPath.WriteServerJsonFile(serverJson);
                         }
                         OfficialServer.GetJsonFileVersionAsync(MainAssemblyInfo.ServerJsonFileName, (serverJsonFileVersion, minerClientVersion) => {
                             SetServerJsonVersion(serverJsonFileVersion);
                             AppVersionChangedEvent.PublishIfNewVersion(minerClientVersion);
                         });
                     }
                     else
                     {
                         if (!File.Exists(SpecialPath.ServerJsonFileFullName))
                         {
                             VirtualRoot.ThisWorkerError(nameof(NTMinerRoot), "配置文件下载失败,这是第一次运行开源矿工,配置文件至少需要成功下载一次,请检查网络是否可用", OutEnum.Warn);
                         }
                         else
                         {
                             VirtualRoot.ThisWorkerWarn(nameof(NTMinerRoot), "配置文件下载失败,使用最后一次成功下载的配置文件", OutEnum.Warn);
                         }
                     }
                     DoInit(isWork, callback);
                 });
                 #region 发生了用户活动时检查serverJson是否有新版本
                 VirtualRoot.BuildEventPath <UserActionEvent>("发生了用户活动时检查serverJson是否有新版本", LogEnum.DevConsole,
                                                              action: message => {
                     RefreshServerJsonFile();
                 });
                 #endregion
             }
         }
         VirtualRoot.ThisWorkerInfo(nameof(NTMinerRoot), "启动");
     });
 }
Exemple #5
0
 public static void Upgrade(string fileName, Action callback)
 {
     try {
         OfficialServer.FileUrlService.GetNTMinerUpdaterUrlAsync((downloadFileUrl, e) => {
             try {
                 string argument = string.Empty;
                 if (!string.IsNullOrEmpty(fileName))
                 {
                     argument = "ntminerFileName=" + fileName;
                 }
                 if (VirtualRoot.IsMinerStudio)
                 {
                     argument += " --minerstudio";
                 }
                 if (string.IsNullOrEmpty(downloadFileUrl))
                 {
                     if (File.Exists(SpecialPath.UpdaterFileFullName))
                     {
                         NTMiner.Windows.Cmd.RunClose(SpecialPath.UpdaterFileFullName, argument);
                     }
                     callback?.Invoke();
                     return;
                 }
                 Uri uri = new Uri(downloadFileUrl);
                 string updaterVersion = string.Empty;
                 if (NTMinerRoot.Instance.LocalAppSettingSet.TryGetAppSetting(VirtualRoot.UpdaterVersionAppSettingKey, out IAppSetting appSetting) && appSetting.Value != null)
                 {
                     updaterVersion = appSetting.Value.ToString();
                 }
                 if (string.IsNullOrEmpty(updaterVersion) || !File.Exists(SpecialPath.UpdaterFileFullName) || uri.AbsolutePath != updaterVersion)
                 {
                     VirtualRoot.Execute(new ShowFileDownloaderCommand(downloadFileUrl, "开源矿工更新器", (window, isSuccess, message, saveFileFullName) => {
                         try {
                             if (isSuccess)
                             {
                                 File.Copy(saveFileFullName, SpecialPath.UpdaterFileFullName, overwrite: true);
                                 File.Delete(saveFileFullName);
                                 VirtualRoot.Execute(new ChangeLocalAppSettingCommand(new AppSettingData {
                                     Key   = VirtualRoot.UpdaterVersionAppSettingKey,
                                     Value = uri.AbsolutePath
                                 }));
                                 window?.Close();
                                 NTMiner.Windows.Cmd.RunClose(SpecialPath.UpdaterFileFullName, argument);
                                 callback?.Invoke();
                             }
                             else
                             {
                                 VirtualRoot.ThisWorkerError(nameof(AppStatic), message, toConsole: true);
                                 callback?.Invoke();
                             }
                         }
                         catch {
                             callback?.Invoke();
                         }
                     }));
                 }
                 else
                 {
                     Windows.Cmd.RunClose(SpecialPath.UpdaterFileFullName, argument);
                     callback?.Invoke();
                 }
             }
             catch {
                 callback?.Invoke();
             }
         });
     }
     catch {
         callback?.Invoke();
     }
 }