Files
deploy.stack/i2c.py/status.py

95 lines
2.3 KiB
Python
Raw Normal View History

import signal
2024-03-05 16:10:20 +08:00
import subprocess
import time
2024-03-05 16:10:20 +08:00
import adafruit_ssd1306
2024-03-05 16:10:20 +08:00
import busio
from board import SCL, SDA
2024-03-05 16:10:20 +08:00
from PIL import Image, ImageDraw, ImageFont
DISPLAY_WIDTH = 128
DISPLAY_HEIGHT = 64
SYSTEM_INFO_INTERVAL = 2.0
DISPLAY_REFRESH_INTERVAL = 0.1
FONT_PATH = '/usr/share/fonts/truetype/wqy/wqy-microhei.ttc'
FONT_SIZE_SMALL = 11
FONT_SIZE_DATE = 16
LINE_HEIGHT = 12
2024-03-05 16:10:20 +08:00
i2c = busio.I2C(SCL, SDA)
disp = adafruit_ssd1306.SSD1306_I2C(DISPLAY_WIDTH, DISPLAY_HEIGHT, i2c)
2024-03-05 16:10:20 +08:00
disp.fill(0)
disp.show()
image = Image.new("1", (DISPLAY_WIDTH, DISPLAY_HEIGHT))
2024-03-05 16:10:20 +08:00
draw = ImageDraw.Draw(image)
def load_font(path: str, size: int):
try:
return ImageFont.truetype(path, size)
except OSError:
return ImageFont.load_default()
font = load_font(FONT_PATH, FONT_SIZE_SMALL)
font_date = load_font(FONT_PATH, FONT_SIZE_DATE)
running = True
def signal_handler(signum, frame):
global running
running = False
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
def run_command(cmd: str) -> str:
try:
result = subprocess.check_output(cmd, shell=True, stderr=subprocess.DEVNULL)
return result.decode("utf-8").strip()
except subprocess.CalledProcessError:
return "N/A"
def get_system_info():
ip = run_command("hostname -I | cut -d' ' -f1")
cpu = run_command('cut -f 1 -d " " /proc/loadavg')
mem = run_command("free -m | awk 'NR==2{printf \"Mem: %s/%s MB %.2f%%\", $3,$2,$3*100/$2 }'")
disk = run_command('df -h | awk \'$NF=="/data"{printf "Disk: %d/%d GB %s", $3,$2,$5}\'')
return ip, cpu, mem, disk
def draw_text(line: int, text: str, font_obj=font):
y = line * LINE_HEIGHT
draw.text((0, y), text, font=font_obj, fill=255)
ip, cpu, mem, disk = get_system_info()
last_info_time = time.time()
while running:
current_time = time.time()
if current_time - last_info_time >= SYSTEM_INFO_INTERVAL:
ip, cpu, mem, disk = get_system_info()
last_info_time = current_time
draw.rectangle((0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT), outline=0, fill=0)
draw_text(0, f"IP: {ip}")
draw_text(1, f"CPU: {cpu}")
draw_text(2, mem)
draw_text(3, disk)
draw_text(4, time.strftime("%Y-%m-%d, %H:%M:%S"), font_date)
2024-03-05 16:10:20 +08:00
disp.image(image)
disp.show()
time.sleep(DISPLAY_REFRESH_INTERVAL)
disp.fill(0)
disp.show()