buba/buba/animations/spaceapi.py
Stefan Bethke 64a3c729be Refactor Animation to simplify
Also add some documentation on how to write animations.
2025-06-16 09:33:22 +02:00

54 lines
1.8 KiB
Python

import json
import logging
from datetime import datetime
from threading import Thread
from time import sleep
import requests
from buba.bubaanimation import BubaAnimation
from buba.bubacmd import BubaCmd
class Spaceapi(BubaAnimation):
def __init__(self, buba, url, title):
super().__init__(buba)
self.url = url
self.title = title
def update(self):
res = requests.get(self.url)
data = json.loads(res.text)
open = "open" if data["state"]["open"] else "closed"
since = datetime.fromtimestamp(data["state"]["lastchange"]).astimezone()
temp = int(data["sensors"]["temperature"][0]["value"])
hum = int(data["sensors"]["humidity"][0]["value"])
printers = {}
for p in data["sensors"]["ext_3d_printer_busy_state"]:
printers[p["name"]] = {
"busy": p["value"] != 0,
}
for p in data["sensors"]["ext_3d_printer_minutes_remaining"]:
printers[p["name"]]["remaining"] = p["value"]
printstatus = []
for n, p in sorted(printers.items()):
if p["busy"]:
printstatus.append(f"{n} {p['remaining']}m left")
else:
printstatus.append(f"{n} idle")
self.rows = [
[f"CCCHH {open} {self.humanize(since)}"],
[f"Outside: {temp}°C at {hum}% rel.hum."],
[", ".join(printstatus)]
]
def humanize(self, dt):
td = dt - datetime.now().astimezone()
if td.total_seconds() > -60:
return "just now"
if td.total_seconds() > -3600:
return f"for {-int(td.total_seconds()/60)} minutes"
if td.total_seconds() >- 86400:
return f"for {-int(td.total_seconds()/3600)} hours"
return dt.strftime("since %y-%m-%d %H:%M")