diff --git a/utils.py b/utils.py index 3d22de7..b758b0e 100644 --- a/utils.py +++ b/utils.py @@ -7,7 +7,7 @@ DEBUG: bool = True RESET = "\033[0m" CYAN = "\033[36m" YELLOW = "\033[33m" - +RED = "\033[31m" class RobotClient: def __init__(self, host, port): @@ -20,11 +20,26 @@ class RobotClient: if DEBUG: print(f"{CYAN}DEBUG: sended:{RESET} {cmd}") self.sock.sendall(json.dumps(cmd).encode("utf-8")) - data = self.sock.recv(1024).decode("utf-8") - ret = json.loads(data) - if DEBUG: - print(f"{YELLOW}DEBUG: received:{RESET} {ret}") - return ret + try: + ret = self._recv_full_json() + if DEBUG: + print(f"{YELLOW}DEBUG: received:{RESET} {ret}") + return ret + except Exception as e: + print(f"{RED}ERROR: {e}{RESET}") + return {} + + def _recv_full_json(self) -> dict: + buffer = "" + while True: + chunk = self.sock.recv(1024).decode("utf-8") + if not chunk: + raise ConnectionError("Connection closed") + buffer += chunk + try: + return json.loads(buffer) + except json.JSONDecodeError: + continue # not полный JSON, продолжаем читать def rpy_to_quat(self, arr): cmd = {"command": "rpy_to_quaternion", "rpy": arr}