import socket import struct import time import numpy as np from threading import Thread, Event, Lock from queue import Empty, Full, Queue from config import cfg import DataTypes as dt # ============================================================ # Protocol definitions (MATCHES THE ULTIMATE .INO) # ============================================================ PACKET_VERSION = 1 PKT_COMMAND = 1 PKT_CONFIG = 2 PKT_DISPLAY = 3 PKT_PING = 4 PKT_PONG = 5 FT_ARRAY_F32 = 1 FT_STRING = 2 FT_UINT8 = 3 FT_CONFIG_VAL = 4 HEADER_FMT = "= self._next_heartbeat_time: self._send_packet(self._build_packet(PKT_PING, []), "heartbeat") self._next_heartbeat_time = now + HEARTBEAT_INTERVAL if self._connection_status == "connected": self._send_pending_config() if now >= next_motion_time: with self._motion_lock: motion_packet = self._latest_motion_packet if motion_packet is not None: self._send_packet(motion_packet, "motion") try: queued_packet = self.tx_queue.get_nowait() except Empty: pass else: self._send_packet(queued_packet, "queued") next_motion_time += cfg.tick_duration if next_motion_time <= now: next_motion_time = now + cfg.tick_duration sleep_time = min(0.01, max(0.0, next_motion_time - time.monotonic())) time.sleep(sleep_time) finally: try: self.sock.close() except OSError: pass def _send_packet(self, packet, packet_type): try: self.sock.sendto(packet, self.addr) except OSError as exc: if self.running.is_set(): print(f"UDP {packet_type.capitalize()} Send Error: {exc}") def _send_pending_config(self): with self._motion_lock: packet = self._config_packet if self._config_pending else None generation = self._config_generation if packet is None: return try: self.sock.sendto(packet, self.addr) except OSError as exc: if self.running.is_set(): print(f"UDP Config Send Error: {exc}") else: with self._motion_lock: if generation == self._config_generation: self._config_pending = False def _receive_loop(self): while self.running.is_set(): try: data, sender = self.sock.recvfrom(1024) except socket.timeout: pass except ConnectionRefusedError: pass except OSError as exc: if self.running.is_set(): print(f"UDP Receive Error: {exc}") time.sleep(0.1) continue return else: self._handle_response(data, sender) now = time.monotonic() if ( self._connection_status == "connected" and self._last_pong_time is not None and now - self._last_pong_time > CONNECTION_TIMEOUT ): self._connection_status = "reconnecting" self._reconnect_deadline = now + RECONNECT_TIMEOUT self._clear_tx_queue() elif ( self._connection_status in ("connecting", "reconnecting") and now >= self._reconnect_deadline ): self._connection_status = "disconnected" self._clear_tx_queue() self.running.clear() return def sync_robot_configs(self): """ Sends the parameters from your config.py to the ESP32. This tells the ESP32 how to map degrees to pulses and how fast the Python loop is running for smoothing. """ print("Sending Config Sync to Robot...") # Calculate interval in ms based on your FPS (tickpersec) interval_ms = int(1000 / cfg.standard_tickpersec) # Config IDs: 1=Min, 2=Max, 3=Interval configs = [ (1, 125), # servoMin (Default for 50Hz) (2, 625), # servoMax (Default for 50Hz) (3, interval_ms) ] fields = [] for c_id, val in configs: # Payload: 1 byte for ID, 2 bytes for Value (Little Endian) payload = struct.pack("