From 353143066116946f199d2e3850cdc83ebdc3870b Mon Sep 17 00:00:00 2001 From: JackM323 Date: Thu, 5 Nov 2026 10:37:24 +0100 Subject: [PATCH] Disconnection detection added PC checks for connection Esp32 send Heartbeat --- BoardCode/libaries/JackBot/src/BotNetwork.cpp | 13 ++ BoardCode/libaries/JackBot/src/Protocol.h | 2 + EspCommunication.py | 197 +++++++++++++++--- Robot.py | 14 ++ gui/MainWindow.py | 13 ++ main.py | 5 +- 6 files changed, 212 insertions(+), 32 deletions(-) diff --git a/BoardCode/libaries/JackBot/src/BotNetwork.cpp b/BoardCode/libaries/JackBot/src/BotNetwork.cpp index 9af3b9c..54f1eca 100644 --- a/BoardCode/libaries/JackBot/src/BotNetwork.cpp +++ b/BoardCode/libaries/JackBot/src/BotNetwork.cpp @@ -53,6 +53,19 @@ void BotNetwork::parsePacket(uint8_t *buffer, size_t size, QueueHandle_t motionQ if (header->version != PACKET_VERSION) return; if (header->payload_len > size - sizeof(PacketHeader)) return; + if (header->packet_id == PKT_PING && header->payload_len == 0) { + PacketHeader response = { + PKT_PONG, + PACKET_VERSION, + 0, + millis() + }; + _udp.beginPacket(_udp.remoteIP(), _udp.remotePort()); + _udp.write((const uint8_t *)&response, sizeof(response)); + _udp.endPacket(); + return; + } + uint8_t *payload = buffer + sizeof(PacketHeader); size_t pos = 0; diff --git a/BoardCode/libaries/JackBot/src/Protocol.h b/BoardCode/libaries/JackBot/src/Protocol.h index 3ebd1e2..9efbbc2 100644 --- a/BoardCode/libaries/JackBot/src/Protocol.h +++ b/BoardCode/libaries/JackBot/src/Protocol.h @@ -5,6 +5,8 @@ #define PKT_COMMAND 1 #define PKT_CONFIG 2 #define PKT_DISPLAY 3 +#define PKT_PING 4 +#define PKT_PONG 5 #define FT_ARRAY_F32 1 #define FT_STRING 2 diff --git a/EspCommunication.py b/EspCommunication.py index c037ad7..c92ee37 100644 --- a/EspCommunication.py +++ b/EspCommunication.py @@ -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 = "= 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): diff --git a/Robot.py b/Robot.py index f1b8886..5b31b1b 100644 --- a/Robot.py +++ b/Robot.py @@ -19,6 +19,8 @@ from ArduinoCommunication import ArduinoCommunication class RobotBackend(Protocol): """Protocol defining hardware abstraction for both Simulation and Hardware backends.""" + @property + def connection_status(self) -> Optional[str]: ... def send_angles(self, rad_array: dt.RadArray) -> None: ... def step_simulation(self) -> None: ... def hard_reset_joints(self, target_angles: np.ndarray) -> None: ... @@ -35,6 +37,10 @@ class HardwareBackend: self.comm_channel = comm_channel self.internal_angles = np.zeros(18, dtype=np.float32) + @property + def connection_status(self) -> Optional[str]: + return getattr(self.comm_channel, "connection_status", None) + def send_angles(self, rad_array: dt.RadArray) -> None: self.internal_angles = rad_array.data.flatten().copy() if self.comm_channel: @@ -71,6 +77,10 @@ class PyBulletBackend: def __init__(self, sim_instance: Simulation): self.sim = sim_instance + @property + def connection_status(self) -> Optional[str]: + return None + def send_angles(self, rad_array: dt.RadArray) -> None: if self.sim: self.sim.set_robot_joint_angles(rad_array) @@ -171,6 +181,10 @@ class Robot: if self.backend: self.backend.send_angles(self.current_rad) + @property + def connection_status(self) -> Optional[str]: + return self.backend.connection_status + def step_sim(self) -> None: if self.backend: self.backend.step_simulation() diff --git a/gui/MainWindow.py b/gui/MainWindow.py index 7ce5d84..0870456 100644 --- a/gui/MainWindow.py +++ b/gui/MainWindow.py @@ -128,6 +128,19 @@ def create_parameter_gui(on_start_callback=None, on_stop_callback=None): dpg.show_viewport() +def update_robot_status(status: str): + """Update the robot connection label from the GUI event loop.""" + labels = { + "connecting": ("Status: CONNECTING TO ROBOT", (255, 200, 0)), + "connected": ("Status: RUNNING", (0, 255, 0)), + "reconnecting": ("Robot Disconnected - Reconnecting...", (255, 150, 0)), + "disconnected": ("Robot Disconnected", (255, 100, 100)), + } + label, color = labels.get(status, ("Status: RUNNING", (0, 255, 0))) + if dpg.is_dearpygui_running(): + dpg.configure_item("status_text", default_value=label, color=color) + + def resolve_active_command(gamepad_cmd: dict | None) -> dict: """Selects motion vector based on current active source in GUI.""" source = input_config["source"] diff --git a/main.py b/main.py index 27403dd..ecf037b 100644 --- a/main.py +++ b/main.py @@ -10,7 +10,8 @@ from gui.MainWindow import ( create_parameter_gui, render_gui_frame, stop_gui, - resolve_active_command + resolve_active_command, + update_robot_status, ) from inputs.PygameController import controller_loop @@ -62,6 +63,8 @@ def main_event_loop(control_queue: Queue): robot_instance.robot_state = active_cmd["state"] robot_instance.vector_dirmov = active_cmd["dirmov"] robot_instance.tick() + if robot_instance.connection_status is not None: + update_robot_status(robot_instance.connection_status) render_gui_frame()