Exemple #1
0
        public OverClockRange GetClockRange(int gpuIndex)
        {
            OverClockRange result = new OverClockRange(gpuIndex);

            try {
                if (!TryGpuAdapterIndex(gpuIndex, out int adapterIndex))
                {
                    return(result);
                }
                ADLODNCapabilitiesX2 info = new ADLODNCapabilitiesX2();
                var r = AdlNativeMethods.ADL2_OverdriveN_CapabilitiesX2_Get(context, adapterIndex, ref info);
                if (r < AdlStatus.ADL_OK)
                {
                    Write.DevError($"{nameof(AdlNativeMethods.ADL2_OverdriveN_CapabilitiesX2_Get)} {r}");
                    return(result);
                }
                result.PowerCurr = GetPowerLimit(gpuIndex);
                result.TempCurr  = GetTempLimit(gpuIndex);
                if (GetMemoryClock(gpuIndex, out int memoryClock, out int iVddc))
                {
                    result.MemoryClockDelta = memoryClock;
                    result.MemoryVoltage    = iVddc;
                }
                if (GetCoreClock(gpuIndex, out int coreClock, out iVddc))
                {
                    result.CoreClockDelta = coreClock;
                    result.CoreVoltage    = iVddc;
                }
                result.CoreClockMin     = info.sEngineClockRange.iMin * 10;
                result.CoreClockMax     = info.sEngineClockRange.iMax * 10;
                result.MemoryClockMin   = info.sMemoryClockRange.iMin * 10;
                result.MemoryClockMax   = info.sMemoryClockRange.iMax * 10;
                result.PowerMin         = info.power.iMin + 100;
                result.PowerMax         = info.power.iMax + 100;
                result.PowerDefault     = info.power.iDefault + 100;
                result.TempLimitMin     = info.powerTuneTemperature.iMin;
                result.TempLimitMax     = info.powerTuneTemperature.iMax;
                result.TempLimitDefault = info.powerTuneTemperature.iDefault;
                result.VoltMin          = info.svddcRange.iMin;
                result.VoltMax          = info.svddcRange.iMax;
                result.VoltDefault      = info.svddcRange.iDefault;
                if (info.fanSpeed.iMax == 0)
                {
                    result.FanSpeedMin = 0;
                }
                else
                {
                    result.FanSpeedMin = info.fanSpeed.iMin * 100 / info.fanSpeed.iMax;
                }
                result.FanSpeedMax     = 100;
                result.FanSpeedDefault = info.fanSpeed.iDefault;
#if DEBUG
                Write.DevWarn($"GetClockRange {result.ToString()}");
#endif
            }
            catch (Exception e) {
                Logger.ErrorDebugLine(e);
            }
            return(result);
        }
Exemple #2
0
        public void LoadGpuState()
        {
#if DEBUG
            VirtualRoot.Stopwatch.Restart();
#endif
            for (int i = 0; i < Count; i++)
            {
                uint power = adlHelper.GetPowerUsageByIndex(i);
                int  temp  = adlHelper.GetTemperatureByIndex(i);
                uint speed = adlHelper.GetFanSpeedByIndex(i);

                Gpu  gpu       = (Gpu)_gpus[i];
                bool isChanged = gpu.Temperature != temp || gpu.PowerUsage != power || gpu.FanSpeed != speed;
                gpu.Temperature = temp;
                gpu.PowerUsage  = power;
                gpu.FanSpeed    = speed;

                if (isChanged)
                {
                    VirtualRoot.Happened(new GpuStateChangedEvent(gpu));
                }
            }
#if DEBUG
            Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.{nameof(LoadGpuState)}");
#endif
        }
Exemple #3
0
 public bool GetMemoryClock(int gpuIndex, out int memoryClock, out int iVddc)
 {
     memoryClock = 0;
     iVddc       = 0;
     try {
         if (!TryGpuAdapterIndex(gpuIndex, out int adapterIndex))
         {
             return(false);
         }
         ADLODNPerformanceLevelsX2 info = ADLODNPerformanceLevelsX2.Create();
         var r = AdlNativeMethods.ADL2_OverdriveN_MemoryClocksX2_Get(context, adapterIndex, ref info);
         if (r < AdlStatus.ADL_OK)
         {
             Write.DevError($"{nameof(AdlNativeMethods.ADL2_OverdriveN_MemoryClocksX2_Get)} {r.ToString()}");
             return(false);
         }
         int index = 0;
         for (int i = 0; i < info.aLevels.Length; i++)
         {
             if (info.aLevels[i].iEnabled != 0)
             {
                 index = i;
             }
             Write.DevWarn("GetMemoryClock " + info.aLevels[i].ToString());
         }
         memoryClock = info.aLevels[index].iClock * 10;
         iVddc       = info.aLevels[index].iVddc;
         return(true);
     }
     catch {
         return(false);
     }
 }
Exemple #4
0
        public bool SetPowerLimit(int gpuIndex, int value)
        {
            if (!TryGpuAdapterIndex(gpuIndex, out int adapterIndex))
            {
                return(false);
            }
            ADLODNPowerLimitSetting info = new ADLODNPowerLimitSetting();

            try {
                var r = AdlNativeMethods.ADL2_OverdriveN_PowerLimit_Get(context, adapterIndex, ref info);
                if (r < AdlStatus.ADL_OK)
                {
                    Write.DevError($"{nameof(AdlNativeMethods.ADL2_OverdriveN_PowerLimit_Get)} {r.ToString()}");
                    return(false);
                }
#if DEBUG
                Write.DevWarn($"{nameof(AdlNativeMethods.ADL2_OverdriveN_PowerLimit_Get)} result={r.ToString()},iMode={info.iMode.ToString()},iTDPLimit={info.iTDPLimit.ToString()},iMaxOperatingTemperature={info.iMaxOperatingTemperature.ToString()}");
#endif
                info.iMode     = AdlConst.ODNControlType_Manual;
                info.iTDPLimit = value - 100;
                r = AdlNativeMethods.ADL2_OverdriveN_PowerLimit_Set(context, adapterIndex, ref info);
                if (r < AdlStatus.ADL_OK)
                {
                    Write.DevError($"{nameof(AdlNativeMethods.ADL2_OverdriveN_PowerLimit_Set)} {r.ToString()}");
                    return(false);
                }
                return(true);
            }
            catch (Exception e) {
                Logger.ErrorDebugLine(e);
                return(false);
            }
        }
Exemple #5
0
        public void GetClockRangeByIndex(
            int gpuIndex,
            out int coreClockDeltaMin, out int coreClockDeltaMax,
            out int memoryClockDeltaMin, out int memoryClockDeltaMax,
            out int powerMin, out int powerMax, out int powerDefault,
            out int tempLimitMin, out int tempLimitMax, out int tempLimitDefault,
            out int fanSpeedMin, out int fanSpeedMax, out int fanSpeedDefault)
        {
            int adapterIndex = GpuIndexToAdapterIndex(gpuIndex);
            ADLODNCapabilitiesX2 lpODCapabilities = new ADLODNCapabilitiesX2();
            var result = ADL.ADL2_OverdriveN_CapabilitiesX2_Get(context, adapterIndex, ref lpODCapabilities);

            coreClockDeltaMin   = lpODCapabilities.sEngineClockRange.iMin * 10;
            coreClockDeltaMax   = lpODCapabilities.sEngineClockRange.iMax * 10;
            memoryClockDeltaMin = lpODCapabilities.sMemoryClockRange.iMin * 10;
            memoryClockDeltaMax = lpODCapabilities.sMemoryClockRange.iMax * 10;
            powerMin            = lpODCapabilities.power.iMin + 100;
            powerMax            = lpODCapabilities.power.iMax + 100;
            powerDefault        = lpODCapabilities.power.iDefault + 100;
            tempLimitMin        = lpODCapabilities.powerTuneTemperature.iMin;
            tempLimitMax        = lpODCapabilities.powerTuneTemperature.iMax;
            tempLimitDefault    = lpODCapabilities.powerTuneTemperature.iDefault;
            fanSpeedMin         = lpODCapabilities.fanSpeed.iMin * 100 / lpODCapabilities.fanSpeed.iMax;
            fanSpeedMax         = 100;
            fanSpeedDefault     = lpODCapabilities.fanSpeed.iDefault;
#if DEBUG
            Write.DevWarn($"ADL2_OverdriveN_CapabilitiesX2_Get result {result} coreClockDeltaMin={coreClockDeltaMin},coreClockDeltaMax={coreClockDeltaMax},memoryClockDeltaMin={memoryClockDeltaMin},memoryClockDeltaMax={memoryClockDeltaMax},powerMin={powerMin},powerMax={powerMax},powerDefault={powerDefault},tempLimitMin={tempLimitMin},tempLimitMax={tempLimitMax},tempLimitDefault={tempLimitDefault},fanSpeedMin={fanSpeedMin},fanSpeedMax={fanSpeedMax},fanSpeedDefault={fanSpeedDefault}");
#endif
        }
Exemple #6
0
        public static bool NvmlInit()
        {
            if (_isNvmlInited)
            {
                return(_isNvmlInited);
            }
            lock (_nvmlInitLocker) {
                if (_isNvmlInited)
                {
                    return(_isNvmlInited);
                }
                if (Directory.Exists(_nvsmiDir))
                {
                    try {
#if DEBUG
                        VirtualRoot.Stopwatch.Restart();
#endif
                        Windows.NativeMethods.SetDllDirectory(_nvsmiDir);
                        var nvmlReturn = NvmlNativeMethods.nvmlInit();
                        SetGpuStatus(Gpu.GpuAll, nvmlReturn);
                        _isNvmlInited = nvmlReturn == nvmlReturn.Success;
#if DEBUG
                        Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {nameof(NVIDIAGpuSet)}.{nameof(NvmlInit)}()");
#endif
                        return(_isNvmlInited);
                    }
                    catch (Exception e) {
                        Logger.ErrorDebugLine(e);
                    }
                }
                return(false);
            }
        }
        public MainWindow()
        {
#if DEBUG
            VirtualRoot.Stopwatch.Restart();
#endif
            UIThread.StartTimer();
            InitializeComponent();
            this.StateChanged += (s, e) => {
                if (Vm.MinerProfile.IsShowInTaskbar)
                {
                    ShowInTaskbar = true;
                }
                else
                {
                    if (WindowState == WindowState.Minimized)
                    {
                        ShowInTaskbar = false;
                    }
                    else
                    {
                        ShowInTaskbar = true;
                    }
                }
            };
            this.SizeChanged += (object sender, SizeChangedEventArgs e) => {
                if (e.WidthChanged)
                {
                    const double width = 720;
                    if (e.NewSize.Width < width)
                    {
                        foreach (var tabItem in this.MainTab.Items.OfType <MainTabItem>())
                        {
                            tabItem.Margin = new Thickness(0);
                        }
                    }
                    else if (e.NewSize.Width >= width)
                    {
                        foreach (var tabItem in this.MainTab.Items.OfType <MainTabItem>())
                        {
                            tabItem.Margin = new Thickness(8, 0, 8, 0);
                        }
                    }
                }
            };
            EventHandler changeNotiCenterWindowLocation = NotiCenterWindow.CreateNotiCenterWindowLocationManager(this);
            this.Activated       += changeNotiCenterWindowLocation;
            this.LocationChanged += changeNotiCenterWindowLocation;
            if (DevMode.IsDevMode)
            {
                this.On <ServerJsonVersionChangedEvent>("开发者模式展示ServerJsonVersion", LogEnum.DevConsole,
                                                        action: message => {
                    Vm.ServerJsonVersion = Vm.GetServerJsonVersion();
                });
            }
#if DEBUG
            Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
        }
Exemple #8
0
        public AMDGpuSet(INTMinerRoot root) : this()
        {
#if DEBUG
            VirtualRoot.Stopwatch.Restart();
#endif
            _root = root;
            adlHelper.Init();
            this.OverClock = new AMDOverClock(adlHelper);
            int deviceCount = 0;
            deviceCount = adlHelper.GpuCount;
            for (int i = 0; i < deviceCount; i++)
            {
                var    atiGpu = adlHelper.GetGpuName(i);
                string name   = atiGpu.AdapterName;
                // short gpu name
                if (!string.IsNullOrEmpty(name))
                {
                    name = name.Replace("Radeon (TM) RX ", string.Empty);
                    name = name.Replace("Radeon RX ", string.Empty);
                }
                var gpu = Gpu.Create(i, atiGpu.BusNumber.ToString(), name);
                gpu.TotalMemory = adlHelper.GetTotalMemoryByIndex(i);
                _gpus.Add(i, gpu);
            }
            if (deviceCount > 0)
            {
                this.DriverVersion = adlHelper.GetDriverVersion();
                this.Properties.Add(new GpuSetProperty(GpuSetProperty.DRIVER_VERSION, "驱动版本", DriverVersion));
                const ulong minG = (ulong)5 * 1024 * 1024 * 1024;
                if (_gpus.Any(a => a.Key != NTMinerRoot.GpuAllId && a.Value.TotalMemory < minG))
                {
                    Dictionary <string, string> kvs = new Dictionary <string, string> {
                        { "GPU_FORCE_64BIT_PTR", "0" },
                        { "GPU_MAX_ALLOC_PERCENT", "100" },
                        { "GPU_MAX_HEAP_SIZE", "100" },
                        { "GPU_SINGLE_ALLOC_PERCENT", "100" },
                        { "GPU_USE_SYNC_OBJECTS", "1" }
                    };
                    foreach (var kv in kvs)
                    {
                        var property = new GpuSetProperty(kv.Key, kv.Key, kv.Value);
                        this.Properties.Add(property);
                    }
                    Task.Factory.StartNew(() => {
                        OverClock.RefreshGpuState(NTMinerRoot.GpuAllId);
                        foreach (var kv in kvs)
                        {
                            Environment.SetEnvironmentVariable(kv.Key, kv.Value);
                        }
                    });
                }
            }
#if DEBUG
            Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
        }
        public SplashWindow()
        {
#if DEBUG
            VirtualRoot.Stopwatch.Restart();
#endif
            InitializeComponent();
#if DEBUG
            Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
        }
Exemple #10
0
        public void SetSystemClockByIndex(int gpuIndex, int value)
        {
            try {
                int adapterIndex = GpuIndexToAdapterIndex(gpuIndex);
                ADLODNCapabilitiesX2 lpODCapabilities = new ADLODNCapabilitiesX2();
                var result = ADL.ADL2_OverdriveN_CapabilitiesX2_Get(context, adapterIndex, ref lpODCapabilities);
                if (result != 0)
                {
                    return;
                }
                ADLODNPerformanceLevelsX2 lpODPerformanceLevels = ADLODNPerformanceLevelsX2.Create();
                result = ADL.ADL2_OverdriveN_SystemClocksX2_Get(context, adapterIndex, ref lpODPerformanceLevels);
                lpODPerformanceLevels.iMode = ADL.ODNControlType_Default;
                result = ADL.ADL2_OverdriveN_SystemClocksX2_Set(context, adapterIndex, ref lpODPerformanceLevels);
                result = ADL.ADL2_OverdriveN_SystemClocksX2_Get(context, adapterIndex, ref lpODPerformanceLevels);
#if DEBUG
                Write.DevWarn("ADL2_OverdriveN_SystemClocksX2_Get result=" + result);
                foreach (var item in lpODPerformanceLevels.aLevels)
                {
                    Write.DevWarn($"iClock={item.iClock},iControl={item.iControl},iEnabled={item.iEnabled},iVddc={item.iVddc}");
                }
#endif
                if (result == ADL.ADL_OK)
                {
                    if (value <= 0)
                    {
                        return;
                    }
                    else
                    {
                        lpODPerformanceLevels.iMode = ADL.ODNControlType_Manual;
                        int index = 0;
                        for (int i = 0; i < lpODPerformanceLevels.aLevels.Length; i++)
                        {
                            if (lpODPerformanceLevels.aLevels[i].iEnabled == 1)
                            {
                                index = i;
                            }
                        }
                        lpODPerformanceLevels.aLevels[index].iClock = value * 100;
                    }
                    result = ADL.ADL2_OverdriveN_SystemClocksX2_Set(context, adapterIndex, ref lpODPerformanceLevels);
#if DEBUG
                    if (result != ADL.ADL_OK)
                    {
                        Write.DevWarn($"ADL2_OverdriveN_SystemClocksX2_Set({value * 100}) result " + result);
                    }
#endif
                }
            }
            catch {
            }
        }
Exemple #11
0
        public AMDGpuSet(INTMinerRoot root) : this()
        {
#if DEBUG
            VirtualRoot.Stopwatch.Restart();
#endif
            _root = root;
            if (Design.IsInDesignMode)
            {
                return;
            }
            adlHelper.Init();
            int deviceCount = 0;
            deviceCount = adlHelper.GpuCount;
            for (int i = 0; i < deviceCount; i++)
            {
                string name = adlHelper.GetGpuName(i);
                // short gpu name
                if (!string.IsNullOrEmpty(name))
                {
                    name = name.Replace("Radeon (TM) RX ", string.Empty);
                    name = name.Replace("Radeon RX ", string.Empty);
                }
                var gpu = Gpu.Create(i, name);
                gpu.TotalMemory = adlHelper.GetTotalMemory(i);
                _gpus.Add(i, gpu);
            }
            if (deviceCount > 0)
            {
                this.Properties.Add(new GpuSetProperty(GpuSetProperty.DRIVER_VERSION, "驱动版本", DriverVersion));
                Dictionary <string, string> kvs = new Dictionary <string, string> {
                    { "GPU_FORCE_64BIT_PTR", "0" },
                    { "GPU_MAX_ALLOC_PERCENT", "100" },
                    { "GPU_MAX_HEAP_SIZE", "100" },
                    { "GPU_SINGLE_ALLOC_PERCENT", "100" },
                    { "GPU_USE_SYNC_OBJECTS", "1" }
                };
                foreach (var kv in kvs)
                {
                    var property = new GpuSetProperty(kv.Key, kv.Key, kv.Value);
                    this.Properties.Add(property);
                }
                Task.Factory.StartNew(() => {
                    foreach (var kv in kvs)
                    {
                        Environment.SetEnvironmentVariable(kv.Key, kv.Value);
                    }
                });
            }
#if DEBUG
            Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
        }
Exemple #12
0
        public void Connect <TMessage>(MessagePath <TMessage> path)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            lock (_locker) {
                var keyType = typeof(TMessage);

                var pathId = path;
                if (!_paths.ContainsKey(pathId.Path))
                {
                    _paths.Add(pathId.Path, new List <IMessagePathId> {
                        pathId
                    });
                }
                else
                {
                    List <IMessagePathId> handlerIds = _paths[pathId.Path];
                    if (handlerIds.Count == 1)
                    {
                        Write.DevWarn($"重复的路径:{handlerIds[0].Path} {handlerIds[0].Description}");
                    }
                    handlerIds.Add(pathId);
                    Write.DevWarn($"重复的路径:{pathId.Path} {pathId.Description}");
                }
                if (_handlers.ContainsKey(keyType))
                {
                    var registeredHandlers = _handlers[keyType];
                    if (registeredHandlers.Count > 0 && typeof(ICmd).IsAssignableFrom(keyType))
                    {
                        // 因为一种命令只应被一个处理器处理,命令实际上可以设计为不走总线,
                        // 之所以设计为统一走总线只是为了将通过命令类型集中表达起文档作用。
                        throw new Exception($"一种命令只应被一个处理器处理:{typeof(TMessage).Name}");
                    }
                    if (!registeredHandlers.Contains(path))
                    {
                        registeredHandlers.Add(path);
                    }
                }
                else
                {
                    var registeredHandlers = new List <dynamic> {
                        path
                    };
                    _handlers.Add(keyType, registeredHandlers);
                }
                Connected?.Invoke(pathId);
            }
        }
Exemple #13
0
        public void DispatchMessage <TMessage>(TMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            var messageType = typeof(TMessage);
            MessageTypeAttribute messageTypeDescription = MessageTypeAttribute.GetMessageTypeDescription(messageType);

            if (_handlers.ContainsKey(messageType))
            {
                var messageHandlers = _handlers[messageType].ToArray();
                foreach (var messageHandler in messageHandlers)
                {
                    var tMessageHandler = (DelegateHandler <TMessage>)messageHandler;
                    if (!tMessageHandler.IsEnabled)
                    {
                        continue;
                    }
                    var evtArgs = new MessageDispatchEventArgs(message, messageHandler.GetType(), messageHandler);
                    switch (tMessageHandler.HandlerId.LogType)
                    {
                    case LogEnum.DevConsole:
                        if (DevMode.IsDevMode)
                        {
                            Write.DevDebug($"({messageType.Name})->({tMessageHandler.HandlerId.Location.Name}){tMessageHandler.HandlerId.Description}");
                        }
                        break;

                    case LogEnum.UserConsole:
                        Write.UserInfo($"({messageType.Name})->({tMessageHandler.HandlerId.Location.Name}){tMessageHandler.HandlerId.Description}");
                        break;

                    case LogEnum.Log:
                        Logger.InfoDebugLine($"({messageType.Name})->({tMessageHandler.HandlerId.Location.Name}){tMessageHandler.HandlerId.Description}");
                        break;

                    case LogEnum.None:
                    default:
                        break;
                    }
                    tMessageHandler.Handle(message);
                }
            }
            else if (!messageTypeDescription.IsCanNoHandler)
            {
                Write.DevWarn(messageType.FullName + "类型的消息没有对应的处理器");
            }
        }
Exemple #14
0
        public OverClockRange GetClockRange(int busId)
        {
            OverClockRange result = new OverClockRange(busId);

            try {
                if (GetClockDelta(busId,
                                  out int outCoreCurrFreqDelta, out int outCoreMinFreqDelta, out int outCoreMaxFreqDelta,
                                  out int outMemoryCurrFreqDelta, out int outMemoryMinFreqDelta, out int outMemoryMaxFreqDelta))
                {
                    result.CoreClockMin     = outCoreMinFreqDelta;
                    result.CoreClockMax     = outCoreMaxFreqDelta;
                    result.CoreClockDelta   = outCoreCurrFreqDelta;
                    result.MemoryClockMin   = outMemoryMinFreqDelta;
                    result.MemoryClockMax   = outMemoryMaxFreqDelta;
                    result.MemoryClockDelta = outMemoryCurrFreqDelta;
                }

                if (GetPowerLimit(busId, out uint outCurrPower, out uint outMinPower, out uint outDefPower, out uint outMaxPower))
                {
                    result.PowerMin     = (int)outMinPower;
                    result.PowerMax     = (int)outMaxPower;
                    result.PowerDefault = (int)outDefPower;
                    result.PowerCurr    = (int)outCurrPower;
                }

                if (GetTempLimit(busId, out int outCurrTemp, out int outMinTemp, out int outDefTemp, out int outMaxTemp))
                {
                    result.TempLimitMin     = outMinTemp;
                    result.TempLimitMax     = outMaxTemp;
                    result.TempLimitDefault = outDefTemp;
                    result.TempCurr         = outCurrTemp;
                }

                if (GetCooler(busId, out uint currCooler, out uint minCooler, out uint defCooler, out uint maxCooler))
                {
                    result.FanSpeedCurr    = (int)currCooler;
                    result.FanSpeedMin     = (int)minCooler;
                    result.FanSpeedMax     = (int)maxCooler;
                    result.FanSpeedDefault = (int)defCooler;
                }
#if DEBUG
                Write.DevWarn($"GetClockRange {result.ToString()}");
#endif
            }
            catch (Exception e) {
                Logger.ErrorDebugLine(e);
            }
            return(result);
        }
Exemple #15
0
        /// <summary>
        /// 获取NTMiner所支持的所有内核的近处名
        /// </summary>
        /// <param name="kernelSet"></param>
        /// <returns></returns>
        public static HashSet <string> GetAllKernelProcessNames(this IKernelSet kernelSet)
        {
#if DEBUG
            VirtualRoot.Stopwatch.Restart();
#endif
            HashSet <string> hashSet = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
            foreach (var kernel in kernelSet)
            {
                hashSet.Add(kernel.GetProcessName());
            }
#if DEBUG
            Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {nameof(KernelSetExtension)}.{nameof(GetAllKernelProcessNames)}()");
#endif
            return(hashSet);
        }
Exemple #16
0
 public void AddMessagePath(MessagePath <TMessage> messagePath)
 {
     lock (_locker) {
         if (typeof(ICmd).IsAssignableFrom(typeof(TMessage)))
         {
             bool isExist = _messagePaths.Any(a => messagePath.PathId == a.PathId);
             if (isExist)
             {
                 /// <see cref="ICmd"/>
                 throw new Exception($"一种命令只应被一个处理器处理:{typeof(TMessage).Name}");
             }
         }
         else if (messagePath.Location != AnonymousMessagePath.Location && _messagePaths.Any(a => a.Path == messagePath.Path && a.PathId == messagePath.PathId))
         {
             Write.DevWarn(() => $"重复的路径:{messagePath.Path} {messagePath.Description}");
         }
         _messagePaths.Add(messagePath);
     }
 }
Exemple #17
0
 public void AddMessagePath(MessagePath <TMessage> messagePath)
 {
     lock (_locker) {
         if (typeof(ICmd).IsAssignableFrom(typeof(TMessage)))
         {
             if (_messagePaths.Any(a => a.Path == messagePath.Path && messagePath.PathId == a.PathId))
             {
                 // 因为一种命令只应被一个处理器处理,命令实际上可以设计为不走总线,
                 // 之所以设计为统一走总线只是为了通过将命令类型集中表达以起文档作用。
                 throw new Exception($"一种命令只应被一个处理器处理:{typeof(TMessage).Name}");
             }
         }
         else if (_messagePaths.Any(a => a.Path == messagePath.Path && a.PathId == messagePath.PathId))
         {
             Write.DevWarn($"重复的路径:{messagePath.Path} {messagePath.Description}");
         }
         _messagePaths.Add(messagePath);
     }
 }
Exemple #18
0
        public void Register <TMessage>(DelegateHandler <TMessage> handler)
        {
            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }
            lock (_locker) {
                var keyType = typeof(TMessage);

                var handlerId = handler.HandlerId;
                if (!_paths.Contains(handlerId.HandlerPath))
                {
                    _paths.Add(handlerId.HandlerPath);
                }
                else
                {
                    Write.DevWarn($"重复的路径:{handlerId.HandlerPath}");
                }
                if (_handlers.ContainsKey(keyType))
                {
                    var registeredHandlers = _handlers[keyType];
                    if (registeredHandlers.Count > 0 && typeof(ICmd).IsAssignableFrom(keyType))
                    {
                        throw new Exception($"one {typeof(TMessage).Name} cmd can be handle and only be handle by one handler");
                    }
                    if (!registeredHandlers.Contains(handler))
                    {
                        registeredHandlers.Add(handler);
                    }
                }
                else
                {
                    var registeredHandlers = new List <dynamic> {
                        handler
                    };
                    _handlers.Add(keyType, registeredHandlers);
                }
                _handlerIds.Add(handler.HandlerId);
                HandlerIdAdded?.Invoke(handler.HandlerId);
            }
        }
Exemple #19
0
        public void SetPowerLimitByIndex(int gpuIndex, int value)
        {
            int adapterIndex = GpuIndexToAdapterIndex(gpuIndex);
            ADLODNPowerLimitSetting lpODPowerLimit = new ADLODNPowerLimitSetting();

            try {
                int result = ADL.ADL2_OverdriveN_PowerLimit_Get(context, adapterIndex, ref lpODPowerLimit);
#if DEBUG
                Write.DevWarn($"ADL2_OverdriveN_PowerLimit_Get result={result},iMode={lpODPowerLimit.iMode},iTDPLimit={lpODPowerLimit.iTDPLimit},iMaxOperatingTemperature={lpODPowerLimit.iMaxOperatingTemperature}");
#endif
                if (result == ADL.ADL_OK)
                {
                    lpODPowerLimit.iMode     = ADL.ODNControlType_Manual;
                    lpODPowerLimit.iTDPLimit = value - 100;
                    ADL.ADL2_OverdriveN_PowerLimit_Set(context, adapterIndex, ref lpODPowerLimit);
                }
            }
            catch (Exception e) {
                Logger.ErrorDebugLine(e);
            }
        }
Exemple #20
0
        public void Dispatch <TMessage>(TMessage message) where TMessage : IMessage
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            var messageType = typeof(TMessage);

            if (_handlers.TryGetValue(messageType, out List <object> list))
            {
                var messagePaths = list.ToArray();
                foreach (var messagePath in messagePaths)
                {
                    var tMessagePath = (MessagePath <TMessage>)messagePath;
                    // isMatch表示该处路径是否可以通过该消息,因为有些路径的PathId属性不为Guid.Empty,非空PathId的路径只允许特定标识造型的消息通过
                    // PathId可以认为是路径的形状,唯一的PathId表明该路径具有唯一的形状从而只允许和路径的形状一样的消息结构体穿过
                    bool isMatch = tMessagePath.PathId == Guid.Empty || message is ICmd;
                    if (!isMatch && message is IEvent evt)
                    {
                        isMatch = tMessagePath.PathId == evt.BornPathId;
                    }
                    if (isMatch)
                    {
                        // ViaLimite小于0表示是不限定通过的次数的路径,不限定通过的次数的路径不需要消息每通过一次递减一次ViaLimit计数
                        if (tMessagePath.ViaLimit > 0)
                        {
                            lock (tMessagePath.Locker) {
                                if (tMessagePath.ViaLimit > 0)
                                {
                                    tMessagePath.ViaLimit--;
                                    if (tMessagePath.ViaLimit == 0)
                                    {
                                        // ViaLimit递减到0从路径列表中移除该路径
                                        Disconnect(tMessagePath);
                                    }
                                }
                            }
                        }
                    }
                    if (!tMessagePath.IsEnabled)
                    {
                        continue;
                    }
                    if (isMatch)
                    {
                        switch (tMessagePath.LogType)
                        {
                        case LogEnum.DevConsole:
                            if (DevMode.IsDevMode)
                            {
                                Write.DevDebug($"({messageType.Name})->({tMessagePath.Location.Name}){tMessagePath.Description}");
                            }
                            break;

                        case LogEnum.Log:
                            Logger.InfoDebugLine($"({messageType.Name})->({tMessagePath.Location.Name}){tMessagePath.Description}");
                            break;

                        case LogEnum.None:
                        default:
                            break;
                        }
                        tMessagePath.Go(message);
                    }
                }
            }
            else
            {
                MessageTypeAttribute messageTypeAttr = MessageTypeAttribute.GetMessageTypeAttribute(messageType);
                if (!messageTypeAttr.IsCanNoHandler)
                {
                    Write.DevWarn(messageType.FullName + "类型的消息没有对应的处理器");
                }
            }
        }
Exemple #21
0
        public MainWindow()
        {
#if DEBUG
            VirtualRoot.Stopwatch.Restart();
#endif
            UIThread.StartTimer();
            InitializeComponent();
            if (Design.IsInDesignMode)
            {
                return;
            }
            this.StateChanged += (s, e) => {
                if (Vm.MinerProfile.IsShowInTaskbar)
                {
                    ShowInTaskbar = true;
                }
                else
                {
                    if (WindowState == WindowState.Minimized)
                    {
                        ShowInTaskbar = false;
                    }
                    else
                    {
                        ShowInTaskbar = true;
                    }
                }
            };
            this.SizeChanged += (object sender, SizeChangedEventArgs e) => {
                if (e.WidthChanged)
                {
                    const double width = 800;
                    if (e.NewSize.Width < width)
                    {
                        Collapse();
                    }
                    else if (e.NewSize.Width >= width)
                    {
                        Expand();
                    }
                }
            };
            EventHandler changeNotiCenterWindowLocation = NotiCenterWindow.CreateNotiCenterWindowLocationManager(this);
            this.Activated       += changeNotiCenterWindowLocation;
            this.LocationChanged += changeNotiCenterWindowLocation;
            if (DevMode.IsDevMode)
            {
                this.On <ServerJsonVersionChangedEvent>("开发者模式展示ServerJsonVersion", LogEnum.DevConsole,
                                                        action: message => {
                    UIThread.Execute(() => {
                        Vm.ServerJsonVersion = Vm.GetServerJsonVersion();
                    });
                });
            }
            this.On <PoolDelayPickedEvent>("从内核输出中提取了矿池延时时展示到界面", LogEnum.DevConsole,
                                           action: message => {
                UIThread.Execute(() => {
                    if (message.IsDual)
                    {
                        Vm.StateBarVm.DualPoolDelayText = message.PoolDelayText;
                    }
                    else
                    {
                        Vm.StateBarVm.PoolDelayText = message.PoolDelayText;
                    }
                });
            });
            this.On <MineStartedEvent>("开始挖矿后将清空矿池延时", LogEnum.DevConsole,
                                       action: message => {
                UIThread.Execute(() => {
                    Vm.StateBarVm.PoolDelayText     = string.Empty;
                    Vm.StateBarVm.DualPoolDelayText = string.Empty;
                });
            });
            this.On <MineStopedEvent>("停止挖矿后将清空矿池延时", LogEnum.DevConsole,
                                      action: message => {
                UIThread.Execute(() => {
                    Vm.StateBarVm.PoolDelayText     = string.Empty;
                    Vm.StateBarVm.DualPoolDelayText = string.Empty;
                });
            });
            this.On <Per1MinuteEvent>("挖矿中时自动切换为无界面模式 和 守护进程状态显示", LogEnum.DevConsole,
                                      action: message => {
                if (NTMinerRoot.IsUiVisible && NTMinerRoot.GetIsAutoNoUi() && NTMinerRoot.Instance.IsMining)
                {
                    if (NTMinerRoot.MainWindowRendedOn.AddMinutes(NTMinerRoot.GetAutoNoUiMinutes()) < message.Timestamp)
                    {
                        VirtualRoot.Execute(new CloseMainWindowCommand($"界面展示{NTMinerRoot.GetAutoNoUiMinutes()}分钟后自动切换为无界面模式,可在选项页调整配置"));
                    }
                }
                Vm.RefreshDaemonStateBrush();
            });
#if DEBUG
            Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
        }
Exemple #22
0
 public void WarnDebugLine(object message, Exception exception)
 {
     Write.DevWarn(message?.ToString() + exception.StackTrace);
     _log.Warn(message, exception);
 }
Exemple #23
0
        private MainWindow()
        {
#if DEBUG
            VirtualRoot.Stopwatch.Restart();
#endif
            UIThread.StartTimer();
            InitializeComponent();
            this.StateChanged += (s, e) => {
                if (Vm.MinerProfile.IsShowInTaskbar)
                {
                    ShowInTaskbar = true;
                }
                else
                {
                    if (WindowState == WindowState.Minimized)
                    {
                        ShowInTaskbar = false;
                    }
                    else
                    {
                        ShowInTaskbar = true;
                    }
                }
            };
            this.SizeChanged += (object sender, SizeChangedEventArgs e) => {
                if (e.WidthChanged)
                {
                    if (e.NewSize.Width < 800)
                    {
                        Collapse();
                    }
                    else if (e.NewSize.Width >= 800)
                    {
                        Expand();
                    }
                }
            };
            EventHandler changeNotiCenterWindowLocation = Wpf.Util.ChangeNotiCenterWindowLocation(this);
            this.Activated       += changeNotiCenterWindowLocation;
            this.LocationChanged += changeNotiCenterWindowLocation;
            if (!Windows.Role.IsAdministrator)
            {
                NotiCenterWindowViewModel.Instance.Manager
                .CreateMessage()
                .Warning("请以管理员身份运行。")
                .WithButton("点击以管理员身份运行", button => {
                    AppStatic.RunAsAdministrator.Execute(null);
                })
                .Dismiss().WithButton("忽略", button => {
                    Vm.IsBtnRunAsAdministratorVisible = Visibility.Visible;
                }).Queue();
            }
            if (NTMinerRoot.Instance.GpuSet.Count == 0)
            {
                NotiCenterWindowViewModel.Instance.Manager.ShowErrorMessage("没有矿卡或矿卡未驱动。");
            }
            this.On <StartingMineFailedEvent>("开始挖矿失败", LogEnum.DevConsole,
                                              action: message => {
                Vm.MinerProfile.IsMining = false;
                Write.UserFail(message.Message);
            });
            if (DevMode.IsDevMode)
            {
                this.On <ServerJsonVersionChangedEvent>("开发者模式展示ServerJsonVersion", LogEnum.DevConsole,
                                                        action: message => {
                    Vm.ServerJsonVersion = Vm.GetServerJsonVersion();
                });
            }
#if DEBUG
            Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {this.GetType().Name}.ctor");
#endif
        }
Exemple #24
0
        public void Route <TMessage>(TMessage message) where TMessage : IMessage
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            MessagePath <TMessage>[] messagePaths = PathSetSet.GetMessagePathSet <TMessage>().GetMessagePaths();
            if (messagePaths.Length == 0)
            {
                Type messageType = typeof(TMessage);
                MessageTypeAttribute messageTypeAttr = MessageTypeAttribute.GetMessageTypeAttribute(messageType);
                if (!messageTypeAttr.IsCanNoHandler)
                {
                    Write.DevWarn(messageType.FullName + "类型的消息没有对应的处理器");
                }
            }
            else
            {
                foreach (var messagePath in messagePaths)
                {
                    bool canGo = false;
                    if (message is IEvent evt)
                    {
                        canGo =
                            evt.TargetPathId == PathId.Empty || // 事件不是特定路径的事件则放行
                            messagePath.PathId == PathId.Empty || // 路径不是特定事件的路径则放行
                            evt.TargetPathId == messagePath.PathId;    // 路径是特定事件的路径且路径和事件造型放行
                    }
                    else if (message is ICmd cmd)
                    {
                        // 路径不是特定命令的路径则放行
                        if (messagePath.PathId == PathId.Empty)
                        {
                            canGo = true;
                        }
                        else
                        {
                            canGo = messagePath.PathId == cmd.MessageId;
                        }
                    }
                    if (canGo && messagePath.ViaTimesLimit > 0)
                    {
                        // ViaTimesLimite小于0表示是不限定通过的次数的路径,不限定通过的次数的路径不需要消息每通过一次递减一次ViaTimesLimit计数
                        messagePath.DecreaseViaTimesLimit(onDownToZero: RemoveMessagePath);
                    }
                    if (!messagePath.IsEnabled)
                    {
                        continue;
                    }
                    if (canGo)
                    {
                        switch (messagePath.LogType)
                        {
                        case LogEnum.DevConsole:
                            if (DevMode.IsDevMode)
                            {
                                Write.DevDebug($"({typeof(TMessage).Name})->({messagePath.Location.Name}){messagePath.Description}");
                            }
                            break;

                        case LogEnum.Log:
                            Logger.InfoDebugLine($"({typeof(TMessage).Name})->({messagePath.Location.Name}){messagePath.Description}");
                            break;

                        case LogEnum.None:
                        default:
                            break;
                        }
                        messagePath.Go(message);
                    }
                }
            }
        }
Exemple #25
0
 public void WarnDebugLine(object message)
 {
     Write.DevWarn(message?.ToString());
     _log.Warn(message);
 }
Exemple #26
0
        public void Route <TMessage>(TMessage message) where TMessage : IMessage
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            MessagePath <TMessage>[] messagePaths = MessagePathSet <TMessage> .Instance.GetMessagePaths();

            if (messagePaths.Length == 0)
            {
                Type messageType = typeof(TMessage);
                MessageTypeAttribute messageTypeAttr = MessageTypeAttribute.GetMessageTypeAttribute(messageType);
                if (!messageTypeAttr.IsCanNoHandler)
                {
                    Write.DevWarn(messageType.FullName + "类型的消息没有对应的处理器");
                }
            }
            else
            {
                foreach (var messagePath in messagePaths)
                {
                    // isMatch表示该处路径是否可以通过该消息,因为有些路径的PathId属性不为Guid.Empty,非空PathId的路径只允许特定标识造型的消息通过
                    // PathId可以认为是路径的形状,唯一的PathId表明该路径具有唯一的形状从而只允许和路径的形状一样的消息结构体穿过
                    bool isMatch = messagePath.PathId == Guid.Empty;
                    if (!isMatch)
                    {
                        if (message is IEvent evt)
                        {
                            isMatch = messagePath.PathId == evt.BornPathId;
                        }
                        else if (message is ICmd cmd)
                        {
                            isMatch = messagePath.PathId == cmd.Id;
                        }
                    }
                    if (isMatch && messagePath.ViaLimit > 0)
                    {
                        // ViaLimite小于0表示是不限定通过的次数的路径,不限定通过的次数的路径不需要消息每通过一次递减一次ViaLimit计数
                        messagePath.DecreaseViaLimit(onDownToZero: RemoveMessagePath);
                    }
                    if (!messagePath.IsEnabled)
                    {
                        continue;
                    }
                    if (isMatch)
                    {
                        switch (messagePath.LogType)
                        {
                        case LogEnum.DevConsole:
                            if (DevMode.IsDevMode)
                            {
                                Write.DevDebug($"({typeof(TMessage).Name})->({messagePath.Location.Name}){messagePath.Description}");
                            }
                            break;

                        case LogEnum.Log:
                            Logger.InfoDebugLine($"({typeof(TMessage).Name})->({messagePath.Location.Name}){messagePath.Description}");
                            break;

                        case LogEnum.None:
                        default:
                            break;
                        }
                        messagePath.Go(message);
                    }
                }
            }
        }