-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
99 lines (73 loc) · 2.67 KB
/
main.py
File metadata and controls
99 lines (73 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import game
from fastapi import FastAPI, WebSocket
from loguru import logger
from timeit import default_timer
tx_engine = FastAPI() # FastAPI service object that hosts TXEngine
# Implement service logic
@tx_engine.get("/")
def root_get():
start = default_timer()
r = game.state_device_controller.get_current_frame()
duration = default_timer() - start
logger.info(f"Completed state retrieval in {duration}s")
return r
@tx_engine.put("/")
def root_put(user_input: int | str):
start = default_timer()
r = game.state_device_controller.deliver_input(user_input)
duration = default_timer() - start
logger.info(f"Completed input submission in {duration}s")
return r
@tx_engine.websocket("/")
async def websocket_endpoint(websocket: WebSocket):
"""
An interactive websocket endpoint. Used to communicate in real time with clients instead of in blocking-series.
Functionally equivalent to get/put.
Args:
websocket: The active websocket object used to manage the connection
Returns: None
"""
await websocket.accept()
data = await websocket.receive_json()
while True:
if isinstance(data, dict):
if "user_input" in data:
# Attempt to coerce into an int
try:
payload: int = int(data["user_input"])
game.state_device_controller.deliver_input(payload)
except ValueError:
game.state_device_controller.deliver_input(data["user_input"])
else:
raise ValueError("Invalid JSON structure! Expected field 'user_input'")
else:
raise TypeError("Expected a JSON dict!")
r = game.state_device_controller.get_current_frame()
await websocket.send_text(r.model_dump_json())
data = await websocket.receive_json()
@tx_engine.get("/cache")
def cache(cache_path: str):
from game.cache import get_cache
obj: any = get_cache()
count: int = 0
if cache_path == r".":
return str(obj)
try:
for key in cache_path.split("."):
obj = obj[key]
count += 1
return str(obj)
except KeyError:
logger.warning("Failed to retrieve")
return f"No value located at {cache_path}! Traveled to {'.'.join(cache_path.split('.')[:count])}"
@tx_engine.get("/cli")
def cli(command: str):
parts = command.split(" ")
if len(parts) < 1:
return ""
from game.cache import from_cache
if parts[0] in from_cache("managers"):
return from_cache("managers")[parts[0]].handle_command(" ".join(parts[1:]))
# Begin service logic
if __name__ == "__main__":
exec("fastapi run")