67 lines
1.9 KiB
Python
Executable File
67 lines
1.9 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
from time import sleep
|
|
import subprocess
|
|
import json
|
|
|
|
def static(**kwargs):
|
|
def decorate(func):
|
|
for k in kwargs:
|
|
setattr(func, k, kwargs[k])
|
|
return func
|
|
return decorate
|
|
|
|
@static(idle = 0, total = 0)
|
|
def cpu_util():
|
|
with open('/proc/stat') as file:
|
|
fields = [float(column) for column in file.readline().strip().split()[1:]]
|
|
idle = fields[3]
|
|
total = sum(fields)
|
|
idle_delta = idle - cpu_util.idle
|
|
total_delta = total - cpu_util.total
|
|
utilization = 100 * (1 - idle_delta / total_delta)
|
|
cpu_util.idle = idle
|
|
cpu_util.total = total
|
|
return f"{int(utilization):2}"
|
|
|
|
def wifi():
|
|
ssid_cmd = subprocess.run(['iwgetid', '-r'], capture_output = True)
|
|
if ssid_cmd.returncode != 0:
|
|
return {"connected": False, "ssid": ""}
|
|
return {"connected": True, "ssid": ssid_cmd.stdout.decode('utf-8').strip()}
|
|
|
|
def netdev(device: str):
|
|
ip_cmd = subprocess.run(['ip', '-j', 'addr', 'show', device], capture_output = True)
|
|
if ip_cmd.returncode != 0:
|
|
return {"exists": False}
|
|
ip_data = json.loads(ip_cmd.stdout.decode('utf-8'))[0]
|
|
online = ip_data["operstate"] == "UP"
|
|
ip4_addr = ""
|
|
ip4_prefix_length = 24
|
|
addr4_info = list(filter(lambda addr: addr.get("family") == "inet", ip_data["addr_info"]))
|
|
if len(addr4_info) >= 1:
|
|
ip4_addr = addr4_info[0]["local"]
|
|
ip4_prefix_length = addr4_info[0]["prefixlen"]
|
|
connecting = ip_data["operstate"] != "DOWN" and (ip4_addr == "" or not online)
|
|
return {
|
|
"exists": True,
|
|
"online": online,
|
|
"connecting": connecting,
|
|
"ip4_addr": ip4_addr,
|
|
"ip4_prefix": ip4_prefix_length
|
|
}
|
|
|
|
# Prime cpu_util() with starting values
|
|
cpu_util()
|
|
sleep(0.1)
|
|
|
|
while True:
|
|
result = {
|
|
"cpu": cpu_util(),
|
|
"network": {
|
|
"br0": netdev("br0")
|
|
}
|
|
}
|
|
print(json.dumps(result), flush=True)
|
|
sleep(1)
|