using System; using System.Diagnostics; using System.Management; using System.Threading.Tasks; namespace PCMonitor { /// /// Monitor Informasi Sistem PC /// public class SystemInfoMonitor : IDisposable { private readonly ApiClient apiClient; private readonly ILog logger = new FileLogger(); public SystemInfoMonitor(ApiClient client) { apiClient = client; } public async Task CollectAsync() { try { var systemInfo = GetSystemInfo(); await apiClient.SendAsync("system-info", "POST", systemInfo); } catch (Exception ex) { logger.Error($"Error collecting system info: {ex.Message}"); } } private dynamic GetSystemInfo() { var totalVisibleMemory = GetTotalMemory(); var availableMemory = GetAvailableMemory(); var usedMemory = totalVisibleMemory - availableMemory; var driveInfo = new System.IO.DriveInfo("C"); return new { cpu_name = GetCpuName(), cpu_cores = Environment.ProcessorCount, cpu_usage = GetCpuUsage(), memory_total = totalVisibleMemory, memory_used = usedMemory, disk_total = driveInfo.TotalSize / 1024 / 1024 / 1024, // GB disk_used = (driveInfo.TotalSize - driveInfo.AvailableFreeSpace) / 1024 / 1024 / 1024, // GB os_name = Environment.OSVersion.Platform.ToString(), os_version = Environment.OSVersion.VersionString, last_boot = DateTime.UtcNow.AddMilliseconds(-Environment.TickCount), updated_at = DateTime.Now }; } private string GetCpuName() { try { var searcher = new System.Management.ManagementObjectSearcher("SELECT Name FROM Win32_Processor"); foreach (var obj in searcher.Get()) { return obj["Name"].ToString(); } } catch { } return "Unknown CPU"; } private double GetCpuUsage() { try { var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true); cpuCounter.NextValue(); return Math.Round(cpuCounter.NextValue(), 2); } catch { return 0; } } private long GetTotalMemory() { try { var wmiObject = new System.Management.ManagementObject("Win32_ComputerSystem"); return long.Parse(wmiObject["TotalPhysicalMemory"].ToString()) / 1024 / 1024; // MB } catch { return 0; } } private long GetAvailableMemory() { try { var wmiObject = new System.Management.ManagementClass("Win32_OperatingSystem"); var instances = wmiObject.GetInstances(); foreach (var instance in instances) { return long.Parse(instance["FreePhysicalMemory"].ToString()) / 1024; // MB } } catch { } return 0; } public void Dispose() { } } }