XscarfX

Monitor Code

Oct 24th, 2024
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.18 KB | None | 0 0
  1. import ctypes
  2. import os
  3. import sys
  4. import time
  5. import serial
  6. import serial.tools.list_ports
  7. import psutil
  8. import subprocess
  9. from ctypes import wintypes, windll, c_size_t
  10.  
  11. def is_admin():
  12. try:
  13. return ctypes.windll.shell32.IsUserAnAdmin()
  14. except:
  15. return False
  16.  
  17. class MSIAfterburner:
  18. def __init__(self):
  19. self.PROCESS_VM_READ = 0x0010
  20. self.INVALID_HANDLE_VALUE = -1
  21.  
  22. self.kernel32 = windll.kernel32
  23. self.process_handle = None
  24. self.find_afterburner()
  25.  
  26. def find_afterburner(self):
  27. try:
  28. for proc in psutil.process_iter(['pid', 'name']):
  29. if 'MSIAfterburner.exe' in proc.info['name']:
  30. self.process_handle = self.kernel32.OpenProcess(
  31. self.PROCESS_VM_READ,
  32. False,
  33. proc.info['pid']
  34. )
  35. if self.process_handle:
  36. print("Successfully connected to MSI Afterburner")
  37. return
  38. print("MSI Afterburner process not found")
  39. except Exception as e:
  40. print(f"Error finding MSI Afterburner: {e}")
  41.  
  42. def read_memory(self, address, size):
  43. buffer = ctypes.create_string_buffer(size)
  44. bytes_read = c_size_t()
  45.  
  46. if self.kernel32.ReadProcessMemory(
  47. self.process_handle,
  48. address,
  49. buffer,
  50. size,
  51. ctypes.byref(bytes_read)
  52. ):
  53. return buffer.raw
  54. return None
  55.  
  56. def get_fps(self):
  57. try:
  58. if not self.process_handle:
  59. return 0
  60.  
  61. potential_offsets = [0x1234, 0x2345, 0x3456] # Example offsets
  62.  
  63. for base_offset in potential_offsets:
  64. data = self.read_memory(base_offset, 4)
  65. if data:
  66. value = struct.unpack('f', data)[0]
  67. if 0 <= value <= 1000: # Valid FPS range
  68. return value
  69. return 0
  70.  
  71. except Exception as e:
  72. print(f"Error reading FPS: {e}")
  73. return 0
  74.  
  75. def close(self):
  76. if self.process_handle:
  77. self.kernel32.CloseHandle(self.process_handle)
  78.  
  79. class GPUMonitor:
  80. def __init__(self):
  81. try:
  82. result = subprocess.run(['nvidia-smi', '--query-gpu=temperature.gpu,utilization.gpu', '--format=csv,noheader,nounits'],
  83. capture_output=True, text=True)
  84. print("GPU monitoring initialized")
  85. self.has_gpu = True
  86. except Exception as e:
  87. print(f"Error initializing GPU monitoring: {e}")
  88. self.has_gpu = False
  89.  
  90. def get_gpu_stats(self):
  91. try:
  92. if not self.has_gpu:
  93. return 0.0, 0.0
  94.  
  95. result = subprocess.run(['nvidia-smi',
  96. '--query-gpu=temperature.gpu,utilization.gpu',
  97. '--format=csv,noheader,nounits'],
  98. capture_output=True, text=True)
  99.  
  100. if result.returncode == 0:
  101. temp, usage = map(float, result.stdout.strip().split(', '))
  102. return float(temp), float(usage)
  103.  
  104. except Exception as e:
  105. print(f"Error reading GPU stats: {e}")
  106.  
  107. return 0.0, 0.0
  108.  
  109. def find_esp32_port():
  110. ports = list(serial.tools.list_ports.comports())
  111. for port in ports:
  112. if "Silicon Labs" in port.description or "CP210x" in port.description:
  113. return port.device
  114. return None
  115.  
  116. def main():
  117. print("Initializing monitoring...")
  118. print("Please ensure MSI Afterburner is running and showing FPS")
  119.  
  120. gpu_monitor = GPUMonitor()
  121. msi = MSIAfterburner()
  122.  
  123. port = find_esp32_port()
  124. if not port:
  125. print("Could not find ESP32 port automatically.")
  126. port = input("Please enter COM port manually (e.g., COM3): ")
  127.  
  128. ser = None
  129. try:
  130. ser = serial.Serial(port, 115200, timeout=1)
  131. print("Monitoring started. Press Ctrl+C to exit.")
  132.  
  133. fps_values = []
  134.  
  135. while True:
  136. try:
  137. gpu_temp, gpu_usage = gpu_monitor.get_gpu_stats()
  138. ram_used = psutil.virtual_memory().used / (1024 * 1024)
  139. cpu_usage = psutil.cpu_percent()
  140. current_fps = float(msi.get_fps())
  141.  
  142. # Update FPS averaging
  143. fps_values.append(current_fps)
  144. fps_values = fps_values[-5:] # Keep last 5 FPS values
  145. avg_fps = sum(fps_values) / len(fps_values) if fps_values else 0.0
  146.  
  147. # Format and display
  148. print("\nCurrent PC Performance:")
  149. print("-----------------------")
  150. print(f"3070TI Temperature: {gpu_temp:.1f}°C")
  151. print(f"3070TI Usage: {gpu_usage:.1f}%")
  152. print(f"RAM Usage: {ram_used:.0f}MB")
  153. print(f"CPU Usage: {cpu_usage:.1f}%")
  154. print(f"Framerate: {int(avg_fps)}FPS")
  155.  
  156. # Send to ESP32
  157. data_str = f"{gpu_temp:.1f},{gpu_usage:.1f},{ram_used:.0f},{cpu_usage:.1f},{int(avg_fps)}\n"
  158. ser.write(data_str.encode())
  159.  
  160. time.sleep(1)
  161.  
  162. except KeyboardInterrupt:
  163. print("\nExiting...")
  164. break
  165. except Exception as e:
  166. print(f"Error: {e}")
  167. time.sleep(1)
  168.  
  169. except serial.SerialException as e:
  170. print(f"\nSerial port error: {e}")
  171. print("1. Make sure the Arduino IDE Serial Monitor is closed")
  172. print("2. Verify the correct COM port is selected")
  173.  
  174. finally:
  175. if ser is not None and ser.is_open:
  176. ser.close()
  177. msi.close()
  178.  
  179. if __name__ == "__main__":
  180. if not is_admin():
  181. ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
  182. sys.exit(0)
  183.  
  184. main()
  185.  
Advertisement
Add Comment
Please, Sign In to add comment