Files
wikipedia/HomeLab/Hermes/oled_cpu_mon.py
T

74 lines
2.4 KiB
Python

import time, os
from luma.core.interface.serial import i2c
from luma.oled.device import ssd1306
from PIL import Image, ImageDraw, ImageFont
serial = i2c(port=1, address=0x3C)
device = ssd1306(serial)
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 10)
font_big = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 16)
device.cleanup = lambda: None
def get_cpu():
with open('/proc/loadavg') as f:
parts = f.read().split()
load = float(parts[0])
cores = os.cpu_count() or 4
percent = (load / cores) * 100
return min(percent, 100), load
def get_ram():
with open('/proc/meminfo') as f:
lines = f.readlines()
mem_total = int([l for l in lines if 'MemTotal' in l][0].split()[1])
mem_avail = int([l for l in lines if 'MemAvailable' in l][0].split()[1])
used = mem_total - mem_avail
return used / mem_total * 100, used // 1024, mem_total // 1024
def get_temp():
try:
with open('/sys/class/thermal/thermal_zone0/temp') as f:
return int(f.read()) / 1000
except:
return 0
while True:
cpu_pct, load = get_cpu()
ram_pct, used_mb, total_mb = get_ram()
temp = get_temp()
img = Image.new('1', device.size, 'black')
draw = ImageDraw.Draw(img)
draw.rectangle((0, 0, 127, 63), outline='white', fill='black')
bar_w = 90
bar_h = 12
# CPU bar
draw.rectangle((32, 4, 32 + bar_w, 4 + bar_h), outline='white', fill='black')
fill_w = int(bar_w * cpu_pct / 100)
if fill_w > 0:
draw.rectangle((32 + 1, 4 + 1, 32 + fill_w, 4 + bar_h - 1), fill='white')
draw.text((2, 5), 'CPU', font=font, fill='white')
draw.text((32 + bar_w + 4, 3), f'{cpu_pct:.0f}%', font=font_big, fill='white')
draw.text((2, 20), f'Load: {load:.2f}', font=font, fill='white')
# RAM bar
draw.rectangle((32, 36, 32 + bar_w, 36 + bar_h), outline='white', fill='black')
fill_w2 = int(bar_w * ram_pct / 100)
if fill_w2 > 0:
draw.rectangle((32 + 1, 36 + 1, 32 + fill_w2, 36 + bar_h - 1), fill='white')
draw.text((2, 38), 'RAM', font=font, fill='white')
draw.text((32 + bar_w + 4, 36), f'{ram_pct:.0f}%', font=font_big, fill='white')
# Temp and PID at bottom
draw.text((2, 52), f'Temp: {temp:.1f}C', font=font, fill='white')
draw.text((72, 52), f'PID: {os.getpid()}', font=font, fill='white')
device.display(img)
time.sleep(1)