Initial commit with webpage
This commit is contained in:
commit
26875de1dd
55 files changed
+5726
No files matched your search
@@ -0,0 +1,136 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Pretend to be a Mamadachi. Standard library only, so it runs anywhere.
|
||||
|
||||
It keeps a queue file like the real firmware keeps flash: presses wait there
|
||||
until a sync succeeds, and are only deleted on HTTP 200.
|
||||
|
||||
python tools/fake_device.py press 6 # queue a press of button 6 (offline)
|
||||
python tools/fake_device.py press 4 --ago 30 # ...that happened 30 min ago
|
||||
python tools/fake_device.py --token mmd_... sync # upload the queue to a local server
|
||||
python tools/fake_device.py --url https://your-app.onrender.com --token mmd_... sync
|
||||
python tools/fake_device.py --token mmd_... sync --clock-off 3600 # RTC 1 h slow
|
||||
python tools/fake_device.py --token mmd_... status # what the e-paper would show
|
||||
|
||||
URL and token can also come from MAMADACHI_URL / MAMADACHI_TOKEN.
|
||||
The default URL is http://127.0.0.1:8000 (on Windows, "localhost" adds a 2 s IPv6 delay).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
STATE = Path(__file__).with_name(".fake_device_state.json")
|
||||
|
||||
|
||||
def load() -> dict:
|
||||
if STATE.exists():
|
||||
return json.loads(STATE.read_text())
|
||||
return {"seq": 0, "queue": [], "boots": 1}
|
||||
|
||||
|
||||
def save(state: dict) -> None:
|
||||
STATE.write_text(json.dumps(state, indent=2))
|
||||
|
||||
|
||||
def post(url: str, token: str, body: dict) -> tuple[int, dict]:
|
||||
req = urllib.request.Request(
|
||||
url.rstrip("/") + "/api/v1/device/sync",
|
||||
data=json.dumps(body).encode(),
|
||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as r:
|
||||
return r.status, json.loads(r.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read() or b"{}")
|
||||
|
||||
|
||||
def show_status(resp: dict) -> None:
|
||||
now = resp["server_time"]
|
||||
s = resp["status"]
|
||||
|
||||
def ago(t: int) -> str:
|
||||
m = (now - t) // 60
|
||||
return f"{m // 60}h {m % 60:02d}m ago" if m >= 60 else f"{m}m ago"
|
||||
|
||||
print(f" {s['baby_name']}")
|
||||
if s["last_feed"]:
|
||||
side = f" next: {s['next_side']}" if s["next_side"] else ""
|
||||
print(f" Fed {ago(s['last_feed']['time'])} ({s['last_feed']['short']}){side}")
|
||||
for o in s["open"]:
|
||||
print(f" {o['short']} since {ago(o['since'])}")
|
||||
t = s["today"]
|
||||
print(f" Today: {t['feeds']} feeds, {t['wet']} wet, {t['dirty']} dirty, {t['sleep_min'] // 60}h{t['sleep_min'] % 60:02d} sleep")
|
||||
print(" Buttons: " + " ".join(f"{b['button']}={b['short']}" for b in resp["buttons"]))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument("--url", default=os.environ.get("MAMADACHI_URL", "http://127.0.0.1:8000"))
|
||||
p.add_argument("--token", default=os.environ.get("MAMADACHI_TOKEN"))
|
||||
sub = p.add_subparsers(dest="cmd", required=True)
|
||||
pr = sub.add_parser("press", help="queue a button press")
|
||||
pr.add_argument("button", type=int, help="1-8")
|
||||
pr.add_argument("--ago", type=float, default=0, help="minutes ago")
|
||||
sy = sub.add_parser("sync", help="upload the queue")
|
||||
sy.add_argument("--clock-off", type=int, default=0, help="seconds the RTC is behind (simulate drift)")
|
||||
sy.add_argument("--battery", type=int, default=3950, help="mV")
|
||||
sub.add_parser("status", help="sync with an empty queue and print what the display would show")
|
||||
sub.add_parser("forget", help="delete the local queue/state file")
|
||||
args = p.parse_args()
|
||||
|
||||
state = load()
|
||||
if args.cmd == "forget":
|
||||
STATE.unlink(missing_ok=True)
|
||||
print("State cleared.")
|
||||
return 0
|
||||
if args.cmd == "press":
|
||||
state["seq"] += 1
|
||||
state["queue"].append({"seq": state["seq"], "time": int(time.time() - args.ago * 60), "button": args.button})
|
||||
save(state)
|
||||
print(f"Queued press #{state['seq']} (button {args.button}). {len(state['queue'])} waiting; run 'sync'.")
|
||||
return 0
|
||||
|
||||
if not args.token:
|
||||
print("Need --token (or MAMADACHI_TOKEN). Create one on the dashboard's Device page.", file=sys.stderr)
|
||||
return 2
|
||||
batch = state["queue"][:500] if args.cmd == "sync" else []
|
||||
clock_off = getattr(args, "clock_off", 0)
|
||||
body = {
|
||||
"device_time": int(time.time()) - clock_off,
|
||||
"firmware": "fake-0.1",
|
||||
"battery_mv": getattr(args, "battery", 3950),
|
||||
"charging": False,
|
||||
"rssi": -60,
|
||||
"boot_count": state["boots"],
|
||||
"queue_len": len(state["queue"]) - len(batch),
|
||||
"events": [dict(e, time=e["time"] - clock_off) for e in batch],
|
||||
}
|
||||
t0 = time.time()
|
||||
try:
|
||||
status, resp = post(args.url, args.token, body)
|
||||
except OSError as e:
|
||||
print(f"Network error, keeping {len(batch)} presses queued: {e}", file=sys.stderr)
|
||||
return 1
|
||||
ms = (time.time() - t0) * 1000
|
||||
if status != 200:
|
||||
print(f"HTTP {status}, keeping {len(batch)} presses queued: {resp.get('detail')}", file=sys.stderr)
|
||||
return 1
|
||||
# HTTP 200: the server has everything we sent. Now (and only now) delete it.
|
||||
sent = {(e["seq"], e["time"]) for e in batch}
|
||||
state["queue"] = [e for e in state["queue"] if (e["seq"], e["time"]) not in sent]
|
||||
save(state)
|
||||
print(f"HTTP 200 in {ms:.0f} ms: {resp['stored']} new, {resp['duplicates']} already known."
|
||||
f" Clock skew {resp['clock_skew_s']} s{' (corrected)' if resp['clock_corrected'] else ''}.")
|
||||
show_status(resp)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user