private static void SetRdpRegistryValue(int value) { using (RegistryKey localMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default), rdpKey = localMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Terminal Server", true)) { if (!int.TryParse(rdpKey.GetValue("fDenyTSConnections").ToString(), out int currentValue)) { currentValue = -1; } //Value was not found do not proceed with change. if (currentValue == -1) { return; } else if (value == 1 && currentValue == 1) { Write.DevDebug("RDP is already disabled. No changes will be made."); return; } else if (value == 0 && currentValue == 0) { Write.DevDebug("RDP is already enabled. No changes will be made."); return; } else { rdpKey.SetValue("fDenyTSConnections", value); } } }
public static bool ExtractPackage(this IKernel kernel) { try { string kernelDir = GetKernelDirFullName(kernel); if (string.IsNullOrEmpty(kernelDir)) { return(false); } if (!Directory.Exists(kernelDir)) { Directory.CreateDirectory(kernelDir); } string packageZipFileFullName = GetPackageFileFullName(kernel); if (string.IsNullOrEmpty(packageZipFileFullName)) { return(false); } if (!File.Exists(packageZipFileFullName)) { Write.DevDebug($"试图解压的{packageZipFileFullName}文件不存在"); return(false); } ZipUtil.DecompressZipFile(packageZipFileFullName, kernelDir); return(true); } catch (Exception e) { Logger.ErrorDebugLine(e.Message, e); return(false); } }
private bool SetRdpRegistryValue(int value, bool forceChange) { int currentValue; if (!int.TryParse(rdpKey.GetValue("fDenyTSConnections").ToString(), out currentValue)) { currentValue = -1; } //Value was not found do not proceed with change. if (currentValue == -1) { return(false); } else if (value == 1 && currentValue == 1 && !forceChange) { Write.DevDebug("RDP is already disabled. No changes will be made."); return(false); } else if (value == 0 && currentValue == 0 && !forceChange) { Write.DevDebug("RDP is already enabled. No changes will be made."); return(false); } else { rdpKey.SetValue("fDenyTSConnections", value); } return(true); }
private void GetSpeed() { Task.Factory.StartNew(() => { while (true) { DateTime now = DateTime.Now; if (_getSpeedOn.AddSeconds(10) <= now) { if (HostRoot.Instance.HostConfig.IsPull) { Write.DevDebug("周期拉取数据更新拍照源数据"); Task.Factory.StartNew(() => { ClientData[] clientDatas = _dicByObjectId.Values.ToArray(); Task[] tasks = clientDatas.Select(CreatePullTask).ToArray(); Task.WaitAll(tasks, 5 * 1000); }); } _getSpeedOn = now; } else { System.Threading.Thread.Sleep((int)(_getSpeedOn.AddSeconds(10) - now).TotalMilliseconds); } } }); }
public bool Init() { try { int status = ADL.ADL_Main_Control_Create(1); #if DEBUG Write.DevDebug("AMD Display Library Status: " + (status == ADL.ADL_OK ? "OK" : status.ToString())); #endif if (status == ADL.ADL_OK) { int numberOfAdapters = 0; ADL.ADL_Adapter_NumberOfAdapters_Get(ref numberOfAdapters); if (numberOfAdapters > 0) { ADLAdapterInfo[] adapterInfo = new ADLAdapterInfo[numberOfAdapters]; if (ADL.ADL_Adapter_AdapterInfo_Get(adapterInfo) == ADL.ADL_OK) { for (int i = 0; i < numberOfAdapters; i++) { #if DEBUG Write.DevDebug(adapterInfo[i].ToString()); #endif if (!string.IsNullOrEmpty(adapterInfo[i].UDID) && adapterInfo[i].VendorID == ADL.ATI_VENDOR_ID) { bool found = false; foreach (ATIGPU gpu in _gpuNames) { if (gpu.BusNumber == adapterInfo[i].BusNumber && gpu.DeviceNumber == adapterInfo[i].DeviceNumber) { found = true; break; } } if (!found) { _gpuNames.Add(new ATIGPU { AdapterName = adapterInfo[i].AdapterName.Trim(), AdapterIndex = adapterInfo[i].AdapterIndex, BusNumber = adapterInfo[i].BusNumber, DeviceNumber = adapterInfo[i].DeviceNumber }); } } } } } ADL.ADL2_Main_Control_Create(ADL.Main_Memory_Alloc, 1, ref context); } _gpuNames = _gpuNames.OrderBy(a => a.BusNumber).ToList(); #if DEBUG Write.DevDebug(string.Join(",", _gpuNames.Select(a => a.AdapterIndex))); #endif } catch { return(false); } return(true); }
public void RemoveMessagePath(IMessagePathId messagePathId) { lock (_locker) { var item = _messagePaths.FirstOrDefault(a => ReferenceEquals(a, messagePathId)); if (item != null) { _messagePaths.Remove(item); Write.DevDebug("拆除路径" + messagePathId.Path + messagePathId.Description); } } }
private void PullSpeedInit() { if (_isPullSpeedInited) { return; } _isPullSpeedInited = true; Task.Factory.StartNew(() => { while (true) { DateTime now = DateTime.Now; if (_getSpeedOn.AddSeconds(10) <= now) { Write.DevDebug("周期拉取数据更新拍照源数据"); ClientData[] clientDatas = _dicByObjectId.Values.ToArray(); Task[] tasks = clientDatas.Select(CreatePullTask).ToArray(); Task.WaitAll(tasks, 5 * 1000); _getSpeedOn = now; #region 将NoSpeedSeconds秒内更新过的记录持久化到磁盘 List <MinerData> minerDatas = new List <MinerData>(); DateTime time = now.AddSeconds(-20); foreach (var clientData in _dicByObjectId.Values) { if (clientData.MinerActiveOn > time) { minerDatas.Add(MinerData.Create(clientData)); } else { clientData.IsMining = false; clientData.MainCoinSpeed = 0; clientData.DualCoinSpeed = 0; foreach (var item in clientData.GpuTable) { item.MainCoinSpeed = 0; item.DualCoinSpeed = 0; } } } if (minerDatas.Count > 0) { DoUpdateSave(minerDatas); } #endregion } else { System.Threading.Thread.Sleep((int)(_getSpeedOn.AddSeconds(10) - now).TotalMilliseconds); } } }, TaskCreationOptions.LongRunning); }
/// <summary> /// 本机网络调用 /// </summary> public void CloseDaemon() { try { using (HttpClient client = RpcRoot.CreateHttpClient()) { client.Timeout = TimeSpan.FromSeconds(2); Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://localhost:{NTKeyword.NTMinerDaemonPort.ToString()}/api/{_controllerName}/{nameof(INTMinerDaemonController.CloseDaemon)}", null); Write.DevDebug($"{nameof(CloseDaemon)} {getHttpResponse.Result.ReasonPhrase}"); } } catch (Exception e) { Write.DevException(e); } }
/// <summary> /// 不会抛出异常,因为吞掉了异常 /// </summary> public static void Kill(int pid, bool waitForExit = false) { try { if (pid <= 0) { return; } string args = $"/F /T /PID {pid.ToString()}"; Cmd.RunClose("taskkill", args, waitForExit); Write.DevDebug(args); } catch { } }
/// <summary> /// 不会抛出异常,因为吞掉了异常 /// </summary> /// <param name="processName"></param> /// <param name="waitForExit"></param> public static void Kill(string processName, bool waitForExit = false) { try { if (string.IsNullOrEmpty(processName)) { return; } string args = $"/F /T /IM {processName}.exe"; Cmd.RunClose("taskkill", args, waitForExit); Write.DevDebug(args); } catch { } }
/// <summary> /// 不会抛出异常,因为吞掉了异常 /// </summary> /// <param name="process"></param> /// <param name="waitForExit"></param> public static void KillOtherProcess(Process process, bool waitForExit = false) { if (process == null) { return; } try { string args = $"/F /FI \"pid ne {process.Id}\" /T /IM {process.ProcessName}.exe"; Cmd.RunClose("taskkill", args, waitForExit); Write.DevDebug(args); } catch { } }
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 + "类型的消息没有对应的处理器"); } }
/// <summary> /// 本机网络调用 /// </summary> public void RefreshAutoBootStartAsync() { Task.Factory.StartNew(() => { try { using (HttpClient client = RpcRoot.CreateHttpClient()) { client.Timeout = TimeSpan.FromSeconds(3); Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://localhost:{NTKeyword.MinerClientPort.ToString()}/api/{_controllerName}/{nameof(IMinerClientController.RefreshAutoBootStart)}", null); Write.DevDebug($"{nameof(RefreshAutoBootStartAsync)} {getHttpResponse.Result.ReasonPhrase}"); } } catch (Exception e) { Logger.ErrorDebugLine(e); } }); }
public void SetAutoBootStartAsync(string clientIp, bool autoBoot, bool autoStart) { Task.Factory.StartNew(() => { try { using (HttpClient client = RpcRoot.CreateHttpClient()) { client.Timeout = TimeSpan.FromSeconds(3); Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://{clientIp}:{NTKeyword.NTMinerDaemonPort.ToString()}/api/{_controllerName}/{nameof(INTMinerDaemonController.SetAutoBootStart)}?autoBoot={autoBoot}&autoStart={autoStart}", null); Write.DevDebug($"{nameof(SetAutoBootStartAsync)} {getHttpResponse.Result.ReasonPhrase}"); } } catch (Exception e) { Logger.ErrorDebugLine(e); } }); }
protected bool IsValidAdmin <TResponse>(ISignableData data, out TResponse response, out UserData user) where TResponse : ResponseBase, new() { user = null; if (!WebApiRoot.UserSet.IsReadied) { string message = "服务器用户集启动中,请稍后"; response = ResponseBase.NotExist <TResponse>(message); return(false); } ClientSignData query = ClientSign; if (!Timestamp.IsInTime(query.Timestamp)) { response = ResponseBase.Expired <TResponse>(); return(false); } if (!string.IsNullOrEmpty(query.LoginName)) { user = WebApiRoot.UserSet.GetUser(query.UserId); } if (user == null && !string.IsNullOrEmpty(query.LoginName)) { user = WebApiRoot.UserSet.GetUser(query.UserId); } if (user == null) { string message = "用户不存在"; response = ResponseBase.NotExist <TResponse>(message); return(false); } else if (!user.IsAdmin()) { string message = "对不起,您不是超管"; response = ResponseBase.NotExist <TResponse>(message); return(false); } string mySign = RpcUser.CalcSign(user.LoginName, user.Password, query.Timestamp, data); if (query.Sign != mySign) { string message = "登录名或密码错误"; response = ResponseBase.Forbidden <TResponse>(message); Write.DevDebug(() => $"{message} sign:{query.Sign} mySign:{mySign}"); return(false); } response = null; return(true); }
public void SaveGpuProfilesJsonAsync(string clientIp, string json) { Task.Factory.StartNew(() => { try { using (HttpClient client = RpcRoot.CreateHttpClient()) { client.Timeout = TimeSpan.FromSeconds(3); HttpContent content = new StringContent(json); Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://{clientIp}:{NTKeyword.NTMinerDaemonPort.ToString()}/api/{_controllerName}/{nameof(INTMinerDaemonController.SaveGpuProfilesJson)}", content); Write.DevDebug($"{nameof(SaveGpuProfilesJsonAsync)} {getHttpResponse.Result.ReasonPhrase}"); } } catch (Exception e) { Logger.ErrorDebugLine(e); } }); }
/// <summary> /// 本机同步网络调用 /// </summary> public void CloseServices() { try { Process[] processes = Process.GetProcessesByName(NTKeyword.NTMinerServicesProcessName); if (processes.Length == 0) { return; } using (HttpClient client = RpcRoot.CreateHttpClient()) { Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://localhost:{NTKeyword.ControlCenterPort.ToString()}/api/{_controllerName}/{nameof(IControlCenterController.CloseServices)}", null); Write.DevDebug($"{nameof(CloseServices)} {getHttpResponse.Result.ReasonPhrase}"); } } catch (Exception e) { Logger.ErrorDebugLine(e); } }
public void ReportStateAsync(string host, Guid clientId, bool isMining) { Task.Factory.StartNew(() => { TimeSpan timeSpan = TimeSpan.FromSeconds(3); try { using (HttpClient client = RpcRoot.CreateHttpClient()) { client.Timeout = timeSpan; ReportState request = new ReportState { ClientId = clientId, IsMining = isMining }; Task <HttpResponseMessage> getHttpResponse = client.PostAsJsonAsync($"http://{host}:{NTKeyword.ControlCenterPort.ToString()}/api/{_controllerName}/{nameof(IReportController.ReportState)}", request); Write.DevDebug($"{nameof(ReportStateAsync)} {getHttpResponse.Result.ReasonPhrase}"); } } catch (Exception e) { Write.DevException(e); } }); }
public void Disconnect(IMessagePathId handlerId) { if (handlerId == null) { return; } lock (_locker) { _paths.Remove(handlerId.Path); var keyType = handlerId.MessageType; if (_handlers.ContainsKey(keyType) && _handlers[keyType] != null && _handlers[keyType].Count > 0 && _handlers[keyType].Contains(handlerId)) { _handlers[keyType].Remove(handlerId); Write.DevDebug("拆除路径" + handlerId.Path); Disconnected?.Invoke(handlerId); } } }
public void UnRegister(IDelegateHandler handler) { if (handler == null) { return; } lock (_locker) { var handlerId = handler.HandlerId; _paths.Remove(handlerId.HandlerPath); var keyType = handlerId.MessageType; if (_handlers.ContainsKey(keyType) && _handlers[keyType] != null && _handlers[keyType].Count > 0 && _handlers[keyType].Contains(handler)) { _handlers[keyType].Remove(handler); _handlerIds.Remove(handlerId); HandlerIdRemoved?.Invoke(handlerId); Write.DevDebug("拆除路径" + handler.HandlerId.HandlerPath); } } }
private void Init() { lock (_locker) { if (!_isInited) { // 将最近20分钟的快照载入内存 DateTime now = DateTime.Now; using (LiteDatabase db = HostRoot.CreateReportDb()) { var col = db.GetCollection <CoinSnapshotData>(); col.EnsureIndex(nameof(CoinSnapshotData.Timestamp), unique: false); foreach (var item in col.Find( Query.And( Query.GT(nameof(CoinSnapshotData.Timestamp), now.AddMinutes(-20)), Query.LTE(nameof(CoinSnapshotData.Timestamp), now)))) { _dataList.Add(item); } } Write.DevDebug("将最近20分钟的快照载入内存"); _isInited = true; } } }
/// <summary> /// /// </summary> private void Snapshot(DateTime now) { InitOnece(); try { int onlineCount = 0; int miningCount = 0; Dictionary <string, CoinSnapshotData> dicByCoinCode = new Dictionary <string, CoinSnapshotData>(); foreach (var clientData in _root.ClientSet.AsEnumerable()) { if (HostRoot.Instance.HostConfig.IsPull) { if (clientData.ModifiedOn.AddSeconds(15) < now) { continue; } } else { if (clientData.ModifiedOn.AddSeconds(130) < now) { continue; } } onlineCount++; if (string.IsNullOrEmpty(clientData.MainCoinCode)) { continue; } if (!dicByCoinCode.TryGetValue(clientData.MainCoinCode, out CoinSnapshotData mainCoinSnapshotData)) { mainCoinSnapshotData = new CoinSnapshotData() { Timestamp = now, CoinCode = clientData.MainCoinCode }; dicByCoinCode.Add(clientData.MainCoinCode, mainCoinSnapshotData); } if (clientData.IsMining) { miningCount++; mainCoinSnapshotData.MainCoinMiningCount += 1; mainCoinSnapshotData.Speed += clientData.MainCoinSpeed; mainCoinSnapshotData.ShareDelta += clientData.GetMainCoinShareDelta(HostRoot.Instance.HostConfig.IsPull); mainCoinSnapshotData.RejectShareDelta += clientData.GetMainCoinRejectShareDelta(HostRoot.Instance.HostConfig.IsPull); } mainCoinSnapshotData.MainCoinOnlineCount += 1; if (!string.IsNullOrEmpty(clientData.DualCoinCode) && clientData.IsDualCoinEnabled) { if (!dicByCoinCode.TryGetValue(clientData.DualCoinCode, out CoinSnapshotData dualCoinSnapshotData)) { dualCoinSnapshotData = new CoinSnapshotData() { Timestamp = now, CoinCode = clientData.DualCoinCode }; dicByCoinCode.Add(clientData.DualCoinCode, dualCoinSnapshotData); } if (clientData.IsMining) { dualCoinSnapshotData.DualCoinMiningCount += 1; dualCoinSnapshotData.Speed += clientData.DualCoinSpeed; dualCoinSnapshotData.ShareDelta += clientData.GetDualCoinShareDelta(HostRoot.Instance.HostConfig.IsPull); dualCoinSnapshotData.RejectShareDelta += clientData.GetDualCoinRejectShareDelta(HostRoot.Instance.HostConfig.IsPull); } dualCoinSnapshotData.DualCoinOnlineCount += 1; } } HostRoot.ClientCount.Update(onlineCount, miningCount); if (dicByCoinCode.Count > 0) { _dataList.AddRange(dicByCoinCode.Values); using (LiteDatabase db = HostRoot.CreateReportDb()) { var col = db.GetCollection <CoinSnapshotData>(); col.Insert(dicByCoinCode.Values); } Write.DevDebug("拍摄快照" + dicByCoinCode.Count + "张,快照时间戳:" + now.ToString("yyyy-MM-dd HH:mm:ss fff")); } } catch (Exception e) { Logger.ErrorDebugLine(e); } }
public bool Init() { try { var r = AdlNativeMethods.ADL_Main_Control_Create(1); if (r < AdlStatus.ADL_OK) { Write.DevError($"ADL_Main_Control_Create {r.ToString()}"); } if (r >= AdlStatus.ADL_OK) { int numberOfAdapters = 0; r = AdlNativeMethods.ADL_Adapter_NumberOfAdapters_Get(ref numberOfAdapters); if (r < AdlStatus.ADL_OK) { Write.DevError($"{nameof(AdlNativeMethods.ADL_Adapter_NumberOfAdapters_Get)} {r.ToString()}"); } if (numberOfAdapters > 0) { ADLAdapterInfo[] adapterInfo = new ADLAdapterInfo[numberOfAdapters]; if (AdlNativeMethods.ADL_Adapter_AdapterInfo_Get(adapterInfo) >= AdlStatus.ADL_OK) { for (int i = 0; i < numberOfAdapters; i++) { #if DEBUG Write.DevDebug(adapterInfo[i].ToString()); #endif if (!string.IsNullOrEmpty(adapterInfo[i].UDID) && adapterInfo[i].VendorID == AdlConst.ATI_VENDOR_ID) { bool found = false; foreach (ATIGPU gpu in _gpuNames) { if (gpu.BusNumber == adapterInfo[i].BusNumber && gpu.DeviceNumber == adapterInfo[i].DeviceNumber) { found = true; break; } } if (!found) { _gpuNames.Add(new ATIGPU { AdapterName = adapterInfo[i].AdapterName.Trim(), AdapterIndex = adapterInfo[i].AdapterIndex, BusNumber = adapterInfo[i].BusNumber, DeviceNumber = adapterInfo[i].DeviceNumber }); } } } } } r = AdlNativeMethods.ADL2_Main_Control_Create(AdlNativeMethods.Main_Memory_Alloc, 1, ref context); if (r < AdlStatus.ADL_OK) { Write.DevError($"{nameof(AdlNativeMethods.ADL2_Main_Control_Create)} {r.ToString()}"); } } _gpuNames = _gpuNames.OrderBy(a => a.BusNumber).ToList(); #if DEBUG Write.DevDebug(string.Join(",", _gpuNames.Select(a => a.AdapterIndex))); #endif } catch { return(false); } return(true); }
public MineWorkViewModel(Guid id) { _id = id; this.Save = new DelegateCommand(() => { if (this.Id == Guid.Empty) { return; } if (string.IsNullOrEmpty(this.Name)) { VirtualRoot.Out.ShowError("作业名称是必须的", autoHideSeconds: 4); } bool isMinerProfileChanged = false; bool isShowEdit = false; MineWorkData mineWorkData = new MineWorkData().Update(this); if (MinerStudioRoot.MineWorkVms.TryGetMineWorkVm(this.Id, out MineWorkViewModel vm)) { string sha1 = NTMinerContext.Instance.MinerProfile.GetSha1(); // 如果作业设置变更了则一定变更了 if (this.Sha1 != sha1) { isMinerProfileChanged = true; } else { // 如果作业设置没变更但作业引用的服务器数据库记录状态变更了则变更了 LocalJsonDb localJsonObj = new LocalJsonDb(NTMinerContext.Instance, mineWorkData); ServerJsonDb serverJsonObj = new ServerJsonDb(NTMinerContext.Instance, localJsonObj); var serverJson = VirtualRoot.JsonSerializer.Serialize(serverJsonObj); sha1 = HashUtil.Sha1(serverJson); if (sha1 != this.ServerJsonSha1) { isMinerProfileChanged = true; } } } else { isMinerProfileChanged = true; isShowEdit = true; } if (RpcRoot.IsOuterNet) { RpcRoot.OfficialServer.UserMineWorkService.AddOrUpdateMineWorkAsync(new MineWorkData().Update(this), (r, ex) => { if (r.IsSuccess()) { if (isMinerProfileChanged) { Write.DevDebug("检测到MinerProfile状态变更"); NTMinerContext.ExportWorkJson(mineWorkData, out string localJson, out string serverJson); if (!string.IsNullOrEmpty(localJson) && !string.IsNullOrEmpty(serverJson)) { RpcRoot.OfficialServer.UserMineWorkService.ExportMineWorkAsync(this.Id, localJson, serverJson, (response, e) => { if (response.IsSuccess()) { if (isShowEdit) { VirtualRoot.RaiseEvent(new MineWorkAddedEvent(Guid.Empty, this)); } else { VirtualRoot.RaiseEvent(new MineWorkUpdatedEvent(Guid.Empty, this)); } if (isShowEdit) { this.Edit.Execute(FormType.Edit); } } else { VirtualRoot.Out.ShowError(response.ReadMessage(e), autoHideSeconds: 4); } }); } if (mineWorkData.ServerJsonSha1 != this.ServerJsonSha1) { this.ServerJsonSha1 = mineWorkData.ServerJsonSha1; } } }
public bool SetMemoryClock(int gpuIndex, int value, int voltage) { if (value < 0) { value = 0; } if (voltage < 0) { voltage = 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); } info.iMode = AdlConst.ODNControlType_Default; r = AdlNativeMethods.ADL2_OverdriveN_MemoryClocksX2_Set(context, adapterIndex, ref info); if (r < AdlStatus.ADL_OK) { Write.DevError($"{nameof(AdlNativeMethods.ADL2_OverdriveN_MemoryClocksX2_Set)} {r.ToString()}"); return(false); } bool isReset = value == 0 && voltage == 0; if (isReset) { return(true); } 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); } info.iMode = AdlConst.ODNControlType_Manual; int index = 0; for (int i = 0; i < info.aLevels.Length; i++) { if (info.aLevels[i].iEnabled != 0) { index = i; } } Write.DevDebug($"SetMemoryClock PState {index.ToString()} value={value.ToString()} voltage={voltage.ToString()}"); if (value != 0) { info.aLevels[index].iClock = value * 100; } if (voltage != 0) { info.aLevels[index].iVddc = voltage; } r = AdlNativeMethods.ADL2_OverdriveN_MemoryClocksX2_Set(context, adapterIndex, ref info); if (r < AdlStatus.ADL_OK) { Write.DevError($"{nameof(AdlNativeMethods.ADL2_OverdriveN_MemoryClocksX2_Set)} {r.ToString()}"); return(false); } return(true); } catch (Exception e) { Logger.ErrorDebugLine(e); return(false); } }
public void Init(INTMinerRoot root) { if (_isInited) { return; } _isInited = true; VirtualRoot.AddEventPath <GpuStateChangedEvent>("当显卡温度变更时守卫温度防线", LogEnum.None, action: message => { IGpu gpu = message.Target; if (gpu.Index == NTMinerRoot.GpuAllId || root.MinerProfile.CoinId == Guid.Empty) { return; } IGpuProfile gpuProfile; if (NTMinerRoot.Instance.GpuProfileSet.IsOverClockGpuAll(root.MinerProfile.CoinId)) { gpuProfile = NTMinerRoot.Instance.GpuProfileSet.GetGpuProfile(root.MinerProfile.CoinId, NTMinerRoot.GpuAllId); } else { gpuProfile = NTMinerRoot.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) { Write.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); Write.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); Write.DevDebug($"GPU{gpu.Index.ToString()} 风扇转速由{gpu.FanSpeed.ToString()}%调高至{cool.ToString()}%"); } } }, location: this.GetType()); }
public MineWorkViewModel(Guid id) { _id = id; this.Save = new DelegateCommand(() => { if (this.Id == Guid.Empty) { return; } if (string.IsNullOrEmpty(this.Name)) { NotiCenterWindowViewModel.Instance.Manager.ShowErrorMessage("作业名称是必须的"); } bool isMinerProfileChanged = false; if (NTMinerRoot.Instance.MineWorkSet.TryGetMineWork(this.Id, out IMineWork entity)) { string sha1 = NTMinerRoot.Instance.MinerProfile.GetSha1(); if (this.Sha1 != sha1) { isMinerProfileChanged = true; } if (entity.Name != this.Name || entity.Description != this.Description) { VirtualRoot.Execute(new UpdateMineWorkCommand(this)); } CloseWindow?.Invoke(); } else { isMinerProfileChanged = true; VirtualRoot.Execute(new AddMineWorkCommand(this)); CloseWindow?.Invoke(); this.Edit.Execute(FormType.Edit); } if (isMinerProfileChanged) { Write.DevDebug("检测到MinerProfile状态变更"); NTMinerRoot.ExportWorkJson(new MineWorkData(this), out string localJson, out string serverJson); if (!string.IsNullOrEmpty(localJson) && !string.IsNullOrEmpty(serverJson)) { Server.ControlCenterService.ExportMineWorkAsync(this.Id, localJson, serverJson, callback: null); } } }); this.Edit = new DelegateCommand <FormType?>((formType) => { if (this.Id == Guid.Empty) { return; } if (!AppContext.Instance.MineWorkVms.TryGetMineWorkVm(this.Id, out MineWorkViewModel mineWorkVm)) { InputWindow.ShowDialog("作业名称", string.Empty, workName => { if (string.IsNullOrEmpty(workName)) { return("作业名称是必须的"); } return(string.Empty); }, onOk: workName => { new MineWorkViewModel(this) { Name = workName }.Save.Execute(null); }); } else { // 编辑作业前切换上下文 // 根据workId下载json保存到本地并调用LocalJson.Instance.ReInit() string json = Server.ControlCenterService.GetLocalJson(this.Id); if (!string.IsNullOrEmpty(json)) { File.WriteAllText(SpecialPath.LocalJsonFileFullName, json); } else { File.Delete(SpecialPath.LocalJsonFileFullName); } NTMinerRoot.Instance.ReInitMinerProfile(); this.Sha1 = NTMinerRoot.Instance.MinerProfile.GetSha1(); MineWorkEdit.ShowWindow(formType ?? FormType.Edit, new MineWorkViewModel(this)); } }, formType => { if (this == PleaseSelect) { return(false); } return(true); }); this.Remove = new DelegateCommand(() => { if (this.Id == Guid.Empty) { return; } DialogWindow.ShowDialog(message: $"您确定删除吗?", title: "确认", onYes: () => { VirtualRoot.Execute(new RemoveMineWorkCommand(this.Id)); }, icon: IconConst.IconConfirm); }, () => { if (this == PleaseSelect) { return(false); } return(true); }); }
public void InfoDebugLine(object message) { Write.DevDebug(message?.ToString()); _log.Info(message); }
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); } } } }
public MineWorkViewModel(Guid id) { _id = id; this.Save = new DelegateCommand(() => { if (this.Id == Guid.Empty) { return; } if (string.IsNullOrEmpty(this.Name)) { VirtualRoot.Out.ShowError("作业名称是必须的"); } bool isMineWorkChanged = false; bool isMinerProfileChanged = false; MineWorkData mineWorkData = new MineWorkData(this); if (NTMinerRoot.Instance.MineWorkSet.TryGetMineWork(this.Id, out IMineWork entity)) { string sha1 = NTMinerRoot.Instance.MinerProfile.GetSha1(); // 如果作业设置变更了则一定变更了 if (this.Sha1 != sha1) { isMinerProfileChanged = true; } else { // 如果作业设置没变更但作业引用的服务器数据库记录状态变更了则变更了 LocalJsonDb localJsonObj = new LocalJsonDb(NTMinerRoot.Instance, mineWorkData); ServerJsonDb serverJsonObj = new ServerJsonDb(NTMinerRoot.Instance, localJsonObj); var serverJson = VirtualRoot.JsonSerializer.Serialize(serverJsonObj); sha1 = HashUtil.Sha1(serverJson); if (sha1 != this.ServerJsonSha1) { isMinerProfileChanged = true; } } if (entity.Name != this.Name || entity.Description != this.Description) { isMineWorkChanged = true; } } else { isMinerProfileChanged = true; VirtualRoot.Execute(new AddMineWorkCommand(this)); this.Edit.Execute(FormType.Edit); } if (isMinerProfileChanged) { Write.DevDebug("检测到MinerProfile状态变更"); NTMinerRoot.ExportWorkJson(mineWorkData, out string localJson, out string serverJson); if (!string.IsNullOrEmpty(localJson) && !string.IsNullOrEmpty(serverJson)) { RpcRoot.Server.MineWorkService.ExportMineWorkAsync(this.Id, localJson, serverJson, callback: null); } if (mineWorkData.ServerJsonSha1 != this.ServerJsonSha1) { this.ServerJsonSha1 = mineWorkData.ServerJsonSha1; isMineWorkChanged = true; } } if (isMineWorkChanged) { VirtualRoot.Execute(new UpdateMineWorkCommand(mineWorkData)); } }); this.Edit = new DelegateCommand <FormType?>((formType) => { if (this.Id == Guid.Empty) { return; } if (!AppContext.Instance.MineWorkVms.TryGetMineWorkVm(this.Id, out MineWorkViewModel mineWorkVm)) { WpfUtil.ShowInputDialog("作业名称", string.Empty, workName => { if (string.IsNullOrEmpty(workName)) { return("作业名称是必须的"); } return(string.Empty); }, onOk: workName => { new MineWorkViewModel(this) { Name = workName }.Save.Execute(null); }); } else { // 编辑作业前切换上下文 // 根据workId下载json保存到本地并调用LocalJson.Instance.ReInit() string json = RpcRoot.Server.MineWorkService.GetLocalJson(this.Id); if (!string.IsNullOrEmpty(json)) { File.WriteAllText(SpecialPath.LocalJsonFileFullName, json); } else { File.Delete(SpecialPath.LocalJsonFileFullName); } NTMinerRoot.Instance.ReInitMinerProfile(); this.Sha1 = NTMinerRoot.Instance.MinerProfile.GetSha1(); VirtualRoot.Execute(new MineWorkEditCommand(formType ?? FormType.Edit, new MineWorkViewModel(this))); } }, formType => { if (this == PleaseSelect) { return(false); } return(true); }); this.Remove = new DelegateCommand(() => { if (this.Id == Guid.Empty) { return; } this.ShowSoftDialog(new DialogWindowViewModel(message: $"您确定删除吗?", title: "确认", onYes: () => { VirtualRoot.Execute(new RemoveMineWorkCommand(this.Id)); })); }, () => { if (this == PleaseSelect) { return(false); } return(true); }); }