add make command make reformat
reformat python files with black
This commit is contained in:
parent
66ed711fec
commit
431ce1c8d0
3 changed files with 82 additions and 58 deletions
2
Makefile
Normal file
2
Makefile
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
reformat:
|
||||
black *py
|
||||
84
db.py
84
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()
|
||||
|
|
|
|||
54
main.py
54
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
|
||||
]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue