Disconnection detection added

PC checks for connection
Esp32 send Heartbeat
This commit is contained in:
2026-11-05 10:37:24 +01:00
parent 4e991a71b5
commit 3531430661
6 changed files with 212 additions and 32 deletions
+166 -31
View File
@@ -2,8 +2,8 @@ import socket
import struct
import time
import numpy as np
from threading import Thread, Event
from queue import Queue
from threading import Thread, Event, Lock
from queue import Empty, Full, Queue
from config import cfg
import DataTypes as dt
@@ -15,6 +15,8 @@ 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
@@ -23,6 +25,9 @@ FT_CONFIG_VAL = 4
HEADER_FMT = "<B B H I" # ID, Ver, Len, Timestamp
TLV_FMT = "<B H"
HEARTBEAT_INTERVAL = 0.5
CONNECTION_TIMEOUT = 2.0
RECONNECT_TIMEOUT = 30.0
class ESP32Communication(Thread):
def __init__(self, host=None, port=None, ip=None):
@@ -33,29 +38,125 @@ class ESP32Communication(Thread):
port = cfg.esp32_port if port is None else port
self.addr = (host, port)
# UDP Socket - Zero Lag
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.settimeout(0.1)
self.tx_queue = Queue()
self.tx_queue = Queue(maxsize=1)
self._motion_lock = Lock()
self._latest_motion_packet = None
self._config_packet = None
self._config_pending = False
self._config_generation = 0
self.running = Event()
self.running.set()
self.last_motion_data = None
self._connection_status = "connecting"
self._last_pong_time = None
self._reconnect_deadline = time.monotonic() + RECONNECT_TIMEOUT
self._next_heartbeat_time = 0.0
self._receiver_thread = None
print(f"Communication Initialized: Target {host}:{port}")
@property
def connection_status(self):
return self._connection_status
def run(self):
# --- THE FIX: Send Configs immediately upon starting the thread ---
self.sync_robot_configs()
self._receiver_thread = Thread(target=self._receive_loop, daemon=True)
self._receiver_thread.start()
next_motion_time = time.monotonic()
try:
while self.running.is_set():
now = time.monotonic()
if self._connection_status != "disconnected" and now >= 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():
if not self.tx_queue.empty():
data = self.tx_queue.get()
try:
self.sock.sendto(data, self.addr)
except Exception as e:
print(f"UDP Send Error: {e}")
# Tiny sleep to prevent 100% CPU usage
time.sleep(0.001)
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):
"""
@@ -82,24 +183,18 @@ class ESP32Communication(Thread):
fields.append(struct.pack(TLV_FMT, FT_CONFIG_VAL, len(payload)) + payload)
packet = self._build_packet(PKT_CONFIG, fields)
self.tx_queue.put(packet)
with self._motion_lock:
self._config_packet = packet
self._config_pending = True
self._config_generation += 1
def send_motion(self, radial_array: dt.RadArray):
"""Sends motion only if the data has changed."""
# 1. Convert to degrees/uint8 as you did before
"""Store the latest command for transmission at the configured tick rate."""
new_data = np.degrees(radial_array.data).astype(np.uint8)
# 2. Check if it's different from the last sent packet
if self.last_motion_data is not None:
if np.array_equal(new_data, self.last_motion_data):
return # Skip sending if data is identical
# 3. Update the tracker and send
self.last_motion_data = new_data.copy()
fields = [self._tlv(FT_ARRAY_F32, new_data.tobytes())]
packet = self._build_packet(PKT_COMMAND, fields)
self.tx_queue.put(packet)
with self._motion_lock:
self._latest_motion_packet = packet
def send_text(self, text=""):
"""Sends a dedicated display packet independent of motion."""
@@ -112,7 +207,47 @@ class ESP32Communication(Thread):
# Build the packet using the PKT_DISPLAY (ID 3)
packet = self._build_packet(PKT_DISPLAY, [field])
self.tx_queue.put(packet)
self._queue_latest(packet)
def _handle_response(self, data, sender):
if self._connection_status == "disconnected":
return
if sender != self.addr:
return
header_size = struct.calcsize(HEADER_FMT)
if len(data) != header_size:
return
packet_id, version, payload_length, _ = struct.unpack(HEADER_FMT, data)
if packet_id != PKT_PONG or version != PACKET_VERSION or payload_length != 0:
return
was_connected = self._connection_status == "connected"
self._connection_status = "connected"
self._last_pong_time = time.monotonic()
if not was_connected:
with self._motion_lock:
self._config_pending = True
self._config_generation += 1
def _queue_latest(self, packet):
try:
self.tx_queue.put_nowait(packet)
except Full:
try:
self.tx_queue.get_nowait()
except Empty:
pass
self.tx_queue.put_nowait(packet)
def _clear_tx_queue(self):
while True:
try:
self.tx_queue.get_nowait()
except Empty:
return
def _tlv(self, ftype, data):
return struct.pack(TLV_FMT, ftype, len(data)) + data
@@ -132,7 +267,7 @@ class ESP32Communication(Thread):
self.running.clear()
try:
self.sock.close()
except Exception:
except OSError:
pass
def close(self):