Repository navigation
Expand file tree
/
Copy pathgui_server.py
More file actions
238 lines (202 loc) · 7.59 KB
/
Copy pathgui_server.py
File metadata and controls
238 lines (202 loc) · 7.59 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import asyncio
import json
import logging
import threading
import time
from queue import Queue, Empty
import websockets
from websocket_logging import IgnoreEmptyHandshakes
from algorithms.constants import constants
server_logger = logging.getLogger("sphero.algorithm.websocket")
server_logger.addFilter(IgnoreEmptyHandshakes())
# ----------------------------------------------------------------------------
# Command support
#
# The GUI client can send simple JSON commands over the same WebSocket
# connection that is used for state broadcasting. We enqueue them so that
# the algorithm driver can consume them at its own pace. Typical commands are
# {"type": "pause"} or {"type": "resume"} but the format is open-ended.
#
# The queue is intentionally small since only the most recent command matters and
# the algorithm loop polls it frequently. Commands that cannot be parsed are
# ignored with a log message.
# ----------------------------------------------------------------------------
command_queue: Queue[dict] = Queue(maxsize=4)
def get_next_command(timeout: float | None = None) -> dict | None:
"""Return next command from GUI or ``None`` if the queue is empty.
``timeout`` behaves like :py:meth:`queue.Queue.get` so the caller can
block briefly while waiting for input. The algorithm driver uses a
non-blocking poll (timeout=0) in its main loop.
To keep the simulation responsive we collapse successive ``step_seconds``
commands: if multiple timing adjustments arrive before the driver
processes them, only the last one is returned and earlier ones are
discarded. Other commands remain in the queue in their original
order.
"""
try:
cmd = command_queue.get(timeout=timeout)
except Empty:
return None
# Drop any later timing commands, preserving the
# most recent value while leaving other pending commands untouched.
if isinstance(cmd, dict) and cmd.get("type") == "step_seconds":
latest = cmd
to_requeue: list[dict] = []
# drain the queue
while True:
try:
nxt = command_queue.get_nowait()
except Empty:
break
if isinstance(nxt, dict) and nxt.get("type") == "step_seconds":
latest = nxt
else:
to_requeue.append(nxt)
# Put back commands other than timing adjustments.
for item in to_requeue:
try:
command_queue.put_nowait(item)
except Exception:
# if the queue is full (unlikely) just drop the item; newer
# commands are more important
pass
return latest
return cmd
state_queue = Queue(maxsize=1)
connected_clients = set()
async def send_state(client, message):
"""Ignore a client that closes while a broadcast is in flight."""
try:
await client.send(message)
except websockets.exceptions.ConnectionClosed:
connected_clients.discard(client)
async def broadcast_state():
while True:
try:
state = state_queue.get_nowait()
except Empty:
await asyncio.sleep(0.01)
continue
message = json.dumps(state)
if connected_clients:
await asyncio.gather(*(send_state(client, message) for client in tuple(connected_clients)))
await asyncio.sleep(0.03)
async def handler(websocket):
"""Register clients, keep connection alive, and accept simple commands.
The client may send JSON strings; anything that parses to a dict is
enqueued for the driver to consume. We still round‑trip state on the
broadcast task so clients see live updates.
"""
connected_clients.add(websocket)
print(f"Client connected: {websocket.remote_address}")
try:
async for message in websocket:
# every incoming message is treated as a command
try:
cmd = json.loads(message)
if isinstance(cmd, dict):
# drop oldest if queue full so that newer commands win
if command_queue.full():
try:
command_queue.get_nowait()
except Empty:
pass
command_queue.put_nowait(cmd)
else:
print(f"[gui_server] ignored non-dict command: {cmd}")
except Exception as e:
print(f"[gui_server] failed to parse command {message!r}: {e}")
except websockets.exceptions.ConnectionClosed:
pass
finally:
connected_clients.discard(websocket)
print(f"Client disconnected: {websocket.remote_address}")
async def run_server():
"""Run both the WebSocket server and state broadcaster."""
async with websockets.serve(handler, "localhost", 6769, logger=server_logger):
await broadcast_state()
def start_server():
"""Start the WebSocket server in a new event loop."""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(run_server())
except KeyboardInterrupt:
pass
finally:
loop.close()
server_thread = threading.Thread(target=start_server, daemon=True)
server_thread.start()
print("Algorithm WebSocket server started on ws://localhost:6769")
def build_state_payload(algorithm) -> dict:
"""
Serialize the current algorithm state into a JSON-serializable dict.
Payload structure:
{
"timestamp": float,
"grid": { "width": int, "height": int, "padding": float },
"spheros": [
{
"id": int,
"x": int,
"y": int,
"color": <color>,
"direction": int
},
...
],
"bonded_groups": [
[id1, id2, ...], # one list per bonded group
...
]
}
"""
if hasattr(algorithm, "find_all_spheros"):
spheros_list = algorithm.find_all_spheros()
else:
spheros_list = [s for s in getattr(algorithm, "spheros", []) if s is not None]
spheros_payload = [
{
"id": sphero.id,
"x": sphero.x,
"y": sphero.y,
"color": sphero.color,
"direction": sphero.direction,
"correction_debug": getattr(sphero, "correction_debug", None),
}
for sphero in spheros_list
]
if hasattr(algorithm, "bonded_groups"):
bonded_groups_payload = [
[sphero.id for sphero in group.spheros]
for group in algorithm.bonded_groups
if len(group.spheros) > 0
]
else:
bonded_groups_payload = getattr(getattr(algorithm, "swarm", None), "bonded_groups", [])
return {
"timestamp": time.time(),
"grid": {
"width": algorithm.grid_width,
"height": algorithm.grid_height,
# arena margin outside the outer nodes, in grid units (camera crop)
"padding": constants.GRID_PADDING,
},
"spheros": spheros_payload,
"bonded_groups": bonded_groups_payload,
}
def send_algorithm_state(algorithm):
"""
Call this after each algorithm step to broadcast the current state.
Drops the previous frame if it hasn't been sent yet (non-blocking).
"""
try:
state = build_state_payload(algorithm)
if state_queue.full():
try:
state_queue.get_nowait()
except Empty:
pass
state_queue.put_nowait(state)
except Exception as e:
print(f"[algorithm_server] Failed to enqueue state: {e}")