Exemple #1
0
 private void Link()
 {
     VirtualRoot.Window <CloseNTMinerCommand>("处理关闭NTMiner客户端命令", LogEnum.UserConsole,
                                              action: message => {
         UIThread.Execute(() => {
             try {
                 if (MainWindow != null)
                 {
                     MainWindow.Close();
                 }
                 Shutdown();
             }
             catch (Exception e) {
                 Logger.ErrorDebugLine(e);
                 Environment.Exit(0);
             }
         });
     });
     VirtualRoot.Window <CloseMainWindowCommand>("处理关闭主界面命令", LogEnum.DevConsole,
                                                 action: message => {
         UIThread.Execute(() => {
             MainWindow = NotiCenterWindow.Instance;
             foreach (Window window in Windows)
             {
                 if (window != MainWindow)
                 {
                     window.Close();
                 }
             }
             NotiCenterWindowViewModel.Instance.Manager.ShowSuccessMessage("已切换为无界面模式运行", "开源矿工");
         });
     });
     #region 周期确保守护进程在运行
     Daemon.DaemonUtil.RunNTMinerDaemon();
     VirtualRoot.On <Per20SecondEvent>("周期确保守护进程在运行", LogEnum.DevConsole,
                                       action: message => {
         if (NTMinerRegistry.GetDaemonActiveOn().AddSeconds(20) < DateTime.Now)
         {
             Daemon.DaemonUtil.RunNTMinerDaemon();
         }
     });
     #endregion
     #region 1080小药丸
     VirtualRoot.On <MineStartedEvent>("开始挖矿后启动1080ti小药丸、挖矿开始后如果需要启动DevConsole则启动DevConsole", LogEnum.DevConsole,
                                       action: message => {
         // 启动DevConsole
         if (NTMinerRoot.IsUseDevConsole)
         {
             var mineContext     = message.MineContext;
             string poolIp       = mineContext.MainCoinPool.GetIp();
             string consoleTitle = mineContext.MainCoinPool.Server;
             Daemon.DaemonUtil.RunDevConsoleAsync(poolIp, consoleTitle);
         }
         OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Start();
     });
     VirtualRoot.On <MineStopedEvent>("停止挖矿后停止1080ti小药丸", LogEnum.DevConsole,
                                      action: message => {
         OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Stop();
     });
     #endregion
     #region 处理开启A卡计算模式
     VirtualRoot.Window <SwitchRadeonGpuCommand>("处理开启A卡计算模式命令", LogEnum.DevConsole,
                                                 action: message => {
         if (NTMinerRoot.Instance.GpuSet.GpuType == GpuType.AMD)
         {
             if (NTMinerRoot.Instance.IsMining)
             {
                 NTMinerRoot.Instance.StopMineAsync(() => {
                     SwitchRadeonGpuMode();
                     NTMinerRoot.Instance.StartMine();
                 });
             }
             else
             {
                 SwitchRadeonGpuMode();
             }
         }
     });
     #endregion
 }
            private KernelOutputTranslaterViewModels()
            {
#if DEBUG
                Write.Stopwatch.Restart();
#endif
                VirtualRoot.On <ServerContextReInitedEvent>("ServerContext刷新后刷新VM内存", LogEnum.DevConsole,
                                                            action: message => {
                    _dicById.Clear();
                    _dicByKernelOutputId.Clear();
                    Init();
                });
                VirtualRoot.On <ServerContextVmsReInitedEvent>("ServerContext的VM集刷新后刷新视图界面", LogEnum.DevConsole,
                                                               action: message => {
                    OnPropertyChanged(nameof(AllKernelOutputTranslaterVms));
                });
                On <KernelOutputTranslaterAddedEvent>("添加了内核输出翻译器后刷新VM内存", LogEnum.DevConsole,
                                                      action: message => {
                    KernelOutputViewModel kernelOutputVm;
                    if (AppContext.Instance.KernelOutputVms.TryGetKernelOutputVm(message.Source.KernelOutputId, out kernelOutputVm))
                    {
                        if (!_dicByKernelOutputId.ContainsKey(message.Source.KernelOutputId))
                        {
                            _dicByKernelOutputId.Add(message.Source.KernelOutputId, new List <KernelOutputTranslaterViewModel>());
                        }
                        var vm = new KernelOutputTranslaterViewModel(message.Source);
                        _dicByKernelOutputId[message.Source.KernelOutputId].Add(vm);
                        _dicById.Add(message.Source.GetId(), vm);
                        kernelOutputVm.OnPropertyChanged(nameof(kernelOutputVm.KernelOutputTranslaters));
                    }
                });
                On <KernelOutputTranslaterUpdatedEvent>("更新了内核输出翻译器后刷新VM内存", LogEnum.DevConsole,
                                                        action: message => {
                    if (_dicByKernelOutputId.ContainsKey(message.Source.KernelOutputId))
                    {
                        var item = _dicByKernelOutputId[message.Source.KernelOutputId].FirstOrDefault(a => a.Id == message.Source.GetId());
                        if (item != null)
                        {
                            item.Update(message.Source);
                        }
                    }
                });
                On <KernelOutputTranslaterRemovedEvent>("移除了内核输出翻译器后刷新VM内存", LogEnum.DevConsole,
                                                        action: message => {
                    if (_dicByKernelOutputId.ContainsKey(message.Source.KernelOutputId))
                    {
                        var item = _dicByKernelOutputId[message.Source.KernelOutputId].FirstOrDefault(a => a.Id == message.Source.GetId());
                        if (item != null)
                        {
                            _dicByKernelOutputId[message.Source.KernelOutputId].Remove(item);
                        }
                    }
                    if (_dicById.ContainsKey(message.Source.GetId()))
                    {
                        _dicById.Remove(message.Source.GetId());
                    }
                    KernelOutputViewModel kernelOutputVm;
                    if (AppContext.Instance.KernelOutputVms.TryGetKernelOutputVm(message.Source.KernelOutputId, out kernelOutputVm))
                    {
                        kernelOutputVm.OnPropertyChanged(nameof(kernelOutputVm.KernelOutputTranslaters));
                    }
                });
                Init();
#if DEBUG
                Write.DevTimeSpan($"耗时{Write.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
            }
            // 创建管道,将输出通过管道转送到日志文件,然后读取日志文件内容打印到控制台
            private static void CreatePipProcess(IMineContext mineContext, string kernelExeFileFullName, string arguments)
            {
                SECURITY_ATTRIBUTES saAttr = new SECURITY_ATTRIBUTES {
                    bInheritHandle       = true,
                    lpSecurityDescriptor = IntPtr.Zero,
                    length = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES))
                };

                //set the bInheritHandle flag so pipe handles are inherited

                saAttr.lpSecurityDescriptor = IntPtr.Zero;
                //get handle to current stdOut

                IntPtr mypointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(STARTUPINFO)));

                Marshal.StructureToPtr(saAttr, mypointer, true);
                var bret = CreatePipe(out var hReadOut, out var hWriteOut, mypointer, 0);

                //ensure the read handle to pipe for stdout is not inherited
                SetHandleInformation(hReadOut, HANDLE_FLAG_INHERIT, 0);
                ////Create pipe for the child process's STDIN
                STARTUPINFO lpStartupInfo = new STARTUPINFO {
                    cb          = (uint)Marshal.SizeOf(typeof(STARTUPINFO)),
                    dwFlags     = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW,
                    wShowWindow = SW_HIDE, // SW_HIDE; //SW_SHOW
                    hStdOutput  = hWriteOut,
                    hStdError   = hWriteOut,
                    hStdInput   = IntPtr.Zero
                };
                string cmdLine = $"\"{kernelExeFileFullName}\" {arguments}";

                Write.UserOk(cmdLine);
                Write.UserInfo("有请内核上场");
                StringBuilder lpEnvironment = new StringBuilder();
                // 复制父进程的环境变量
                IDictionary dic = Environment.GetEnvironmentVariables();

                // 追加环境变量
                foreach (var item in mineContext.CoinKernel.EnvironmentVariables)
                {
                    dic.Add(item.Key, item.Value);
                }
                foreach (var key in dic.Keys)
                {
                    if (key == null || key.ToString().Contains("\0"))
                    {
                        continue;
                    }
                    var value = dic[key];
                    if (value == null || value.ToString().Contains("\0"))
                    {
                        continue;
                    }
                    lpEnvironment.Append($"{key.ToString()}={value.ToString()}\0");
                }
                if (CreateProcess(
                        lpApplicationName: null,
                        lpCommandLine: new StringBuilder(cmdLine),
                        lpProcessAttributes: IntPtr.Zero,
                        lpThreadAttributes: IntPtr.Zero,
                        bInheritHandles: true,
                        dwCreationFlags: NORMAL_PRIORITY_CLASS,
                        lpEnvironment: lpEnvironment,
                        lpCurrentDirectory: Path.GetDirectoryName(kernelExeFileFullName),
                        lpStartupInfo: ref lpStartupInfo,
                        lpProcessInformation: out _))
                {
                    if (bret == false)
                    {
                        int lasterr = Marshal.GetLastWin32Error();
                        VirtualRoot.Happened(new StartingMineFailedEvent($"管道型进程创建失败 lasterr:{lasterr}"));
                    }
                    else
                    {
                        Bus.DelegateHandler <MineStopedEvent> closeHandle = null;
                        bool isHWriteOutHasClosed = false;
                        Daemon(mineContext, () => {
                            if (!isHWriteOutHasClosed)
                            {
                                CloseHandle(hWriteOut);
                                isHWriteOutHasClosed = true;
                            }
                            VirtualRoot.UnPath(closeHandle);
                        });
                        closeHandle = VirtualRoot.On <MineStopedEvent>("挖矿停止后关闭非托管的日志句柄", LogEnum.DevConsole,
                                                                       action: message => {
                            // 挖矿停止后摘除挖矿内核进程守护器
                            if (_sDaemon != null)
                            {
                                VirtualRoot.UnPath(_sDaemon);
                                _sDaemon = null;
                            }
                            if (!isHWriteOutHasClosed)
                            {
                                CloseHandle(hWriteOut);
                                isHWriteOutHasClosed = true;
                            }
                            VirtualRoot.UnPath(closeHandle);
                        });
                        string pipLogFileFullName = Path.Combine(SpecialPath.LogsDirFullName, mineContext.PipeFileName);
                        Task.Factory.StartNew(() => {
                            FileStream fs = new FileStream(pipLogFileFullName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                            using (StreamReader sr = new StreamReader(fs)) {
                                byte[] buffer = new byte[1024];
                                int ret;
                                // Read会阻塞,直到读取到字符或者hWriteOut被关闭
                                while ((ret = Read(buffer, 0, buffer.Length, hReadOut)) > 0)
                                {
                                    fs.Write(buffer, 0, ret);
                                    if (buffer[ret - 1] == '\r' || buffer[ret - 1] == '\n')
                                    {
                                        fs.Flush();
                                    }
                                }
                            }
                            CloseHandle(hReadOut);
                        }, TaskCreationOptions.LongRunning);
                        ReadPrintLoopLogFileAsync(mineContext, pipLogFileFullName);
                    }
                }
                else
                {
                    VirtualRoot.Happened(new StartingMineFailedEvent($"内核启动失败,请重试"));
                }
            }
Exemple #4
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;
                            }
                        }
            private KernelInputViewModels()
            {
#if DEBUG
                VirtualRoot.Stopwatch.Restart();
#endif
                VirtualRoot.On <ServerContextReInitedEvent>("ServerContext刷新后刷新VM内存", LogEnum.DevConsole,
                                                            action: message => {
                    _dicById.Clear();
                    Init();
                });
                VirtualRoot.On <ServerContextVmsReInitedEvent>("ServerContext的VM集刷新后刷新视图界面", LogEnum.DevConsole,
                                                               action: message => {
                    OnPropertyChangeds();
                });
                On <KernelInputAddedEvent>("添加了内核输入后刷新VM内存", LogEnum.DevConsole,
                                           action: message => {
                    var vm = new KernelInputViewModel(message.Source);
                    _dicById.Add(message.Source.GetId(), vm);
                    OnPropertyChangeds();
                });
                On <KernelInputUpdatedEvent>("更新了内核输入后刷新VM内存", LogEnum.DevConsole,
                                             action: message => {
                    if (_dicById.ContainsKey(message.Source.GetId()))
                    {
                        var item = _dicById[message.Source.GetId()];
                        if (item != null)
                        {
                            bool isSupportDualMine = item.IsSupportDualMine;
                            string args            = item.Args;
                            string dualFullArgs    = item.DualFullArgs;
                            item.Update(message.Source);
                            if (args != item.Args || dualFullArgs != item.DualFullArgs)
                            {
                                CoinViewModel coinVm = AppContext.Instance.MinerProfileVm.CoinVm;
                                if (coinVm != null && coinVm.CoinKernel != null && coinVm.CoinKernel.Kernel.KernelInputId == item.Id)
                                {
                                    NTMinerRoot.RefreshArgsAssembly.Invoke();
                                }
                            }
                            if (isSupportDualMine != item.IsSupportDualMine)
                            {
                                foreach (var coinKernelVm in AppContext.Instance.CoinKernelVms.AllCoinKernels.Where(a => a.KernelId == message.Source.GetId()))
                                {
                                    coinKernelVm.OnPropertyChanged(nameof(coinKernelVm.IsSupportDualMine));
                                    coinKernelVm.OnPropertyChanged(nameof(coinKernelVm.DualCoinGroup));
                                }
                            }
                        }
                    }
                });
                On <KernelInputRemovedEvent>("移除了内核输入后刷新VM内存", LogEnum.DevConsole,
                                             action: message => {
                    if (_dicById.ContainsKey(message.Source.GetId()))
                    {
                        _dicById.Remove(message.Source.GetId());
                        OnPropertyChangeds();
                    }
                });
                Init();
#if DEBUG
                Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
            }
            // 创建管道,将输出通过管道转送到日志文件,然后读取日志文件内容打印到控制台
            private static void CreatePipProcess(IMineContext mineContext, string cmdLine)
            {
                SECURITY_ATTRIBUTES saAttr = new SECURITY_ATTRIBUTES
                {
                    bInheritHandle       = true,
                    lpSecurityDescriptor = IntPtr.Zero,
                    length = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES))
                };

                //set the bInheritHandle flag so pipe handles are inherited

                saAttr.lpSecurityDescriptor = IntPtr.Zero;
                //get handle to current stdOut

                IntPtr mypointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(STARTUPINFO)));

                Marshal.StructureToPtr(saAttr, mypointer, true);
                var bret = CreatePipe(out var hReadOut, out var hWriteOut, mypointer, 0);

                //ensure the read handle to pipe for stdout is not inherited
                SetHandleInformation(hReadOut, HANDLE_FLAG_INHERIT, 0);
                ////Create pipe for the child process's STDIN
                STARTUPINFO lpStartupInfo = new STARTUPINFO {
                    cb          = (uint)Marshal.SizeOf(typeof(STARTUPINFO)),
                    dwFlags     = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW,
                    wShowWindow = SW_HIDE, // SW_HIDE; //SW_SHOW
                    hStdOutput  = hWriteOut,
                    hStdError   = hWriteOut,
                    hStdInput   = IntPtr.Zero
                };

                if (CreateProcess(
                        lpApplicationName: null,
                        lpCommandLine: new StringBuilder(cmdLine),
                        lpProcessAttributes: IntPtr.Zero,
                        lpThreadAttributes: IntPtr.Zero,
                        bInheritHandles: true,
                        dwCreationFlags: NORMAL_PRIORITY_CLASS,
                        lpEnvironment: IntPtr.Zero,
                        lpCurrentDirectory: SpecialPath.KernelsDirFullName,
                        lpStartupInfo: ref lpStartupInfo,
                        lpProcessInformation: out _))
                {
                    if (bret == false)
                    {
                        int lasterr = Marshal.GetLastWin32Error();
                        Write.UserLine($"管道型进程创建失败 lasterr:{lasterr}", ConsoleColor.Red);
                    }
                    else
                    {
                        Bus.DelegateHandler <MineStopedEvent> closeHandle = null;
                        bool isHWriteOutHasClosed = false;
                        Daemon(mineContext, () => {
                            if (!isHWriteOutHasClosed)
                            {
                                CloseHandle(hWriteOut);
                                isHWriteOutHasClosed = true;
                            }
                            VirtualRoot.UnPath(closeHandle);
                        });
                        closeHandle = VirtualRoot.On <MineStopedEvent>("挖矿停止后关闭非托管的日志句柄", LogEnum.DevConsole,
                                                                       action: message => {
                            // 挖矿停止后摘除挖矿内核进程守护器
                            if (_sDaemon != null)
                            {
                                VirtualRoot.UnPath(_sDaemon);
                                _sDaemon = null;
                            }
                            if (!isHWriteOutHasClosed)
                            {
                                CloseHandle(hWriteOut);
                                isHWriteOutHasClosed = true;
                            }
                            VirtualRoot.UnPath(closeHandle);
                        });
                        string pipLogFileFullName = Path.Combine(SpecialPath.LogsDirFullName, mineContext.PipeFileName);
                        Task.Factory.StartNew(() => {
                            FileStream fs = new FileStream(pipLogFileFullName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                            using (StreamReader sr = new StreamReader(fs)) {
                                byte[] buffer = new byte[1024];
                                int ret;
                                // Read会阻塞,直到读取到字符或者hWriteOut被关闭
                                while ((ret = Read(buffer, 0, buffer.Length, hReadOut)) > 0)
                                {
                                    fs.Write(buffer, 0, ret);
                                    if (buffer[ret - 1] == '\r' || buffer[ret - 1] == '\n')
                                    {
                                        fs.Flush();
                                    }
                                }
                            }
                            CloseHandle(hReadOut);
                        });
                        ReadPrintLoopLogFileAsync(mineContext, pipLogFileFullName);
                    }
                }
                else
                {
                    Logger.ErrorWriteLine("内核启动失败,请重试");
                }
            }
Exemple #7
0
        public void Start()
        {
            OfficialServer.GetTimeAsync((remoteTime) => {
                if (Math.Abs((DateTime.Now - remoteTime).TotalSeconds) < Timestamp.DesyncSeconds)
                {
                    Logger.OkDebugLine("时间同步");
                }
                else
                {
                    Logger.WarnDebugLine($"本机时间和服务器时间不同步,请调整,本地:{DateTime.Now},服务器:{remoteTime}");
                }
            });

            Report.Init(this);

            #region 挖矿开始时将无份额内核重启份额计数置0
            int      shareCount = 0;
            DateTime shareOn    = DateTime.Now;
            VirtualRoot.On <MineStartedEvent>("挖矿开始后将无份额内核重启份额计数置0,应用超频,启动NoDevFee,启动DevConsole,清理除当前外的Temp/Kernel", LogEnum.DevConsole,
                                              action: message => {
                // 将无份额内核重启份额计数置0
                shareCount = 0;
                shareOn    = DateTime.Now;
                Task.Factory.StartNew(() => {
                    try {
                        if (GpuProfileSet.Instance.IsOverClockEnabled(message.MineContext.MainCoin.GetId()))
                        {
                            VirtualRoot.Execute(new CoinOverClockCommand(message.MineContext.MainCoin.GetId()));
                        }
                    }
                    catch (Exception e) {
                        Logger.ErrorDebugLine(e.Message, e);
                    }
                });
                StartNoDevFeeAsync();
                // 启动DevConsole
                if (IsUseDevConsole)
                {
                    string poolIp       = CurrentMineContext.MainCoinPool.GetIp();
                    string consoleTitle = CurrentMineContext.MainCoinPool.Server;
                    DaemonUtil.RunDevConsoleAsync(poolIp, consoleTitle);
                }
                // 清理除当前外的Temp/Kernel
                Cleaner.CleanKernels();
            });
            #endregion
            #region 每10秒钟检查是否需要重启
            VirtualRoot.On <Per10SecondEvent>("每10秒钟检查是否需要重启", LogEnum.None,
                                              action: message => {
                #region 重启电脑
                try {
                    if (MinerProfile.IsPeriodicRestartComputer)
                    {
                        if ((DateTime.Now - this.CreatedOn).TotalHours > MinerProfile.PeriodicRestartComputerHours)
                        {
                            Logger.WarnWriteLine($"每运行{MinerProfile.PeriodicRestartKernelHours}小时重启电脑");
                            Windows.Power.Restart();
                            return;    // 退出
                        }
                    }
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e.Message, e);
                }
                #endregion

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

                #region 收益没有增加重启内核
                try {
                    if (IsMining && MinerProfile.IsNoShareRestartKernel)
                    {
                        if ((DateTime.Now - shareOn).TotalMinutes > MinerProfile.NoShareRestartKernelMinutes)
                        {
                            if (this.CurrentMineContext.MainCoin != null)
                            {
                                ICoinShare mainCoinShare = this.CoinShareSet.GetOrCreate(this.CurrentMineContext.MainCoin.GetId());
                                int 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)
                                {
                                    Logger.WarnWriteLine($"{MinerProfile.NoShareRestartKernelMinutes}分钟收益没有增加重启内核");
                                    RestartMine();
                                }
                                else
                                {
                                    shareCount = totalShare;
                                    shareOn    = DateTime.Now;
                                }
                            }
Exemple #8
0
 public void Init(Action callback)
 {
     Task.Factory.StartNew(() => {
         bool isWork = Environment.GetCommandLineArgs().Contains("--work", StringComparer.OrdinalIgnoreCase);
         if (isWork)
         {
             DoInit(isWork, callback);
             if (IsMinerClient)
             {
                 NTMinerRegistry.SetIsLastIsWork(true);
             }
             return;
         }
         else
         {
             if (IsMinerClient)
             {
                 NTMinerRegistry.SetIsLastIsWork(false);
             }
         }
         // 如果是Debug模式且不是群控客户端且不是作业则使用本地数据库初始化
         if (DevMode.IsDebugMode && !VirtualRoot.IsMinerStudio)
         {
             DoInit(isWork: false, callback: callback);
             return;
         }
         Logger.InfoDebugLine("开始下载server.json");
         SpecialPath.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(AssemblyInfo.ServerJsonFileName, (serverJsonFileVersion, minerClientVersion) => {
                     SetServerJsonVersion(serverJsonFileVersion);
                     AppVersionChangedEvent.PublishIfNewVersion(minerClientVersion);
                 });
             }
             else
             {
                 Logger.InfoDebugLine("GetAliyunServerJson下载失败");
             }
             DoInit(isWork, callback);
         });
         #region 发生了用户活动时检查serverJson是否有新版本
         VirtualRoot.On <UserActionEvent>("发生了用户活动时检查serverJson是否有新版本", LogEnum.DevConsole,
                                          action: message => {
             OfficialServer.GetJsonFileVersionAsync(AssemblyInfo.ServerJsonFileName, (serverJsonFileVersion, minerClientVersion) => {
                 AppVersionChangedEvent.PublishIfNewVersion(minerClientVersion);
                 string localServerJsonFileVersion = GetServerJsonVersion();
                 if (!string.IsNullOrEmpty(serverJsonFileVersion) && localServerJsonFileVersion != serverJsonFileVersion)
                 {
                     SpecialPath.GetAliyunServerJson((data) => {
                         Write.UserInfo($"server.json配置文件有新版本{localServerJsonFileVersion}->{serverJsonFileVersion}");
                         string rawJson = Encoding.UTF8.GetString(data);
                         SpecialPath.WriteServerJsonFile(rawJson);
                         SetServerJsonVersion(serverJsonFileVersion);
                         ReInitServerJson();
                         bool isUseJson = !DevMode.IsDebugMode || VirtualRoot.IsMinerStudio;
                         if (isUseJson)
                         {
                             // 作业模式下界面是禁用的,所以这里的初始化isWork必然是false
                             ContextReInit(isWork: VirtualRoot.IsMinerStudio);
                             Write.UserInfo("刷新完成");
                         }
                         else
                         {
                             Write.UserInfo("不是使用的server.json,无需刷新");
                         }
                     });
                 }
                 else
                 {
                     Write.DevDebug("server.json没有新版本");
                 }
             });
         });
         #endregion
     });
     // 因为这个操作大概需要200毫秒
     Task.Factory.StartNew(() => {
         NVIDIAGpuSet.NvmlInit();
     });
 }
            private MinerProfileViewModel()
            {
#if DEBUG
                VirtualRoot.Stopwatch.Restart();
#endif
                if (Design.IsInDesignMode)
                {
                    return;
                }
                this.AutoStartDelaySecondsUp = new DelegateCommand(() => {
                    this.AutoStartDelaySeconds++;
                });
                this.AutoStartDelaySecondsDown = new DelegateCommand(() => {
                    if (this.AutoStartDelaySeconds > 0)
                    {
                        this.AutoStartDelaySeconds--;
                    }
                });
                this.AutoRestartKernelTimesUp = new DelegateCommand(() => {
                    this.AutoRestartKernelTimes++;
                });
                this.AutoRestartKernelTimesDown = new DelegateCommand(() => {
                    if (this.AutoRestartKernelTimes > 0)
                    {
                        this.AutoRestartKernelTimes--;
                    }
                });
                this.NoShareRestartKernelMinutesUp = new DelegateCommand(() => {
                    this.NoShareRestartKernelMinutes++;
                });
                this.NoShareRestartKernelMinutesDown = new DelegateCommand(() => {
                    if (this.NoShareRestartKernelMinutes > 0)
                    {
                        this.NoShareRestartKernelMinutes--;
                    }
                });
                this.PeriodicRestartKernelHoursUp = new DelegateCommand(() => {
                    this.PeriodicRestartKernelHours++;
                });
                this.PeriodicRestartKernelHoursDown = new DelegateCommand(() => {
                    if (this.PeriodicRestartKernelHours > 0)
                    {
                        this.PeriodicRestartKernelHours--;
                    }
                });
                this.PeriodicRestartKernelMinutesUp = new DelegateCommand(() => {
                    this.PeriodicRestartKernelMinutes++;
                });
                this.PeriodicRestartKernelMinutesDown = new DelegateCommand(() => {
                    if (this.PeriodicRestartKernelMinutes > 0)
                    {
                        this.PeriodicRestartKernelMinutes--;
                    }
                });
                this.PeriodicRestartComputerHoursUp = new DelegateCommand(() => {
                    this.PeriodicRestartComputerHours++;
                });
                this.PeriodicRestartComputerHoursDown = new DelegateCommand(() => {
                    if (this.PeriodicRestartComputerHours > 0)
                    {
                        this.PeriodicRestartComputerHours--;
                    }
                });
                this.PeriodicRestartComputerMinutesUp = new DelegateCommand(() => {
                    this.PeriodicRestartComputerMinutes++;
                });
                this.PeriodicRestartComputerMinutesDown = new DelegateCommand(() => {
                    if (this.PeriodicRestartComputerMinutes > 0)
                    {
                        this.PeriodicRestartComputerMinutes--;
                    }
                });
                this.EPriceUp = new DelegateCommand(() => {
                    this.EPrice = Math.Round(this.EPrice + 0.1, 2);
                });
                this.EPriceDown = new DelegateCommand(() => {
                    if (this.EPrice > 0.1)
                    {
                        this.EPrice = Math.Round(this.EPrice - 0.1, 2);
                    }
                });
                this.PowerAppendUp = new DelegateCommand(() => {
                    this.PowerAppend++;
                });
                this.PowerAppendDown = new DelegateCommand(() => {
                    if (this.PowerAppend > 0)
                    {
                        this.PowerAppend--;
                    }
                });
                this.MaxTempUp = new DelegateCommand(() => {
                    this.MaxTemp++;
                });
                this.MaxTempDown = new DelegateCommand(() => {
                    if (this.MaxTemp > 0)
                    {
                        this.MaxTemp--;
                    }
                });
                this.AutoNoUiMinutesUp = new DelegateCommand(() => {
                    this.AutoNoUiMinutes++;
                });
                this.AutoNoUiMinutesDown = new DelegateCommand(() => {
                    if (this.AutoNoUiMinutes > 0)
                    {
                        this.AutoNoUiMinutes--;
                    }
                });
                NTMinerRoot.SetRefreshArgsAssembly(() => {
                    if (CoinVm != null && CoinVm.CoinKernel != null && CoinVm.CoinKernel.Kernel != null)
                    {
                        var coinKernelProfile = CoinVm.CoinKernel.CoinKernelProfile;
                        var kernelInput       = CoinVm.CoinKernel.Kernel.KernelInputVm;
                        if (coinKernelProfile != null && kernelInput != null)
                        {
                            if (coinKernelProfile.IsDualCoinEnabled && !kernelInput.IsAutoDualWeight)
                            {
                                if (coinKernelProfile.DualCoinWeight > kernelInput.DualWeightMax)
                                {
                                    coinKernelProfile.DualCoinWeight = kernelInput.DualWeightMax;
                                }
                                else if (coinKernelProfile.DualCoinWeight < kernelInput.DualWeightMin)
                                {
                                    coinKernelProfile.DualCoinWeight = kernelInput.DualWeightMin;
                                }
                                NTMinerRoot.Instance.MinerProfile.SetCoinKernelProfileProperty(coinKernelProfile.CoinKernelId, nameof(coinKernelProfile.DualCoinWeight), coinKernelProfile.DualCoinWeight);
                            }
                        }
                    }
                    this.ArgsAssembly = NTMinerRoot.Instance.BuildAssembleArgs(out _, out _, out _);
                });
                VirtualRoot.On <ServerContextVmsReInitedEvent>("ServerContext的VM集刷新后刷新视图界面", LogEnum.DevConsole,
                                                               action: message => {
                    OnPropertyChanged(nameof(CoinVm));
                });
                Window <RefreshAutoBootStartCommand>("刷新开机启动和自动挖矿的展示", LogEnum.UserConsole,
                                                     action: message => {
                    OnPropertyChanged(nameof(IsAutoBoot));
                    OnPropertyChanged(nameof(IsAutoStart));
                });
                On <MinerProfilePropertyChangedEvent>("MinerProfile设置变更后刷新VM内存", LogEnum.DevConsole,
                                                      action: message => {
                    OnPropertyChanged(message.PropertyName);
                });
                On <MineWorkPropertyChangedEvent>("MineWork设置变更后刷新VM内存", LogEnum.DevConsole,
                                                  action: message => {
                    OnPropertyChanged(message.PropertyName);
                });

                VirtualRoot.On <LocalContextVmsReInitedEvent>("本地上下文视图模型集刷新后刷新界面", LogEnum.DevConsole,
                                                              action: message => {
                    AllPropertyChanged();
                });
#if DEBUG
                Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
            }
Exemple #10
0
        private void DoInit(bool isWork, Action callback)
        {
            this.PackageDownloader = new PackageDownloader(this);
            this.AppSettingSet     = new AppSettingSet(this);
            this.CalcConfigSet     = new CalcConfigSet(this);

            ContextInit(isWork);

            // 打码支持内核品牌
            if (!string.IsNullOrEmpty(CommandLineArgs.KernelBrand))
            {
                if (SysDicItemSet.TryGetDicItem("KernelBrand", CommandLineArgs.KernelBrand, out ISysDicItem brandItem))
                {
                    #region KernelBrandId
                    string brand = $"KernelBrandId{brandItem.GetId()}KernelBrandId";
                    byte[] data  = Encoding.UTF8.GetBytes(brand);
                    if (data.Length != KernelBrandRaw.Length)
                    {
                        throw new InvalidProgramException();
                    }
                    byte[] source = File.ReadAllBytes(ClientId.AppFileFullName);
                    int    index  = 0;
                    for (int i = 0; i < source.Length - KernelBrandRaw.Length; i++)
                    {
                        int j = 0;
                        for (; j < KernelBrandRaw.Length; j++)
                        {
                            if (source[i + j] != KernelBrandRaw[j])
                            {
                                break;
                            }
                        }
                        if (j == KernelBrandRaw.Length)
                        {
                            index = i;
                            break;
                        }
                    }
                    for (int i = index; i < index + data.Length; i++)
                    {
                        source[i] = data[i - index];
                    }
                    string brandExeFullName = Path.Combine(Path.GetDirectoryName(ClientId.AppFileFullName), Path.GetFileNameWithoutExtension(ClientId.AppFileFullName) + $"_{CommandLineArgs.KernelBrand}.exe");
                    File.WriteAllBytes(brandExeFullName, source);
                    #endregion
                    Environment.Exit(0);
                    return;
                }
            }

            this.UserSet          = new UserSet();
            this.KernelProfileSet = new KernelProfileSet(this);
            this.GpusSpeed        = new GpusSpeed(this);
            this.CoinShareSet     = new CoinShareSet(this);
            this.MineWorkSet      = new MineWorkSet(this);
            this.MinerGroupSet    = new MinerGroupSet(this);
            this.OverClockDataSet = new OverClockDataSet(this);
            this.ColumnsShowSet   = new ColumnsShowSet(this);
            MineWorkData mineWorkData = null;
            if (isWork)
            {
                mineWorkData = LocalJson.MineWork;
            }
            this._minerProfile = new MinerProfile(this, mineWorkData);

            // 这几个注册表内部区分挖矿端和群控客户端
            NTMinerRegistry.SetLocation(ClientId.AppFileFullName);
            NTMinerRegistry.SetArguments(string.Join(" ", CommandLineArgs.Args));
            NTMinerRegistry.SetCurrentVersion(CurrentVersion.ToString());
            NTMinerRegistry.SetCurrentVersionTag(CurrentVersionTag);

            #region 发生了用户活动时检查serverJson是否有新版本
            VirtualRoot.On <UserActionEvent>("发生了用户活动时检查serverJson是否有新版本", LogEnum.DevConsole,
                                             action: message => {
                OfficialServer.GetJsonFileVersionAsync(AssemblyInfo.ServerJsonFileName, (jsonFileVersion) => {
                    if (!string.IsNullOrEmpty(jsonFileVersion) && JsonFileVersion != jsonFileVersion)
                    {
                        SpecialPath.GetAliyunServerJson((data) => {
                            Write.DevLine($"有新版本{JsonFileVersion}->{jsonFileVersion}");
                            string rawJson = Encoding.UTF8.GetString(data);
                            SpecialPath.WriteServerJsonFile(rawJson);
                            ReInitServerJson();
                            bool isUseJson = !DevMode.IsDebugMode || VirtualRoot.IsMinerStudio;
                            if (isUseJson)
                            {
                                // 作业模式下界面是禁用的,所以这里的初始化isWork必然是false
                                ContextReInit(isWork: false);
                                Logger.InfoDebugLine("刷新完成");
                            }
                            else
                            {
                                Write.DevLine("不是使用的json,无需刷新");
                            }
                            JsonFileVersion = jsonFileVersion;
                        });
                    }
                    else
                    {
                        Write.DevLine("server.json没有新版本", ConsoleColor.Green);
                    }
                });
            });
            #endregion

            callback?.Invoke();
        }
Exemple #11
0
        public void Start()
        {
            OfficialServer.GetTimeAsync((remoteTime) => {
                if (Math.Abs((DateTime.Now - remoteTime).TotalSeconds) < Timestamp.DesyncSeconds)
                {
                    Logger.OkDebugLine("时间同步");
                }
                else
                {
                    Logger.WarnDebugLine($"本机时间和服务器时间不同步,请调整,本地:{DateTime.Now},服务器:{remoteTime}");
                }
            });

            Report.Init(this);

            VirtualRoot.Window <RegCmdHereCommand>("处理注册右键打开windows命令行菜单命令", LogEnum.DevConsole,
                                                   action: message => {
                string cmdHere          = "SOFTWARE\\Classes\\Directory\\background\\shell\\cmd_here";
                string cmdHereCommand   = cmdHere + "\\command";
                string cmdPrompt        = "SOFTWARE\\Classes\\Folder\\shell\\cmdPrompt";
                string cmdPromptCommand = cmdPrompt + "\\command";
                try {
                    Windows.WinRegistry.SetValue(Registry.LocalMachine, cmdHere, "", "命令行");
                    Windows.WinRegistry.SetValue(Registry.LocalMachine, cmdHere, "Icon", "cmd.exe");
                    Windows.WinRegistry.SetValue(Registry.LocalMachine, cmdHereCommand, "", "\"cmd.exe\"");
                    Windows.WinRegistry.SetValue(Registry.LocalMachine, cmdPrompt, "", "命令行");
                    Windows.WinRegistry.SetValue(Registry.LocalMachine, cmdPromptCommand, "", "\"cmd.exe\" \"cd %1\"");
                    cmdHere        = "SOFTWARE\\Classes\\Directory\\shell\\cmd_here";
                    cmdHereCommand = cmdHere + "\\command";
                    Windows.WinRegistry.SetValue(Registry.LocalMachine, cmdHere, "", "命令行");
                    Windows.WinRegistry.SetValue(Registry.LocalMachine, cmdHere, "Icon", "cmd.exe");
                    Windows.WinRegistry.SetValue(Registry.LocalMachine, cmdHereCommand, "", "\"cmd.exe\"");
                    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,应用超频,启动NoDevFee,启动DevConsole,清理除当前外的Temp/Kernel", LogEnum.DevConsole,
                                              action: message => {
                // 将无份额内核重启份额计数置0
                shareCount = 0;
                shareOn    = DateTime.Now;
                try {
                    if (GpuProfileSet.Instance.IsOverClockEnabled(message.MineContext.MainCoin.GetId()))
                    {
                        VirtualRoot.Execute(new CoinOverClockCommand(message.MineContext.MainCoin.GetId()));
                    }
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                }
                StartNoDevFeeAsync();
            });
            #endregion
            #region 每20秒钟检查是否需要重启
            VirtualRoot.On <Per20SecondEvent>("每20秒钟阻止windows系统休眠、检查是否需要重启", LogEnum.None,
                                              action: message => {
                // 阻止windows休眠
                Windows.Power.PreventWindowsSleep();
                #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();
                            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 && MinerProfile.IsNoShareRestartKernel)
                    {
                        if ((DateTime.Now - shareOn).TotalMinutes > MinerProfile.NoShareRestartKernelMinutes)
                        {
                            if (this.CurrentMineContext.MainCoin != null)
                            {
                                ICoinShare mainCoinShare = this.CoinShareSet.GetOrCreate(this.CurrentMineContext.MainCoin.GetId());
                                int 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)
                                {
                                    Logger.WarnWriteLine($"{MinerProfile.NoShareRestartKernelMinutes}分钟收益没有增加重启内核");
                                    RestartMine();
                                    return;    // 退出
                                }
                                else
                                {
                                    shareCount = totalShare;
                                    shareOn    = DateTime.Now;
                                }
                            }
Exemple #12
0
            private CoinViewModels()
            {
#if DEBUG
                Write.Stopwatch.Restart();
#endif
                if (Design.IsInDesignMode)
                {
                    return;
                }
                VirtualRoot.On <ServerContextReInitedEvent>("ServerContext刷新后刷新VM内存", LogEnum.DevConsole,
                                                            action: message => {
                    _dicById.Clear();
                    Init();
                });
                VirtualRoot.On <ServerContextVmsReInitedEvent>("ServerContext的VM集刷新后刷新视图界面", LogEnum.DevConsole,
                                                               action: message => {
                    AllPropertyChanged();
                });
                On <CoinAddedEvent>("添加了币种后刷新VM内存", LogEnum.DevConsole,
                                    action: (message) => {
                    _dicById.Add(message.Source.GetId(), new CoinViewModel(message.Source));
                    AppContext.Instance.MinerProfileVm.OnPropertyChanged(nameof(NTMiner.AppContext.Instance.MinerProfileVm.CoinVm));
                    AllPropertyChanged();
                });
                On <CoinRemovedEvent>("移除了币种后刷新VM内存", LogEnum.DevConsole,
                                      action: message => {
                    _dicById.Remove(message.Source.GetId());
                    AppContext.Instance.MinerProfileVm.OnPropertyChanged(nameof(NTMiner.AppContext.Instance.MinerProfileVm.CoinVm));
                    AllPropertyChanged();
                });
                On <CoinUpdatedEvent>("更新了币种后刷新VM内存", LogEnum.DevConsole,
                                      action: message => {
                    CoinViewModel coinVm = _dicById[message.Source.GetId()];
                    bool justAsDualCoin  = coinVm.JustAsDualCoin;
                    coinVm.Update(message.Source);
                    coinVm.TestWalletVm.Address = message.Source.TestWallet;
                    coinVm.OnPropertyChanged(nameof(coinVm.Wallets));
                    coinVm.OnPropertyChanged(nameof(coinVm.WalletItems));
                    if (AppContext.Instance.MinerProfileVm.CoinId == message.Source.GetId())
                    {
                        AppContext.Instance.MinerProfileVm.OnPropertyChanged(nameof(NTMiner.AppContext.Instance.MinerProfileVm.CoinVm));
                    }
                    CoinKernelViewModel coinKernelVm = AppContext.Instance.MinerProfileVm.CoinVm.CoinKernel;
                    if (coinKernelVm != null &&
                        coinKernelVm.CoinKernelProfile.SelectedDualCoin != null &&
                        coinKernelVm.CoinKernelProfile.SelectedDualCoin.GetId() == message.Source.GetId())
                    {
                        coinKernelVm.CoinKernelProfile.OnPropertyChanged(nameof(coinKernelVm.CoinKernelProfile.SelectedDualCoin));
                    }
                    if (justAsDualCoin != coinVm.JustAsDualCoin)
                    {
                        OnPropertyChanged(nameof(MainCoins));
                    }
                });
                On <CoinIconDownloadedEvent>("下载了币种图标后", LogEnum.DevConsole,
                                             action: message => {
                    try {
                        if (string.IsNullOrEmpty(message.Source.Icon))
                        {
                            return;
                        }
                        string iconFileFullName = SpecialPath.GetIconFileFullName(message.Source);
                        if (string.IsNullOrEmpty(iconFileFullName) || !File.Exists(iconFileFullName))
                        {
                            return;
                        }
                        CoinViewModel coinVm;
                        if (_dicById.TryGetValue(message.Source.GetId(), out coinVm))
                        {
                            try {
                                coinVm.IconImageSource = new Uri(iconFileFullName, UriKind.Absolute).ToString();
                            }
                            catch (Exception e) {
                                File.Delete(iconFileFullName);
                                Logger.ErrorDebugLine(e);
                            }
                        }
                    }
                    catch (Exception e) {
                        Logger.ErrorDebugLine(e);
                    }
                });
                Init();
#if DEBUG
                Write.DevTimeSpan($"耗时{Write.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
            }
Exemple #13
0
            private SysDicItemViewModels()
            {
#if DEBUG
                VirtualRoot.Stopwatch.Restart();
#endif
                VirtualRoot.On <ServerContextReInitedEvent>("ServerContext刷新后刷新VM内存", LogEnum.DevConsole,
                                                            action: message => {
                    _dicById.Clear();
                    Init();
                });
                VirtualRoot.On <ServerContextVmsReInitedEvent>("ServerContext的VM集刷新后刷新视图界面", LogEnum.DevConsole,
                                                               action: message => {
                    OnPropertyChangeds();
                });
                On <SysDicItemAddedEvent>("添加了系统字典项后调整VM内存", LogEnum.DevConsole,
                                          action: (message) => {
                    if (!_dicById.ContainsKey(message.Source.GetId()))
                    {
                        _dicById.Add(message.Source.GetId(), new SysDicItemViewModel(message.Source));
                        OnPropertyChangeds();
                        SysDicViewModel sysDicVm;
                        if (AppContext.Instance.SysDicVms.TryGetSysDicVm(message.Source.DicId, out sysDicVm))
                        {
                            sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItems));
                            sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItemsSelect));
                        }
                    }
                });
                On <SysDicItemUpdatedEvent>("更新了系统字典项后调整VM内存", LogEnum.DevConsole,
                                            action: (message) => {
                    if (_dicById.ContainsKey(message.Source.GetId()))
                    {
                        SysDicItemViewModel entity = _dicById[message.Source.GetId()];
                        int sortNumber             = entity.SortNumber;
                        entity.Update(message.Source);
                        if (sortNumber != entity.SortNumber)
                        {
                            SysDicViewModel sysDicVm;
                            if (AppContext.Instance.SysDicVms.TryGetSysDicVm(entity.DicId, out sysDicVm))
                            {
                                sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItems));
                                sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItemsSelect));
                            }
                        }
                    }
                });
                On <SysDicItemRemovedEvent>("删除了系统字典项后调整VM内存", LogEnum.DevConsole,
                                            action: (message) => {
                    _dicById.Remove(message.Source.GetId());
                    OnPropertyChangeds();
                    SysDicViewModel sysDicVm;
                    if (AppContext.Instance.SysDicVms.TryGetSysDicVm(message.Source.DicId, out sysDicVm))
                    {
                        sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItems));
                        sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItemsSelect));
                    }
                });
                Init();
#if DEBUG
                Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
            }
Exemple #14
0
 protected override void OnStartup(StartupEventArgs e)
 {
     RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
     if (!string.IsNullOrEmpty(CommandLineArgs.Upgrade))
     {
         Vms.AppStatic.Upgrade(CommandLineArgs.Upgrade, () => {
             Environment.Exit(0);
         });
     }
     else
     {
         try {
             appMutex = new Mutex(true, s_appPipName, out createdNew);
         }
         catch (Exception) {
             createdNew = false;
         }
         if (createdNew)
         {
             Vms.AppStatic.IsMinerClient = true;
             SplashWindow splashWindow = new SplashWindow();
             splashWindow.Show();
             NTMinerRoot.KernelBrandId = Brand.BrandUtil.KernelBrandId;
             NotiCenterWindow.Instance.Show();
             NTMinerRoot.AppName = "开源矿工挖矿客户端";
             NTMinerRoot.Current.Init(() => {
                 NTMinerRoot.KernelDownloader = new KernelDownloader();
                 UIThread.Execute(() => {
                     MainWindow window      = new MainWindow();
                     IMainWindow mainWindow = window;
                     this.MainWindow        = window;
                     this.MainWindow.Show();
                     this.MainWindow.Activate();
                     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 => {
                         Dispatcher.Invoke((ThreadStart)mainWindow.ShowThisWindow);
                     });
                     #endregion
                     splashWindow?.Close();
                     Task.Factory.StartNew(() => {
                         try {
                             HttpServer.Start($"http://localhost:{WebApiConst.MinerClientPort}");
                             NTMinerRoot.Current.Start();
                         }
                         catch (Exception ex) {
                             Logger.ErrorDebugLine(ex.Message, ex);
                         }
                     });
                 });
             });
             VirtualRoot.Window <CloseNTMinerCommand>("处理关闭NTMiner客户端命令", LogEnum.UserConsole,
                                                      action: message => {
                 UIThread.Execute(() => {
                     if (MainWindow != null)
                     {
                         MainWindow.Close();
                     }
                     Shutdown();
                     Environment.Exit(0);
                 });
             });
             VirtualRoot.On <MineStartedEvent>("开始挖矿后启动1080ti小药丸", LogEnum.DevConsole,
                                               action: message => {
                 OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Start();
             });
             VirtualRoot.On <MineStopedEvent>("停止挖矿后停止1080ti小药丸", LogEnum.DevConsole,
                                              action: message => {
                 OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Stop();
             });
             NTMinerOverClockUtil.ExtractResource();
         }
         else
         {
             try {
                 AppHelper.ShowMainWindow(this, MinerServer.NTMinerAppType.MinerClient);
             }
             catch (Exception) {
                 DialogWindow.ShowDialog(message: "另一个NTMiner正在运行,请手动结束正在运行的NTMiner进程后再次尝试。", title: "alert", icon: "Icon_Error");
                 Process   currentProcess = Process.GetCurrentProcess();
                 Process[] processes      = Process.GetProcessesByName(currentProcess.ProcessName);
                 foreach (var process in processes)
                 {
                     if (process.Id != currentProcess.Id)
                     {
                         NTMiner.Windows.TaskKill.Kill(process.Id);
                     }
                 }
             }
         }
     }
     base.OnStartup(e);
 }
Exemple #15
0
 private void Link()
 {
     VirtualRoot.Window <CloseNTMinerCommand>("处理关闭NTMiner客户端命令", LogEnum.UserConsole,
                                              action: message => {
         UIThread.Execute(() => {
             try {
                 if (MainWindow != null)
                 {
                     MainWindow.Close();
                 }
                 Shutdown();
             }
             catch (Exception e) {
                 Logger.ErrorDebugLine(e);
                 Environment.Exit(0);
             }
         });
     });
     VirtualRoot.Window <CloseMainWindowCommand>("处理关闭主界面命令", LogEnum.DevConsole,
                                                 action: message => {
         UIThread.Execute(() => {
             if (NTMinerRoot.GetIsCloseMeanExit())
             {
                 VirtualRoot.Execute(new CloseNTMinerCommand());
                 return;
             }
             MainWindow = NotiCenterWindow.Instance;
             foreach (Window window in Windows)
             {
                 if (window != MainWindow)
                 {
                     window.Close();
                 }
             }
             NotiCenterWindowViewModel.Instance.Manager.ShowSuccessMessage(message.Message, "开源矿工");
         });
     });
     #region 周期确保守护进程在运行
     VirtualRoot.On <Per1MinuteEvent>("周期确保守护进程在运行", LogEnum.DevConsole,
                                      action: message => {
         Daemon.DaemonUtil.RunNTMinerDaemon();
     });
     #endregion
     #region 1080小药丸
     VirtualRoot.On <MineStartedEvent>("开始挖矿后启动1080ti小药丸、挖矿开始后如果需要启动DevConsole则启动DevConsole", LogEnum.DevConsole,
                                       action: message => {
         // 启动DevConsole
         if (NTMinerRoot.IsUseDevConsole)
         {
             var mineContext     = message.MineContext;
             string poolIp       = mineContext.MainCoinPool.GetIp();
             string consoleTitle = mineContext.MainCoinPool.Server;
             Daemon.DaemonUtil.RunDevConsoleAsync(poolIp, consoleTitle);
         }
         OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Start();
     });
     VirtualRoot.On <MineStopedEvent>("停止挖矿后停止1080ti小药丸", LogEnum.DevConsole,
                                      action: message => {
         OhGodAnETHlargementPill.OhGodAnETHlargementPillUtil.Stop();
     });
     #endregion
     #region 处理禁用win10系统更新
     VirtualRoot.Window <BlockWAUCommand>("处理禁用win10系统更新命令", LogEnum.DevConsole,
                                          action: message => {
         NTMiner.Windows.WindowsUtil.BlockWAU();
     });
     #endregion
     #region 优化windows
     VirtualRoot.Window <Win10OptimizeCommand>("处理优化windows命令", LogEnum.DevConsole,
                                               action: message => {
         NTMiner.Windows.WindowsUtil.Win10Optimize();
     });
     #endregion
     #region 处理开启A卡计算模式
     VirtualRoot.Window <SwitchRadeonGpuCommand>("处理开启A卡计算模式命令", LogEnum.DevConsole,
                                                 action: message => {
         if (NTMinerRoot.Instance.GpuSet.GpuType == GpuType.AMD)
         {
             SwitchRadeonGpuMode();
         }
     });
     #endregion
     #region 处理A卡驱动签名
     VirtualRoot.Window <AtikmdagPatcherCommand>("处理A卡驱动签名命令", LogEnum.DevConsole,
                                                 action: message => {
         if (NTMinerRoot.Instance.GpuSet.GpuType == GpuType.AMD)
         {
             AtikmdagPatcher.AtikmdagPatcherUtil.Run();
         }
     });
     #endregion
     #region 启用或禁用windows远程桌面
     VirtualRoot.Window <EnableWindowsRemoteDesktopCommand>("处理启用或禁用Windows远程桌面命令", LogEnum.DevConsole,
                                                            action: message => {
         if (NTMinerRoot.GetIsRemoteDesktopEnabled())
         {
             return;
         }
         string msg = "确定启用Windows远程桌面吗?";
         DialogWindow.ShowDialog(message: msg, title: "确认", onYes: () => {
             Rdp.SetRdpEnabled(true, true);
             Firewall.AddRemoteDesktopRule();
         }, icon: IconConst.IconConfirm);
     });
     #endregion
     #region 启用或禁用windows开机自动登录
     VirtualRoot.Window <EnableOrDisableWindowsAutoLoginCommand>("处理启用或禁用Windows开机自动登录命令", LogEnum.DevConsole,
                                                                 action: message => {
         if (NTMiner.Windows.OS.Instance.IsAutoAdminLogon)
         {
             return;
         }
         NTMiner.Windows.Cmd.RunClose("control", "userpasswords2");
     });
     #endregion
 }
            private CoinKernelViewModels()
            {
#if DEBUG
                Write.Stopwatch.Restart();
#endif
                VirtualRoot.On <ServerContextReInitedEvent>("ServerContext刷新后刷新VM内存", LogEnum.DevConsole,
                                                            action: message => {
                    _dicById.Clear();
                    Init();
                });
                VirtualRoot.On <ServerContextVmsReInitedEvent>("ServerContext的VM集刷新后刷新视图界面", LogEnum.DevConsole,
                                                               action: message => {
                    OnPropertyChanged(nameof(AllCoinKernels));
                });
                On <CoinKernelAddedEvent>("添加了币种内核后刷新VM内存", LogEnum.DevConsole,
                                          action: (message) => {
                    var coinKernelVm = new CoinKernelViewModel(message.Source);
                    _dicById.Add(message.Source.GetId(), coinKernelVm);
                    OnPropertyChanged(nameof(AllCoinKernels));
                    CoinViewModel coinVm;
                    if (AppContext.Instance.CoinVms.TryGetCoinVm((Guid)message.Source.CoinId, out coinVm))
                    {
                        coinVm.OnPropertyChanged(nameof(CoinViewModel.CoinKernel));
                        coinVm.OnPropertyChanged(nameof(CoinViewModel.CoinKernels));
                        coinVm.OnPropertyChanged(nameof(NTMiner.Vms.CoinViewModel.IsSupported));
                    }
                    var kernelVm = coinKernelVm.Kernel;
                    if (kernelVm != null)
                    {
                        kernelVm.OnPropertyChanged(nameof(kernelVm.CoinKernels));
                        kernelVm.OnPropertyChanged(nameof(kernelVm.CoinVms));
                        kernelVm.OnPropertyChanged(nameof(kernelVm.SupportedCoinVms));
                        kernelVm.OnPropertyChanged(nameof(kernelVm.SupportedCoins));
                    }
                });
                On <CoinKernelUpdatedEvent>("更新了币种内核后刷新VM内存", LogEnum.DevConsole,
                                            action: (message) => {
                    CoinKernelViewModel entity = _dicById[message.Source.GetId()];
                    var supportedGpu           = entity.SupportedGpu;
                    Guid dualCoinGroupId       = entity.DualCoinGroupId;
                    entity.Update(message.Source);
                    if (supportedGpu != entity.SupportedGpu)
                    {
                        var coinKernels = AllCoinKernels.Where(a => a.KernelId == entity.Id);
                        foreach (var coinKernel in coinKernels)
                        {
                            CoinViewModel coinVm;
                            if (AppContext.Instance.CoinVms.TryGetCoinVm(coinKernel.CoinId, out coinVm))
                            {
                                coinVm.OnPropertyChanged(nameof(coinVm.IsSupported));
                                coinVm.OnPropertyChanged(nameof(coinVm.CoinKernels));
                            }
                        }
                        var kernelVm = entity.Kernel;
                        kernelVm.OnPropertyChanged(nameof(kernelVm.CoinKernels));
                    }
                });
                On <CoinKernelRemovedEvent>("移除了币种内核后刷新VM内存", LogEnum.DevConsole,
                                            action: (message) => {
                    CoinKernelViewModel coinKernelVm;
                    if (_dicById.TryGetValue(message.Source.GetId(), out coinKernelVm))
                    {
                        _dicById.Remove(message.Source.GetId());
                        OnPropertyChanged(nameof(AllCoinKernels));
                        CoinViewModel coinVm;
                        if (AppContext.Instance.CoinVms.TryGetCoinVm((Guid)message.Source.CoinId, out coinVm))
                        {
                            coinVm.OnPropertyChanged(nameof(CoinViewModel.CoinKernel));
                            coinVm.OnPropertyChanged(nameof(CoinViewModel.CoinKernels));
                            coinVm.OnPropertyChanged(nameof(NTMiner.Vms.CoinViewModel.IsSupported));
                        }
                        var kernelVm = coinKernelVm.Kernel;
                        kernelVm.OnPropertyChanged(nameof(kernelVm.CoinKernels));
                        kernelVm.OnPropertyChanged(nameof(kernelVm.CoinVms));
                        kernelVm.OnPropertyChanged(nameof(kernelVm.SupportedCoinVms));
                        kernelVm.OnPropertyChanged(nameof(kernelVm.SupportedCoins));
                    }
                });
                Init();
#if DEBUG
                Write.DevTimeSpan($"耗时{Write.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
            }
Exemple #17
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);
        }
Exemple #18
0
            private GpuProfileViewModels()
            {
#if DEBUG
                VirtualRoot.Stopwatch.Restart();
#endif
                VirtualRoot.On <GpuProfileSetRefreshedEvent>("Gpu超频集合刷新后刷新附着在当前币种上的超频数据", LogEnum.DevConsole,
                                                             action: message => {
                    lock (_locker) {
                        _listByCoinId.Clear();
                        _gpuAllVmDicByCoinId.Clear();
                    }
                    var coinVm = AppContext.Instance.MinerProfileVm.CoinVm;
                    if (coinVm != null)
                    {
                        coinVm.OnOverClockPropertiesChanges();
                        VirtualRoot.Execute(new CoinOverClockCommand(coinVm.Id));
                    }
                });
                On <GpuProfileAddedOrUpdatedEvent>("添加或更新了Gpu超频数据后刷新VM内存", LogEnum.DevConsole,
                                                   action: message => {
                    lock (_locker) {
                        List <GpuProfileViewModel> list;
                        if (_listByCoinId.TryGetValue(message.Source.CoinId, out list))
                        {
                            var vm = list.FirstOrDefault(a => a.Index == message.Source.Index);
                            if (vm != null)
                            {
                                vm.Update(message.Source);
                            }
                            else
                            {
                                if (AppContext.Instance.GpuVms.TryGetGpuVm(message.Source.Index, out GpuViewModel gpuVm))
                                {
                                    var item = new GpuProfileViewModel(message.Source, gpuVm);
                                    list.Add(item);
                                    list.Sort(new CompareByGpuIndex());
                                    if (item.Index == NTMinerRoot.GpuAllId)
                                    {
                                        _gpuAllVmDicByCoinId.Add(message.Source.CoinId, item);
                                    }
                                }
                            }
                        }
                        else
                        {
                            list = new List <GpuProfileViewModel>();
                            if (AppContext.Instance.GpuVms.TryGetGpuVm(message.Source.Index, out GpuViewModel gpuVm))
                            {
                                var item = new GpuProfileViewModel(message.Source, gpuVm);
                                list.Add(item);
                                list.Sort(new CompareByGpuIndex());
                                if (item.Index == NTMinerRoot.GpuAllId)
                                {
                                    _gpuAllVmDicByCoinId.Add(message.Source.CoinId, item);
                                }
                            }
                            _listByCoinId.Add(message.Source.CoinId, list);
                        }
                    }
                });
#if DEBUG
                Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
            }