Files
JackBot/EspCommunication.py
T
JackM323 3531430661 Disconnection detection added
PC checks for connection
Esp32 send Heartbeat
2026-11-05 10:37:24 +01:00

274 lines
9.4 KiB
Python

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 = "<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):
super().__init__(daemon=True)
if ip is not None:
host = ip
host = cfg.esp32_ip if host is None else host
port = cfg.esp32_port if port is None else port
self.addr = (host, port)
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.settimeout(0.1)
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._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):
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():
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("<B h", c_id, val)
fields.append(struct.pack(TLV_FMT, FT_CONFIG_VAL, len(payload)) + payload)
packet = self._build_packet(PKT_CONFIG, fields)
with self._motion_lock:
self._config_packet = packet
self._config_pending = True
self._config_generation += 1
def send_motion(self, radial_array: dt.RadArray):
"""Store the latest command for transmission at the configured tick rate."""
new_data = np.degrees(radial_array.data).astype(np.uint8)
fields = [self._tlv(FT_ARRAY_F32, new_data.tobytes())]
packet = self._build_packet(PKT_COMMAND, fields)
with self._motion_lock:
self._latest_motion_packet = packet
def send_text(self, text=""):
"""Sends a dedicated display packet independent of motion."""
# Convert string to bytes
text_bytes = text.encode("utf-8")
# Wrap in TLV format (Type 2 = FT_STRING)
field = self._tlv(FT_STRING, text_bytes)
# Build the packet using the PKT_DISPLAY (ID 3)
packet = self._build_packet(PKT_DISPLAY, [field])
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
def _build_packet(self, packet_id, fields):
payload = b"".join(fields)
header = struct.pack(
HEADER_FMT,
packet_id,
PACKET_VERSION,
len(payload),
int(time.time() * 1000) & 0xFFFFFFFF
)
return header + payload
def stop(self):
self.running.clear()
try:
self.sock.close()
except OSError:
pass
def close(self):
self.stop()