Implementation of the 1 hour budgeting system.

This commit is contained in:
2026-06-09 08:07:45 +02:00
parent c5b9036644
commit d3493f50d1
2 changed files with 297 additions and 55 deletions

101
server.py
View File

@ -4,7 +4,7 @@
import json
from http.server import HTTPServer, BaseHTTPRequestHandler
from devices import shutdown_all
from devices import shutdown_all, status_all, _set_budget, _get_budget, BUDGET_SECONDS, TICK_INTERVAL
class Handler(BaseHTTPRequestHandler):
@ -14,10 +14,18 @@ class Handler(BaseHTTPRequestHandler):
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(HTML.encode())
elif self.path == "/status":
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(status_all()).encode())
else:
self.send_error(404)
def do_POST(self):
content_length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(content_length).decode() if content_length > 0 else ""
if self.path == "/run":
try:
actions = shutdown_all()
@ -30,6 +38,24 @@ class Handler(BaseHTTPRequestHandler):
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps({"status": status, "actions": actions}).encode())
elif self.path == "/budget":
try:
data = json.loads(body) if body else {}
dev_id = data.get("device", "")
delta = int(data.get("delta", 0))
current = _get_budget(dev_id)
new_budget = max(0, min(BUDGET_SECONDS, current + delta))
_set_budget(dev_id, new_budget)
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps({"status": "ok"}).encode())
except Exception as e:
self.send_response(400)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps({"status": "error", "detail": str(e)}).encode())
else:
self.send_error(404)
@ -77,12 +103,39 @@ HTML = """\
.action-item .info { flex: 1; }
.action-item .title { font-weight: 600; font-size: .95rem; }
.action-item .detail { color: #aaa; font-size: .82rem; margin-top: .15rem; }
#status {
margin-bottom: 2rem;
}
.status-item {
display: flex; align-items: center;
padding: .4rem .75rem; margin-bottom: .3rem;
border-radius: 6px; background: #0f3460; font-size: .8rem;
gap: .5rem;
}
.status-item .center {
display: flex; align-items: center; gap: .5rem;
flex: 1; min-width: 0;
}
.status-item .icon { font-size: 1.1rem; flex-shrink: 0; }
.status-item .name { font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.status-item .budget { color: #aaa; font-size: .75rem; margin-left: auto; flex-shrink: 0; }
.status-item .actions {
display: flex; align-items: center; gap: .25rem;
flex-shrink: 0;
}
.budget-icon {
background: none; border: none;
color: #666; font-size: 1rem; cursor: pointer;
padding: 0; line-height: 1; transition: .15s;
}
.budget-icon:hover { color: #fff; }
</style>
</head>
<body>
<div class="card">
<h1>📺 Kids Devices</h1>
<p>TV + Gabi's computer + Gaja's computer</p>
<div id="status"></div>
<button id="btn" onclick="run()">TURN OFF</button>
<div id="output"></div>
</div>
@ -120,13 +173,57 @@ HTML = """\
btn.disabled = false;
btn.textContent = 'TURN OFF';
}
async function refreshStatus() {
try {
const res = await fetch('https://noom.cc/off/status');
const data = await res.json();
document.getElementById('status').innerHTML = data.map(s => {
const devId = s.title === 'TV' ? 'tv' : s.title.includes("Gabi") ? 'gabi' : 'gaja';
return `<div class="status-item">
<span class="center">
<span class="icon">${s.icon}</span>
<span class="name">${s.title}</span>
<span class="budget">${s.detail}</span>
</span>
<span class="actions">
<button class="budget-icon" onclick="adjustBudget('${devId}', -300)"></button>
<button class="budget-icon" onclick="adjustBudget('${devId}', 300)">+</button>
</span>
</div>`;
}).join('');
} catch(e) {
// Ignore status errors
}
}
async function adjustBudget(device, delta) {
try {
await fetch('https://noom.cc/off/budget', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({device, delta})
});
} catch(e) {}
refreshStatus();
}
refreshStatus();
setInterval(refreshStatus, 60000);
</script>
</body>
</html>
"""
if __name__ == "__main__":
from devices import start_timer
port = int(__import__("os").environ.get("PORT", "10000"))
start_timer()
server = HTTPServer(("0.0.0.0", port), Handler)
print(f"🚀 Open http://localhost:{port}")
server.serve_forever()
print(f"⏱️ Budget timer running (checks every {TICK_INTERVAL}s, reset at 7:00 AM)")
try:
server.serve_forever()
except KeyboardInterrupt:
from devices import stop_timer
stop_timer()