Remove network monitoring features and related code; update GPU monitoring in dashboard for improved performance and clarity.

This commit is contained in:
Din
2025-08-08 11:45:48 +08:00
parent 35828f189c
commit 5ece1fbe27
6 changed files with 71 additions and 164 deletions
-1
View File
@@ -6,7 +6,6 @@ namespace ResourceMonitorService.Configuration
public int DataRetentionDays { get; set; } = 7; public int DataRetentionDays { get; set; } = 7;
public bool EnableGpuMonitoring { get; set; } = true; public bool EnableGpuMonitoring { get; set; } = true;
public bool EnableDiskMonitoring { get; set; } = true; public bool EnableDiskMonitoring { get; set; } = true;
public bool EnableNetworkMonitoring { get; set; } = true;
public bool EnableTemperatureMonitoring { get; set; } = true; public bool EnableTemperatureMonitoring { get; set; } = true;
public bool EnableProcessMonitoring { get; set; } = true; public bool EnableProcessMonitoring { get; set; } = true;
public bool EnableGameDetection { get; set; } = true; public bool EnableGameDetection { get; set; } = true;
-15
View File
@@ -113,21 +113,6 @@ namespace ResourceMonitorService.Controllers
} }
} }
[HttpGet("network")]
public async Task<ActionResult<NetworkUsage>> GetNetworkUsage()
{
try
{
var networkUsage = await _resourceMonitorService.GetNetworkUsageAsync();
return Ok(networkUsage);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting network usage");
return StatusCode(500, "Internal server error");
}
}
[HttpGet("processes")] [HttpGet("processes")]
public async Task<ActionResult<List<ProcessInfo>>> GetTopProcesses([FromQuery] int count = 10) public async Task<ActionResult<List<ProcessInfo>>> GetTopProcesses([FromQuery] int count = 10)
{ {
-22
View File
@@ -24,7 +24,6 @@ namespace ResourceMonitorService.Models
public MemoryUsage Memory { get; set; } = new(); public MemoryUsage Memory { get; set; } = new();
public GpuUsage GPU { get; set; } = new(); public GpuUsage GPU { get; set; } = new();
public List<DiskUsage> Disks { get; set; } = new(); public List<DiskUsage> Disks { get; set; } = new();
public NetworkUsage Network { get; set; } = new();
public List<ProcessInfo> TopProcesses { get; set; } = new(); public List<ProcessInfo> TopProcesses { get; set; } = new();
public TemperatureInfo Temperature { get; set; } = new(); public TemperatureInfo Temperature { get; set; } = new();
public GameInfo? RunningGame { get; set; } public GameInfo? RunningGame { get; set; }
@@ -84,27 +83,6 @@ namespace ResourceMonitorService.Models
public long WriteOperations { get; set; } public long WriteOperations { get; set; }
} }
public class NetworkUsage
{
public float UploadSpeed { get; set; } // MB/s
public float DownloadSpeed { get; set; } // MB/s
public ulong BytesSent { get; set; }
public ulong BytesReceived { get; set; }
public List<NetworkAdapter> Adapters { get; set; } = new();
}
public class NetworkAdapter
{
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public bool IsOperational { get; set; }
public long Speed { get; set; }
public float UploadSpeed { get; set; }
public float DownloadSpeed { get; set; }
public string IPAddress { get; set; } = string.Empty;
public string MACAddress { get; set; } = string.Empty;
}
public class ProcessInfo public class ProcessInfo
{ {
public int ProcessId { get; set; } public int ProcessId { get; set; }
-100
View File
@@ -14,7 +14,6 @@ namespace ResourceMonitorService.Services
Task<MemoryUsage> GetMemoryUsageAsync(); Task<MemoryUsage> GetMemoryUsageAsync();
Task<GpuUsage> GetGpuUsageAsync(); Task<GpuUsage> GetGpuUsageAsync();
Task<List<DiskUsage>> GetDiskUsageAsync(); Task<List<DiskUsage>> GetDiskUsageAsync();
Task<NetworkUsage> GetNetworkUsageAsync();
Task<List<ProcessInfo>> GetTopProcessesAsync(int count = 10); Task<List<ProcessInfo>> GetTopProcessesAsync(int count = 10);
} }
@@ -23,8 +22,6 @@ namespace ResourceMonitorService.Services
private readonly ILogger<ResourceMonitorService> _logger; private readonly ILogger<ResourceMonitorService> _logger;
private readonly MonitoringSettings _settings; private readonly MonitoringSettings _settings;
private readonly Dictionary<string, PerformanceCounter> _counters; private readonly Dictionary<string, PerformanceCounter> _counters;
private readonly Dictionary<string, long> _previousNetworkBytes;
private readonly Dictionary<string, DateTime> _previousNetworkTime;
private readonly Dictionary<string, long> _previousDiskBytes; private readonly Dictionary<string, long> _previousDiskBytes;
private readonly Dictionary<string, DateTime> _previousDiskTime; private readonly Dictionary<string, DateTime> _previousDiskTime;
private readonly Dictionary<string, int> _errorCounts; private readonly Dictionary<string, int> _errorCounts;
@@ -35,8 +32,6 @@ namespace ResourceMonitorService.Services
_logger = logger; _logger = logger;
_settings = settings.Value; _settings = settings.Value;
_counters = new Dictionary<string, PerformanceCounter>(); _counters = new Dictionary<string, PerformanceCounter>();
_previousNetworkBytes = new Dictionary<string, long>();
_previousNetworkTime = new Dictionary<string, DateTime>();
_previousDiskBytes = new Dictionary<string, long>(); _previousDiskBytes = new Dictionary<string, long>();
_previousDiskTime = new Dictionary<string, DateTime>(); _previousDiskTime = new Dictionary<string, DateTime>();
_errorCounts = new Dictionary<string, int>(); _errorCounts = new Dictionary<string, int>();
@@ -52,12 +47,6 @@ namespace ResourceMonitorService.Services
_counters["cpu"] = new PerformanceCounter("Processor", "% Processor Time", "_Total"); _counters["cpu"] = new PerformanceCounter("Processor", "% Processor Time", "_Total");
_counters["memory_available"] = new PerformanceCounter("Memory", "Available MBytes"); _counters["memory_available"] = new PerformanceCounter("Memory", "Available MBytes");
if (_settings.EnableNetworkMonitoring)
{
_counters["network_bytes_sent"] = new PerformanceCounter("Network Interface", "Bytes Sent/sec", "*");
_counters["network_bytes_received"] = new PerformanceCounter("Network Interface", "Bytes Received/sec", "*");
}
if (_settings.EnableDiskMonitoring) if (_settings.EnableDiskMonitoring)
{ {
_counters["disk_read"] = new PerformanceCounter("PhysicalDisk", "Disk Read Bytes/sec", "_Total"); _counters["disk_read"] = new PerformanceCounter("PhysicalDisk", "Disk Read Bytes/sec", "_Total");
@@ -119,9 +108,6 @@ namespace ResourceMonitorService.Services
if (_settings.EnableDiskMonitoring) if (_settings.EnableDiskMonitoring)
tasks.Add(Task.Run(async () => await GetDiskUsageAsync())); tasks.Add(Task.Run(async () => await GetDiskUsageAsync()));
if (_settings.EnableNetworkMonitoring)
tasks.Add(Task.Run(async () => await GetNetworkUsageAsync()));
if (_settings.EnableProcessMonitoring) if (_settings.EnableProcessMonitoring)
tasks.Add(Task.Run(async () => await GetTopProcessesAsync(_settings.MaxProcessesToTrack))); tasks.Add(Task.Run(async () => await GetTopProcessesAsync(_settings.MaxProcessesToTrack)));
@@ -134,7 +120,6 @@ namespace ResourceMonitorService.Services
Memory = await GetMemoryUsageAsync(), Memory = await GetMemoryUsageAsync(),
GPU = _settings.EnableGpuMonitoring ? await GetGpuUsageAsync() : new GpuUsage(), GPU = _settings.EnableGpuMonitoring ? await GetGpuUsageAsync() : new GpuUsage(),
Disks = _settings.EnableDiskMonitoring ? await GetDiskUsageAsync() : new List<DiskUsage>(), Disks = _settings.EnableDiskMonitoring ? await GetDiskUsageAsync() : new List<DiskUsage>(),
Network = _settings.EnableNetworkMonitoring ? await GetNetworkUsageAsync() : new NetworkUsage(),
TopProcesses = _settings.EnableProcessMonitoring ? await GetTopProcessesAsync(_settings.MaxProcessesToTrack) : new List<ProcessInfo>(), TopProcesses = _settings.EnableProcessMonitoring ? await GetTopProcessesAsync(_settings.MaxProcessesToTrack) : new List<ProcessInfo>(),
Temperature = _settings.EnableTemperatureMonitoring ? await GetTemperatureInfoAsync() : new TemperatureInfo() Temperature = _settings.EnableTemperatureMonitoring ? await GetTemperatureInfoAsync() : new TemperatureInfo()
}; };
@@ -654,91 +639,6 @@ namespace ResourceMonitorService.Services
return false; return false;
} }
public async Task<NetworkUsage> GetNetworkUsageAsync()
{
try
{
return await Task.Run(() =>
{
var networkUsage = new NetworkUsage();
var adapters = new List<NetworkAdapter>();
try
{
#pragma warning disable CA1416 // Validate platform compatibility
using var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PerfRawData_Tcpip_NetworkInterface WHERE Name != 'Loopback'");
using var collection = searcher.Get();
foreach (ManagementObject obj in collection)
{
var name = obj["Name"]?.ToString() ?? "";
if (name.Contains("Loopback") || name.Contains("Isatap") || name.Contains("Teredo"))
continue;
var bytesSent = Convert.ToInt64(obj["BytesSentPerSec"] ?? 0);
var bytesReceived = Convert.ToInt64(obj["BytesReceivedPerSec"] ?? 0);
var timestamp = DateTime.Now;
var adapter = new NetworkAdapter
{
Name = name,
IsOperational = true
};
// Calculate speeds if we have previous data
var key = $"{name}_sent";
if (_previousNetworkBytes.ContainsKey(key) && _previousNetworkTime.ContainsKey(key))
{
var timeDiff = (timestamp - _previousNetworkTime[key]).TotalSeconds;
if (timeDiff > 0)
{
var bytesDiff = bytesSent - _previousNetworkBytes[key];
adapter.UploadSpeed = (float)(bytesDiff / timeDiff / (1024 * 1024)); // MB/s
networkUsage.UploadSpeed += adapter.UploadSpeed;
}
}
key = $"{name}_received";
if (_previousNetworkBytes.ContainsKey(key) && _previousNetworkTime.ContainsKey(key))
{
var timeDiff = (timestamp - _previousNetworkTime[key]).TotalSeconds;
if (timeDiff > 0)
{
var bytesDiff = bytesReceived - _previousNetworkBytes[key];
adapter.DownloadSpeed = (float)(bytesDiff / timeDiff / (1024 * 1024)); // MB/s
networkUsage.DownloadSpeed += adapter.DownloadSpeed;
}
}
// Store current values for next calculation
_previousNetworkBytes[$"{name}_sent"] = bytesSent;
_previousNetworkBytes[$"{name}_received"] = bytesReceived;
_previousNetworkTime[$"{name}_sent"] = timestamp;
_previousNetworkTime[$"{name}_received"] = timestamp;
networkUsage.BytesSent += (ulong)bytesSent;
networkUsage.BytesReceived += (ulong)bytesReceived;
adapters.Add(adapter);
}
#pragma warning restore CA1416 // Validate platform compatibility
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Could not get network performance data");
}
networkUsage.Adapters = adapters;
return networkUsage;
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting network usage");
return new NetworkUsage();
}
}
public async Task<List<ProcessInfo>> GetTopProcessesAsync(int count = 10) public async Task<List<ProcessInfo>> GetTopProcessesAsync(int count = 10)
{ {
try try
+7 -16
View File
@@ -41,7 +41,7 @@
<!-- Main Content --> <!-- Main Content -->
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6"> <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
<!-- Dashboard Overview --> <!-- Dashboard Overview -->
<div id="dashboard" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8"> <div id="dashboard" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
<!-- CPU Card --> <!-- CPU Card -->
<div class="bg-white rounded-lg shadow-lg p-6"> <div class="bg-white rounded-lg shadow-lg p-6">
<div class="flex items-center justify-between"> <div class="flex items-center justify-between">
@@ -93,22 +93,13 @@
<div class="w-full bg-gray-200 rounded-full h-2"> <div class="w-full bg-gray-200 rounded-full h-2">
<div id="gpuBar" class="bg-purple-600 h-2 rounded-full transition-all duration-300" style="width: 0%"></div> <div id="gpuBar" class="bg-purple-600 h-2 rounded-full transition-all duration-300" style="width: 0%"></div>
</div> </div>
</div> <div class="mt-2 flex items-center justify-between text-sm">
</div> <span class="text-gray-500">
<i class="fas fa-thermometer-half mr-1"></i>
<!-- Network Card --> <span id="gpuTemp" class="font-medium">0°C</span>
<div class="bg-white rounded-lg shadow-lg p-6"> </span>
<div class="flex items-center justify-between"> <span id="gpuTempStatus" class="text-green-600">Normal</span>
<div>
<p class="text-sm font-medium text-gray-500">Network</p>
<p id="networkSpeed" class="text-3xl font-bold text-orange-600">0 MB/s</p>
</div> </div>
<div class="bg-orange-100 p-3 rounded-full">
<i class="fas fa-network-wired text-orange-600 text-xl"></i>
</div>
</div>
<div class="mt-4">
<p id="networkDetail" class="text-sm text-gray-500">↑ 0 MB/s ↓ 0 MB/s</p>
</div> </div>
</div> </div>
</div> </div>
+64 -10
View File
@@ -228,18 +228,29 @@ class ResourceDashboard {
// Update GPU // Update GPU
if (data.gpu) { if (data.gpu) {
const gpuUsage = data.gpu.usage || 0; const gpuUsage = data.gpu.usage || 0;
const gpuTemp = data.gpu.temperature || 0;
document.getElementById('gpuUsage').textContent = `${gpuUsage.toFixed(1)}%`; document.getElementById('gpuUsage').textContent = `${gpuUsage.toFixed(1)}%`;
document.getElementById('gpuBar').style.width = `${gpuUsage}%`; document.getElementById('gpuBar').style.width = `${gpuUsage}%`;
}
// Update GPU temperature
// Update Network document.getElementById('gpuTemp').textContent = `${gpuTemp}°C`;
if (data.network) {
const bytesReceived = data.network.bytesReceived || 0; // Set temperature status color based on temperature ranges
const bytesSent = data.network.bytesSent || 0; const tempStatusElement = document.getElementById('gpuTempStatus');
const totalSpeed = (bytesReceived + bytesSent) / 1024 / 1024; if (gpuTemp <= 60) {
document.getElementById('networkSpeed').textContent = `${totalSpeed.toFixed(1)} MB/s`; tempStatusElement.textContent = 'Cool';
document.getElementById('networkDetail').textContent = tempStatusElement.className = 'text-green-600';
`${(bytesSent / 1024 / 1024).toFixed(1)} MB/s ↓ ${(bytesReceived / 1024 / 1024).toFixed(1)} MB/s`; } else if (gpuTemp <= 75) {
tempStatusElement.textContent = 'Normal';
tempStatusElement.className = 'text-yellow-600';
} else if (gpuTemp <= 85) {
tempStatusElement.textContent = 'Warm';
tempStatusElement.className = 'text-orange-600';
} else {
tempStatusElement.textContent = 'Hot';
tempStatusElement.className = 'text-red-600';
}
} }
// Update Game Detection // Update Game Detection
@@ -258,6 +269,11 @@ class ResourceDashboard {
if (data.disks && !document.getElementById('detailsSection').classList.contains('hidden')) { if (data.disks && !document.getElementById('detailsSection').classList.contains('hidden')) {
this.updateDiskUsage(data.disks); this.updateDiskUsage(data.disks);
} }
// Update System Info GPU details (only if details section is visible and we have system info)
if (!document.getElementById('detailsSection').classList.contains('hidden') && this.lastSystemInfo) {
this.updateSystemInfo(this.lastSystemInfo);
}
} catch (error) { } catch (error) {
console.error('Error updating dashboard:', error); console.error('Error updating dashboard:', error);
this.showNotification('Error updating dashboard data', 'error'); this.showNotification('Error updating dashboard data', 'error');
@@ -343,6 +359,43 @@ class ResourceDashboard {
// Store the latest system info // Store the latest system info
this.lastSystemInfo = systemInfo; this.lastSystemInfo = systemInfo;
// Get GPU info from the latest resource data if available
const gpuInfo = this.lastResourceData?.gpu;
let gpuSection = '';
if (gpuInfo && gpuInfo.isAvailable) {
gpuSection = `
<div class="bg-gray-50 p-4 rounded-lg">
<h4 class="font-semibold text-gray-700">GPU</h4>
<p class="text-gray-600">${gpuInfo.name || 'Unknown GPU'}</p>
<div class="mt-2 space-y-1">
<div class="flex justify-between text-sm">
<span class="text-gray-500">Usage:</span>
<span class="text-gray-700">${gpuInfo.usage || 0}%</span>
</div>
<div class="flex justify-between text-sm">
<span class="text-gray-500">Temperature:</span>
<span class="text-gray-700 ${gpuInfo.temperature > 85 ? 'text-red-600' : gpuInfo.temperature > 75 ? 'text-orange-600' : gpuInfo.temperature > 60 ? 'text-yellow-600' : 'text-green-600'}">${gpuInfo.temperature || 0}°C</span>
</div>
<div class="flex justify-between text-sm">
<span class="text-gray-500">Memory:</span>
<span class="text-gray-700">${gpuInfo.memoryUsed && gpuInfo.memoryTotal ? ((gpuInfo.memoryUsed / gpuInfo.memoryTotal) * 100).toFixed(1) : 0}%</span>
</div>
${gpuInfo.fanSpeed ? `
<div class="flex justify-between text-sm">
<span class="text-gray-500">Fan Speed:</span>
<span class="text-gray-700">${gpuInfo.fanSpeed}%</span>
</div>` : ''}
${gpuInfo.powerUsage ? `
<div class="flex justify-between text-sm">
<span class="text-gray-500">Power:</span>
<span class="text-gray-700">${gpuInfo.powerUsage}W</span>
</div>` : ''}
</div>
</div>
`;
}
const systemInfoDiv = document.getElementById('systemInfo'); const systemInfoDiv = document.getElementById('systemInfo');
systemInfoDiv.innerHTML = ` systemInfoDiv.innerHTML = `
<div class="bg-gray-50 p-4 rounded-lg"> <div class="bg-gray-50 p-4 rounded-lg">
@@ -369,6 +422,7 @@ class ResourceDashboard {
<h4 class="font-semibold text-gray-700">Uptime</h4> <h4 class="font-semibold text-gray-700">Uptime</h4>
<p class="text-gray-600">${systemInfo.uptime ? this.formatUptime(systemInfo.uptime) : 'N/A'}</p> <p class="text-gray-600">${systemInfo.uptime ? this.formatUptime(systemInfo.uptime) : 'N/A'}</p>
</div> </div>
${gpuSection}
`; `;
} }