Disconnection detection added
PC checks for connection Esp32 send Heartbeat
This commit is contained in:
@@ -53,6 +53,19 @@ void BotNetwork::parsePacket(uint8_t *buffer, size_t size, QueueHandle_t motionQ
|
|||||||
if (header->version != PACKET_VERSION) return;
|
if (header->version != PACKET_VERSION) return;
|
||||||
if (header->payload_len > size - sizeof(PacketHeader)) 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);
|
uint8_t *payload = buffer + sizeof(PacketHeader);
|
||||||
size_t pos = 0;
|
size_t pos = 0;
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,8 @@
|
|||||||
#define PKT_COMMAND 1
|
#define PKT_COMMAND 1
|
||||||
#define PKT_CONFIG 2
|
#define PKT_CONFIG 2
|
||||||
#define PKT_DISPLAY 3
|
#define PKT_DISPLAY 3
|
||||||
|
#define PKT_PING 4
|
||||||
|
#define PKT_PONG 5
|
||||||
|
|
||||||
#define FT_ARRAY_F32 1
|
#define FT_ARRAY_F32 1
|
||||||
#define FT_STRING 2
|
#define FT_STRING 2
|
||||||
|
|||||||
+164
-29
@@ -2,8 +2,8 @@ import socket
|
|||||||
import struct
|
import struct
|
||||||
import time
|
import time
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from threading import Thread, Event
|
from threading import Thread, Event, Lock
|
||||||
from queue import Queue
|
from queue import Empty, Full, Queue
|
||||||
|
|
||||||
from config import cfg
|
from config import cfg
|
||||||
import DataTypes as dt
|
import DataTypes as dt
|
||||||
@@ -15,6 +15,8 @@ PACKET_VERSION = 1
|
|||||||
PKT_COMMAND = 1
|
PKT_COMMAND = 1
|
||||||
PKT_CONFIG = 2
|
PKT_CONFIG = 2
|
||||||
PKT_DISPLAY = 3
|
PKT_DISPLAY = 3
|
||||||
|
PKT_PING = 4
|
||||||
|
PKT_PONG = 5
|
||||||
|
|
||||||
FT_ARRAY_F32 = 1
|
FT_ARRAY_F32 = 1
|
||||||
FT_STRING = 2
|
FT_STRING = 2
|
||||||
@@ -23,6 +25,9 @@ FT_CONFIG_VAL = 4
|
|||||||
|
|
||||||
HEADER_FMT = "<B B H I" # ID, Ver, Len, Timestamp
|
HEADER_FMT = "<B B H I" # ID, Ver, Len, Timestamp
|
||||||
TLV_FMT = "<B H"
|
TLV_FMT = "<B H"
|
||||||
|
HEARTBEAT_INTERVAL = 0.5
|
||||||
|
CONNECTION_TIMEOUT = 2.0
|
||||||
|
RECONNECT_TIMEOUT = 30.0
|
||||||
|
|
||||||
class ESP32Communication(Thread):
|
class ESP32Communication(Thread):
|
||||||
def __init__(self, host=None, port=None, ip=None):
|
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
|
port = cfg.esp32_port if port is None else port
|
||||||
self.addr = (host, port)
|
self.addr = (host, port)
|
||||||
|
|
||||||
# UDP Socket - Zero Lag
|
|
||||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
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 = Event()
|
||||||
self.running.set()
|
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}")
|
print(f"Communication Initialized: Target {host}:{port}")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def connection_status(self):
|
||||||
|
return self._connection_status
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
# --- THE FIX: Send Configs immediately upon starting the thread ---
|
|
||||||
self.sync_robot_configs()
|
self.sync_robot_configs()
|
||||||
|
self._receiver_thread = Thread(target=self._receive_loop, daemon=True)
|
||||||
|
self._receiver_thread.start()
|
||||||
|
next_motion_time = time.monotonic()
|
||||||
|
|
||||||
while self.running.is_set():
|
|
||||||
if not self.tx_queue.empty():
|
|
||||||
data = self.tx_queue.get()
|
|
||||||
try:
|
try:
|
||||||
self.sock.sendto(data, self.addr)
|
while self.running.is_set():
|
||||||
except Exception as e:
|
now = time.monotonic()
|
||||||
print(f"UDP Send Error: {e}")
|
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
|
||||||
|
|
||||||
# Tiny sleep to prevent 100% CPU usage
|
if self._connection_status == "connected":
|
||||||
time.sleep(0.001)
|
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):
|
def sync_robot_configs(self):
|
||||||
"""
|
"""
|
||||||
@@ -82,24 +183,18 @@ class ESP32Communication(Thread):
|
|||||||
fields.append(struct.pack(TLV_FMT, FT_CONFIG_VAL, len(payload)) + payload)
|
fields.append(struct.pack(TLV_FMT, FT_CONFIG_VAL, len(payload)) + payload)
|
||||||
|
|
||||||
packet = self._build_packet(PKT_CONFIG, fields)
|
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):
|
def send_motion(self, radial_array: dt.RadArray):
|
||||||
"""Sends motion only if the data has changed."""
|
"""Store the latest command for transmission at the configured tick rate."""
|
||||||
# 1. Convert to degrees/uint8 as you did before
|
|
||||||
new_data = np.degrees(radial_array.data).astype(np.uint8)
|
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())]
|
fields = [self._tlv(FT_ARRAY_F32, new_data.tobytes())]
|
||||||
packet = self._build_packet(PKT_COMMAND, fields)
|
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=""):
|
def send_text(self, text=""):
|
||||||
"""Sends a dedicated display packet independent of motion."""
|
"""Sends a dedicated display packet independent of motion."""
|
||||||
@@ -112,7 +207,47 @@ class ESP32Communication(Thread):
|
|||||||
# Build the packet using the PKT_DISPLAY (ID 3)
|
# Build the packet using the PKT_DISPLAY (ID 3)
|
||||||
packet = self._build_packet(PKT_DISPLAY, [field])
|
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):
|
def _tlv(self, ftype, data):
|
||||||
return struct.pack(TLV_FMT, ftype, len(data)) + data
|
return struct.pack(TLV_FMT, ftype, len(data)) + data
|
||||||
@@ -132,7 +267,7 @@ class ESP32Communication(Thread):
|
|||||||
self.running.clear()
|
self.running.clear()
|
||||||
try:
|
try:
|
||||||
self.sock.close()
|
self.sock.close()
|
||||||
except Exception:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ from ArduinoCommunication import ArduinoCommunication
|
|||||||
|
|
||||||
class RobotBackend(Protocol):
|
class RobotBackend(Protocol):
|
||||||
"""Protocol defining hardware abstraction for both Simulation and Hardware backends."""
|
"""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 send_angles(self, rad_array: dt.RadArray) -> None: ...
|
||||||
def step_simulation(self) -> None: ...
|
def step_simulation(self) -> None: ...
|
||||||
def hard_reset_joints(self, target_angles: np.ndarray) -> None: ...
|
def hard_reset_joints(self, target_angles: np.ndarray) -> None: ...
|
||||||
@@ -35,6 +37,10 @@ class HardwareBackend:
|
|||||||
self.comm_channel = comm_channel
|
self.comm_channel = comm_channel
|
||||||
self.internal_angles = np.zeros(18, dtype=np.float32)
|
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:
|
def send_angles(self, rad_array: dt.RadArray) -> None:
|
||||||
self.internal_angles = rad_array.data.flatten().copy()
|
self.internal_angles = rad_array.data.flatten().copy()
|
||||||
if self.comm_channel:
|
if self.comm_channel:
|
||||||
@@ -71,6 +77,10 @@ class PyBulletBackend:
|
|||||||
def __init__(self, sim_instance: Simulation):
|
def __init__(self, sim_instance: Simulation):
|
||||||
self.sim = sim_instance
|
self.sim = sim_instance
|
||||||
|
|
||||||
|
@property
|
||||||
|
def connection_status(self) -> Optional[str]:
|
||||||
|
return None
|
||||||
|
|
||||||
def send_angles(self, rad_array: dt.RadArray) -> None:
|
def send_angles(self, rad_array: dt.RadArray) -> None:
|
||||||
if self.sim:
|
if self.sim:
|
||||||
self.sim.set_robot_joint_angles(rad_array)
|
self.sim.set_robot_joint_angles(rad_array)
|
||||||
@@ -171,6 +181,10 @@ class Robot:
|
|||||||
if self.backend:
|
if self.backend:
|
||||||
self.backend.send_angles(self.current_rad)
|
self.backend.send_angles(self.current_rad)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def connection_status(self) -> Optional[str]:
|
||||||
|
return self.backend.connection_status
|
||||||
|
|
||||||
def step_sim(self) -> None:
|
def step_sim(self) -> None:
|
||||||
if self.backend:
|
if self.backend:
|
||||||
self.backend.step_simulation()
|
self.backend.step_simulation()
|
||||||
|
|||||||
@@ -128,6 +128,19 @@ def create_parameter_gui(on_start_callback=None, on_stop_callback=None):
|
|||||||
dpg.show_viewport()
|
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:
|
def resolve_active_command(gamepad_cmd: dict | None) -> dict:
|
||||||
"""Selects motion vector based on current active source in GUI."""
|
"""Selects motion vector based on current active source in GUI."""
|
||||||
source = input_config["source"]
|
source = input_config["source"]
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ from gui.MainWindow import (
|
|||||||
create_parameter_gui,
|
create_parameter_gui,
|
||||||
render_gui_frame,
|
render_gui_frame,
|
||||||
stop_gui,
|
stop_gui,
|
||||||
resolve_active_command
|
resolve_active_command,
|
||||||
|
update_robot_status,
|
||||||
)
|
)
|
||||||
from inputs.PygameController import controller_loop
|
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.robot_state = active_cmd["state"]
|
||||||
robot_instance.vector_dirmov = active_cmd["dirmov"]
|
robot_instance.vector_dirmov = active_cmd["dirmov"]
|
||||||
robot_instance.tick()
|
robot_instance.tick()
|
||||||
|
if robot_instance.connection_status is not None:
|
||||||
|
update_robot_status(robot_instance.connection_status)
|
||||||
|
|
||||||
render_gui_frame()
|
render_gui_frame()
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user