Esempio n. 1
0
 private void KbCancelButton_Click(object sender, System.Windows.RoutedEventArgs e)
 {
     _isCanceled = true;
     VirtualRoot.Execute(new CloseWindowCommand(this.Vm.Id));
     VirtualRoot.ThisLocalInfo(nameof(RestartWindows), "取消重启电脑");
 }
Esempio n. 2
0
 public void Refresh()
 {
     _isInited = false;
     VirtualRoot.Happened(new GpuProfileSetRefreshedEvent());
 }
Esempio n. 3
0
        public MinerProfileViewModel()
        {
#if DEBUG
            NTStopwatch.Start();
#endif
            if (WpfUtil.IsInDesignMode)
            {
                return;
            }
            if (Instance != null)
            {
                throw new InvalidProgramException();
            }
            if (this.IsCreateShortcut)
            {
                CreateShortcut();
            }
            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.CpuGETemperatureSecondsUp = new DelegateCommand(() => {
                this.CpuGETemperatureSeconds++;
            });
            this.CpuGETemperatureSecondsDown = new DelegateCommand(() => {
                this.CpuGETemperatureSeconds--;
            });
            this.CpuStopTemperatureUp = new DelegateCommand(() => {
                this.CpuStopTemperature++;
            });
            this.CpuStopTemperatureDown = new DelegateCommand(() => {
                this.CpuStopTemperature--;
            });
            this.CpuLETemperatureSecondsUp = new DelegateCommand(() => {
                this.CpuLETemperatureSeconds++;
            });
            this.CpuLETemperatureSecondsDown = new DelegateCommand(() => {
                this.CpuLETemperatureSeconds--;
            });
            this.CpuStartTemperatureUp = new DelegateCommand(() => {
                this.CpuStartTemperature++;
            });
            this.CpuStartTemperatureDown = new DelegateCommand(() => {
                this.CpuStartTemperature--;
            });
            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--;
                }
            });
            this.HighCpuBaselineUp = new DelegateCommand(() => {
                this.HighCpuBaseline++;
            });
            this.HighCpuBaselineDown = new DelegateCommand(() => {
                if (this.HighCpuBaseline > 0)
                {
                    this.HighCpuBaseline--;
                }
            });
            this.HighCpuSecondsUp = new DelegateCommand(() => {
                this.HighCpuSeconds++;
            });
            this.HighCpuSecondsDown = new DelegateCommand(() => {
                if (this.HighCpuSeconds > 0)
                {
                    this.HighCpuSeconds--;
                }
            });
            NTMinerRoot.SetRefreshArgsAssembly(() => {
#if DEBUG
                NTStopwatch.Start();
#endif
                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);
                        }
                    }
                }
                NTMinerRoot.Instance.CurrentMineContext = NTMinerRoot.Instance.CreateMineContext();
                if (NTMinerRoot.Instance.CurrentMineContext != null)
                {
                    this.ArgsAssembly = NTMinerRoot.Instance.CurrentMineContext.CommandLine;
                }
                else
                {
                    this.ArgsAssembly = string.Empty;
                }
#if DEBUG
                var milliseconds = NTStopwatch.Stop();
                if (milliseconds.ElapsedMilliseconds > NTStopwatch.ElapsedMilliseconds)
                {
                    Write.DevTimeSpan($"耗时{milliseconds} {this.GetType().Name}.SetRefreshArgsAssembly");
                }
#endif
            });
            VirtualRoot.AddEventPath <ServerContextVmsReInitedEvent>("ServerContext的VM集刷新后刷新视图界面", LogEnum.DevConsole,
                                                                     action: message => {
                OnPropertyChanged(nameof(CoinVm));
            }, location: this.GetType());
            AppContext.AddCmdPath <RefreshAutoBootStartCommand>("刷新开机启动和自动挖矿的展示", LogEnum.DevConsole,
                                                                action: message => {
                MinerProfileData data = NTMinerRoot.CreateLocalRepository <MinerProfileData>().GetByKey(this.Id);
                if (data != null)
                {
                    this.IsAutoBoot  = data.IsAutoBoot;
                    this.IsAutoStart = data.IsAutoStart;
                }
            }, location: this.GetType());
            AppContext.AddEventPath <MinerProfilePropertyChangedEvent>("MinerProfile设置变更后刷新VM内存", LogEnum.DevConsole,
                                                                       action: message => {
                OnPropertyChanged(message.PropertyName);
            }, location: this.GetType());

            VirtualRoot.AddEventPath <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));
                }
            }, location: this.GetType());
#if DEBUG
            var elapsedMilliseconds = NTStopwatch.Stop();
            if (elapsedMilliseconds.ElapsedMilliseconds > NTStopwatch.ElapsedMilliseconds)
            {
                Write.DevTimeSpan($"耗时{elapsedMilliseconds} {this.GetType().Name}.ctor");
            }
#endif
        }
 protected AbstractMqMessagePath(string queue) : base(queue)
 {
     VirtualRoot.BuildOnecePath <TEvent>($"{typeof(TEvent).Name}事件已经发生,可以订阅对应的Mq了", LogEnum.UserConsole, PathId.Empty, this.GetType(), PathPriority.Normal, path: message => {
         _isEventHappended = true;
     });
 }
Esempio n. 5
0
        public void SetCurrentSpeed(int gpuIndex, double speed, bool isDual, DateTime now)
        {
            InitOnece();
            GpuSpeed gpuSpeed;

            if (!_currentGpuSpeed.TryGetValue(gpuIndex, out gpuSpeed))
            {
                return;
            }
            Guid mainCoinId = _root.MinerProfile.CoinId;

            if (this._mainCoinId != mainCoinId)
            {
                this._mainCoinId = mainCoinId;
                // 切换币种了,清空历史算力
                lock (_gpuSpeedHistoryValuesLocker) {
                    foreach (var item in _gpuSpeedHistory)
                    {
                        item.Value.Clear();
                    }
                }
                // 切换币种了,将所有显卡的当前算力置为0
                foreach (var item in _currentGpuSpeed.Values)
                {
                    item.UpdateMainCoinSpeed(0, now);
                    item.UpdateDualCoinSpeed(0, now);
                }
            }
            lock (_gpuSpeedHistoryValuesLocker) {
                // 将当前的旧算力加入历史列表
                if (_gpuSpeedHistory.TryGetValue(gpuSpeed.Gpu.Index, out List <IGpuSpeed> list))
                {
                    list.Add(gpuSpeed.Clone());
                }
            }
            bool isChanged = false;

            // 如果变化幅度大于等于百分之一或者距离上一次算力记录的时间超过了10分钟则视为算力变化
            if (isDual)
            {
                isChanged = gpuSpeed.DualCoinSpeed.SpeedOn.AddSeconds(10) < now || gpuSpeed.DualCoinSpeed.Value.IsChange(speed, 0.01);
                if (isChanged)
                {
                    gpuSpeed.UpdateDualCoinSpeed(speed, now);
                }
            }
            else
            {
                isChanged = gpuSpeed.MainCoinSpeed.SpeedOn.AddSeconds(10) < now || gpuSpeed.MainCoinSpeed.Value.IsChange(speed, 0.01);
                if (isChanged)
                {
                    gpuSpeed.UpdateMainCoinSpeed(speed, now);
                }
            }
            if (_averageGpuSpeed.TryGetValue(gpuIndex, out AverageSpeed averageSpeed))
            {
                if (isDual)
                {
                    var array = _gpuSpeedHistory[gpuIndex].Where(a => a.DualCoinSpeed.Value != 0).ToArray();
                    if (array.Length != 0)
                    {
                        averageSpeed.DualSpeed = array.Average(a => a.DualCoinSpeed.Value);
                    }
                }
                else
                {
                    var array = _gpuSpeedHistory[gpuIndex].Where(a => a.MainCoinSpeed.Value != 0).ToArray();
                    if (array.Length != 0)
                    {
                        averageSpeed.Speed = array.Average(a => a.MainCoinSpeed.Value);
                    }
                }
            }
            if (isChanged)
            {
                VirtualRoot.Happened(new GpuSpeedChangedEvent(isDualSpeed: isDual, gpuSpeed: gpuSpeed));
            }
        }
Esempio n. 6
0
 internal void Init()
 {
     if (ClientAppType.IsMinerClient)
     {
         Task.Factory.StartNew(() => {
             // 注意:第一次GetTemperature请求约需要160毫秒,所以提前在非UI线程做第一次请求。
             GetTemperature();
             VirtualRoot.BuildEventPath <Per2SecondEvent>("周期更新CpuAll的状态", LogEnum.None, location: this.GetType(), PathPriority.Normal,
                                                          path: message => {
                 Task.Factory.StartNew(() => {
                     // 因为获取cpu温度的操作耗时100毫秒
                     Update();
                     #region CPU温度过高时自动停止挖矿和温度降低时自动开始挖矿
                     if (_minerProfile.IsAutoStopByCpu)
                     {
                         if (NTMinerContext.Instance.IsMining)
                         {
                             /* 挖矿中时周期更新最后一次温度低于挖矿停止温度的时刻,然后检查最后一次低于
                              * 挖矿停止温度的时刻距离现在是否已经超过了设定的时常,如果超过了则自动停止挖矿*/
                             HighTemperatureOn = message.BornOn;
                             // 如果当前温度低于挖矿停止温度则更新记录的低温时刻
                             if (this.Temperature < _minerProfile.CpuStopTemperature)
                             {
                                 LowTemperatureOn = message.BornOn;
                             }
                             if ((message.BornOn - LowTemperatureOn).TotalSeconds >= _minerProfile.CpuGETemperatureSeconds)
                             {
                                 LowTemperatureOn = message.BornOn;
                                 VirtualRoot.ThisLocalWarn(nameof(CpuPackage), $"自动停止挖矿,因为 CPU 温度连续{_minerProfile.CpuGETemperatureSeconds.ToString()}秒不低于{_minerProfile.CpuStopTemperature.ToString()}℃", toConsole: true);
                                 NTMinerContext.Instance.StopMineAsync(StopMineReason.HighCpuTemperature);
                             }
                         }
                         else
                         {
                             /* 高温停止挖矿后周期更新最后一次温度高于挖矿停止温度的时刻,然后检查最后一次高于
                             * 挖矿停止温度的时刻距离现在是否已经超过了设定的时常,如果超过了则自动开始挖矿*/
                             LowTemperatureOn = message.BornOn;
                             if (_minerProfile.IsAutoStartByCpu && NTMinerContext.Instance.StopReason == StopMineReason.HighCpuTemperature)
                             {
                                 // 当前温度高于挖矿停止温度则更新记录的高温时刻
                                 if (this.Temperature > _minerProfile.CpuStartTemperature)
                                 {
                                     HighTemperatureOn = message.BornOn;
                                 }
                                 if ((message.BornOn - HighTemperatureOn).TotalSeconds >= _minerProfile.CpuLETemperatureSeconds)
                                 {
                                     HighTemperatureOn = message.BornOn;
                                     VirtualRoot.ThisLocalWarn(nameof(CpuPackage), $"自动开始挖矿,因为 CPU 温度连续{_minerProfile.CpuLETemperatureSeconds.ToString()}秒不高于{_minerProfile.CpuStartTemperature.ToString()}℃", toConsole: true);
                                     NTMinerContext.Instance.StartMine();
                                 }
                             }
                         }
                     }
                     #endregion
                     if (_minerProfile.IsRaiseHighCpuEvent)
                     {
                         if (this.Performance < _minerProfile.HighCpuBaseline)
                         {
                             LowPerformanceOn = message.BornOn;
                         }
                         if ((message.BornOn - LowPerformanceOn).TotalSeconds >= _minerProfile.HighCpuSeconds)
                         {
                             LowPerformanceOn = message.BornOn;
                             VirtualRoot.ThisLocalWarn(nameof(CpuPackage), $"CPU使用率过高:连续{_minerProfile.HighCpuSeconds.ToString()}秒不低于{_minerProfile.HighCpuBaseline.ToString()}%");
                         }
                     }
                 });
             });
         });
     }
 }
Esempio n. 7
0
        public KernelSet(INTMinerRoot root)
        {
            _root = root;
            _root.ServerContextWindow <AddKernelCommand>("添加内核", LogEnum.DevConsole,
                                                         action: message => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (string.IsNullOrEmpty(message.Input.Code))
                {
                    throw new ValidationException($"{nameof(message.Input.Code)} can't be null or empty");
                }
                if (_dicById.ContainsKey(message.Input.GetId()))
                {
                    return;
                }
                KernelData entity = new KernelData().Update(message.Input);
                _dicById.Add(entity.Id, entity);
                IRepository <KernelData> repository = NTMinerRoot.CreateServerRepository <KernelData>();
                repository.Add(entity);

                VirtualRoot.Happened(new KernelAddedEvent(entity));
            });
            _root.ServerContextWindow <UpdateKernelCommand>("更新内核", LogEnum.DevConsole,
                                                            action: message => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (string.IsNullOrEmpty(message.Input.Code))
                {
                    throw new ValidationException($"{nameof(message.Input.Code)} can't be null or empty");
                }
                if (!_dicById.ContainsKey(message.Input.GetId()))
                {
                    return;
                }
                KernelData entity = _dicById[message.Input.GetId()];
                if (ReferenceEquals(entity, message.Input))
                {
                    return;
                }
                entity.Update(message.Input);
                IRepository <KernelData> repository = NTMinerRoot.CreateServerRepository <KernelData>();
                repository.Update(entity);

                VirtualRoot.Happened(new KernelUpdatedEvent(entity));
            });
            _root.ServerContextWindow <RemoveKernelCommand>("移除内核", LogEnum.DevConsole,
                                                            action: message => {
                InitOnece();
                if (message == null || message.EntityId == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (!_dicById.ContainsKey(message.EntityId))
                {
                    return;
                }
                KernelData entity         = _dicById[message.EntityId];
                List <Guid> coinKernelIds = root.CoinKernelSet.Where(a => a.KernelId == entity.Id).Select(a => a.GetId()).ToList();
                foreach (var coinKernelId in coinKernelIds)
                {
                    VirtualRoot.Execute(new RemoveCoinKernelCommand(coinKernelId));
                }
                _dicById.Remove(entity.Id);
                IRepository <KernelData> repository = NTMinerRoot.CreateServerRepository <KernelData>();
                repository.Remove(entity.Id);

                VirtualRoot.Happened(new KernelRemovedEvent(entity));
            });
        }
        public MinerClientAddViewModel()
        {
            if (WpfUtil.IsInDesignMode)
            {
                return;
            }
            this.Save = new DelegateCommand(() => {
                if (!IPAddress.TryParse(this.LeftIp, out _))
                {
                    this.ShowMessage("IP格式不正确");
                    return;
                }

                if (this.IsIpRange)
                {
                    if (!IPAddress.TryParse(this.RightIp, out _))
                    {
                        this.ShowMessage("IP格式不正确");
                        return;
                    }

                    List <string> clientIps = Net.IpUtil.CreateIpRange(this.LeftIp, this.RightIp);

                    if (clientIps.Count > 101)
                    {
                        this.ShowMessage("最多支持一次添加101个IP");
                        return;
                    }

                    if (clientIps.Count == 0)
                    {
                        this.ShowMessage("没有IP");
                        return;
                    }
                    RpcRoot.Server.ClientService.AddClientsAsync(clientIps, (response, e) => {
                        if (!response.IsSuccess())
                        {
                            this.ShowMessage(response.ReadMessage(e));
                        }
                        else
                        {
                            AppContext.Instance.MinerClientsWindowVm.QueryMinerClients();
                            UIThread.Execute(() => VirtualRoot.Execute(new CloseWindowCommand(this.Id)));
                        }
                    });
                }
                else
                {
                    RpcRoot.Server.ClientService.AddClientsAsync(new List <string> {
                        this.LeftIp
                    }, (response, e) => {
                        if (!response.IsSuccess())
                        {
                            this.ShowMessage(response.ReadMessage(e));
                        }
                        else
                        {
                            AppContext.Instance.MinerClientsWindowVm.QueryMinerClients();
                            UIThread.Execute(() => VirtualRoot.Execute(new CloseWindowCommand(this.Id)));
                        }
                    });
                }
            });
            var localIp = VirtualRoot.LocalIpSet.AsEnumerable().FirstOrDefault();

            if (localIp != null)
            {
                uint left = Net.IpUtil.ConvertToIpNum(localIp.DefaultIPGateway) + 1;
                this._leftIp  = Net.IpUtil.ConvertToIpString(left);
                this._rightIp = Net.IpUtil.ConvertToIpString(left + 100);
            }
        }
Esempio n. 9
0
        public SysDicSet(IServerContext context)
        {
            _context = context;
            context.AddCmdPath <AddSysDicCommand>("添加系统字典", LogEnum.DevConsole,
                                                  action: message => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (string.IsNullOrEmpty(message.Input.Code))
                {
                    throw new ValidationException("dic code can't be null or empty");
                }
                if (_dicById.ContainsKey(message.Input.GetId()))
                {
                    return;
                }
                if (_dicByCode.ContainsKey(message.Input.Code))
                {
                    throw new ValidationException("编码重复");
                }
                SysDicData entity = new SysDicData().Update(message.Input);
                _dicById.Add(entity.Id, entity);
                _dicByCode.Add(entity.Code, entity);
                var repository = context.CreateServerRepository <SysDicData>();
                repository.Add(entity);

                VirtualRoot.RaiseEvent(new SysDicAddedEvent(message.MessageId, entity));
            }, location: this.GetType());
            context.AddCmdPath <UpdateSysDicCommand>("更新系统字典", LogEnum.DevConsole,
                                                     action: message => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (string.IsNullOrEmpty(message.Input.Code))
                {
                    throw new ValidationException("sysDic code can't be null or empty");
                }
                if (!_dicById.TryGetValue(message.Input.GetId(), out SysDicData entity))
                {
                    return;
                }
                if (ReferenceEquals(entity, message.Input))
                {
                    return;
                }
                entity.Update(message.Input);
                var repository = context.CreateServerRepository <SysDicData>();
                repository.Update(entity);

                VirtualRoot.RaiseEvent(new SysDicUpdatedEvent(message.MessageId, entity));
            }, location: this.GetType());
            context.AddCmdPath <RemoveSysDicCommand>("移除系统字典", LogEnum.DevConsole,
                                                     action: message => {
                InitOnece();
                if (message == null || message.EntityId == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (!_dicById.ContainsKey(message.EntityId))
                {
                    return;
                }
                SysDicData entity     = _dicById[message.EntityId];
                List <Guid> toRemoves = context.SysDicItemSet.GetSysDicItems(entity.Code).Select(a => a.GetId()).ToList();
                foreach (var id in toRemoves)
                {
                    VirtualRoot.Execute(new RemoveSysDicItemCommand(id));
                }
                _dicById.Remove(entity.Id);
                if (_dicByCode.ContainsKey(entity.Code))
                {
                    _dicByCode.Remove(entity.Code);
                }
                var repository = context.CreateServerRepository <SysDicData>();
                repository.Remove(entity.Id);

                VirtualRoot.RaiseEvent(new SysDicRemovedEvent(message.MessageId, entity));
            }, location: this.GetType());
        }
Esempio n. 10
0
 public MinerClientSessionSet(IWsSessionsAdapter wsSessions) : base(wsSessions)
 {
     VirtualRoot.BuildEventPath <GetConsoleOutLinesMqEvent>("收到GetConsoleOutLines Mq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(GetConsoleOutLinesMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(GetConsoleOutLinesMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.GetConsoleOutLines)
         {
             Data = message.Data
         });
         #endregion
     });
     VirtualRoot.BuildEventPath <GetLocalMessagesMqEvent>("收到GetLocalMessages Mq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(GetLocalMessagesMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(GetLocalMessagesMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.GetLocalMessages)
         {
             Data = message.Data
         });
         #endregion
     });
     VirtualRoot.BuildEventPath <GetOperationResultsMqEvent>("收到GetOperationResults Mq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(GetOperationResultsMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(GetOperationResultsMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.GetOperationResults)
         {
             Data = message.Data
         });
         #endregion
     });
     VirtualRoot.BuildEventPath <GetDrivesMqEvent>("收到GetDrives Mq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(GetDrivesMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(GetDrivesMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.GetDrives));
         #endregion
     });
     VirtualRoot.BuildEventPath <GetLocalIpsMqEvent>("收到GetLocalIps Mq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(GetLocalIpsMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(GetLocalIpsMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.GetLocalIps));
         #endregion
     });
     VirtualRoot.BuildEventPath <GetSpeedMqEvent>("收到GetSpeedMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (message.Requests == null || message.Requests.Length == 0)
         {
             return;
         }
         if (IsTooOld(message.Timestamp))
         {
             return;
         }
         foreach (var request in message.Requests)
         {
             ServerRoot.IfStudioClientTestIdLogElseNothing(request.StudioId, nameof(GetSpeedMqEvent));
             foreach (var clientId in request.ClientIds.Where(a => TryGetByClientId(a, out _)))
             {
                 if (!IsOwnerBy(clientId, request.LoginName, message.Timestamp))
                 {
                     continue;
                 }
                 ServerRoot.IfMinerClientTestIdLogElseNothing(clientId, nameof(GetSpeedMqEvent));
                 SendToMinerClientAsync(clientId, new WsMessage(message.MessageId, WsMessage.GetSpeed));
             }
         }
         #endregion
     });
     VirtualRoot.BuildEventPath <EnableRemoteDesktopMqEvent>("收到EnableRemoteDesktopMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(EnableRemoteDesktopMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(EnableRemoteDesktopMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.EnableRemoteDesktop));
         #endregion
     });
     VirtualRoot.BuildEventPath <BlockWAUMqEvent>("收到BlockWAUMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(BlockWAUMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(BlockWAUMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.BlockWAU));
         #endregion
     });
     VirtualRoot.BuildEventPath <SetVirtualMemoryMqEvent>("收到SetVirtualMemoryMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(SetVirtualMemoryMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(SetVirtualMemoryMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.SetVirtualMemory)
         {
             Data = message.Data
         });
         #endregion
     });
     VirtualRoot.BuildEventPath <SetLocalIpsMqEvent>("收到SetLocalIpsMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(SetLocalIpsMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(SetLocalIpsMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.SetLocalIps)
         {
             Data = message.Data
         });
         #endregion
     });
     VirtualRoot.BuildEventPath <SwitchRadeonGpuMqEvent>("收到SwitchRadeonGpuMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(SwitchRadeonGpuMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(SwitchRadeonGpuMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.SwitchRadeonGpu)
         {
             Data = message.On
         });
         #endregion
     });
     VirtualRoot.BuildEventPath <GetSelfWorkLocalJsonMqEvent>("收到GetSelfWorkLocalJsonMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(GetSelfWorkLocalJsonMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(GetSelfWorkLocalJsonMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.GetSelfWorkLocalJson));
         #endregion
     });
     VirtualRoot.BuildEventPath <SaveSelfWorkLocalJsonMqEvent>("收到SaveSelfWorkLocalJsonMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(SaveSelfWorkLocalJsonMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(SaveSelfWorkLocalJsonMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.SaveSelfWorkLocalJson)
         {
             Data = message.Data
         });
         #endregion
     });
     VirtualRoot.BuildEventPath <GetGpuProfilesJsonMqEvent>("收到GetGpuProfilesJsonMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(GetGpuProfilesJsonMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(GetGpuProfilesJsonMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.GetGpuProfilesJson));
         #endregion
     });
     VirtualRoot.BuildEventPath <SaveGpuProfilesJsonMqEvent>("收到SaveGpuProfilesJsonMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(SaveGpuProfilesJsonMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(SaveGpuProfilesJsonMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.SaveGpuProfilesJson)
         {
             Data = message.Data
         });
         #endregion
     });
     VirtualRoot.BuildEventPath <SetAutoBootStartMqEvent>("收到SetAutoBootStartMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(SetAutoBootStartMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(SetAutoBootStartMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.SetAutoBootStart)
         {
             Data = message.Data
         });
         #endregion
     });
     VirtualRoot.BuildEventPath <RestartWindowsMqEvent>("收到RestartWindowsMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(RestartWindowsMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(RestartWindowsMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.RestartWindows));
         #endregion
     });
     VirtualRoot.BuildEventPath <ShutdownWindowsMqEvent>("收到ShutdownWindowsMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(ShutdownWindowsMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(ShutdownWindowsMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.ShutdownWindows));
         #endregion
     });
     VirtualRoot.BuildEventPath <UpgradeNTMinerMqEvent>("收到UpgradeNTMinerMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(UpgradeNTMinerMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(UpgradeNTMinerMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.UpgradeNTMiner)
         {
             Data = message.Data
         });
         #endregion
     });
     // WsServer节点和WebApiServer节点都订阅了该消息,WsServer节点只处理非作业消息,WebApiServer节点只处理作业消息
     VirtualRoot.BuildEventPath <StartMineMqEvent>("收到StartMineMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(StartMineMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(StartMineMqEvent));
         Guid workId = message.Data;
         // 只处理非作业的
         if (workId == Guid.Empty)
         {
             SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.StartMine)
             {
                 Data = new WorkRequest {
                     WorkId     = workId,
                     WorkerName = string.Empty,
                     LocalJson  = string.Empty,
                     ServerJson = string.Empty
                 }
             });
         }
         #endregion
     });
     // WebApiServer节点订阅了StartMineMqMessage消息,当StartMineMqMessage消息是作业消息时WebApiServer节点重新广播StartWorkMineMqMessage消息
     VirtualRoot.BuildEventPath <StartWorkMineMqEvent>("收到StartWorkMineMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(StartWorkMineMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(StartWorkMineMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.StartMine)
         {
             Data = message.Data
         });
         #endregion
     });
     VirtualRoot.BuildEventPath <StopMineMqEvent>("收到StopMineMq消息后检查是否是应由本节点处理的消息,如果是则处理,否则忽略", LogEnum.None, this.GetType(), PathPriority.Normal, path: message => {
         #region
         if (!IsOwnerBy(message.ClientId, message.LoginName, message.Timestamp))
         {
             return;
         }
         ServerRoot.IfMinerClientTestIdLogElseNothing(message.ClientId, nameof(StopMineMqEvent));
         ServerRoot.IfStudioClientTestIdLogElseNothing(message.StudioId, nameof(StopMineMqEvent));
         SendToMinerClientAsync(message.ClientId, new WsMessage(message.MessageId, WsMessage.StopMine));
         #endregion
     });
 }
Esempio n. 11
0
        public CoinViewModel(Guid id)
        {
            _id             = id;
            this.BrowseIcon = new DelegateCommand(() => {
                if (!DevMode.IsDevMode)
                {
                    return;
                }
                OpenFileDialog openFileDialog = new OpenFileDialog {
                    InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                    Filter           = "png (*.png)|*.png",
                    FilterIndex      = 1
                };
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    try {
                        string iconFileFullName = openFileDialog.FileName;
                        this.IconImageSource    = new Uri(iconFileFullName, UriKind.Absolute).ToString();
                        string pngFileName      = Path.GetFileName(iconFileFullName);
                        if (AppContext.Instance.CoinVms.AllCoins.Any(a => a.Icon == pngFileName && a.Id != this.Id))
                        {
                            throw new ValidationException("币种图标不能重名");
                        }
                        this.Icon = pngFileName;
                    }
                    catch (Exception e) {
                        Logger.ErrorDebugLine(e.Message, e);
                    }
                }
            });
            this.ApplyTemplateOverClock = new DelegateCommand <OverClockDataViewModel>((data) => {
                DialogWindow.ShowDialog(message: data.Tooltip, title: "确定应用该超频设置吗?", onYes: () => {
                    FillOverClock(data);
                    ApplyOverClock();
                }, icon: IconConst.IconConfirm);
            });
            this.ApplyCustomOverClock = new DelegateCommand(() => {
                DialogWindow.ShowDialog(message: $"确定应用您的自定义超频吗?", title: "确认自定义超频", onYes: () => {
                    ApplyOverClock();
                }, icon: IconConst.IconConfirm);
            });
            this.FillOverClockForm = new DelegateCommand <OverClockDataViewModel>((data) => {
                FillOverClock(data);
            });
            this.AddOverClockData = new DelegateCommand(() => {
                new OverClockDataViewModel(Guid.NewGuid())
                {
                    CoinId = this.Id
                }.Edit.Execute(FormType.Add);
            });
            this.Save = new DelegateCommand(() => {
                if (this.Id == Guid.Empty)
                {
                    return;
                }
                if (NTMinerRoot.Instance.CoinSet.Contains(this.Id))
                {
                    VirtualRoot.Execute(new UpdateCoinCommand(this));
                }
                else
                {
                    VirtualRoot.Execute(new AddCoinCommand(this));
                }
                CloseWindow?.Invoke();
            });
            this.Edit = new DelegateCommand <FormType?>((formType) => {
                if (this.Id == Guid.Empty)
                {
                    return;
                }
                CoinEdit.ShowWindow(formType ?? FormType.Edit, this);
            });
            this.Remove = new DelegateCommand(() => {
                if (this.Id == Guid.Empty)
                {
                    return;
                }
                DialogWindow.ShowDialog(message: $"您确定删除{this.Code}币种吗?", title: "确认", onYes: () => {
                    VirtualRoot.Execute(new RemoveCoinCommand(this.Id));
                }, icon: IconConst.IconConfirm);
            });
            this.SortUp = new DelegateCommand(() => {
                CoinViewModel upOne = AppContext.Instance.CoinVms.AllCoins.OrderByDescending(a => a.SortNumber).FirstOrDefault(a => a.SortNumber < this.SortNumber);
                if (upOne != null)
                {
                    int sortNumber   = upOne.SortNumber;
                    upOne.SortNumber = this.SortNumber;
                    VirtualRoot.Execute(new UpdateCoinCommand(upOne));
                    this.SortNumber = sortNumber;
                    VirtualRoot.Execute(new UpdateCoinCommand(this));
                    AppContext.Instance.CoinVms.OnPropertyChanged(nameof(AppContext.CoinViewModels.MainCoins));
                    AppContext.Instance.CoinVms.OnPropertyChanged(nameof(AppContext.CoinViewModels.AllCoins));
                }
            });
            this.SortDown = new DelegateCommand(() => {
                CoinViewModel nextOne = AppContext.Instance.CoinVms.AllCoins.OrderBy(a => a.SortNumber).FirstOrDefault(a => a.SortNumber > this.SortNumber);
                if (nextOne != null)
                {
                    int sortNumber     = nextOne.SortNumber;
                    nextOne.SortNumber = this.SortNumber;
                    VirtualRoot.Execute(new UpdateCoinCommand(nextOne));
                    this.SortNumber = sortNumber;
                    VirtualRoot.Execute(new UpdateCoinCommand(this));
                    AppContext.Instance.CoinVms.OnPropertyChanged(nameof(AppContext.CoinViewModels.MainCoins));
                    AppContext.Instance.CoinVms.OnPropertyChanged(nameof(AppContext.CoinViewModels.AllCoins));
                }
            });

            this.AddPool = new DelegateCommand(() => {
                int sortNumber = this.Pools.Count == 0 ? 1 : this.Pools.Max(a => a.SortNumber) + 1;
                new PoolViewModel(Guid.NewGuid())
                {
                    CoinId     = Id,
                    SortNumber = sortNumber
                }.Edit.Execute(FormType.Add);
            });
            this.AddWallet = new DelegateCommand(() => {
                int sortNumber = this.Wallets.Count == 0 ? 1 : this.Wallets.Max(a => a.SortNumber) + 1;
                new WalletViewModel(Guid.NewGuid())
                {
                    CoinId     = Id,
                    SortNumber = sortNumber
                }.Edit.Execute(FormType.Add);
            });
        }
Esempio n. 12
0
 public void Pick(ref string line, IMineContext mineContext)
 {
     try {
         InitOnece();
         if (string.IsNullOrEmpty(line))
         {
             return;
         }
         // 使用Claymore挖非ETH币种时它也打印ETH,所以这里需要纠正它
         if ("Claymore".Equals(mineContext.Kernel.Code, StringComparison.OrdinalIgnoreCase))
         {
             if (mineContext.MainCoin.Code != "ETH" && line.Contains("ETH"))
             {
                 line = line.Replace("ETH", mineContext.MainCoin.Code);
             }
         }
         if (!string.IsNullOrEmpty(mineContext.KernelOutput.KernelRestartKeyword) && line.Contains(mineContext.KernelOutput.KernelRestartKeyword))
         {
             if (_kernelRestartKeywordOn.AddSeconds(10) < DateTime.Now)
             {
                 mineContext.KernelSelfRestartCount += 1;
                 _kernelRestartKeywordOn             = DateTime.Now;
                 VirtualRoot.RaiseEvent(new KernelSelfRestartedEvent());
             }
         }
         ICoin coin   = mineContext.MainCoin;
         bool  isDual = false;
         Guid  poolId = mineContext.MainCoinPool.GetId();
         // 如果是双挖上下文且当前输入行中没有主币关键字则视为双挖币
         if ((mineContext is IDualMineContext dualMineContext) && !line.Contains(mineContext.MainCoin.Code))
         {
             isDual = true;
             coin   = dualMineContext.DualCoin;
             poolId = dualMineContext.DualCoinPool.GetId();
         }
         INTMinerRoot root = NTMinerRoot.Instance;
         // 这些方法输出的是事件消息
         PickTotalSpeed(root, line, mineContext.KernelOutput, isDual);
         PickGpuSpeed(root, mineContext, line, mineContext.KernelOutput, isDual);
         PickTotalShare(root, line, mineContext.KernelOutput, coin, isDual);
         PickAcceptShare(root, line, mineContext.KernelOutput, coin, isDual);
         PickAcceptOneShare(root, mineContext, line, _preline, mineContext.KernelOutput, coin, isDual);
         PickRejectPattern(root, line, mineContext.KernelOutput, coin, isDual);
         PickRejectOneShare(root, mineContext, line, _preline, mineContext.KernelOutput, coin, isDual);
         PickRejectPercent(root, line, mineContext.KernelOutput, coin, isDual);
         PickPoolDelay(line, mineContext.KernelOutput, isDual, poolId);
         if (!isDual)
         {
             // 决定不支持双挖的单卡份额统计
             PicFoundOneShare(root, mineContext, line, _preline, mineContext.KernelOutput);
             PicGotOneIncorrectShare(root, mineContext, line, _preline, mineContext.KernelOutput);
         }
         // 如果是像BMiner那样的主币和双挖币的输出在同一行那样的模式则一行输出既要视为主币又要视为双挖币
         if (isDual && mineContext.KernelOutput.IsDualInSameLine)
         {
             coin   = mineContext.MainCoin;
             isDual = false;
             PickTotalSpeed(root, line, mineContext.KernelOutput, isDual);
             PickGpuSpeed(root, mineContext, line, mineContext.KernelOutput, isDual);
             PickTotalShare(root, line, mineContext.KernelOutput, coin, isDual);
             PickAcceptShare(root, line, mineContext.KernelOutput, coin, isDual);
             PickAcceptOneShare(root, mineContext, line, _preline, mineContext.KernelOutput, coin, isDual);
             PickRejectPattern(root, line, mineContext.KernelOutput, coin, isDual);
             PickRejectOneShare(root, mineContext, line, _preline, mineContext.KernelOutput, coin, isDual);
             PickRejectPercent(root, line, mineContext.KernelOutput, coin, isDual);
             PickPoolDelay(line, mineContext.KernelOutput, isDual, poolId);
         }
         _preline = line;
     }
     catch (Exception e) {
         Logger.ErrorDebugLine(e);
     }
 }
Esempio n. 13
0
 private MainWindowViewModel()
 {
     if (App.IsInDesignMode)
     {
         return;
     }
     this.Refresh();
     this.ShowOrHideServerLatestDescription = new DelegateCommand(() => {
         if (ServerLatestDescriptionVisible == Visibility.Visible)
         {
             ServerLatestDescriptionVisible = Visibility.Collapsed;
         }
         else
         {
             ServerLatestDescriptionVisible = Visibility.Visible;
         }
     });
     this.CancelDownload = new DelegateCommand(() => {
         this._cancel?.Invoke();
     });
     this.Install = new DelegateCommand(() => {
         this.IsDownloading = true;
         string ntMinerFile = string.Empty;
         string version     = string.Empty;
         if (IsHistoryVisible == Visibility.Collapsed)
         {
             if (ServerLatestVm != null)
             {
                 ntMinerFile = ServerLatestVm.FileName;
                 version     = ServerLatestVm.Version;
             }
         }
         else
         {
             ntMinerFile = SelectedNTMinerFile.FileName;
             version     = SelectedNTMinerFile.Version;
         }
         Download(ntMinerFile, version,
                  progressChanged: (percent) => {
             this.DownloadMessage = percent + "%";
             this.DownloadPercent = (double)percent / 100;
         },
                  downloadComplete: (isSuccess, message, saveFileFullName) => {
             this.DownloadMessage = message;
             this.DownloadPercent = 0;
             if (isSuccess)
             {
                 this.DownloadMessage = "更新成功,正在重启";
                 if (VirtualRoot.IsMinerStudio)
                 {
                     Client.MinerStudioService.CloseMinerStudio();
                 }
                 else
                 {
                     Client.MinerClientService.CloseNTMiner();
                 }
                 TimeSpan.FromSeconds(3).Delay().ContinueWith((t) => {
                     string location = NTMinerRegistry.GetLocation();
                     if (string.IsNullOrEmpty(location) || !File.Exists(location))
                     {
                         location = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ntMinerFile);
                     }
                     try {
                         if (File.Exists(location))
                         {
                             Guid kernelBrandId = VirtualRoot.GetBrandId(location, VirtualRoot.KernelBrandId);
                             if (kernelBrandId != Guid.Empty)
                             {
                                 VirtualRoot.TagBrandId(VirtualRoot.KernelBrandId, kernelBrandId, saveFileFullName, saveFileFullName);
                             }
                             Guid poolBrandId = VirtualRoot.GetBrandId(location, VirtualRoot.PoolBrandId);
                             if (poolBrandId != Guid.Empty)
                             {
                                 VirtualRoot.TagBrandId(VirtualRoot.PoolBrandId, poolBrandId, saveFileFullName, saveFileFullName);
                             }
                         }
                     }
                     catch (Exception e) {
                         Logger.ErrorDebugLine(e);
                     }
                     int failCount = 0;
                     while (true)
                     {
                         try {
                             File.Copy(saveFileFullName, location, overwrite: true);
                             break;
                         }
                         catch (Exception e) {
                             failCount++;
                             if (failCount == 3)
                             {
                                 VirtualRoot.Out.ShowError(e.Message);
                                 break;
                             }
                             else
                             {
                                 System.Threading.Thread.Sleep(3000);
                             }
                         }
                     }
                     File.Delete(saveFileFullName);
                     string arguments = NTMinerRegistry.GetArguments();
                     Process.Start(location, arguments);
                     this.IsDownloading = false;
                     UIThread.Execute(() => {
                         Application.Current.MainWindow?.Close();
                     });
                 });
             }
             else
             {
                 TimeSpan.FromSeconds(2).Delay().ContinueWith((t) => {
                     this.IsDownloading = false;
                 });
             }
         }, cancel: out _cancel);
     }, () => !IsDownloading);
     this.ShowHistory = new DelegateCommand(() => {
         if (IsHistoryVisible == Visibility.Visible)
         {
             IsHistoryVisible = Visibility.Collapsed;
         }
         else
         {
             IsHistoryVisible = Visibility.Visible;
         }
     });
     this.AddNTMinerFile = new DelegateCommand(() => {
         NTMinerFileEdit window = new NTMinerFileEdit("Icon_Add", new NTMinerFileViewModel()
         {
             AppType = App.AppType
         });
         window.ShowDialogEx();
     });
 }
Esempio n. 14
0
        private MinerClientsWindow()
        {
            if (WpfUtil.IsInDesignMode)
            {
                return;
            }
            Width            = SystemParameters.FullPrimaryScreenWidth * 0.95;
            Height           = SystemParameters.FullPrimaryScreenHeight * 0.95;
            this.DataContext = Vm;
            ConsoleWindow.Instance.Show();
            ConsoleWindow.Instance.MouseDown += (sender, e) => {
                MoveConsoleWindow();
            };
            this.Owner   = ConsoleWindow.Instance;
            this.Loaded += (sender, e) => {
                MoveConsoleWindow();
                hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource;
                hwndSource.AddHook(new HwndSourceHook(Win32Proc.WindowProc));
                this.WindowState = WindowState.Maximized;
            };
            InitializeComponent();
            // 这一行是为了看见设计视图
            this.ResizeCursors.Visibility = Visibility.Visible;
            this.TbUcName.Text            = nameof(MinerClientsWindow);
            DateTime lastGetServerMessageOn = DateTime.MinValue;

            this.MinerStudioTabControl.SelectionChanged += (sender, e) => {
                // 延迟创建,以加快主界面的启动
                #region
                var  selectedItem            = MinerStudioTabControl.SelectedItem;
                bool isServerMessagesVisible = selectedItem == MinerStudioTabItemMessage;
                RpcRoot.SetIsServerMessagesVisible(isServerMessagesVisible);
                // 在SetIsServerMessagesVisible之后执行LoadNewServerMessageCommand,因为如果消息tab页不可见执行LoadNewServerMessageCommand会被忽略。
                if (isServerMessagesVisible)
                {
                    if (MinerStudioMessagesContainer.Child == null)
                    {
                        MinerStudioMessagesContainer.Child = new Messages();
                    }
                    if (lastGetServerMessageOn.AddSeconds(10) < DateTime.Now)
                    {
                        lastGetServerMessageOn = DateTime.Now;
                        VirtualRoot.Execute(new LoadNewServerMessageCommand());
                    }
                }
                #endregion
            };
            this.MinerClienTabControl.SelectionChanged += (sender, e) => {
                // 延迟创建,以加快主界面的启动
                #region
                var selectedItem = MinerClienTabControl.SelectedItem;
                if (selectedItem == MinerClientTabItemMessage)
                {
                    if (MinerClientMessagesContainer.Child == null)
                    {
                        MinerClientMessagesContainer.Child = new MinerClientMessages();
                    }
                    MinerStudioRoot.SetIsMinerClientMessagesVisible(true);
                }
                else
                {
                    MinerStudioRoot.SetIsMinerClientMessagesVisible(false);
                }
                #endregion
            };
            this.ConsoleRectangle.IsVisibleChanged += (sender, e) => {
                MoveConsoleWindow();
            };
            this.ConsoleRectangle.SizeChanged += (s, e) => {
                MoveConsoleWindow();
            };
            this.StateChanged += (s, e) => {
                #region
                if (WindowState == WindowState.Maximized)
                {
                    ResizeCursors.Visibility = Visibility.Collapsed;
                }
                else
                {
                    ResizeCursors.Visibility = Visibility.Visible;
                }
                MoveConsoleWindow();
                #endregion
            };
            this.SizeChanged += (s, e) => {
                #region
                if (!this.ConsoleRectangle.IsVisible)
                {
                    if (e.WidthChanged)
                    {
                        ConsoleWindow.Instance.Width = e.NewSize.Width;
                    }
                    if (e.HeightChanged)
                    {
                        ConsoleWindow.Instance.Height = e.NewSize.Height;
                    }
                }
                #endregion
            };
            this.LocationChanged += (sender, e) => {
                MoveConsoleWindow();
            };
            this.BuildEventPath <Per1SecondEvent>("刷新倒计时秒表", LogEnum.None,
                                                  path: message => {
                #region
                var minerClients = Vm.MinerClients.ToArray();
                if (Vm.CountDown > 0)
                {
                    Vm.CountDown = Vm.CountDown - 1;
                    foreach (var item in minerClients)
                    {
                        item.OnPropertyChanged(nameof(item.LastActivedOnText));
                    }
                    if (RpcRoot.IsOuterNet && Vm.CountDown == 5)
                    {
                        // 外网群控时在矿机列表页数据刷新前5秒通过Ws刷新矿机的算力数据
                        MinerStudioRoot.WsClient.SendAsync(new WsMessage(Guid.NewGuid(), WsMessage.GetSpeed)
                        {
                            Data = Vm.MinerClients.Select(a => a.ClientId).ToList()
                        });
                    }
                }
                else if (Vm.CountDown == 0)
                {
                    MinerStudioRoot.MinerClientsWindowVm.QueryMinerClients(isAuto: true);
                }
                #endregion
            }, location: this.GetType());
            NotiCenterWindow.Bind(this, ownerIsTopmost: true);
            MinerStudioRoot.MinerClientsWindowVm.QueryMinerClients();
        }
Esempio n. 15
0
        public KernelOutputSet(INTMinerRoot root, bool isUseJson)
        {
            _root      = root;
            _isUseJson = isUseJson;
            _root.ServerContextWindow <AddKernelOutputCommand>("添加内核输出组", LogEnum.DevConsole,
                                                               action: (message) => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (_dicById.ContainsKey(message.Input.GetId()))
                {
                    return;
                }
                KernelOutputData entity = new KernelOutputData().Update(message.Input);
                _dicById.Add(entity.Id, entity);
                var repository = NTMinerRoot.CreateServerRepository <KernelOutputData>(isUseJson);
                repository.Add(entity);

                VirtualRoot.Happened(new KernelOutputAddedEvent(entity));
            });
            _root.ServerContextWindow <UpdateKernelOutputCommand>("更新内核输出组", LogEnum.DevConsole,
                                                                  action: (message) => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (string.IsNullOrEmpty(message.Input.Name))
                {
                    throw new ValidationException("KernelOutput name can't be null or empty");
                }
                if (!_dicById.ContainsKey(message.Input.GetId()))
                {
                    return;
                }
                KernelOutputData entity = _dicById[message.Input.GetId()];
                if (ReferenceEquals(entity, message.Input))
                {
                    return;
                }
                entity.Update(message.Input);
                var repository = NTMinerRoot.CreateServerRepository <KernelOutputData>(isUseJson);
                repository.Update(entity);

                VirtualRoot.Happened(new KernelOutputUpdatedEvent(entity));
            });
            _root.ServerContextWindow <RemoveKernelOutputCommand>("移除内核输出组", LogEnum.DevConsole,
                                                                  action: (message) => {
                InitOnece();
                if (message == null || message.EntityId == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (!_dicById.ContainsKey(message.EntityId))
                {
                    return;
                }
                IKernel[] outputUsers = root.KernelSet.Where(a => a.KernelOutputId == message.EntityId).ToArray();
                if (outputUsers.Length != 0)
                {
                    throw new ValidationException($"这些内核在使用该内核输出组,删除前请先解除使用:{string.Join(",", outputUsers.Select(a => a.GetFullName()))}");
                }
                KernelOutputData entity               = _dicById[message.EntityId];
                List <Guid> kernelOutputFilterIds     = root.KernelOutputFilterSet.Where(a => a.KernelOutputId == entity.Id).Select(a => a.GetId()).ToList();
                List <Guid> kernelOutputTranslaterIds = root.KernelOutputTranslaterSet.Where(a => a.KernelOutputId == entity.Id).Select(a => a.GetId()).ToList();
                foreach (var kernelOutputFilterId in kernelOutputFilterIds)
                {
                    VirtualRoot.Execute(new RemoveKernelOutputFilterCommand(kernelOutputFilterId));
                }
                foreach (var kernelOutputTranslaterId in kernelOutputTranslaterIds)
                {
                    VirtualRoot.Execute(new RemoveKernelOutputTranslaterCommand(kernelOutputTranslaterId));
                }
                _dicById.Remove(entity.GetId());
                var repository = NTMinerRoot.CreateServerRepository <KernelOutputData>(isUseJson);
                repository.Remove(message.EntityId);

                VirtualRoot.Happened(new KernelOutputRemovedEvent(entity));
            });
        }
Esempio n. 16
0
 public KernelOutputTranslaterViewModel(Guid id)
 {
     _id       = id;
     this.Save = new DelegateCommand(() => {
         int sortNumber = this.SortNumber;
         if (NTMinerRoot.Instance.KernelOutputTranslaterSet.Contains(this.Id))
         {
             VirtualRoot.Execute(new UpdateKernelOutputTranslaterCommand(this));
         }
         else
         {
             VirtualRoot.Execute(new AddKernelOutputTranslaterCommand(this));
         }
         if (sortNumber != this.SortNumber)
         {
             if (AppContext.Instance.KernelOutputVms.TryGetKernelOutputVm(this.KernelOutputId, out KernelOutputViewModel kernelOutputVm))
             {
                 kernelOutputVm.OnPropertyChanged(nameof(kernelOutputVm.KernelOutputTranslaters));
             }
         }
         CloseWindow?.Invoke();
     });
     this.Edit = new DelegateCommand <FormType?>((formType) => {
         VirtualRoot.Execute(new KernelOutputTranslaterEditCommand(formType ?? FormType.Edit, this));
     });
     this.Remove = new DelegateCommand(() => {
         if (this.Id == Guid.Empty)
         {
             return;
         }
         this.ShowDialog(message: $"您确定删除{this.RegexPattern}内核输出翻译器吗?", title: "确认", onYes: () => {
             VirtualRoot.Execute(new RemoveKernelOutputTranslaterCommand(this.Id));
         }, icon: IconConst.IconConfirm);
     });
     this.SortUp = new DelegateCommand(() => {
         KernelOutputTranslaterViewModel upOne = AppContext.Instance.KernelOutputTranslaterVms.GetUpOne(this.KernelOutputId, this.SortNumber);
         if (upOne != null)
         {
             int sortNumber   = upOne.SortNumber;
             upOne.SortNumber = this.SortNumber;
             VirtualRoot.Execute(new UpdateKernelOutputTranslaterCommand(upOne));
             this.SortNumber = sortNumber;
             VirtualRoot.Execute(new UpdateKernelOutputTranslaterCommand(this));
             AppContext.Instance.KernelOutputTranslaterVms.OnPropertyChanged(nameof(AppContext.KernelOutputTranslaterViewModels.AllKernelOutputTranslaterVms));
             if (AppContext.Instance.KernelOutputVms.TryGetKernelOutputVm(this.KernelOutputId, out KernelOutputViewModel kernelOutputVm))
             {
                 kernelOutputVm.OnPropertyChanged(nameof(kernelOutputVm.KernelOutputTranslaters));
             }
         }
     });
     this.SortDown = new DelegateCommand(() => {
         KernelOutputTranslaterViewModel nextOne = AppContext.Instance.KernelOutputTranslaterVms.GetNextOne(this.KernelOutputId, this.SortNumber);
         if (nextOne != null)
         {
             int sortNumber     = nextOne.SortNumber;
             nextOne.SortNumber = this.SortNumber;
             VirtualRoot.Execute(new UpdateKernelOutputTranslaterCommand(nextOne));
             this.SortNumber = sortNumber;
             VirtualRoot.Execute(new UpdateKernelOutputTranslaterCommand(this));
             AppContext.Instance.KernelOutputTranslaterVms.OnPropertyChanged(nameof(AppContext.KernelOutputTranslaterViewModels.AllKernelOutputTranslaterVms));
             if (AppContext.Instance.KernelOutputVms.TryGetKernelOutputVm(this.KernelOutputId, out KernelOutputViewModel kernelOutputVm))
             {
                 kernelOutputVm.OnPropertyChanged(nameof(kernelOutputVm.KernelOutputTranslaters));
             }
         }
     });
 }
Esempio n. 17
0
 public void Init(INTMinerContext root)
 {
     if (_isInited)
     {
         return;
     }
     _isInited = true;
     VirtualRoot.AddEventPath <GpuStateChangedEvent>("当显卡温度变更时守卫温度防线", LogEnum.None,
                                                     action: message => {
         IGpu gpu = message.Source;
         if (gpu.Index == NTMinerContext.GpuAllId || root.MinerProfile.CoinId == Guid.Empty)
         {
             return;
         }
         IGpuProfile gpuProfile;
         if (NTMinerContext.Instance.GpuProfileSet.IsOverClockGpuAll(root.MinerProfile.CoinId))
         {
             gpuProfile = NTMinerContext.Instance.GpuProfileSet.GetGpuProfile(root.MinerProfile.CoinId, NTMinerContext.GpuAllId);
         }
         else
         {
             gpuProfile = NTMinerContext.Instance.GpuProfileSet.GetGpuProfile(root.MinerProfile.CoinId, gpu.Index);
         }
         if (!gpuProfile.IsAutoFanSpeed)
         {
             return;
         }
         // 显卡温度抵达防御温度的时间
         if (!_fightedOnDic.TryGetValue(gpu.Index, out DateTime fightedOn))
         {
             fightedOn = DateTime.Now;
             _fightedOnDic.Add(gpu.Index, fightedOn);
         }
         if (gpu.FanSpeed == 100 && gpu.Temperature > _guardTemp)
         {
             NTMinerConsole.DevDebug(() => $"GPU{gpu.Index.ToString()} 温度{gpu.Temperature.ToString()}大于防线温度{_guardTemp.ToString()},但风扇转速已达100%");
         }
         else if (gpu.Temperature < _guardTemp)
         {
             if (!_preTempDic.ContainsKey(gpu.Index))
             {
                 _preTempDic.Add(gpu.Index, 0);
             }
             // 如果当前温度比上次的温度大
             if (gpu.Temperature > _preTempDic[gpu.Index])
             {
                 fightedOn = DateTime.Now;
                 _fightedOnDic[gpu.Index] = fightedOn;
             }
             _preTempDic[gpu.Index] = gpu.Temperature;
             // 如果距离抵达防御温度的时间已经很久了则降速风扇
             if (fightedOn.AddSeconds(_fanSpeedDownSeconds) < DateTime.Now)
             {
                 int cool = (int)(gpu.FanSpeed - _fanSpeedDownStep);
                 // 如果温度低于50度则直接将风扇设为驱动默认的最小转速
                 if (gpu.Temperature < 50)
                 {
                     cool = gpu.CoolMin;
                 }
                 if (cool >= gpu.CoolMin)
                 {
                     _fightedOnDic[gpu.Index] = DateTime.Now;
                     root.GpuSet.OverClock.SetFanSpeed(gpu.Index, cool);
                     NTMinerConsole.DevDebug(() => $"GPU{gpu.Index.ToString()} 风扇转速由{gpu.FanSpeed.ToString()}%调低至{cool.ToString()}%");
                 }
             }
         }
         else if (gpu.Temperature > _guardTemp)
         {
             uint cool;
             uint len;
             // 防线突破可能是由于小量降低风扇转速造成的
             if (fightedOn.AddSeconds(_fanSpeedDownSeconds) < DateTime.Now)
             {
                 _fightedOnDic[gpu.Index] = DateTime.Now;
                 len = 100 - gpu.FanSpeed;
             }
             else
             {
                 len = _fanSpeedDownStep;
             }
             cool = gpu.FanSpeed + (uint)Math.Ceiling(len / 2.0);
             if (cool > 100)
             {
                 cool = 100;
             }
             if (cool <= 100)
             {
                 root.GpuSet.OverClock.SetFanSpeed(gpu.Index, (int)cool);
                 NTMinerConsole.DevDebug(() => $"GPU{gpu.Index.ToString()} 风扇转速由{gpu.FanSpeed.ToString()}%调高至{cool.ToString()}%");
             }
         }
     }, location: this.GetType());
 }
Esempio n. 18
0
        public LocalMessagesViewModel()
        {
            if (WpfUtil.IsInDesignMode)
            {
                return;
            }
            foreach (var messageChannel in LocalMessageChannelEnumItems)
            {
                var values = new Dictionary <LocalMessageType, MessageTypeItem <LocalMessageType> >();
                foreach (var messageType in Enums.LocalMessageTypeEnumItems)
                {
                    values.Add(messageType.Value, new MessageTypeItem <LocalMessageType>(messageType, LocalMessageViewModel.GetIcon, LocalMessageViewModel.GetIconFill, RefreshQueryResults));
                }
                _count.Add(messageChannel, values);
            }
            _selectedChannel = LocalMessageChannelEnumItems.FirstOrDefault();
            Init();

            this.ClearKeyword = new DelegateCommand(() => {
                this.Keyword = string.Empty;
            });
            this.Clear = new DelegateCommand(() => {
                this.ShowSoftDialog(new DialogWindowViewModel(message: "确定清空吗?", title: "确认", onYes: () => {
                    VirtualRoot.Execute(new ClearLocalMessageSetCommand());
                }));
            });
            VirtualRoot.BuildEventPath <LocalMessageSetClearedEvent>("清空本地消息集后刷新VM内存", LogEnum.DevConsole,
                                                                     path: message => {
                Init();
            }, location: this.GetType());
            VirtualRoot.BuildEventPath <LocalMessageAddedEvent>("发生了本地消息后刷新Vm内存", LogEnum.DevConsole,
                                                                path: message => {
                UIThread.Execute(() => {
                    var vm = new LocalMessageViewModel(message.Source);
                    _localMessageVms.Insert(0, vm);
                    if (IsSatisfyQuery(vm))
                    {
                        _queyResults.Insert(0, vm);
                    }
                    foreach (var item in message.Removes)
                    {
                        var toRemove = _localMessageVms.FirstOrDefault(a => a.Id == item.Id);
                        if (toRemove != null)
                        {
                            _localMessageVms.Remove(toRemove);
                            if (IsSatisfyQuery(toRemove))
                            {
                                _queyResults.Remove(toRemove);
                            }
                        }
                    }
                    int removedCount = message.Removes.Count(a => a.MessageType == vm.MessageTypeEnum.GetName());
                    if (removedCount != 1)
                    {
                        _count[vm.ChannelEnum.GetEnumItem()][vm.MessageTypeEnum].Count += 1 - removedCount;
                        UpdateChannelAll();
                    }
                    OnPropertyChanged(nameof(IsNoRecord));
                });
            }, location: this.GetType());
            VirtualRoot.BuildEventPath <NewDayEvent>("新的一天到来时刷新消息集中的可读性时间戳展示", LogEnum.DevConsole,
                                                     path: message => {
                if (QueryResults == null)
                {
                    return;
                }
                foreach (var item in QueryResults)
                {
                    if (item.Timestamp.Date.AddDays(3) >= message.BornOn.Date)
                    {
                        item.OnPropertyChanged(nameof(item.TimestampText));
                    }
                    else
                    {
                        // 因为是按照时间倒叙排列的,所以可以break
                        break;
                    }
                }
            }, location: this.GetType());
        }
Esempio n. 19
0
        public GroupSet(IServerContext context)
        {
            _context = context;
            context.AddCmdPath <AddGroupCommand>("添加组", LogEnum.DevConsole,
                                                 action: (message) => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (_dicById.ContainsKey(message.Input.GetId()))
                {
                    return;
                }
                if (string.IsNullOrEmpty(message.Input.Name))
                {
                    throw new ValidationException("Group name can't be null or empty");
                }
                GroupData entity = new GroupData().Update(message.Input);
                _dicById.Add(entity.Id, entity);
                var repository = context.CreateServerRepository <GroupData>();
                repository.Add(entity);

                VirtualRoot.RaiseEvent(new GroupAddedEvent(message.MessageId, entity));
            }, location: this.GetType());
            context.AddCmdPath <UpdateGroupCommand>("更新组", LogEnum.DevConsole,
                                                    action: (message) => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (string.IsNullOrEmpty(message.Input.Name))
                {
                    throw new ValidationException("Group name can't be null or empty");
                }
                if (!_dicById.TryGetValue(message.Input.GetId(), out GroupData entity))
                {
                    return;
                }
                if (ReferenceEquals(entity, message.Input))
                {
                    return;
                }
                entity.Update(message.Input);
                var repository = context.CreateServerRepository <GroupData>();
                repository.Update(entity);

                VirtualRoot.RaiseEvent(new GroupUpdatedEvent(message.MessageId, entity));
            }, location: this.GetType());
            context.AddCmdPath <RemoveGroupCommand>("移除组", LogEnum.DevConsole,
                                                    action: (message) => {
                InitOnece();
                if (message == null || message.EntityId == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (!_dicById.ContainsKey(message.EntityId))
                {
                    return;
                }
                GroupData entity = _dicById[message.EntityId];
                Guid[] toRemoves = context.CoinGroupSet.GetGroupCoinIds(entity.Id).ToArray();
                foreach (var id in toRemoves)
                {
                    VirtualRoot.Execute(new RemoveCoinGroupCommand(id));
                }
                _dicById.Remove(entity.GetId());
                var repository = context.CreateServerRepository <GroupData>();
                repository.Remove(message.EntityId);

                VirtualRoot.RaiseEvent(new GroupRemovedEvent(message.MessageId, entity));
            }, location: this.GetType());
        }
Esempio n. 20
0
        public KernelInputSet(IServerContext context)
        {
            _context = context;
            context.AddCmdPath <AddKernelInputCommand>("添加内核输入组", LogEnum.DevConsole,
                                                       action: (message) => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (_dicById.ContainsKey(message.Input.GetId()))
                {
                    return;
                }
                KernelInputData entity = new KernelInputData().Update(message.Input);
                _dicById.Add(entity.Id, entity);
                var repository = context.CreateServerRepository <KernelInputData>();
                repository.Add(entity);

                VirtualRoot.RaiseEvent(new KernelInputAddedEvent(message.MessageId, entity));
            }, location: this.GetType());
            context.AddCmdPath <UpdateKernelInputCommand>("更新内核输入组", LogEnum.DevConsole,
                                                          action: (message) => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (string.IsNullOrEmpty(message.Input.Name))
                {
                    throw new ValidationException($"{nameof(message.Input.Name)} can't be null or empty");
                }
                if (!_dicById.TryGetValue(message.Input.GetId(), out KernelInputData entity))
                {
                    return;
                }
                if (ReferenceEquals(entity, message.Input))
                {
                    return;
                }
                entity.Update(message.Input);
                var repository = context.CreateServerRepository <KernelInputData>();
                repository.Update(entity);

                VirtualRoot.RaiseEvent(new KernelInputUpdatedEvent(message.MessageId, entity));
            }, location: this.GetType());
            context.AddCmdPath <RemoveKernelInputCommand>("移除内核输入组", LogEnum.DevConsole,
                                                          action: (message) => {
                InitOnece();
                if (message == null || message.EntityId == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (!_dicById.ContainsKey(message.EntityId))
                {
                    return;
                }
                KernelInputData entity = _dicById[message.EntityId];
                _dicById.Remove(entity.GetId());
                var repository = context.CreateServerRepository <KernelInputData>();
                repository.Remove(message.EntityId);

                VirtualRoot.RaiseEvent(new KernelInputRemovedEvent(message.MessageId, entity));
            }, location: this.GetType());
        }
Esempio n. 21
0
 public MinerGroupSet()
 {
     VirtualRoot.BuildCmdPath <AddMinerGroupCommand>(action: (message) => {
         InitOnece();
         if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (string.IsNullOrEmpty(message.Input.Name))
         {
             throw new ValidationException("minerGroup name can't be null or empty");
         }
         if (_dicById.ContainsKey(message.Input.GetId()))
         {
             return;
         }
         MinerGroupData entity = new MinerGroupData().Update(message.Input);
         Server.MinerGroupService.AddOrUpdateMinerGroupAsync(entity, (response, exception) => {
             if (response.IsSuccess())
             {
                 _dicById.Add(entity.Id, entity);
                 VirtualRoot.RaiseEvent(new MinerGroupAddedEvent(entity));
             }
             else
             {
                 Write.UserFail(response.ReadMessage(exception));
             }
         });
     });
     VirtualRoot.BuildCmdPath <UpdateMinerGroupCommand>(action: (message) => {
         InitOnece();
         if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (string.IsNullOrEmpty(message.Input.Name))
         {
             throw new ValidationException("minerGroup name can't be null or empty");
         }
         if (!_dicById.ContainsKey(message.Input.GetId()))
         {
             return;
         }
         MinerGroupData entity   = _dicById[message.Input.GetId()];
         MinerGroupData oldValue = new MinerGroupData().Update(entity);
         entity.Update(message.Input);
         Server.MinerGroupService.AddOrUpdateMinerGroupAsync(entity, (response, exception) => {
             if (!response.IsSuccess())
             {
                 entity.Update(oldValue);
                 VirtualRoot.RaiseEvent(new MinerGroupUpdatedEvent(entity));
                 Write.UserFail(response.ReadMessage(exception));
             }
         });
         VirtualRoot.RaiseEvent(new MinerGroupUpdatedEvent(entity));
     });
     VirtualRoot.BuildCmdPath <RemoveMinerGroupCommand>(action: (message) => {
         InitOnece();
         if (message == null || message.EntityId == Guid.Empty)
         {
             throw new ArgumentNullException();
         }
         if (!_dicById.ContainsKey(message.EntityId))
         {
             return;
         }
         MinerGroupData entity = _dicById[message.EntityId];
         Server.MinerGroupService.RemoveMinerGroupAsync(entity.Id, (response, exception) => {
             if (response.IsSuccess())
             {
                 _dicById.Remove(entity.Id);
                 VirtualRoot.RaiseEvent(new MinerGroupRemovedEvent(entity));
             }
             else
             {
                 Write.UserFail(response.ReadMessage(exception));
             }
         });
     });
 }
Esempio n. 22
0
        public override bool Go(BasicDeliverEventArgs ea)
        {
            switch (ea.RoutingKey)
            {
            case WsMqKeyword.GetConsoleOutLinesRoutingKey: {
                string   loginName      = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp      = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId          = ea.BasicProperties.AppId;
                long     afterTimestamp = OperationMqBodyUtil.GetGetConsoleOutLinesMqReceiveBody(ea.Body);
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    VirtualRoot.RaiseEvent(new GetConsoleOutLinesMqMessage(appId, loginName, timestamp, clientId, afterTimestamp));
                }
            }
            break;

            case WsMqKeyword.ConsoleOutLinesRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                var      data      = OperationMqBodyUtil.GetConsoleOutLinesMqReceiveBody(ea.Body);
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    VirtualRoot.RaiseEvent(new ConsoleOutLinesMqMessage(appId, loginName, timestamp, clientId, data));
                }
            }
            break;

            case WsMqKeyword.GetLocalMessagesRoutingKey: {
                string   loginName      = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp      = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId          = ea.BasicProperties.AppId;
                long     afterTimestamp = OperationMqBodyUtil.GetGetLocalMessagesMqReceiveBody(ea.Body);
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    VirtualRoot.RaiseEvent(new GetLocalMessagesMqMessage(appId, loginName, timestamp, clientId, afterTimestamp));
                }
            }
            break;

            case WsMqKeyword.LocalMessagesRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                var      data      = OperationMqBodyUtil.GetLocalMessagesMqReceiveBody(ea.Body);
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    VirtualRoot.RaiseEvent(new LocalMessagesMqMessage(appId, loginName, timestamp, clientId, data));
                }
            }
            break;

            case WsMqKeyword.GetDrivesRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    VirtualRoot.RaiseEvent(new GetDrivesMqMessage(appId, loginName, timestamp, clientId));
                }
            }
            break;

            case WsMqKeyword.DrivesRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                var      data      = OperationMqBodyUtil.GetDrivesMqReceiveBody(ea.Body);
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    VirtualRoot.RaiseEvent(new DrivesMqMessage(appId, loginName, timestamp, clientId, data));
                }
            }
            break;

            case WsMqKeyword.GetLocalIpsRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    VirtualRoot.RaiseEvent(new GetLocalIpsMqMessage(appId, loginName, timestamp, clientId));
                }
            }
            break;

            case WsMqKeyword.LocalIpsRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                var      data      = OperationMqBodyUtil.GetLocalIpsMqReceiveBody(ea.Body);
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    VirtualRoot.RaiseEvent(new LocalIpsMqMessage(appId, loginName, timestamp, clientId, data));
                }
            }
            break;

            case WsMqKeyword.GetOperationResultsRoutingKey: {
                string   loginName      = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp      = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId          = ea.BasicProperties.AppId;
                long     afterTimestamp = OperationMqBodyUtil.GetGetOperationResultsMqReceiveBody(ea.Body);
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    VirtualRoot.RaiseEvent(new GetOperationResultsMqMessage(appId, loginName, timestamp, clientId, afterTimestamp));
                }
            }
            break;

            case WsMqKeyword.OperationResultsRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                var      data      = OperationMqBodyUtil.GetOperationResultsMqReceiveBody(ea.Body);
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    VirtualRoot.RaiseEvent(new OperationResultsMqMessage(appId, loginName, timestamp, clientId, data));
                }
            }
            break;

            case WsMqKeyword.OperationReceivedRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    VirtualRoot.RaiseEvent(new OperationReceivedMqMessage(appId, loginName, timestamp, clientId));
                }
            }
            break;

            case WsMqKeyword.GetSpeedRoutingKey: {
                string      loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime    timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string      appId     = ea.BasicProperties.AppId;
                List <Guid> clientIds = OperationMqBodyUtil.GetGetSpeedMqReceiveBody(ea.Body);
                if (clientIds != null && clientIds.Count != 0)
                {
                    VirtualRoot.RaiseEvent(new GetSpeedMqMessage(appId, loginName, timestamp, clientIds));
                }
            }
            break;

            case WsMqKeyword.SetVirtualMemoryRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    var data = OperationMqBodyUtil.GetSetVirtualMemoryMqReceiveBody(ea.Body);
                    VirtualRoot.RaiseEvent(new SetVirtualMemoryMqMessage(appId, loginName, timestamp, clientId, data));
                }
            }
            break;

            case WsMqKeyword.SetLocalIpsRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    var data = OperationMqBodyUtil.GetSetLocalIpsMqReceiveBody(ea.Body);
                    VirtualRoot.RaiseEvent(new SetLocalIpsMqMessage(appId, loginName, timestamp, clientId, data));
                }
            }
            break;

            case WsMqKeyword.SwitchRadeonGpuRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    bool on = OperationMqBodyUtil.GetSwitchRadeonGpuMqReceiveBody(ea.Body);
                    VirtualRoot.RaiseEvent(new SwitchRadeonGpuMqMessage(appId, loginName, timestamp, clientId, on));
                }
            }
            break;

            case WsMqKeyword.GetSelfWorkLocalJsonRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    VirtualRoot.RaiseEvent(new GetSelfWorkLocalJsonMqMessage(appId, loginName, timestamp, clientId));
                }
            }
            break;

            case WsMqKeyword.SelfWorkLocalJsonRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    string json = OperationMqBodyUtil.GetSelfWorkLocalJsonMqReceiveBody(ea.Body);
                    VirtualRoot.RaiseEvent(new LocalJsonMqMessage(appId, loginName, timestamp, clientId, json));
                }
            }
            break;

            case WsMqKeyword.SaveSelfWorkLocalJsonRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    WorkRequest request = OperationMqBodyUtil.GetSaveSelfWorkLocalJsonMqReceiveBody(ea.Body);
                    VirtualRoot.RaiseEvent(new SaveSelfWorkLocalJsonMqMessage(appId, loginName, timestamp, clientId, request));
                }
            }
            break;

            case WsMqKeyword.GetGpuProfilesJsonRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    VirtualRoot.RaiseEvent(new GetGpuProfilesJsonMqMessage(appId, loginName, timestamp, clientId));
                }
            }
            break;

            case WsMqKeyword.GpuProfilesJsonRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    string json = OperationMqBodyUtil.GetGpuProfilesJsonMqReceiveBody(ea.Body);
                    VirtualRoot.RaiseEvent(new GpuProfilesJsonMqMessage(appId, loginName, timestamp, clientId, json));
                }
            }
            break;

            case WsMqKeyword.SaveGpuProfilesJsonRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    string json = OperationMqBodyUtil.GetSaveGpuProfilesJsonMqReceiveBody(ea.Body);
                    VirtualRoot.RaiseEvent(new SaveGpuProfilesJsonMqMessage(appId, loginName, timestamp, clientId, json));
                }
            }
            break;

            case WsMqKeyword.UpgradeNTMinerRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    string ntminerFileName = OperationMqBodyUtil.GetUpgradeNTMinerMqReceiveBody(ea.Body);
                    if (!string.IsNullOrEmpty(ntminerFileName))
                    {
                        VirtualRoot.RaiseEvent(new UpgradeNTMinerMqMessage(appId, loginName, timestamp, clientId, ntminerFileName));
                    }
                }
            }
            break;

            case WsMqKeyword.StartMineRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    Guid workId = OperationMqBodyUtil.GetStartMineMqReceiveBody(ea.Body);
                    VirtualRoot.RaiseEvent(new StartMineMqMessage(appId, loginName, timestamp, clientId, workId));
                }
            }
            break;

            case WsMqKeyword.StopMineRoutingKey: {
                string   loginName = ea.BasicProperties.ReadHeaderString(MqKeyword.LoginNameHeaderName);
                DateTime timestamp = Timestamp.FromTimestamp(ea.BasicProperties.Timestamp.UnixTime);
                string   appId     = ea.BasicProperties.AppId;
                if (ea.BasicProperties.ReadHeaderGuid(WsMqKeyword.ClientIdHeaderName, out Guid clientId))
                {
                    VirtualRoot.RaiseEvent(new StopMineMqMessage(appId, loginName, timestamp, clientId));
                }
            }
            break;

            default:
                return(false);
            }
            return(true);
        }
Esempio n. 23
0
 public KernelOutputKeywordSet(string dbFileFullName)
 {
     if (string.IsNullOrEmpty(dbFileFullName))
     {
         throw new ArgumentNullException(nameof(dbFileFullName));
     }
     _connectionString = $"filename={dbFileFullName}";
     VirtualRoot.BuildCmdPath <LoadKernelOutputKeywordCommand>(location: this.GetType(), LogEnum.DevConsole, path: message => {
         DateTime localTimestamp = VirtualRoot.LocalKernelOutputKeywordSetTimestamp;
         // 如果已知服务器端最新内核输出关键字时间戳不比本地已加载的最新内核输出关键字时间戳新就不用加载了
         if (message.KnowKernelOutputKeywordTimestamp <= Timestamp.GetTimestamp(localTimestamp))
         {
             return;
         }
         RpcRoot.OfficialServer.KernelOutputKeywordService.GetKernelOutputKeywords((response, e) => {
             if (response.IsSuccess())
             {
                 KernelOutputKeywordData[] toRemoves = _dicById.Where(a => a.Value.GetDataLevel() == DataLevel.Global).Select(a => a.Value).ToArray();
                 foreach (var item in toRemoves)
                 {
                     _dicById.Remove(item.Id);
                     if (_dicByKernelOutputId.TryGetValue(item.KernelOutputId, out List <IKernelOutputKeyword> list))
                     {
                         list.Remove(item);
                     }
                 }
                 if (response.Data.Count != 0)
                 {
                     foreach (var item in response.Data)
                     {
                         item.SetDataLevel(DataLevel.Global);
                         _dicById.Add(item.Id, item);
                         if (!_dicByKernelOutputId.TryGetValue(item.KernelOutputId, out List <IKernelOutputKeyword> list))
                         {
                             list = new List <IKernelOutputKeyword>();
                             _dicByKernelOutputId.Add(item.KernelOutputId, list);
                         }
                         list.Add(item);
                     }
                     if (response.Timestamp != Timestamp.GetTimestamp(localTimestamp))
                     {
                         VirtualRoot.LocalKernelOutputKeywordSetTimestamp = Timestamp.FromTimestamp(response.Timestamp);
                     }
                     CacheServerKernelOutputKeywords(response.Data);
                     VirtualRoot.RaiseEvent(new KernelOutputKeywordLoadedEvent(response.Data));
                 }
             }
             else
             {
                 VirtualRoot.Out.ShowError(response.ReadMessage(e), autoHideSeconds: 4);
             }
         });
     });
     VirtualRoot.BuildCmdPath <AddOrUpdateKernelOutputKeywordCommand>(location: this.GetType(), LogEnum.DevConsole, path: (message) => {
         InitOnece();
         if (ClientAppType.IsMinerClient)
         {
             DataLevel dataLevel = DataLevel.Profile;
             if (_dicById.TryGetValue(message.Input.GetId(), out KernelOutputKeywordData exist))
             {
                 exist.Update(message.Input);
                 exist.SetDataLevel(dataLevel);
                 using (LiteDatabase db = new LiteDatabase(_connectionString)) {
                     var col = db.GetCollection <KernelOutputKeywordData>();
                     col.Update(exist);
                 }
                 VirtualRoot.RaiseEvent(new UserKernelOutputKeywordUpdatedEvent(message.MessageId, exist));
             }
             else
             {
                 KernelOutputKeywordData entity = new KernelOutputKeywordData().Update(message.Input);
                 entity.SetDataLevel(dataLevel);
                 _dicById.Add(entity.Id, entity);
                 if (!_dicByKernelOutputId.TryGetValue(entity.KernelOutputId, out List <IKernelOutputKeyword> list))
                 {
                     list = new List <IKernelOutputKeyword>();
                     _dicByKernelOutputId.Add(entity.KernelOutputId, list);
                 }
                 list.Add(entity);
                 using (LiteDatabase db = new LiteDatabase(_connectionString)) {
                     var col = db.GetCollection <KernelOutputKeywordData>();
                     col.Insert(entity);
                 }
                 VirtualRoot.RaiseEvent(new UserKernelOutputKeywordAddedEvent(message.MessageId, entity));
             }
         }
         else if (ClientAppType.IsMinerStudio)
         {
             message.Input.SetDataLevel(DataLevel.Global);
             RpcRoot.OfficialServer.KernelOutputKeywordService.AddOrUpdateKernelOutputKeywordAsync(KernelOutputKeywordData.Create(message.Input), (response, e) => {
                 if (response.IsSuccess())
                 {
                     VirtualRoot.Execute(new LoadKernelOutputKeywordCommand());
                 }
                 else
                 {
                     VirtualRoot.Out.ShowError(response.ReadMessage(e), autoHideSeconds: 4);
                 }
             });
         }
     });
     VirtualRoot.BuildCmdPath <RemoveKernelOutputKeywordCommand>(location: this.GetType(), LogEnum.DevConsole, path: (message) => {
         InitOnece();
         if (ClientAppType.IsMinerClient)
         {
             if (message == null || message.EntityId == Guid.Empty)
             {
                 return;
             }
             if (!_dicById.ContainsKey(message.EntityId))
             {
                 return;
             }
             KernelOutputKeywordData entity = _dicById[message.EntityId];
             _dicById.Remove(entity.GetId());
             if (_dicByKernelOutputId.TryGetValue(entity.KernelOutputId, out List <IKernelOutputKeyword> list))
             {
                 list.Remove(entity);
             }
             using (LiteDatabase db = new LiteDatabase(_connectionString)) {
                 var col = db.GetCollection <KernelOutputKeywordData>();
                 col.Delete(message.EntityId);
             }
             VirtualRoot.RaiseEvent(new UserKernelOutputKeywordRemovedEvent(message.MessageId, entity));
         }
         else if (ClientAppType.IsMinerStudio)
         {
             RpcRoot.OfficialServer.KernelOutputKeywordService.RemoveKernelOutputKeyword(message.EntityId, (response, e) => {
                 if (response.IsSuccess())
                 {
                     VirtualRoot.Execute(new LoadKernelOutputKeywordCommand());
                 }
                 else
                 {
                     VirtualRoot.Out.ShowError(response.ReadMessage(e), autoHideSeconds: 4);
                 }
             });
         }
     });
 }
Esempio n. 24
0
        public KernelOutputSet(IServerContext context)
        {
            _context = context;
            #region 接线
            context.AddCmdPath <AddKernelOutputCommand>("添加内核输出组", LogEnum.DevConsole,
                                                        action: (message) => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (_dicById.ContainsKey(message.Input.GetId()))
                {
                    return;
                }
                KernelOutputData entity = new KernelOutputData().Update(message.Input);
                _dicById.Add(entity.Id, entity);
                var repository = context.CreateServerRepository <KernelOutputData>();
                repository.Add(entity);

                VirtualRoot.RaiseEvent(new KernelOutputAddedEvent(message.MessageId, entity));
            }, location: this.GetType());
            context.AddCmdPath <UpdateKernelOutputCommand>("更新内核输出组", LogEnum.DevConsole,
                                                           action: (message) => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (string.IsNullOrEmpty(message.Input.Name))
                {
                    throw new ValidationException($"{nameof(message.Input.Name)} can't be null or empty");
                }
                if (!_dicById.TryGetValue(message.Input.GetId(), out KernelOutputData entity))
                {
                    return;
                }
                if (ReferenceEquals(entity, message.Input))
                {
                    return;
                }
                entity.Update(message.Input);
                var repository = context.CreateServerRepository <KernelOutputData>();
                repository.Update(entity);

                VirtualRoot.RaiseEvent(new KernelOutputUpdatedEvent(message.MessageId, entity));
            }, location: this.GetType());
            context.AddCmdPath <RemoveKernelOutputCommand>("移除内核输出组", LogEnum.DevConsole,
                                                           action: (message) => {
                InitOnece();
                if (message == null || message.EntityId == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (!_dicById.ContainsKey(message.EntityId))
                {
                    return;
                }
                IKernel[] outputUses = context.KernelSet.AsEnumerable().Where(a => a.KernelOutputId == message.EntityId).ToArray();
                if (outputUses.Length != 0)
                {
                    throw new ValidationException($"这些内核在使用该内核输出组,删除前请先解除使用:{string.Join(",", outputUses.Select(a => a.GetFullName()))}");
                }
                KernelOutputData entity = _dicById[message.EntityId];
                List <Guid> kernelOutputTranslaterIds = context.KernelOutputTranslaterSet.AsEnumerable().Where(a => a.KernelOutputId == entity.Id).Select(a => a.GetId()).ToList();
                foreach (var kernelOutputTranslaterId in kernelOutputTranslaterIds)
                {
                    VirtualRoot.Execute(new RemoveKernelOutputTranslaterCommand(kernelOutputTranslaterId));
                }
                _dicById.Remove(entity.GetId());
                var repository = context.CreateServerRepository <KernelOutputData>();
                repository.Remove(message.EntityId);

                VirtualRoot.RaiseEvent(new KernelOutputRemovedEvent(message.MessageId, entity));
            }, location: this.GetType());
            #endregion
        }
Esempio n. 25
0
        public FragmentWriterSet(IServerContext context)
        {
            context.BuildCmdPath <AddFragmentWriterCommand>("添加命令行片段书写器", LogEnum.DevConsole,
                                                            action: (message) => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (_dicById.ContainsKey(message.Input.GetId()))
                {
                    return;
                }
                if (string.IsNullOrEmpty(message.Input.Body))
                {
                    throw new ValidationException("FragmentWriter body can't be null or empty");
                }
                FragmentWriterData entity = new FragmentWriterData().Update(message.Input);
                _dicById.Add(entity.Id, entity);
                var repository = NTMinerRoot.CreateServerRepository <FragmentWriterData>();
                repository.Add(entity);

                VirtualRoot.RaiseEvent(new FragmentWriterAddedEvent(message.Id, entity));
            });
            context.BuildCmdPath <UpdateFragmentWriterCommand>("更新命令行片段书写器", LogEnum.DevConsole,
                                                               action: (message) => {
                InitOnece();
                if (message == null || message.Input == null || message.Input.GetId() == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (string.IsNullOrEmpty(message.Input.Body))
                {
                    throw new ValidationException("FragmentWriter body can't be null or empty");
                }
                if (!_dicById.ContainsKey(message.Input.GetId()))
                {
                    return;
                }
                FragmentWriterData entity = _dicById[message.Input.GetId()];
                if (ReferenceEquals(entity, message.Input))
                {
                    return;
                }
                entity.Update(message.Input);
                var repository = NTMinerRoot.CreateServerRepository <FragmentWriterData>();
                repository.Update(entity);

                VirtualRoot.RaiseEvent(new FragmentWriterUpdatedEvent(message.Id, entity));
            });
            context.BuildCmdPath <RemoveFragmentWriterCommand>("移除组", LogEnum.DevConsole,
                                                               action: (message) => {
                InitOnece();
                if (message == null || message.EntityId == Guid.Empty)
                {
                    throw new ArgumentNullException();
                }
                if (!_dicById.ContainsKey(message.EntityId))
                {
                    return;
                }
                FragmentWriterData entity = _dicById[message.EntityId];
                _dicById.Remove(entity.GetId());
                var repository = NTMinerRoot.CreateServerRepository <FragmentWriterData>();
                repository.Remove(message.EntityId);

                VirtualRoot.RaiseEvent(new FragmentWriterRemovedEvent(message.Id, entity));
            });
        }
Esempio n. 26
0
        private static void PickGpuSpeed(INTMinerContext root, IMineContext mineContext, string input, IKernelOutput kernelOutput, bool isDual)
        {
            string gpuSpeedPattern = kernelOutput.GpuSpeedPattern;

            if (isDual)
            {
                gpuSpeedPattern = kernelOutput.DualGpuSpeedPattern;
            }
            if (string.IsNullOrEmpty(gpuSpeedPattern))
            {
                return;
            }
            var             now      = DateTime.Now;
            bool            hasGpuId = gpuSpeedPattern.Contains($"?<{NTKeyword.GpuIndexGroupName}>");
            Regex           regex    = VirtualRoot.GetRegex(gpuSpeedPattern);
            MatchCollection matches  = regex.Matches(input);

            if (matches.Count > 0)
            {
                IGpusSpeed gpuSpeeds = NTMinerContext.Instance.GpusSpeed;
                for (int i = 0; i < matches.Count; i++)
                {
                    Match  match        = matches[i];
                    string gpuSpeedText = match.Groups[NTKeyword.GpuSpeedGroupName].Value;
                    string gpuSpeedUnit = match.Groups[NTKeyword.GpuSpeedUnitGroupName].Value;
                    if (string.IsNullOrEmpty(gpuSpeedUnit))
                    {
                        if (isDual)
                        {
                            gpuSpeedUnit = kernelOutput.DualSpeedUnit;
                        }
                        else
                        {
                            gpuSpeedUnit = kernelOutput.SpeedUnit;
                        }
                    }
                    int gpu = i;
                    if (hasGpuId)
                    {
                        string gpuText = match.Groups[NTKeyword.GpuIndexGroupName].Value;
                        if (!int.TryParse(gpuText, out gpu))
                        {
                            gpu = i;
                        }
                        else
                        {
                            gpu -= kernelOutput.GpuBaseIndex;
                            if (gpu < 0)
                            {
                                continue;
                            }
                        }
                    }
                    if (kernelOutput.IsMapGpuIndex && !string.IsNullOrWhiteSpace(mineContext.KernelInput.DevicesArg))
                    {
                        if (mineContext.UseDevices.Length != 0 && mineContext.UseDevices.Length != root.GpuSet.Count && gpu < mineContext.UseDevices.Length)
                        {
                            gpu = mineContext.UseDevices[gpu];
                        }
                    }
                    if (double.TryParse(gpuSpeedText, out double gpuSpeed))
                    {
                        double gpuSpeedL = gpuSpeed.FromUnitSpeed(gpuSpeedUnit);
                        gpuSpeeds.SetCurrentSpeed(gpu, gpuSpeedL, isDual, now);
                    }
                }
                string totalSpeedPattern = kernelOutput.TotalSpeedPattern;
                if (isDual)
                {
                    totalSpeedPattern = kernelOutput.DualTotalSpeedPattern;
                }
                if (string.IsNullOrEmpty(totalSpeedPattern))
                {
                    // 求和分算力
                    double speed = isDual? gpuSpeeds.AsEnumerable().Where(a => a.Gpu.Index != NTMinerContext.GpuAllId).Sum(a => a.DualCoinSpeed.Value)
                                         : gpuSpeeds.AsEnumerable().Where(a => a.Gpu.Index != NTMinerContext.GpuAllId).Sum(a => a.MainCoinSpeed.Value);
                    gpuSpeeds.SetCurrentSpeed(NTMinerContext.GpuAllId, speed, isDual, now);
                }
            }
        }
Esempio n. 27
0
 public SysDicItemViewModel(Guid id)
 {
     _id       = id;
     this.Save = new DelegateCommand(() => {
         if (this.Id == Guid.Empty)
         {
             return;
         }
         if (NTMinerRoot.Current.SysDicItemSet.ContainsKey(this.Id))
         {
             VirtualRoot.Execute(new UpdateSysDicItemCommand(this));
         }
         else
         {
             VirtualRoot.Execute(new AddSysDicItemCommand(this));
         }
         CloseWindow?.Invoke();
     });
     this.Edit = new DelegateCommand <FormType?>((formType) => {
         if (this.Id == Guid.Empty)
         {
             return;
         }
         SysDicItemEdit.ShowWindow(formType ?? FormType.Edit, this);
     });
     this.Remove = new DelegateCommand(() => {
         if (this.Id == Guid.Empty)
         {
             return;
         }
         DialogWindow.ShowDialog(message: $"您确定删除{this.Code}系统字典项吗?", title: "确认", onYes: () => {
             VirtualRoot.Execute(new RemoveSysDicItemCommand(this.Id));
         }, icon: IconConst.IconConfirm);
     });
     this.SortUp = new DelegateCommand(() => {
         SysDicItemViewModel upOne = SysDicItemViewModels.Current.List.OrderByDescending(a => a.SortNumber).FirstOrDefault(a => a.SortNumber < this.SortNumber);
         if (upOne != null)
         {
             int sortNumber   = upOne.SortNumber;
             upOne.SortNumber = this.SortNumber;
             VirtualRoot.Execute(new UpdateSysDicItemCommand(upOne));
             this.SortNumber = sortNumber;
             VirtualRoot.Execute(new UpdateSysDicItemCommand(this));
             SysDicViewModel sysDicVm;
             if (SysDicViewModels.Current.TryGetSysDicVm(this.DicId, out sysDicVm))
             {
                 sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItems));
                 sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItemsSelect));
             }
         }
     });
     this.SortDown = new DelegateCommand(() => {
         SysDicItemViewModel nextOne = SysDicItemViewModels.Current.List.OrderBy(a => a.SortNumber).FirstOrDefault(a => a.SortNumber > this.SortNumber);
         if (nextOne != null)
         {
             int sortNumber     = nextOne.SortNumber;
             nextOne.SortNumber = this.SortNumber;
             VirtualRoot.Execute(new UpdateSysDicItemCommand(nextOne));
             this.SortNumber = sortNumber;
             VirtualRoot.Execute(new UpdateSysDicItemCommand(this));
             SysDicViewModel sysDicVm;
             if (SysDicViewModels.Current.TryGetSysDicVm(this.DicId, out sysDicVm))
             {
                 sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItems));
                 sysDicVm.OnPropertyChanged(nameof(sysDicVm.SysDicItemsSelect));
             }
         }
     });
 }
Esempio n. 28
0
        private static void PickRejectOneShare(INTMinerContext root, IMineContext mineContext, string input, string preline, IKernelOutput kernelOutput, ICoin coin, bool isDual)
        {
            string rejectOneShare = kernelOutput.RejectOneShare;

            if (isDual)
            {
                rejectOneShare = kernelOutput.DualRejectOneShare;
            }
            if (string.IsNullOrEmpty(rejectOneShare))
            {
                return;
            }
            if (rejectOneShare.Contains("\n"))
            {
                input = preline + "\n" + input;
            }
            Regex regex = VirtualRoot.GetRegex(rejectOneShare);
            var   match = regex.Match(input);

            if (match.Success)
            {
                if (!isDual)
                {
                    // 决定不支持双挖的单卡份额统计
                    string gpuText = match.Groups[NTKeyword.GpuIndexGroupName].Value;
                    if (!string.IsNullOrEmpty(gpuText))
                    {
                        if (int.TryParse(gpuText, out int gpuIndex))
                        {
                            if (kernelOutput.IsMapGpuIndex && !string.IsNullOrWhiteSpace(mineContext.KernelInput.DevicesArg))
                            {
                                if (mineContext.UseDevices.Length != 0 && mineContext.UseDevices.Length != root.GpuSet.Count && gpuIndex < mineContext.UseDevices.Length)
                                {
                                    gpuIndex = mineContext.UseDevices[gpuIndex];
                                }
                            }
                            if (string.IsNullOrEmpty(kernelOutput.FoundOneShare))
                            {
                                root.GpusSpeed.IncreaseFoundShare(gpuIndex);
                            }
                            root.GpusSpeed.IncreaseRejectShare(gpuIndex);
                        }
                    }
                    else if (!string.IsNullOrEmpty(kernelOutput.FoundOneShare))
                    {
                        // 哪个GPU最近找到了一个share就是那个GPU拒绝了一个share
                        var       gpuSpeeds = root.GpusSpeed.AsEnumerable();
                        IGpuSpeed gpuSpeed  = null;
                        foreach (var item in gpuSpeeds)
                        {
                            if (gpuSpeed == null)
                            {
                                gpuSpeed = item;
                            }
                            else if (item.FoundShareOn > gpuSpeed.FoundShareOn)
                            {
                                gpuSpeed = item;
                            }
                        }
                        if (gpuSpeed != null)
                        {
                            var gpuIndex = gpuSpeed.Gpu.Index;
                            root.GpusSpeed.IncreaseRejectShare(gpuIndex);
                        }
                    }
                }
                ICoinShare share = root.CoinShareSet.GetOrCreate(coin.GetId());
                root.CoinShareSet.UpdateShare(coin.GetId(), null, share.RejectShareCount + 1, DateTime.Now);
            }
        }
Esempio n. 29
0
        public MainWindow()
        {
            if (WpfUtil.IsInDesignMode)
            {
                return;
            }
            if (!NTMinerConsole.IsEnabled)
            {
                NTMinerConsole.Enable();
            }
            this.Vm          = new MainWindowViewModel();
            this.DataContext = Vm;
            this.MinHeight   = 430;
            this.MinWidth    = 640;
            this.Width       = AppRoot.MainWindowWidth;
            this.Height      = AppRoot.MainWindowHeight;
#if DEBUG
            NTStopwatch.Start();
#endif
            ConsoleWindow.Instance.Show();
            ConsoleWindow.Instance.MouseDown += (sender, e) => {
                MoveConsoleWindow();
            };
            this.Owner = ConsoleWindow.Instance;
            SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
            this.Loaded += (sender, e) => {
                ConsoleTabItemTopBorder.Margin = new Thickness(0, ConsoleTabItem.ActualHeight - 1, 0, 0);
                MoveConsoleWindow();
                hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource;
                hwndSource.AddHook(new HwndSourceHook(Win32Proc.WindowProc));
            };
            InitializeComponent();
            _leftDrawerGripWidth    = LeftDrawerGrip.Width;
            _btnOverClockBackground = BtnOverClock.Background;
            // 下面几行是为了看见设计视图
            this.ResizeCursors.Visibility = Visibility.Visible;
            this.HideLeftDrawerGrid();
            // 上面几行是为了看见设计视图

            DateTime lastGetServerMessageOn = DateTime.MinValue;
            // 切换了主界面上的Tab时
            this.MainTabControl.SelectionChanged += (sender, e) => {
                // 延迟创建,以加快主界面的启动
                #region
                var selectedItem = MainTabControl.SelectedItem;
                if (selectedItem == TabItemSpeedTable)
                {
                    if (SpeedTableContainer.Child == null)
                    {
                        SpeedTableContainer.Child = GetSpeedTable();
                    }
                }
                else if (selectedItem == TabItemMessage)
                {
                    if (MessagesContainer.Child == null)
                    {
                        MessagesContainer.Child = new Messages();
                    }
                }
                else if (selectedItem == TabItemToolbox)
                {
                    if (ToolboxContainer.Child == null)
                    {
                        ToolboxContainer.Child = new Toolbox();
                    }
                }
                else if (selectedItem == TabItemMinerProfileOption)
                {
                    if (MinerProfileOptionContainer.Child == null)
                    {
                        MinerProfileOptionContainer.Child = new MinerProfileOption();
                    }
                }
                RpcRoot.SetIsServerMessagesVisible(selectedItem == TabItemMessage);
                if (selectedItem == TabItemMessage)
                {
                    if (lastGetServerMessageOn.AddSeconds(10) < DateTime.Now)
                    {
                        lastGetServerMessageOn = DateTime.Now;
                        VirtualRoot.Execute(new LoadNewServerMessageCommand());
                    }
                }
                if (selectedItem == ConsoleTabItem)
                {
                    ConsoleTabItemTopBorder.Visibility = Visibility.Visible;
                }
                else
                {
                    ConsoleTabItemTopBorder.Visibility = Visibility.Collapsed;
                }
                #endregion
            };
            this.IsVisibleChanged += (sender, e) => {
                #region
                if (this.IsVisible)
                {
                    NTMinerContext.IsUiVisible = true;
                }
                else
                {
                    NTMinerContext.IsUiVisible = false;
                }
                MoveConsoleWindow();
                #endregion
            };
            this.StateChanged += (s, e) => {
                #region
                if (Vm.MinerProfile.IsShowInTaskbar)
                {
                    ShowInTaskbar = true;
                }
                else
                {
                    if (WindowState == WindowState.Minimized)
                    {
                        ShowInTaskbar = false;
                    }
                    else
                    {
                        ShowInTaskbar = true;
                    }
                }
                if (WindowState == WindowState.Maximized)
                {
                    ResizeCursors.Visibility = Visibility.Collapsed;
                }
                else
                {
                    ResizeCursors.Visibility = Visibility.Visible;
                }
                MoveConsoleWindow();
                #endregion
            };
            this.ConsoleRectangle.IsVisibleChanged += (sender, e) => {
                MoveConsoleWindow();
            };
            this.ConsoleRectangle.SizeChanged += (s, e) => {
                MoveConsoleWindow();
            };
            if (this.Width < 860)
            {
                NTMinerConsole.UserWarn("左侧面板已折叠,可点击侧边的'开始挖矿'按钮展开。");
            }
            this.SizeChanged += (s, e) => {
                #region
                if (this.Width < 860)
                {
                    this.CloseLeftDrawer();
                    this.BtnAboutNTMiner.Visibility = Visibility.Collapsed;
                }
                else
                {
                    this.OpenLeftDrawer();
                    this.BtnAboutNTMiner.Visibility = Visibility.Visible;
                }
                if (!this.ConsoleRectangle.IsVisible)
                {
                    if (e.WidthChanged)
                    {
                        ConsoleWindow.Instance.Width = e.NewSize.Width;
                    }
                    if (e.HeightChanged)
                    {
                        ConsoleWindow.Instance.Height = e.NewSize.Height;
                    }
                }
                #endregion
            };
            NotiCenterWindow.Bind(this, ownerIsTopmost: true);
            this.LocationChanged += (sender, e) => {
                MoveConsoleWindow();
            };
            VirtualRoot.AddCmdPath <TopmostCommand>(action: message => {
                UIThread.Execute(() => {
                    if (!this.Topmost)
                    {
                        this.Topmost = true;
                    }
                });
            }, this.GetType());
            VirtualRoot.AddCmdPath <UnTopmostCommand>(action: message => {
                UIThread.Execute(() => {
                    if (this.Topmost)
                    {
                        this.Topmost = false;
                    }
                });
            }, this.GetType());
            VirtualRoot.AddCmdPath <CloseMainWindowCommand>(action: message => {
                UIThread.Execute(() => {
                    if (message.IsAutoNoUi)
                    {
                        SwitchToNoUi();
                    }
                    else
                    {
                        this.Close();
                    }
                });
            }, location: this.GetType());
            this.AddEventPath <Per1MinuteEvent>("挖矿中时自动切换为无界面模式", LogEnum.DevConsole,
                                                action: message => {
                if (NTMinerContext.IsUiVisible && NTMinerContext.Instance.MinerProfile.IsAutoNoUi && NTMinerContext.Instance.IsMining)
                {
                    if (NTMinerContext.MainWindowRendedOn.AddMinutes(NTMinerContext.Instance.MinerProfile.AutoNoUiMinutes) < message.BornOn)
                    {
                        VirtualRoot.ThisLocalInfo(nameof(MainWindow), $"挖矿中界面展示{NTMinerContext.Instance.MinerProfile.AutoNoUiMinutes}分钟后自动切换为无界面模式,可在选项页调整配置");
                        VirtualRoot.Execute(new CloseMainWindowCommand(isAutoNoUi: true));
                    }
                }
            }, location: this.GetType());
#if DEBUG
            var elapsedMilliseconds = NTStopwatch.Stop();
            if (elapsedMilliseconds.ElapsedMilliseconds > NTStopwatch.ElapsedMilliseconds)
            {
                NTMinerConsole.DevTimeSpan($"耗时{elapsedMilliseconds} {this.GetType().Name}.ctor");
            }
#endif
        }
Esempio n. 30
0
        public MinerSignSet(IMinerDataRedis redis)
        {
            _redis = redis;
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            redis.GetAllAsync().ContinueWith(t => {
                _initedOn = DateTime.Now;
                foreach (var item in t.Result)
                {
                    _dicByClientId[item.ClientId] = MinerSign.Create(item);
                }
                IsReadied = true;
                stopwatch.Stop();
                NTMinerConsole.UserOk($"矿机签名集就绪,耗时 {stopwatch.GetElapsedSeconds().ToString("f2")} 秒");
                VirtualRoot.RaiseEvent(new MinerSignSetInitedEvent());
            });
            // 收到Mq消息之前一定已经初始化完成,因为Mq消费者在MinerSignSetInitedEvent事件之后才会创建
            VirtualRoot.BuildEventPath <MinerDataRemovedMqEvent>("收到MinerClientRemovedMq消息后移除内存中对应的记录", LogEnum.None, path: message => {
                #region
                if (message.AppId == ServerRoot.HostConfig.ThisServerAddress)
                {
                    return;
                }
                if (IsOldMqMessage(message.Timestamp))
                {
                    NTMinerConsole.UserOk(nameof(MinerDataRemovedMqEvent) + ":" + MqKeyword.SafeIgnoreMessage);
                    return;
                }
                if (_dicByClientId.TryRemove(message.ClientId, out MinerSign minerSign))
                {
                    if (AppRoot.MinerClientSessionSet.TryGetByClientId(minerSign.ClientId, out IMinerClientSession ntminerSession))
                    {
                        ntminerSession.CloseAsync(WsCloseCode.Normal, "服务端移除了该矿机");
                    }
                }
                #endregion
            }, this.GetType());
            VirtualRoot.BuildEventPath <MinerDatasRemovedMqEvent>("收到MinerClientsRemovedMq消息后移除内存中对应的记录", LogEnum.None, path: message => {
                #region
                if (message.AppId == ServerRoot.HostConfig.ThisServerAddress)
                {
                    return;
                }
                if (IsOldMqMessage(message.Timestamp))
                {
                    NTMinerConsole.UserOk(nameof(MinerDataRemovedMqEvent) + ":" + MqKeyword.SafeIgnoreMessage);
                    return;
                }
                foreach (var clientId in message.ClientIds)
                {
                    if (_dicByClientId.TryRemove(clientId, out MinerSign minerSign))
                    {
                        if (AppRoot.MinerClientSessionSet.TryGetByClientId(clientId, out IMinerClientSession ntminerSession))
                        {
                            ntminerSession.CloseAsync(WsCloseCode.Normal, "服务端移除了该矿机");
                        }
                    }
                }
                #endregion
            }, this.GetType());
            VirtualRoot.BuildEventPath <Per1SecondEvent>("每秒钟将暂存的新设置的MinerSign发送到Mq", LogEnum.None, message => {
                Task.Factory.StartNew(() => {
                    MinerSign[] minerSignsSeted;
                    lock (_lockForMinerSignsSeted) {
                        minerSignsSeted = _minerSignsSeted.ToArray();
                        _minerSignsSeted.Clear();
                    }
                    AppRoot.MinerClientMqSender.SendMinerSignsSeted(minerSignsSeted);
                });
            }, this.GetType());
        }