Thought it’d be nice to learn a little about Python so I bought a Unicorn HAT. Here’s my first attempt at doing something with it - a graphical representation of the system status. As coded, it requires the latest version of the psutil python library (https://github.com/giampaolo/psutil) - the one included in Raspbian is a little out of date and lacks certain functionality (thus providing good experience in learning how to install and manage python libraries).
It provides a measure of CPU load (user, system and overall), memory usage (virtual and swap) and disk usage (root and one other). The last row is still a work in progress (it’ll be used for monitoring specific processes) - have removed the code for now.
As I said earlier, I’m new to python and am aware that my coding could improve. Any advice would be greatly appreciated.
Well, here’s the code (status.py):
#!/usr/bin/env python
import unicornhat as unicorn
import time
import psutil
unicorn.brightness(0.35)
# Set orientation - Legend at bottom
unicorn.rotation(270)
# Function get_rgb(name) - returns tuple containing RGB values
def get_rgb(name):
# Define colors
_rgb = {"red": [255,0,0],
"orange": [255,165,0],
"yellow": [255,255,0],
"green": [0,128,0],
"blue": [0,0,255],
"indigo": [75,0,130],
"violet": [238,130,238],
"white": [255,255,255],
"black": [0,0,0]
}
return _rgb[name]
# Main
# x is (0,7) from left to right
# y is (0,7) from top to bottom
# Set default background colors, row-by-row
default_bg=["black","blue","blue","indigo","indigo","green","green","green"]
while True:
for y in range(8):
rgb = get_rgb(default_bg[y])
for x in range(8):
unicorn.set_pixel(x,y,rgb[0],rgb[1],rgb[2])
# Row 7 thro 5: CPU Load (user/system/idle)
cpu = psutil.cpu_times_percent(1)
for x in range(8):
if round(cpu.user*8.0/100.0) > x:
unicorn.set_pixel(x,7,255,0,0)
else:
break
for x in range(8):
if round(cpu.system*8.0/100.0) > x:
unicorn.set_pixel(x,6,255,0,0)
else:
break
for x in range(8):
if round((100.0-cpu.idle)*8.0/100.0) > x:
unicorn.set_pixel(x,5,255,0,0)
else:
break
# Row 4: Swap memory
swap = psutil.swap_memory().percent
for x in range(8):
if round(swap*8.0/100.0) > x:
unicorn.set_pixel(x,4,255,0,0)
else:
break
# Row 3: Virtual memory
virtual = psutil.virtual_memory().percent
for x in range(8):
if round(virtual*8.0/100.0) > x:
unicorn.set_pixel(x,3,255,0,0)
else:
break
# Row 2 & 1: /mnt/public & /
partitions = psutil.disk_partitions()
for partition in partitions:
if partition.mountpoint == "/mnt/public":
for x in range(8):
if round(psutil.disk_usage(partition.mountpoint).percent*8.0/100.0) > x:
unicorn.set_pixel(x,2,255,0,0)
else:
break
elif partition.mountpoint == "/":
for x in range(8):
if round(psutil.disk_usage(partition.mountpoint).percent*8.0/100.0) > x:
unicorn.set_pixel(x,1,255,0,0)
else:
break
unicorn.show()