High-level client for Serial Studio API. Provides clean interface for testing without worrying about low-level socket communication details.
| 24 | |
| 25 | |
| 26 | class SerialStudioClient: |
| 27 | """ |
| 28 | High-level client for Serial Studio API. |
| 29 | |
| 30 | Provides clean interface for testing without worrying about |
| 31 | low-level socket communication details. |
| 32 | """ |
| 33 | |
| 34 | DEFAULT_HOST = "127.0.0.1" |
| 35 | DEFAULT_PORT = 7777 |
| 36 | TIMEOUT = 5.0 |
| 37 | |
| 38 | def __init__( |
| 39 | self, |
| 40 | host: str = DEFAULT_HOST, |
| 41 | port: int = DEFAULT_PORT, |
| 42 | timeout: float = TIMEOUT, |
| 43 | ): |
| 44 | self.host = host |
| 45 | self.port = port |
| 46 | self.timeout = timeout |
| 47 | self._socket: Optional[socket.socket] = None |
| 48 | self._buffer = b"" |
| 49 | |
| 50 | def __enter__(self): |
| 51 | self.connect() |
| 52 | return self |
| 53 | |
| 54 | def __exit__(self, exc_type, exc_val, exc_tb): |
| 55 | self.disconnect() |
| 56 | |
| 57 | def connect(self) -> None: |
| 58 | """Establish connection to Serial Studio API.""" |
| 59 | if self._socket: |
| 60 | return |
| 61 | |
| 62 | self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 63 | self._socket.settimeout(self.timeout) |
| 64 | try: |
| 65 | self._socket.connect((self.host, self.port)) |
| 66 | except (ConnectionRefusedError, socket.timeout) as e: |
| 67 | raise ConnectionError( |
| 68 | f"Could not connect to Serial Studio at {self.host}:{self.port}. " |
| 69 | f"Ensure Serial Studio is running with API Server enabled." |
| 70 | ) from e |
| 71 | |
| 72 | def disconnect(self) -> None: |
| 73 | """Close the connection.""" |
| 74 | if self._socket: |
| 75 | try: |
| 76 | self._socket.close() |
| 77 | except Exception: |
| 78 | pass |
| 79 | self._socket = None |
| 80 | self._buffer = b"" |
| 81 | |
| 82 | def _recv_message(self, timeout: Optional[float] = None) -> dict: |
| 83 | """Receive a single JSON message from the socket.""" |
no outgoing calls