From 431ce1c8d0a14a24ee85e843126ee4a75878d1c4 Mon Sep 17 00:00:00 2001 From: Johan Lundberg Date: Thu, 1 May 2025 20:41:53 +0200 Subject: [PATCH] add make command make reformat reformat python files with black --- Makefile | 2 ++ db.py | 84 +++++++++++++++++++++++++++++++++----------------------- main.py | 54 ++++++++++++++++++++---------------- 3 files changed, 82 insertions(+), 58 deletions(-) create mode 100644 Makefile diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..1358d3a3 --- /dev/null +++ b/Makefile @@ -0,0 +1,2 @@ +reformat: + black *py diff --git a/db.py b/db.py index a05c2fbf..91e97369 100644 --- a/db.py +++ b/db.py @@ -3,13 +3,15 @@ from typing import Dict DB_FILE = "dereth.db" + def init_db() -> None: """Create tables if they do not exist (extended with kills_per_hour and onlinetime).""" conn = sqlite3.connect(DB_FILE) c = conn.cursor() # History log - c.execute(""" + c.execute( + """ CREATE TABLE IF NOT EXISTS telemetry_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, character_name TEXT NOT NULL, @@ -27,10 +29,12 @@ def init_db() -> None: prismatic_taper_count INTEGER, vt_state TEXT ) - """) + """ + ) # Live snapshot (upsert) - c.execute(""" + c.execute( + """ CREATE TABLE IF NOT EXISTS live_state ( character_name TEXT PRIMARY KEY, char_tag TEXT, @@ -47,41 +51,49 @@ def init_db() -> None: prismatic_taper_count INTEGER, vt_state TEXT ) - """) + """ + ) conn.commit() conn.close() + def save_snapshot(data: Dict) -> None: """Insert snapshot into history and upsert into live_state (with new fields).""" conn = sqlite3.connect(DB_FILE) c = conn.cursor() # Insert full history row - c.execute(""" + c.execute( + """ INSERT INTO telemetry_log ( character_name, char_tag, session_id, timestamp, ew, ns, z, kills, kills_per_hour, onlinetime, deaths, rares_found, prismatic_taper_count, vt_state ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - """, ( - data["character_name"], - data.get("char_tag", ""), - data["session_id"], - data["timestamp"], - data["ew"], data["ns"], data.get("z", 0.0), - data["kills"], - data.get("kills_per_hour", ""), - data.get("onlinetime", ""), - data.get("deaths", 0), - data.get("rares_found", 0), - data.get("prismatic_taper_count", 0), - data.get("vt_state", "Unknown"), - )) + """, + ( + data["character_name"], + data.get("char_tag", ""), + data["session_id"], + data["timestamp"], + data["ew"], + data["ns"], + data.get("z", 0.0), + data["kills"], + data.get("kills_per_hour", ""), + data.get("onlinetime", ""), + data.get("deaths", 0), + data.get("rares_found", 0), + data.get("prismatic_taper_count", 0), + data.get("vt_state", "Unknown"), + ), + ) # Upsert into live_state - c.execute(""" + c.execute( + """ INSERT INTO live_state ( character_name, char_tag, session_id, timestamp, ew, ns, z, @@ -102,20 +114,24 @@ def save_snapshot(data: Dict) -> None: rares_found = excluded.rares_found, prismatic_taper_count = excluded.prismatic_taper_count, vt_state = excluded.vt_state - """, ( - data["character_name"], - data.get("char_tag", ""), - data["session_id"], - data["timestamp"], - data["ew"], data["ns"], data.get("z", 0.0), - data["kills"], - data.get("kills_per_hour", ""), - data.get("onlinetime", ""), - data.get("deaths", 0), - data.get("rares_found", 0), - data.get("prismatic_taper_count", 0), - data.get("vt_state", "Unknown"), - )) + """, + ( + data["character_name"], + data.get("char_tag", ""), + data["session_id"], + data["timestamp"], + data["ew"], + data["ns"], + data.get("z", 0.0), + data["kills"], + data.get("kills_per_hour", ""), + data.get("onlinetime", ""), + data.get("deaths", 0), + data.get("rares_found", 0), + data.get("prismatic_taper_count", 0), + data.get("vt_state", "Unknown"), + ), + ) conn.commit() conn.close() diff --git a/main.py b/main.py index eb841192..0892dcd8 100644 --- a/main.py +++ b/main.py @@ -19,9 +19,10 @@ app = FastAPI() live_snapshots: Dict[str, dict] = {} SHARED_SECRET = "your_shared_secret" -#LOG_FILE = "telemetry_log.jsonl" +# LOG_FILE = "telemetry_log.jsonl" # ------------------------------------------------------------------ -ACTIVE_WINDOW = timedelta(seconds=30) # player is “online” if seen in last 30 s +ACTIVE_WINDOW = timedelta(seconds=30) # player is “online” if seen in last 30 s + class TelemetrySnapshot(BaseModel): character_name: str @@ -29,9 +30,9 @@ class TelemetrySnapshot(BaseModel): session_id: str timestamp: datetime - ew: float # +E / –W - ns: float # +N / –S - z: float + ew: float # +E / –W + ns: float # +N / –S + z: float kills: int kills_per_hour: Optional[str] = None # now optional @@ -51,8 +52,7 @@ def on_startup(): @app.post("/position") @app.post("/position/") async def receive_snapshot( - snapshot: TelemetrySnapshot, - x_plugin_secret: str = Header(None) + snapshot: TelemetrySnapshot, x_plugin_secret: str = Header(None) ): if x_plugin_secret != SHARED_SECRET: raise HTTPException(status_code=401, detail="Unauthorized") @@ -64,10 +64,12 @@ async def receive_snapshot( save_snapshot(snapshot.dict()) # optional log-file append - #with open(LOG_FILE, "a") as f: + # with open(LOG_FILE, "a") as f: # f.write(json.dumps(snapshot.dict(), default=str) + "\n") - print(f"[{datetime.now()}] {snapshot.character_name} @ NS={snapshot.ns:+.2f}, EW={snapshot.ew:+.2f}") + print( + f"[{datetime.now()}] {snapshot.character_name} @ NS={snapshot.ns:+.2f}, EW={snapshot.ew:+.2f}" + ) return {"status": "ok"} @@ -90,18 +92,19 @@ def get_live_players(): cutoff = datetime.utcnow().replace(tzinfo=timezone.utc) - ACTIVE_WINDOW players = [ - dict(r) for r in rows - if datetime.fromisoformat( - r["timestamp"].replace('Z', '+00:00') - ) > cutoff + dict(r) + for r in rows + if datetime.fromisoformat(r["timestamp"].replace("Z", "+00:00")) > cutoff ] return JSONResponse(content={"players": players}) + + @app.get("/history/") @app.get("/history") def get_history( from_ts: str | None = Query(None, alias="from"), - to_ts: str | None = Query(None, alias="to"), + to_ts: str | None = Query(None, alias="to"), ): """ Returns a time‐ordered list of telemetry snapshots: @@ -142,15 +145,16 @@ def get_history( data = [ { - "timestamp": row["timestamp"], - "character_name":row["character_name"], - "kills": row["kills"], - "kph": row["kph"], + "timestamp": row["timestamp"], + "character_name": row["character_name"], + "kills": row["kills"], + "kph": row["kph"], } for row in rows ] return JSONResponse(content={"data": data}) + # ------------------------ GET Trails --------------------------------- @app.get("/trails") @app.get("/trails/") @@ -162,7 +166,9 @@ def get_trails( for the past `seconds` seconds. """ # match the same string format as stored timestamps (via str(datetime)) - cutoff_dt = datetime.utcnow().replace(tzinfo=timezone.utc) - timedelta(seconds=seconds) + cutoff_dt = datetime.utcnow().replace(tzinfo=timezone.utc) - timedelta( + seconds=seconds + ) cutoff = str(cutoff_dt) conn = sqlite3.connect(DB_FILE) conn.row_factory = sqlite3.Row @@ -173,16 +179,16 @@ def get_trails( WHERE timestamp >= ? ORDER BY character_name, timestamp """, - (cutoff,) + (cutoff,), ).fetchall() conn.close() trails = [ { - "timestamp": r["timestamp"], + "timestamp": r["timestamp"], "character_name": r["character_name"], - "ew": r["ew"], - "ns": r["ns"], - "z": r["z"], + "ew": r["ew"], + "ns": r["ns"], + "z": r["z"], } for r in rows ]