Exemple #1
0
 protected override void OnError(ErrorEventArgs e)
 {
     base.OnError(e);
     Write.DevException(e.Exception);
 }
            private GpuViewModels()
            {
#if DEBUG
                Write.Stopwatch.Start();
#endif
                if (WpfUtil.IsInDesignMode)
                {
                    return;
                }
                foreach (var gpu in NTMinerRoot.Instance.GpuSet.AsEnumerable())
                {
                    _gpuVms.Add(gpu.Index, new GpuViewModel(gpu));
                }
                if (_gpuVms.ContainsKey(NTMinerRoot.GpuAllId))
                {
                    _gpuAllVm = _gpuVms[NTMinerRoot.GpuAllId];
                }
                else
                {
                    _gpuAllVm = new GpuViewModel(Gpu.GpuAll);
                }
                BuildEventPath <EPriceChangedEvent>("电价变更后更新电费显示", LogEnum.DevConsole,
                                                    action: message => {
                    foreach (var gpuVm in _gpuVms.Values)
                    {
                        gpuVm.OnPropertyChanged(nameof(GpuViewModel.EChargeText));
                    }
                    AppContext.Instance.GpuSpeedVms.OnPropertyChanged(nameof(GpuSpeedViewModels.ProfitCnyPerDayText));
                });
                BuildEventPath <MaxTempChangedEvent>("高温红色阈值变更后更新显卡温度颜色", LogEnum.DevConsole,
                                                     action: message => {
                    foreach (var gpuVm in _gpuVms.Values)
                    {
                        gpuVm.OnPropertyChanged(nameof(GpuViewModel.TemperatureForeground));
                    }
                });
                BuildEventPath <PowerAppendChangedEvent>("功耗补偿变更后更新功耗显示", LogEnum.DevConsole,
                                                         action: message => {
                    foreach (var gpuVm in _gpuVms.Values)
                    {
                        gpuVm.OnPropertyChanged(nameof(GpuViewModel.PowerUsageWText));
                    }
                    AppContext.Instance.GpuSpeedVms.OnPropertyChanged(nameof(GpuSpeedViewModels.ProfitCnyPerDayText));
                });
                BuildEventPath <GpuStateChangedEvent>("显卡状态变更后刷新VM内存", LogEnum.None,
                                                      action: message => {
                    if (_gpuVms.ContainsKey(message.Source.Index))
                    {
                        GpuViewModel vm        = _gpuVms[message.Source.Index];
                        vm.Temperature         = message.Source.Temperature;
                        vm.FanSpeed            = message.Source.FanSpeed;
                        vm.PowerUsage          = message.Source.PowerUsage;
                        vm.CoreClockDelta      = message.Source.CoreClockDelta;
                        vm.MemoryClockDelta    = message.Source.MemoryClockDelta;
                        vm.CoreClockDeltaMin   = message.Source.CoreClockDeltaMin;
                        vm.CoreClockDeltaMax   = message.Source.CoreClockDeltaMax;
                        vm.MemoryClockDeltaMin = message.Source.MemoryClockDeltaMin;
                        vm.MemoryClockDeltaMax = message.Source.MemoryClockDeltaMax;
                        vm.Cool             = message.Source.Cool;
                        vm.CoolMin          = message.Source.CoolMin;
                        vm.CoolMax          = message.Source.CoolMax;
                        vm.PowerCapacity    = message.Source.PowerCapacity;
                        vm.PowerMin         = message.Source.PowerMin;
                        vm.PowerMax         = message.Source.PowerMax;
                        vm.TempLimit        = message.Source.TempLimit;
                        vm.TempLimitDefault = message.Source.TempLimitDefault;
                        vm.TempLimitMax     = message.Source.TempLimitMax;
                        vm.TempLimitMin     = message.Source.TempLimitMin;
                        vm.CoreVoltage      = message.Source.CoreVoltage;
                        vm.MemoryVoltage    = message.Source.MemoryVoltage;
                        vm.VoltMin          = message.Source.VoltMin;
                        vm.VoltMax          = message.Source.VoltMax;
                        vm.VoltDefault      = message.Source.VoltDefault;
                        if (_gpuAllVm != null)
                        {
                            _gpuAllVm.OnPropertyChanged(nameof(_gpuAllVm.TemperatureText));
                            _gpuAllVm.OnPropertyChanged(nameof(_gpuAllVm.FanSpeedText));
                            _gpuAllVm.OnPropertyChanged(nameof(_gpuAllVm.PowerUsageWText));
                            _gpuAllVm.OnPropertyChanged(nameof(_gpuAllVm.CoreClockDeltaMText));
                            _gpuAllVm.OnPropertyChanged(nameof(_gpuAllVm.MemoryClockDeltaMText));
                            _gpuAllVm.OnPropertyChanged(nameof(_gpuAllVm.CoreClockDeltaMinMaxMText));
                            _gpuAllVm.OnPropertyChanged(nameof(_gpuAllVm.MemoryClockDeltaMinMaxMText));
                            _gpuAllVm.OnPropertyChanged(nameof(_gpuAllVm.CoolMinMaxText));
                            _gpuAllVm.OnPropertyChanged(nameof(_gpuAllVm.PowerMinMaxText));
                            _gpuAllVm.OnPropertyChanged(nameof(_gpuAllVm.TempLimitMinMaxText));
                            _gpuAllVm.OnPropertyChanged(nameof(_gpuAllVm.EChargeText));
                            AppContext.Instance.GpuSpeedVms.OnPropertyChanged(nameof(GpuSpeedViewModels.ProfitCnyPerDayText));
                        }
                        UpdateMinMax();
                    }
                });
#if DEBUG
                var elapsedMilliseconds = Write.Stopwatch.Stop();
                if (elapsedMilliseconds.ElapsedMilliseconds > NTStopwatch.ElapsedMilliseconds)
                {
                    Write.DevTimeSpan($"耗时{elapsedMilliseconds} {this.GetType().Name}.ctor");
                }
#endif
            }
            private KernelInputViewModels()
            {
#if DEBUG
                VirtualRoot.Stopwatch.Restart();
#endif
                On <ServerContextReInitedEvent>("ServerContext刷新后刷新VM内存", LogEnum.DevConsole,
                                                action: message => {
                    _dicById.Clear();
                    Init();
                });
                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 CoinViewModels()
            {
#if DEBUG
                Write.Stopwatch.Start();
#endif
                if (WpfUtil.IsInDesignMode)
                {
                    return;
                }
                VirtualRoot.BuildEventPath <ServerContextReInitedEvent>("ServerContext刷新后刷新VM内存", LogEnum.DevConsole,
                                                                        action: message => {
                    _dicById.Clear();
                    Init();
                });
                VirtualRoot.BuildEventPath <ServerContextVmsReInitedEvent>("ServerContext的VM集刷新后刷新视图界面", LogEnum.DevConsole,
                                                                           action: message => {
                    AllPropertyChanged();
                });
                BuildEventPath <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();
                });
                BuildEventPath <CoinRemovedEvent>("移除了币种后刷新VM内存", LogEnum.DevConsole,
                                                  action: message => {
                    _dicById.Remove(message.Source.GetId());
                    AppContext.Instance.MinerProfileVm.OnPropertyChanged(nameof(NTMiner.AppContext.Instance.MinerProfileVm.CoinVm));
                    AllPropertyChanged();
                });
                BuildEventPath <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));
                    }
                });
                BuildEventPath <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;
                        }
                        if (_dicById.TryGetValue(message.Source.GetId(), out CoinViewModel 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
                var elapsedMilliseconds = Write.Stopwatch.Stop();
                if (elapsedMilliseconds.ElapsedMilliseconds > NTStopwatch.ElapsedMilliseconds)
                {
                    Write.DevTimeSpan($"耗时{elapsedMilliseconds} {this.GetType().Name}.ctor");
                }
#endif
            }
Exemple #5
0
            private CoinKernelViewModels()
            {
#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 => {
                    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;
                    int sortNumber             = entity.SortNumber;
                    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));
                    }
                    if (dualCoinGroupId != entity.DualCoinGroupId)
                    {
                        entity.OnPropertyChanged(nameof(entity.DualCoinGroup));
                    }
                    if (sortNumber != entity.SortNumber)
                    {
                        CoinViewModel coinVm;
                        if (AppContext.Instance.CoinVms.TryGetCoinVm(entity.CoinId, out coinVm))
                        {
                            coinVm.OnPropertyChanged(nameof(coinVm.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.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
            }
 public void ShowError(string message, string header = "错误", int autoHideSeconds = 0, bool toConsole = false)
 {
     Write.UserError(message);
 }
 public void ShowSuccess(string message, string header = "成功", int autoHideSeconds = 4, bool toConsole = false)
 {
     Write.UserOk(message);
 }
Exemple #8
0
            private GpuSpeedViewModels()
            {
#if DEBUG
                NTStopwatch.Start();
#endif
                if (WpfUtil.IsInDesignMode)
                {
                    return;
                }
                this.GpuAllVm = AppContext.Instance.GpuVms.Items.FirstOrDefault(a => a.Index == NTMinerRoot.GpuAllId);
                IGpusSpeed gpuSpeeds = NTMinerRoot.Instance.GpusSpeed;
                foreach (var item in gpuSpeeds.AsEnumerable())
                {
                    this._list.Add(new GpuSpeedViewModel(item));
                }
                _totalSpeedVm = this._list.FirstOrDefault(a => a.GpuVm.Index == NTMinerRoot.GpuAllId);
                AddEventPath <GpuShareChangedEvent>("显卡份额变更后刷新VM内存", LogEnum.DevConsole,
                                                    action: message => {
                    ResetIfMainCoinSwitched();
                    int index = message.Target.Gpu.Index;
                    GpuSpeedViewModel gpuSpeedVm = _list.FirstOrDefault(a => a.GpuVm.Index == index);
                    if (gpuSpeedVm != null)
                    {
                        gpuSpeedVm.MainCoinSpeed.FoundShare  = message.Target.MainCoinSpeed.FoundShare;
                        gpuSpeedVm.MainCoinSpeed.AcceptShare = message.Target.MainCoinSpeed.AcceptShare;
                        gpuSpeedVm.MainCoinSpeed.RejectShare = message.Target.MainCoinSpeed.RejectShare;
                    }
                }, location: this.GetType());
                AddEventPath <FoundShareIncreasedEvent>("找到一个份额后刷新VM内存", LogEnum.DevConsole,
                                                        action: message => {
                    ResetIfMainCoinSwitched();
                    int index = message.Target.Gpu.Index;
                    GpuSpeedViewModel gpuSpeedVm = _list.FirstOrDefault(a => a.GpuVm.Index == index);
                    if (gpuSpeedVm != null)
                    {
                        gpuSpeedVm.MainCoinSpeed.FoundShare = message.Target.MainCoinSpeed.FoundShare;
                    }
                }, location: this.GetType());
                AddEventPath <AcceptShareIncreasedEvent>("接受一个份额后刷新VM内存", LogEnum.DevConsole,
                                                         action: message => {
                    ResetIfMainCoinSwitched();
                    int index = message.Target.Gpu.Index;
                    GpuSpeedViewModel gpuSpeedVm = _list.FirstOrDefault(a => a.GpuVm.Index == index);
                    if (gpuSpeedVm != null)
                    {
                        gpuSpeedVm.MainCoinSpeed.AcceptShare = message.Target.MainCoinSpeed.AcceptShare;
                    }
                }, location: this.GetType());
                AddEventPath <RejectShareIncreasedEvent>("拒绝一个份额后刷新VM内存", LogEnum.DevConsole,
                                                         action: message => {
                    ResetIfMainCoinSwitched();
                    int index = message.Target.Gpu.Index;
                    GpuSpeedViewModel gpuSpeedVm = _list.FirstOrDefault(a => a.GpuVm.Index == index);
                    if (gpuSpeedVm != null)
                    {
                        gpuSpeedVm.MainCoinSpeed.RejectShare = message.Target.MainCoinSpeed.RejectShare;
                    }
                }, location: this.GetType());
                AddEventPath <IncorrectShareIncreasedEvent>("产生一个错误份额后刷新VM内存", LogEnum.DevConsole,
                                                            action: message => {
                    ResetIfMainCoinSwitched();
                    int index = message.Target.Gpu.Index;
                    GpuSpeedViewModel gpuSpeedVm = _list.FirstOrDefault(a => a.GpuVm.Index == index);
                    if (gpuSpeedVm != null)
                    {
                        gpuSpeedVm.MainCoinSpeed.IncorrectShare = message.Target.MainCoinSpeed.IncorrectShare;
                    }
                }, location: this.GetType());
                AddEventPath <GpuSpeedChangedEvent>("显卡算力变更后刷新VM内存", LogEnum.DevConsole,
                                                    action: (message) => {
                    ResetIfMainCoinSwitched();
                    int index = message.Target.Gpu.Index;
                    GpuSpeedViewModel gpuSpeedVm = _list.FirstOrDefault(a => a.GpuVm.Index == index);
                    if (gpuSpeedVm != null)
                    {
                        if (message.IsDual)
                        {
                            gpuSpeedVm.DualCoinSpeed.UpdateSpeed(message.Target.DualCoinSpeed.Value, message.Target.DualCoinSpeed.SpeedOn);
                            gpuSpeedVm.OnPropertyChanged(nameof(gpuSpeedVm.AverageDualCoinSpeedText));
                        }
                        else
                        {
                            gpuSpeedVm.MainCoinSpeed.UpdateSpeed(message.Target.MainCoinSpeed.Value, message.Target.MainCoinSpeed.SpeedOn);
                            gpuSpeedVm.OnPropertyChanged(nameof(gpuSpeedVm.AverageMainCoinSpeedText));
                        }
                    }
                    if (index == _totalSpeedVm.GpuVm.Index)
                    {
                        IMineContext mineContext = NTMinerRoot.Instance.LockedMineContext;
                        if (mineContext == null)
                        {
                            IncomeMainCoinPerDay    = 0;
                            IncomeMainCoinUsdPerDay = 0;
                            IncomeMainCoinCnyPerDay = 0;
                            IncomeDualCoinPerDay    = 0;
                            IncomeDualCoinUsdPerDay = 0;
                            IncomeDualCoinCnyPerDay = 0;
                        }
                        else
                        {
                            if (message.IsDual)
                            {
                                if (mineContext is IDualMineContext dualMineContext)
                                {
                                    IncomePerDay incomePerDay = NTMinerRoot.Instance.CalcConfigSet.GetIncomePerHashPerDay(dualMineContext.DualCoin.Code);
                                    IncomeDualCoinPerDay      = _totalSpeedVm.DualCoinSpeed.Value * incomePerDay.IncomeCoin;
                                    IncomeDualCoinUsdPerDay   = _totalSpeedVm.DualCoinSpeed.Value * incomePerDay.IncomeUsd;
                                    IncomeDualCoinCnyPerDay   = _totalSpeedVm.DualCoinSpeed.Value * incomePerDay.IncomeCny;
                                }
                            }
                            else
                            {
                                IncomePerDay incomePerDay = NTMinerRoot.Instance.CalcConfigSet.GetIncomePerHashPerDay(mineContext.MainCoin.Code);
                                IncomeMainCoinPerDay      = _totalSpeedVm.MainCoinSpeed.Value * incomePerDay.IncomeCoin;
                                IncomeMainCoinUsdPerDay   = _totalSpeedVm.MainCoinSpeed.Value * incomePerDay.IncomeUsd;
                                IncomeMainCoinCnyPerDay   = _totalSpeedVm.MainCoinSpeed.Value * incomePerDay.IncomeCny;
                            }
                        }
                    }
                }, location: this.GetType());
                AddEventPath <Per1SecondEvent>("每秒钟更新算力活动时间", LogEnum.None,
                                               action: message => {
                    TotalSpeedVm.MainCoinSpeed.OnPropertyChanged(nameof(SpeedViewModel.LastSpeedOnText));
                    TotalSpeedVm.DualCoinSpeed.OnPropertyChanged(nameof(SpeedViewModel.LastSpeedOnText));
                }, location: this.GetType());
#if DEBUG
                var elapsedMilliseconds = NTStopwatch.Stop();
                if (elapsedMilliseconds.ElapsedMilliseconds > NTStopwatch.ElapsedMilliseconds)
                {
                    Write.DevTimeSpan($"耗时{elapsedMilliseconds} {this.GetType().Name}.ctor");
                }
#endif
            }
Exemple #9
0
        private void DoInit(bool isWork, Action callback)
        {
            this.ServerAppSettingSet = new ServerAppSettingSet(this);
            this.CalcConfigSet       = new CalcConfigSet(this);

            ServerContextInit(isWork);

            this.GpuProfileSet    = new GpuProfileSet(this);
            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.NTMinerWalletSet = new NTMinerWalletSet(this);
            this.OverClockDataSet = new OverClockDataSet(this);
            this.ColumnsShowSet   = new ColumnsShowSet(this);
            // 作业和在群控客户端管理作业时
            IsJsonLocal        = isWork || VirtualRoot.IsMinerStudio;
            this._minerProfile = new MinerProfile(this);

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

            if (VirtualRoot.IsMinerClient)
            {
                OfficialServer.GetTimeAsync((remoteTime) => {
                    if (Math.Abs((DateTime.Now - remoteTime).TotalSeconds) < Timestamp.DesyncSeconds)
                    {
                        Logger.OkDebugLine("时间同步");
                    }
                    else
                    {
                        Write.UserWarn($"本机时间和服务器时间不同步,请调整,本地:{DateTime.Now},服务器:{remoteTime}");
                    }
                });

                Report.Init();
                Link();
                // 当显卡温度变更时守卫温度防线
                TempGruarder.Instance.Init(this);
                // 因为这里耗时500毫秒左右
                Task.Factory.StartNew(() => {
                    Windows.Error.DisableWindowsErrorUI();
                    if (MinerProfile.IsAutoDisableWindowsFirewall)
                    {
                        Windows.Firewall.DisableFirewall();
                    }
                    Windows.UAC.DisableUAC();
                    Windows.WAU.DisableWAUAsync();
                    Windows.Defender.DisableAntiSpyware();
                    Windows.Power.PowerCfgOff();
                    Windows.BcdEdit.IgnoreAllFailures();
                });
            }

            callback?.Invoke();
        }
Exemple #10
0
        protected override void OnStartup(StartupEventArgs e)
        {
            RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
            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)
                {
                    if (!NTMiner.Windows.WMI.IsWmiEnabled)
                    {
                        DialogWindow.ShowDialog(message: "开源矿工无法运行所需的组件,因为本机未开启WMI服务,开源矿工需要使用WMI服务检测windows的内存、显卡等信息,请先手动开启WMI。", title: "提醒", icon: "Icon_Error");
                        Shutdown();
                        Environment.Exit(0);
                    }
                    NTMinerOverClockUtil.ExtractResource();

                    NTMinerRoot.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() && Registry.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();
                            }
                            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);
        }
            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.NoShareRestartComputerMinutesUp = new DelegateCommand(() => {
                    this.NoShareRestartComputerMinutes++;
                });
                this.NoShareRestartComputerMinutesDown = new DelegateCommand(() => {
                    if (this.NoShareRestartComputerMinutes > 0)
                    {
                        this.NoShareRestartComputerMinutes--;
                    }
                });
                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 (CoinVm != null)
                    {
                        CoinVm.OnPropertyChanged(nameof(CoinVm.Wallets));
                        CoinVm.CoinKernel?.CoinKernelProfile.SelectedDualCoin?.OnPropertyChanged(nameof(CoinVm.Wallets));
                        CoinVm.CoinProfile.OnPropertyChanged(nameof(CoinVm.CoinProfile.SelectedWallet));
                        CoinVm.CoinKernel?.CoinKernelProfile.SelectedDualCoin?.CoinProfile.OnPropertyChanged(nameof(CoinVm.CoinProfile.SelectedDualCoinWallet));
                    }
                });
#if DEBUG
                Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
            }
Exemple #12
0
 private static void StartConsumer(IModel channel, AbstractMqMessagePath[] mqMessagePaths)
 {
     Task.Factory.StartNew(() => {
         DateTime startOn = DateTime.Now;
         bool isTimeout   = false;
         while (!mqMessagePaths.All(a => a.IsReadyToBuild))
         {
             if (startOn.AddSeconds(20) < DateTime.Now)
             {
                 isTimeout = true;
                 break;
             }
             System.Threading.Thread.Sleep(100);
         }
         if (isTimeout)
         {
             Write.UserFail("订阅Mq失败,因为超时");
         }
         else
         {
             foreach (var mqMessagePathsByQueue in mqMessagePaths.GroupBy(a => a.Queue))
             {
                 string queue = mqMessagePathsByQueue.Key;
                 bool durable = queue.EndsWith(MqKeyword.DurableQueueEndsWith);
                 channel.QueueDeclare(
                     queue: queue,
                     durable: durable,
                     exclusive: false,
                     autoDelete: !durable,
                     arguments: null);
                 EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
                 foreach (var mqMessagePath in mqMessagePathsByQueue)
                 {
                     mqMessagePath.Build(channel);
                 }
                 consumer.Received += (model, ea) => {
                     foreach (var mqMessagePath in mqMessagePathsByQueue)
                     {
                         try {
                             mqMessagePath.Go(ea);
                         }
                         catch (Exception e) {
                             Logger.ErrorDebugLine(e);
                         }
                     }
                     if (durable)
                     {
                         channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                     }
                 };
                 if (durable)
                 {
                     channel.BasicConsume(queue: queue, autoAck: false, consumer: consumer);
                 }
                 else
                 {
                     channel.BasicConsume(queue: queue, autoAck: true, consumer: consumer);
                 }
             }
             Write.UserOk("订阅Mq成功");
         }
     });
 }
Exemple #13
0
        static void Main(string[] args)
        {
            if (args.Length != 0)
            {
                if (args.Contains("--sha1"))
                {
                    File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sha1"), Sha1);
                    return;
                }
            }
            try {
                SystemEvents.SessionEnding += (sender, e) => {
                    OsSessionEndingEvent.ReasonSessionEnding reason;
                    switch (e.Reason)
                    {
                    case SessionEndReasons.Logoff:
                        reason = OsSessionEndingEvent.ReasonSessionEnding.Logoff;
                        break;

                    case SessionEndReasons.SystemShutdown:
                        reason = OsSessionEndingEvent.ReasonSessionEnding.Shutdown;
                        break;

                    default:
                        reason = OsSessionEndingEvent.ReasonSessionEnding.Unknown;
                        break;
                    }
                    VirtualRoot.RaiseEvent(new OsSessionEndingEvent(reason));
                };
                VirtualRoot.StartTimer();
                _waitHandle = new AutoResetEvent(false);
                bool mutexCreated;
                try {
                    _sMutexApp = new Mutex(true, "NTMinerDaemonAppMutex", out mutexCreated);
                }
                catch {
                    mutexCreated = false;
                }
                if (mutexCreated)
                {
                    NTMinerRegistry.SetDaemonVersion(Sha1);
                    NTMinerRegistry.SetAutoBoot("NTMinerDaemon", true);
                    bool isAutoBoot = MinerProfileUtil.GetIsAutoBoot();
                    if (isAutoBoot)
                    {
                        string location = NTMinerRegistry.GetLocation();
                        if (!string.IsNullOrEmpty(location) && File.Exists(location))
                        {
                            string    processName = Path.GetFileName(location);
                            Process[] processes   = Process.GetProcessesByName(processName);
                            if (processes.Length == 0)
                            {
                                string arguments = NTMinerRegistry.GetArguments();
                                if (NTMinerRegistry.GetIsLastIsWork())
                                {
                                    arguments = "--work " + arguments;
                                }
                                try {
                                    Process.Start(location, arguments);
                                    Write.DevOk($"启动挖矿端 {location} {arguments}");
                                }
                                catch (Exception e) {
                                    Logger.ErrorDebugLine($"启动挖矿端失败因为异常 {location} {arguments}", e);
                                }
                            }
                            else
                            {
                                Write.DevDebug($"挖矿端已经在运行中无需启动");
                            }
                        }
                    }
                    else
                    {
                        Write.DevDebug($"挖矿端未设置为自动启动");
                    }
                    Run();
                }
            }
            catch (Exception e) {
                Logger.ErrorDebugLine(e);
            }
        }
Exemple #14
0
 protected override void OnOpen()
 {
     base.OnOpen();
     Write.DevWarn("ConnCount " + Sessions.Count);
 }
Exemple #15
0
            private GpuSpeedViewModels()
            {
#if DEBUG
                VirtualRoot.Stopwatch.Restart();
#endif
                if (Design.IsInDesignMode)
                {
                    return;
                }
                this.GpuAllVm = AppContext.Instance.GpuVms.FirstOrDefault(a => a.Index == NTMinerRoot.GpuAllId);
                IGpusSpeed gpuSpeeds = NTMinerRoot.Instance.GpusSpeed;
                foreach (var item in gpuSpeeds)
                {
                    this._list.Add(new GpuSpeedViewModel(item));
                }
                _totalSpeedVm = this._list.FirstOrDefault(a => a.GpuVm.Index == NTMinerRoot.GpuAllId);
                On <GpuSpeedChangedEvent>("显卡算力变更后刷新VM内存", LogEnum.DevConsole,
                                          action: (message) => {
                    Guid mainCoinId = NTMinerRoot.Instance.MinerProfile.CoinId;
                    if (_mainCoinId != mainCoinId)
                    {
                        _mainCoinId  = mainCoinId;
                        DateTime now = DateTime.Now;
                        foreach (var item in _list)
                        {
                            item.MainCoinSpeed.Value   = 0;
                            item.MainCoinSpeed.SpeedOn = now;
                            item.DualCoinSpeed.Value   = 0;
                            item.DualCoinSpeed.SpeedOn = now;
                        }
                        IncomeMainCoinPerDay    = 0;
                        IncomeMainCoinUsdPerDay = 0;
                        IncomeMainCoinCnyPerDay = 0;
                        IncomeDualCoinPerDay    = 0;
                        IncomeDualCoinUsdPerDay = 0;
                        IncomeDualCoinCnyPerDay = 0;
                    }
                    int index = message.Source.Gpu.Index;
                    GpuSpeedViewModel gpuSpeedVm = _list.FirstOrDefault(a => a.GpuVm.Index == index);
                    if (gpuSpeedVm != null)
                    {
                        if (message.IsDualSpeed)
                        {
                            gpuSpeedVm.DualCoinSpeed.Update(message.Source.DualCoinSpeed);
                            gpuSpeedVm.OnPropertyChanged(nameof(gpuSpeedVm.AverageDualCoinSpeedText));
                        }
                        else
                        {
                            gpuSpeedVm.MainCoinSpeed.Update(message.Source.MainCoinSpeed);
                            gpuSpeedVm.OnPropertyChanged(nameof(gpuSpeedVm.AverageMainCoinSpeedText));
                        }
                    }
                    if (index == _totalSpeedVm.GpuVm.Index)
                    {
                        IMineContext mineContext = NTMinerRoot.Instance.CurrentMineContext;
                        if (mineContext == null)
                        {
                            IncomeMainCoinPerDay    = 0;
                            IncomeMainCoinUsdPerDay = 0;
                            IncomeMainCoinCnyPerDay = 0;
                            IncomeDualCoinPerDay    = 0;
                            IncomeDualCoinUsdPerDay = 0;
                            IncomeDualCoinCnyPerDay = 0;
                        }
                        else
                        {
                            if (message.IsDualSpeed)
                            {
                                if (mineContext is IDualMineContext dualMineContext)
                                {
                                    IncomePerDay incomePerDay = NTMinerRoot.Instance.CalcConfigSet.GetIncomePerHashPerDay(dualMineContext.DualCoin.Code);
                                    IncomeDualCoinPerDay      = _totalSpeedVm.DualCoinSpeed.Value * incomePerDay.IncomeCoin;
                                    IncomeDualCoinUsdPerDay   = _totalSpeedVm.DualCoinSpeed.Value * incomePerDay.IncomeUsd;
                                    IncomeDualCoinCnyPerDay   = _totalSpeedVm.DualCoinSpeed.Value * incomePerDay.IncomeCny;
                                }
                            }
                            else
                            {
                                IncomePerDay incomePerDay = NTMinerRoot.Instance.CalcConfigSet.GetIncomePerHashPerDay(mineContext.MainCoin.Code);
                                IncomeMainCoinPerDay      = _totalSpeedVm.MainCoinSpeed.Value * incomePerDay.IncomeCoin;
                                IncomeMainCoinUsdPerDay   = _totalSpeedVm.MainCoinSpeed.Value * incomePerDay.IncomeUsd;
                                IncomeMainCoinCnyPerDay   = _totalSpeedVm.MainCoinSpeed.Value * incomePerDay.IncomeCny;
                            }
                        }
                    }
                });
                On <Per1SecondEvent>("每秒钟更新算力活动时间", LogEnum.None,
                                     action: message => {
                    TotalSpeedVm.MainCoinSpeed.OnPropertyChanged(nameof(SpeedViewModel.LastSpeedOnText));
                    TotalSpeedVm.DualCoinSpeed.OnPropertyChanged(nameof(SpeedViewModel.LastSpeedOnText));
                });
#if DEBUG
                Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
            }
Exemple #16
0
            private KernelViewModels()
            {
#if DEBUG
                NTStopwatch.Start();
#endif
                VirtualRoot.AddEventPath <ServerContextReInitedEvent>("ServerContext刷新后刷新VM内存", LogEnum.DevConsole,
                                                                      action: message => {
                    _dicById.Clear();
                    Init();
                }, location: this.GetType());
                VirtualRoot.AddEventPath <ServerContextVmsReInitedEvent>("ServerContext的VM集刷新后刷新视图界面", LogEnum.DevConsole,
                                                                         action: message => {
                    OnPropertyChanged(nameof(AllKernels));
                }, location: this.GetType());
                AddEventPath <KernelAddedEvent>("添加了内核后调整VM内存", LogEnum.DevConsole,
                                                action: (message) => {
                    _dicById.Add(message.Target.GetId(), new KernelViewModel(message.Target));
                    OnPropertyChanged(nameof(AllKernels));
                    foreach (var coinKernelVm in AppContext.Instance.CoinKernelVms.AllCoinKernels.Where(a => a.KernelId == message.Target.GetId()))
                    {
                        coinKernelVm.OnPropertyChanged(nameof(coinKernelVm.IsSupportDualMine));
                    }
                }, location: this.GetType());
                AddEventPath <KernelRemovedEvent>("删除了内核后调整VM内存", LogEnum.DevConsole,
                                                  action: message => {
                    _dicById.Remove(message.Target.GetId());
                    OnPropertyChanged(nameof(AllKernels));
                    foreach (var coinKernelVm in AppContext.Instance.CoinKernelVms.AllCoinKernels.Where(a => a.KernelId == message.Target.GetId()))
                    {
                        coinKernelVm.OnPropertyChanged(nameof(coinKernelVm.IsSupportDualMine));
                    }
                }, location: this.GetType());
                AddEventPath <KernelUpdatedEvent>("更新了内核后调整VM内存", LogEnum.DevConsole,
                                                  action: message => {
                    var entity = _dicById[message.Target.GetId()];
                    PublishStatus publishStatus = entity.PublishState;
                    Guid kernelInputId          = entity.KernelInputId;
                    entity.Update(message.Target);
                    if (publishStatus != entity.PublishState)
                    {
                        foreach (var coinKernelVm in AppContext.Instance.CoinKernelVms.AllCoinKernels.Where(a => a.KernelId == entity.Id))
                        {
                            foreach (var coinVm in AppContext.Instance.CoinVms.AllCoins.Where(a => a.Id == coinKernelVm.CoinId))
                            {
                                coinVm.OnPropertyChanged(nameof(coinVm.CoinKernels));
                            }
                        }
                    }
                    if (kernelInputId != entity.KernelInputId)
                    {
                        NTMinerRoot.RefreshArgsAssembly.Invoke();
                    }
                }, location: this.GetType());
                Init();
#if DEBUG
                var elapsedMilliseconds = NTStopwatch.Stop();
                if (elapsedMilliseconds.ElapsedMilliseconds > NTStopwatch.ElapsedMilliseconds)
                {
                    Write.DevTimeSpan($"耗时{elapsedMilliseconds} {this.GetType().Name}.ctor");
                }
#endif
            }
            private KernelOutputTranslaterViewModels()
            {
#if DEBUG
                VirtualRoot.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.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
            }
 private static void ReadPrintLoopLogFileAsync(IMineContext mineContext, string logFile)
 {
     Task.Factory.StartNew(() => {
         bool isLogFileCreated = true;
         int n = 0;
         while (!File.Exists(logFile))
         {
             if (n >= 10)
             {
                 // 10秒钟都没有建立日志文件,不可能
                 isLogFileCreated = false;
                 Write.UserFail("呃!竟然10秒钟未产生内核输出文件,请联系开发人员解决。");
                 break;
             }
             Write.UserInfo("等待内核输出");
             Thread.Sleep(1000);
             if (mineContext != Instance.CurrentMineContext)
             {
                 Write.UserInfo("挖矿上下文变更,结束内核输出等待。");
                 isLogFileCreated = false;
                 break;
             }
             n++;
         }
         if (isLogFileCreated)
         {
             Write.UserOk("成功得到内核输出。");
             StreamReader sreader = null;
             try {
                 sreader = new StreamReader(File.Open(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.Default);
                 while (mineContext == Instance.CurrentMineContext)
                 {
                     string outline = sreader.ReadLine();
                     if (string.IsNullOrEmpty(outline) && sreader.EndOfStream)
                     {
                         Thread.Sleep(1000);
                     }
                     else
                     {
                         string input        = outline;
                         Guid kernelOutputId = mineContext.Kernel.KernelOutputId;
                         Instance.KernelOutputFilterSet.Filter(kernelOutputId, ref input);
                         ConsoleColor color = ConsoleColor.White;
                         Instance.KernelOutputTranslaterSet.Translate(kernelOutputId, ref input, ref color, isPre: true);
                         // 使用Claymore挖其非ETH币种时它也打印ETH,所以这里需要纠正它
                         if ("Claymore".Equals(mineContext.Kernel.Code, StringComparison.OrdinalIgnoreCase))
                         {
                             if (mineContext.MainCoin.Code != "ETH" && input.Contains("ETH"))
                             {
                                 input = input.Replace("ETH", mineContext.MainCoin.Code);
                             }
                         }
                         Instance.KernelOutputSet.Pick(kernelOutputId, ref input, mineContext);
                         if (IsUiVisible)
                         {
                             Instance.KernelOutputTranslaterSet.Translate(kernelOutputId, ref input, ref color);
                         }
                         if (!string.IsNullOrEmpty(input))
                         {
                             if (Instance.KernelOutputSet.TryGetKernelOutput(kernelOutputId, out IKernelOutput kernelOutput))
                             {
                                 if (kernelOutput.PrependDateTime)
                                 {
                                     Write.UserLine($"{DateTime.Now}    {input}", color);
                                 }
                                 else
                                 {
                                     Write.UserLine(input, color);
                                 }
                             }
                             else
                             {
                                 Write.UserLine(input, color);
                             }
                         }
                     }
                 }
             }
             catch (Exception e) {
                 Logger.ErrorDebugLine(e.Message, e);
             }
             finally {
                 sreader?.Close();
                 sreader?.Dispose();
             }
             Logger.WarnWriteLine("内核输出结束");
         }
     });
 }
 public void ShowInfo(string message, string header = "信息", int autoHideSeconds = 4, bool toConsole = false)
 {
     Write.UserInfo(message);
 }
            private SysDicItemViewModels()
            {
                if (WpfUtil.IsInDesignMode)
                {
                    return;
                }
#if DEBUG
                NTStopwatch.Start();
#endif
                VirtualRoot.AddEventPath <ServerContextReInitedEvent>("ServerContext刷新后刷新VM内存", LogEnum.DevConsole,
                                                                      action: message => {
                    _dicById.Clear();
                    Init();
                }, location: this.GetType());
                VirtualRoot.AddEventPath <ServerContextVmsReInitedEvent>("ServerContext的VM集刷新后刷新视图界面", LogEnum.DevConsole,
                                                                         action: message => {
                    OnPropertyChangeds();
                }, location: this.GetType());
                AddEventPath <SysDicItemAddedEvent>("添加了系统字典项后调整VM内存", LogEnum.DevConsole,
                                                    action: (message) => {
                    if (!_dicById.ContainsKey(message.Source.GetId()))
                    {
                        _dicById.Add(message.Source.GetId(), new SysDicItemViewModel(message.Source));
                        OnPropertyChangeds();
                        if (SysDicVms.TryGetSysDicVm(message.Source.DicId, out SysDicViewModel sysDicVm))
                        {
                            sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItems));
                            sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItemsSelect));
                        }
                    }
                }, location: this.GetType());
                AddEventPath <SysDicItemUpdatedEvent>("更新了系统字典项后调整VM内存", LogEnum.DevConsole,
                                                      action: (message) => {
                    if (_dicById.TryGetValue(message.Source.GetId(), out SysDicItemViewModel vm))
                    {
                        int sortNumber = vm.SortNumber;
                        vm.Update(message.Source);
                        if (sortNumber != vm.SortNumber)
                        {
                            if (SysDicVms.TryGetSysDicVm(vm.DicId, out SysDicViewModel sysDicVm))
                            {
                                sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItems));
                                sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItemsSelect));
                            }
                        }
                    }
                }, location: this.GetType());
                AddEventPath <SysDicItemRemovedEvent>("删除了系统字典项后调整VM内存", LogEnum.DevConsole,
                                                      action: (message) => {
                    _dicById.Remove(message.Source.GetId());
                    OnPropertyChangeds();
                    if (SysDicVms.TryGetSysDicVm(message.Source.DicId, out SysDicViewModel sysDicVm))
                    {
                        sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItems));
                        sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItemsSelect));
                    }
                }, location: this.GetType());
                Init();
#if DEBUG
                var elapsedMilliseconds = NTStopwatch.Stop();
                if (elapsedMilliseconds.ElapsedMilliseconds > NTStopwatch.ElapsedMilliseconds)
                {
                    Write.DevTimeSpan($"耗时{elapsedMilliseconds} {this.GetType().Name}.ctor");
                }
#endif
            }
 public void ShowWarn(string message, string header = "警告", int autoHideSeconds = 0, bool toConsole = false)
 {
     Write.UserWarn(message);
 }
Exemple #22
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
            }
            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 #24
0
        private static void UpdateAsync()
        {
            Task.Factory.StartNew(() => {
                try {
                    var vdsUUDataTask = GetHtmlAsync("https://uupool.cn/api/getAllInfo.php");
                    var vdsZtDataTask = GetHtmlAsync("https://www.zt.com/api/v1/symbol");
                    var htmlDataTask  = GetHtmlAsync("https://www.f2pool.com/");
                    byte[] htmlData   = null;
                    byte[] vdsUUData  = null;
                    byte[] vdsZtData  = null;
                    try {
                        Task.WaitAll(new Task[] { vdsUUDataTask, vdsZtDataTask, htmlDataTask }, 30 * 1000);
                        htmlData  = htmlDataTask.Result;
                        vdsUUData = vdsUUDataTask.Result;
                        vdsZtData = vdsZtDataTask.Result;
                    }
                    catch {
                    }
                    if (htmlData != null && htmlData.Length != 0)
                    {
                        Write.UserOk($"{DateTime.Now.ToString()} - 鱼池首页html获取成功");
                        string html      = Encoding.UTF8.GetString(htmlData);
                        string vdsUUHtml = string.Empty;
                        string vdsZtHtml = string.Empty;
                        if (vdsUUData != null && vdsUUData.Length != 0)
                        {
                            vdsUUHtml = Encoding.UTF8.GetString(vdsUUData);
                        }
                        if (vdsZtData != null && vdsZtData.Length != 0)
                        {
                            vdsZtHtml = Encoding.UTF8.GetString(vdsZtData);
                        }
                        double usdCny = PickUsdCny(html);
                        Write.UserInfo($"usdCny={usdCny.ToString()}");
                        List <IncomeItem> incomeItems = PickIncomeItems(html);
                        IncomeItem vdsIncomeItem      = PickVDSIncomeItem(vdsUUHtml, vdsZtHtml, usdCny);
                        if (vdsIncomeItem != null && incomeItems.All(a => a.CoinCode != "VDS"))
                        {
                            incomeItems.Add(vdsIncomeItem);
                        }
                        Write.UserInfo($"鱼池首页有{incomeItems.Count.ToString()}个币种");
                        FillCny(incomeItems, usdCny);
                        NeatenSpeedUnit(incomeItems);
                        if (incomeItems != null && incomeItems.Count != 0)
                        {
                            Login();
                            RpcRoot.OfficialServer.ControlCenterService.GetCalcConfigsAsync(data => {
                                Write.UserInfo($"NTMiner有{data.Count.ToString()}个币种");
                                HashSet <string> coinCodes = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                                foreach (CalcConfigData calcConfigData in data)
                                {
                                    IncomeItem incomeItem = incomeItems.FirstOrDefault(a => string.Equals(a.CoinCode, calcConfigData.CoinCode, StringComparison.OrdinalIgnoreCase));
                                    if (incomeItem != null)
                                    {
                                        coinCodes.Add(calcConfigData.CoinCode);
                                        calcConfigData.Speed           = incomeItem.Speed;
                                        calcConfigData.SpeedUnit       = incomeItem.SpeedUnit;
                                        calcConfigData.NetSpeed        = incomeItem.NetSpeed;
                                        calcConfigData.NetSpeedUnit    = incomeItem.NetSpeedUnit;
                                        calcConfigData.IncomePerDay    = incomeItem.IncomeCoin;
                                        calcConfigData.IncomeUsdPerDay = incomeItem.IncomeUsd;
                                        calcConfigData.IncomeCnyPerDay = incomeItem.IncomeCny;
                                        calcConfigData.ModifiedOn      = DateTime.Now;
                                        if (calcConfigData.ModifiedOn.AddMinutes(15) > calcConfigData.ModifiedOn.Date.AddDays(1))
                                        {
                                            calcConfigData.BaseNetSpeed     = calcConfigData.NetSpeed;
                                            calcConfigData.BaseNetSpeedUnit = calcConfigData.NetSpeedUnit;
                                        }
                                        else if (calcConfigData.BaseNetSpeed != 0)
                                        {
                                            if (calcConfigData.NetSpeedUnit == calcConfigData.BaseNetSpeedUnit)
                                            {
                                                calcConfigData.DayWave = (calcConfigData.NetSpeed - calcConfigData.BaseNetSpeed) / calcConfigData.BaseNetSpeed;
                                            }
                                            else
                                            {
                                                if (string.IsNullOrEmpty(calcConfigData.BaseNetSpeedUnit))
                                                {
                                                    calcConfigData.BaseNetSpeedUnit = calcConfigData.NetSpeedUnit;
                                                }
                                                var netSpeed           = calcConfigData.NetSpeed.FromUnitSpeed(calcConfigData.NetSpeedUnit);
                                                var baseNetSpeed       = calcConfigData.BaseNetSpeed.FromUnitSpeed(calcConfigData.BaseNetSpeedUnit);
                                                calcConfigData.DayWave = (netSpeed - baseNetSpeed) / baseNetSpeed;
                                            }
                                        }
                                    }
                                }
                                RpcRoot.OfficialServer.ControlCenterService.SaveCalcConfigsAsync(data, callback: (res, e) => {
                                    if (!res.IsSuccess())
                                    {
                                        VirtualRoot.Out.ShowError(res.ReadMessage(e), autoHideSeconds: 4);
                                    }
                                });
                                foreach (IncomeItem incomeItem in incomeItems)
                                {
                                    if (coinCodes.Contains(incomeItem.CoinCode))
                                    {
                                        continue;
                                    }
                                    Write.UserInfo(incomeItem.ToString());
                                }

                                foreach (var incomeItem in incomeItems)
                                {
                                    if (!coinCodes.Contains(incomeItem.CoinCode))
                                    {
                                        continue;
                                    }
                                    Write.UserOk(incomeItem.ToString());
                                }

                                Write.UserOk($"更新了{coinCodes.Count.ToString()}个币种:{string.Join(",", coinCodes)}");
                                int unUpdatedCount = data.Count - coinCodes.Count;
                                Write.UserWarn($"{unUpdatedCount.ToString()}个币种未更新{(unUpdatedCount == 0 ? string.Empty : ":" + string.Join(",", data.Select(a => a.CoinCode).Except(coinCodes)))}");
                            });
                        }
                    }
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                }
            });
        }
Exemple #25
0
 static void Main(string[] args)
 {
     if (args.Length != 0)
     {
         if (args.Contains("--sha1"))
         {
             File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sha1"), Sha1);
             return;
         }
     }
     try {
         VirtualRoot.StartTimer();
         if (!Debugger.IsAttached && DevMode.IsDevMode)
         {
             Write.Init();
         }
         _waitHandle = new AutoResetEvent(false);
         bool mutexCreated;
         try {
             _sMutexApp = new Mutex(true, "NTMinerDaemonAppMutex", out mutexCreated);
         }
         catch {
             mutexCreated = false;
         }
         if (mutexCreated)
         {
             NTMinerRegistry.SetDaemonVersion(Sha1);
             NTMinerRegistry.SetAutoBoot("NTMinerDaemon", true);
             bool isAutoBoot = NTMinerRegistry.GetIsAutoBoot();
             if (isAutoBoot)
             {
                 string location = NTMinerRegistry.GetLocation();
                 if (!string.IsNullOrEmpty(location) && File.Exists(location))
                 {
                     string    processName = Path.GetFileName(location);
                     Process[] processes   = Process.GetProcessesByName(processName);
                     if (processes.Length == 0)
                     {
                         string arguments = NTMinerRegistry.GetArguments();
                         if (NTMinerRegistry.GetIsLastIsWork())
                         {
                             arguments = "--work " + arguments;
                         }
                         try {
                             Process.Start(location, arguments);
                             Write.DevOk($"启动挖矿端 {location} {arguments}");
                         }
                         catch (Exception e) {
                             Logger.ErrorDebugLine($"启动挖矿端失败因为异常 {location} {arguments}", e);
                         }
                     }
                     else
                     {
                         Write.DevDebug($"挖矿端已经在运行中无需启动");
                     }
                 }
             }
             else
             {
                 Write.DevDebug($"挖矿端未设置为自动启动");
             }
             Run();
         }
     }
     catch (Exception e) {
         Logger.ErrorDebugLine(e);
     }
 }
Exemple #26
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.Message, e);
                 Environment.Exit(0);
             }
         });
     });
     VirtualRoot.Window <CloseMainWindowCommand>("处理关闭主界面命令", LogEnum.DevConsole,
                                                 action: message => {
         UIThread.Execute(() => {
             Write.SetConsoleUserLineMethod();
             MainWindow = NotiCenterWindow.Instance;
             foreach (Window window in Windows)
             {
                 if (window != NotiCenterWindow.Instance)
                 {
                     window.Close();
                 }
             }
             AppContext.Disable();
             NotiCenterWindowViewModel.Instance.Manager.ShowSuccessMessage("已切换为无界面模式运行", "开源矿工");
         });
     });
     #region 周期确保守护进程在运行
     Daemon.DaemonUtil.RunNTMinerDaemon();
     VirtualRoot.On <Per20SecondEvent>("周期确保守护进程在运行", LogEnum.None,
                                       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
 }
Exemple #27
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, serverState => {
                             SetServerJsonVersion(serverState.JsonFileVersion);
                             AppVersionChangedEvent.PublishIfNewVersion(serverState.MinerClientVersion);
                             if (Math.Abs((long)Timestamp.GetTimestamp() - (long)serverState.Time) < Timestamp.DesyncSeconds)
                             {
                                 Logger.OkDebugLine("时间同步");
                             }
                             else
                             {
                                 Write.UserWarn($"本机时间和服务器时间不同步,请调整,本地:{DateTime.Now},服务器:{Timestamp.FromTimestamp(serverState.Time)}");
                             }
                             // 因为挖矿端上报算力时会触发加载服务端消息的逻辑所以这里就不加载了
                             if (VirtualRoot.IsMinerStudio)
                             {
                                 VirtualRoot.Execute(new LoadNewServerMessageCommand(serverState.MessageTimestamp));
                             }
                         });
                     }
                     else
                     {
                         if (!File.Exists(SpecialPath.ServerJsonFileFullName))
                         {
                             VirtualRoot.ThisLocalError(nameof(NTMinerRoot), "配置文件下载失败,这是第一次运行开源矿工,配置文件至少需要成功下载一次,请检查网络是否可用", OutEnum.Warn);
                         }
                         else
                         {
                             VirtualRoot.ThisLocalWarn(nameof(NTMinerRoot), "配置文件下载失败,使用最后一次成功下载的配置文件", OutEnum.Warn);
                         }
                     }
                     DoInit(isWork, callback);
                 });
                 #region 发生了用户活动时检查serverJson是否有新版本
                 VirtualRoot.BuildEventPath <UserActionEvent>("发生了用户活动时检查serverJson是否有新版本", LogEnum.DevConsole,
                                                              action: message => {
                     RefreshServerJsonFile();
                 });
                 #endregion
             }
         }
         VirtualRoot.ThisLocalInfo(nameof(NTMinerRoot), $"启动{VirtualRoot.AppName}");
     });
 }
Exemple #28
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();
     });
 }
Exemple #29
0
        private static void UpdateAsync()
        {
            Task.Factory.StartNew(() => {
                try {
                    byte[] htmlData = GetHtmlAsync("https://www.f2pool.com/").Result;
                    if (htmlData != null && htmlData.Length != 0)
                    {
                        Write.UserOk($"{DateTime.Now} - 鱼池首页html获取成功");
                        string html   = Encoding.UTF8.GetString(htmlData);
                        double usdCny = PickUsdCny(html);
                        Write.UserInfo($"usdCny={usdCny}");
                        List <IncomeItem> incomeItems = PickIncomeItems(html);
                        Write.UserInfo($"鱼池首页有{incomeItems.Count}个币种");
                        FillCny(incomeItems, usdCny);
                        NeatenSpeedUnit(incomeItems);
                        if (incomeItems != null && incomeItems.Count != 0)
                        {
                            Login();
                            OfficialServer.CalcConfigService.GetCalcConfigsAsync(data => {
                                Write.UserInfo($"NTMiner有{data.Count}个币种");
                                HashSet <string> coinCodes = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                                foreach (CalcConfigData calcConfigData in data)
                                {
                                    IncomeItem incomeItem = incomeItems.FirstOrDefault(a => string.Equals(a.CoinCode, calcConfigData.CoinCode, StringComparison.OrdinalIgnoreCase));
                                    if (incomeItem != null)
                                    {
                                        coinCodes.Add(calcConfigData.CoinCode);
                                        calcConfigData.Speed           = incomeItem.Speed;
                                        calcConfigData.SpeedUnit       = incomeItem.SpeedUnit;
                                        calcConfigData.IncomePerDay    = incomeItem.IncomeCoin;
                                        calcConfigData.IncomeUsdPerDay = incomeItem.IncomeUsd;
                                        calcConfigData.IncomeCnyPerDay = incomeItem.IncomeCny;
                                        calcConfigData.ModifiedOn      = DateTime.Now;
                                    }
                                }
                                OfficialServer.CalcConfigService.SaveCalcConfigsAsync(data, callback: (res, e) => {
                                    if (!res.IsSuccess())
                                    {
                                        Write.UserFail(res.ReadMessage(e));
                                    }
                                });
                                foreach (IncomeItem incomeItem in incomeItems)
                                {
                                    if (coinCodes.Contains(incomeItem.CoinCode))
                                    {
                                        continue;
                                    }
                                    Write.UserInfo(incomeItem.ToString());
                                }

                                foreach (var incomeItem in incomeItems)
                                {
                                    if (!coinCodes.Contains(incomeItem.CoinCode))
                                    {
                                        continue;
                                    }
                                    Write.UserOk(incomeItem.ToString());
                                }

                                Write.UserOk($"更新了{coinCodes.Count}个币种:{string.Join(",", coinCodes)}");
                                int unUpdatedCount = data.Count - coinCodes.Count;
                                Write.UserWarn($"{unUpdatedCount}个币种未更新{(unUpdatedCount == 0 ? string.Empty : ":" + string.Join(",", data.Select(a => a.CoinCode).Except(coinCodes)))}");
                            });
                        }
                    }
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                }
            });
        }
Exemple #30
0
 protected override void OnClose(CloseEventArgs e)
 {
     base.OnClose(e);
     Write.DevWarn("ConnCount " + Sessions.Count);
 }