Refactor WebSocket handling and remove redundant functions

Improved error handling for WebSocket connections by wrapping `ws.run_forever()` in a try-except block. Simplified `tellupdater` by removing unused functions (`convert_pucks` and `pucks_equal`) and ensuring consistent puck state updates. Enhanced logging for better traceability during WebSocket operations.
This commit is contained in:
GotthardG committed 2025-07-16 16:56:38 +02:00
1 parent 09be1864a5
commit 14c8780616
2 files changed
+29 -55

No files matched your search

+13 -17
View File
@@ -114,24 +114,20 @@ def main():
"""
Main function to initiate WebSocket connection.
"""
# Support clean exit on SIGINT/SIGTERM
def exit_gracefully(*args):
print('\n[EXIT] Caught signal, exiting.')
exit(0)
signal.signal(signal.SIGINT, exit_gracefully)
signal.signal(signal.SIGTERM, exit_gracefully)
while True:
ws = websocket.WebSocketApp(
WS_URL,
header=WS_HEADERS,
on_message=on_message,
on_error=on_error,
on_close=on_close,
on_open=on_open,
)
ws.run_forever(sslopt={"cert_reqs": 0})
try:
ws = websocket.WebSocketApp(
WS_URL,
header=WS_HEADERS,
on_message=on_message,
on_error=on_error,
on_close=on_close,
on_open=on_open,
)
ws.run_forever(sslopt={"cert_reqs": 0})
except Exception as e:
print(f"[MAIN][ERROR] ws.run_forever() crashed with: {e}")
print("[WS][INFO] WebSocket connection lost. Reconnecting in 5 seconds...")
time.sleep(5)
+16 -38
View File
@@ -51,25 +51,6 @@ def ws_update_samples_info(pucks):
"""Send sample info to TELL robot."""
tell_client.set_samples_info(pucks)
def convert_pucks(puck_list):
return [PuckWithTellPosition(
id=p.puck_id,
puck_name=p.puck_name,
puck_type=getattr(p, 'puck_type', None),
puck_location_in_dewar=getattr(p, 'puck_location_in_dewar', None),
dewar_id=getattr(p, 'dewar_id', None),
dewar_name=getattr(p, 'dewar_name', None),
pgroup=getattr(p, 'pgroup', None),
samples=getattr(p, 'samples', None),
tell_position=getattr(p, 'tell_position', None),
) for p in puck_list]
def pucks_equal(pucks1, pucks2):
# Implement a simple equality check, e.g., comparing sorted ids, or full data
if len(pucks1) != len(pucks2): return False
return all(p1.id == p2.id for p1, p2 in zip(sorted(pucks1, key=lambda p: p.id),
sorted(pucks2, key=lambda p: p.id)))
def handle_tell_change_event():
"""Fetch the latest detected pucks from TELL and update the database."""
try:
@@ -87,21 +68,14 @@ def on_sse_event(event):
handle_tell_change_event()
def on_message(ws, message):
global current_pucks
try:
data = json.loads(message)
print("[WS][MESSAGE]", data)
if isinstance(data, list):
new_pucks = [PuckWithTellPosition(**item) for item in data]
joined, left = compare_and_report_change(
current_pucks, new_pucks, key_func=lambda p: p.id
)
if joined or left:
print(f"[WS][UPDATE] joined={joined}, left={left}")
current_pucks = new_pucks
ws_update_samples_info(new_pucks)
else:
print("[WS][NO CHANGE]")
# Always forward the current state to TELL or your API
ws_update_samples_info(new_pucks)
print("[WS][INFO] Sent current pucks state to TELL.")
else:
print("[WS][ERROR] Unknown message format")
except Exception as exc:
@@ -123,15 +97,19 @@ def main():
# Main thread runs websocket client loop
while True:
ws = websocket.WebSocketApp(
WS_URL,
header=WS_HEADERS,
on_message=on_message,
on_error=on_error,
on_close=on_close,
on_open=on_open,
)
ws.run_forever(sslopt={"cert_reqs": 0})
try:
ws = websocket.WebSocketApp(
WS_URL,
header=WS_HEADERS,
on_message=on_message,
on_error=on_error,
on_close=on_close,
on_open=on_open,
)
ws.run_forever(sslopt={"cert_reqs": 0})
except Exception as e:
print(f"[MAIN][ERROR] ws.run_forever() crashed with: {e}")
print("[WS][INFO] WebSocket connection lost. Reconnecting in 5 seconds...")
time.sleep(5)