| 14 | WEBSOCKET_URI = "ws://localhost:876" |
| 15 | |
| 16 | class TermNetClient: |
| 17 | def __init__(self, uri=WEBSOCKET_URI): |
| 18 | self.uri = uri |
| 19 | self.websocket = None |
| 20 | |
| 21 | |
| 22 | import re |
| 23 | |
| 24 | def normalize_text(text: str) -> str: |
| 25 | # Simple detection: jammed datetime looks like WedSep242025,22:09:27EDT |
| 26 | compact_dt = re.findall(r"[A-Z][a-z]{2}[A-Z][a-z]{2}\d{1,2}\d{4},\d{2}:\d{2}:\d{2}[A-Z]{2,4}", text) |
| 27 | for dt in compact_dt: |
| 28 | # slice it instead of regex replace |
| 29 | day = dt[0:3] # Wed |
| 30 | month = dt[3:6] # Sep |
| 31 | date = dt[6:8] # 24 |
| 32 | year = dt[8:12] # 2025 |
| 33 | time = dt.split(",")[1][0:8] # 22:09:27 |
| 34 | tz = dt.split(",")[1][8:] # EDT |
| 35 | fixed = f"{day} {month} {int(date)} {year}, {time} {tz}" |
| 36 | text = text.replace(dt, fixed) |
| 37 | return text |
| 38 | |
| 39 | |
| 40 | async def connect(self): |
| 41 | self.websocket = await websockets.connect(self.uri) |
| 42 | print("Connected to TermNet server") |
| 43 | welcome = await self.websocket.recv() # consume welcome |
| 44 | _ = json.loads(welcome) |
| 45 | |
| 46 | async def send_and_stream_to_queue(self, message: str, queue: Queue): |
| 47 | """Stream responses to a queue that can be consumed by Flask""" |
| 48 | try: |
| 49 | if not self.websocket: |
| 50 | await self.connect() |
| 51 | |
| 52 | msg_data = { |
| 53 | "type": "message", |
| 54 | "message": message, |
| 55 | "timestamp": asyncio.get_event_loop().time() |
| 56 | } |
| 57 | await self.websocket.send(json.dumps(msg_data)) |
| 58 | |
| 59 | |
| 60 | while True: |
| 61 | try: |
| 62 | response = await self.websocket.recv() |
| 63 | data = json.loads(response) |
| 64 | |
| 65 | # Put data in queue for Flask to consume |
| 66 | queue.put(json.dumps(data)) |
| 67 | |
| 68 | if data["type"] in ["response_end", "error"]: |
| 69 | break |
| 70 | |
| 71 | except Exception as e: |
| 72 | queue.put(json.dumps({"type": "error", "message": str(e)})) |
| 73 | break |