connection_manager.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. import threading
  2. import time
  3. import logging
  4. import serial
  5. import serial.tools.list_ports
  6. import websocket
  7. import asyncio
  8. from modules.core.state import state
  9. from modules.led.led_controller import effect_loading, effect_idle, effect_connected, LEDController
  10. logger = logging.getLogger(__name__)
  11. IGNORE_PORTS = ['/dev/cu.debug-console', '/dev/cu.Bluetooth-Incoming-Port']
  12. # Global lock to prevent concurrent homing operations
  13. _homing_lock = threading.Lock()
  14. _is_homing = False
  15. ###############################################################################
  16. # Connection Abstraction
  17. ###############################################################################
  18. class BaseConnection:
  19. """Abstract base class for a connection."""
  20. def send(self, data: str) -> None:
  21. raise NotImplementedError
  22. def flush(self) -> None:
  23. raise NotImplementedError
  24. def readline(self) -> str:
  25. raise NotImplementedError
  26. def in_waiting(self) -> int:
  27. raise NotImplementedError
  28. def is_connected(self) -> bool:
  29. raise NotImplementedError
  30. def close(self) -> None:
  31. raise NotImplementedError
  32. ###############################################################################
  33. # Serial Connection Implementation
  34. ###############################################################################
  35. class SerialConnection(BaseConnection):
  36. def __init__(self, port: str, baudrate: int = 115200, timeout: int = 2):
  37. self.port = port
  38. self.baudrate = baudrate
  39. self.timeout = timeout
  40. self.lock = threading.RLock()
  41. logger.info(f'Connecting to Serial port {port}')
  42. self.ser = serial.Serial(port, baudrate, timeout=timeout)
  43. state.port = port
  44. logger.info(f'Connected to Serial port {port}')
  45. def send(self, data: str) -> None:
  46. with self.lock:
  47. self.ser.write(data.encode())
  48. self.ser.flush()
  49. def flush(self) -> None:
  50. with self.lock:
  51. self.ser.flush()
  52. def readline(self) -> str:
  53. with self.lock:
  54. return self.ser.readline().decode().strip()
  55. def in_waiting(self) -> int:
  56. with self.lock:
  57. return self.ser.in_waiting
  58. def is_connected(self) -> bool:
  59. return self.ser is not None and self.ser.is_open
  60. def close(self) -> None:
  61. # Run async update_machine_position in sync context
  62. try:
  63. loop = asyncio.new_event_loop()
  64. asyncio.set_event_loop(loop)
  65. loop.run_until_complete(update_machine_position())
  66. loop.close()
  67. except Exception as e:
  68. logger.error(f"Error updating machine position on close: {e}")
  69. with self.lock:
  70. if self.ser.is_open:
  71. self.ser.close()
  72. # Release the lock resources
  73. self.lock = None
  74. ###############################################################################
  75. # WebSocket Connection Implementation
  76. ###############################################################################
  77. class WebSocketConnection(BaseConnection):
  78. def __init__(self, url: str, timeout: int = 5):
  79. self.url = url
  80. self.timeout = timeout
  81. self.lock = threading.RLock()
  82. self.ws = None
  83. self.connect()
  84. def connect(self):
  85. logger.info(f'Connecting to Websocket {self.url}')
  86. self.ws = websocket.create_connection(self.url, timeout=self.timeout)
  87. state.port = self.url
  88. logger.info(f'Connected to Websocket {self.url}')
  89. def send(self, data: str) -> None:
  90. with self.lock:
  91. self.ws.send(data)
  92. def flush(self) -> None:
  93. # WebSocket sends immediately; nothing to flush.
  94. pass
  95. def readline(self) -> str:
  96. with self.lock:
  97. data = self.ws.recv()
  98. # Decode bytes to string if necessary
  99. if isinstance(data, bytes):
  100. data = data.decode('utf-8')
  101. return data.strip()
  102. def in_waiting(self) -> int:
  103. return 0 # Not applicable for WebSocket
  104. def is_connected(self) -> bool:
  105. return self.ws is not None
  106. def close(self) -> None:
  107. # Run async update_machine_position in sync context
  108. try:
  109. loop = asyncio.new_event_loop()
  110. asyncio.set_event_loop(loop)
  111. loop.run_until_complete(update_machine_position())
  112. loop.close()
  113. except Exception as e:
  114. logger.error(f"Error updating machine position on close: {e}")
  115. with self.lock:
  116. if self.ws:
  117. self.ws.close()
  118. # Release the lock resources
  119. self.lock = None
  120. def list_serial_ports():
  121. """Return a list of available serial ports."""
  122. ports = serial.tools.list_ports.comports()
  123. available_ports = [port.device for port in ports if port.device not in IGNORE_PORTS]
  124. logger.debug(f"Available serial ports: {available_ports}")
  125. return available_ports
  126. def device_init(homing=True):
  127. try:
  128. if get_machine_steps():
  129. logger.info(f"x_steps_per_mm: {state.x_steps_per_mm}, y_steps_per_mm: {state.y_steps_per_mm}, gear_ratio: {state.gear_ratio}")
  130. else:
  131. logger.fatal("Failed to get machine steps")
  132. state.conn.close()
  133. return False
  134. except:
  135. logger.fatal("Not GRBL firmware")
  136. state.conn.close()
  137. return False
  138. machine_x, machine_y = get_machine_position()
  139. if machine_x != state.machine_x or machine_y != state.machine_y:
  140. logger.info(f'x, y; {machine_x}, {machine_y}')
  141. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  142. if homing:
  143. success = home()
  144. if not success:
  145. logger.error("Homing failed during device initialization")
  146. else:
  147. logger.info('Machine position known, skipping home')
  148. logger.info(f'Theta: {state.current_theta}, rho: {state.current_rho}')
  149. logger.info(f'x, y; {machine_x}, {machine_y}')
  150. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  151. time.sleep(2) # Allow time for the connection to establish
  152. def connect_device(homing=True):
  153. if state.wled_ip:
  154. state.led_controller = LEDController(state.wled_ip)
  155. effect_loading(state.led_controller)
  156. ports = list_serial_ports()
  157. if state.port and state.port in ports:
  158. state.conn = SerialConnection(state.port)
  159. elif ports:
  160. state.conn = SerialConnection(ports[0])
  161. else:
  162. logger.error("Auto connect failed.")
  163. # state.conn = WebSocketConnection('ws://fluidnc.local:81')
  164. if (state.conn.is_connected() if state.conn else False):
  165. device_init(homing)
  166. if state.led_controller:
  167. effect_connected(state.led_controller)
  168. def get_status_response() -> str:
  169. """
  170. Send a status query ('?') and return the response if available.
  171. """
  172. while True:
  173. try:
  174. state.conn.send('?')
  175. response = state.conn.readline()
  176. if "MPos" in response:
  177. logger.debug(f"Status response: {response}")
  178. return response
  179. except Exception as e:
  180. logger.error(f"Error getting status response: {e}")
  181. return False
  182. time.sleep(1)
  183. def parse_machine_position(response: str):
  184. """
  185. Parse the work position (MPos) from a status response.
  186. Expected format: "<...|MPos:-994.869,-321.861,0.000|...>"
  187. Returns a tuple (work_x, work_y) if found, else None.
  188. """
  189. if "MPos:" not in response:
  190. return None
  191. try:
  192. wpos_section = next((part for part in response.split("|") if part.startswith("MPos:")), None)
  193. if wpos_section:
  194. wpos_str = wpos_section.split(":", 1)[1]
  195. wpos_values = wpos_str.split(",")
  196. work_x = float(wpos_values[0])
  197. work_y = float(wpos_values[1])
  198. return work_x, work_y
  199. except Exception as e:
  200. logger.error(f"Error parsing work position: {e}")
  201. return None
  202. async def send_grbl_coordinates(x, y, speed=600, timeout=2, home=False):
  203. """
  204. Send a G-code command to FluidNC and wait for an 'ok' response.
  205. If no response after set timeout, sets state to stop and disconnects.
  206. """
  207. logger.debug(f"Sending G-code: X{x} Y{y} at F{speed}")
  208. # Track overall attempt time
  209. overall_start_time = time.time()
  210. while True:
  211. try:
  212. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  213. # Use asyncio.to_thread for both send and receive operations to avoid blocking
  214. await asyncio.to_thread(state.conn.send, gcode + "\n")
  215. logger.debug(f"Sent command: {gcode}")
  216. start_time = time.time()
  217. while True:
  218. # Use asyncio.to_thread for blocking I/O operations
  219. response = await asyncio.to_thread(state.conn.readline)
  220. logger.debug(f"Response: {response}")
  221. if response.lower() == "ok":
  222. logger.debug("Command execution confirmed.")
  223. return
  224. except Exception as e:
  225. # Store the error string inside the exception block
  226. error_str = str(e)
  227. logger.warning(f"Error sending command: {error_str}")
  228. # Immediately return for device not configured errors
  229. if "Device not configured" in error_str or "Errno 6" in error_str:
  230. logger.error(f"Device configuration error detected: {error_str}")
  231. state.stop_requested = True
  232. state.conn = None
  233. state.is_connected = False
  234. logger.info("Connection marked as disconnected due to device error")
  235. return False
  236. logger.warning(f"No 'ok' received for X{x} Y{y}, speed {speed}. Retrying...")
  237. await asyncio.sleep(0.1)
  238. # If we reach here, the timeout has occurred
  239. logger.error(f"Failed to receive 'ok' response after {max_total_attempt_time} seconds. Stopping and disconnecting.")
  240. # Set state to stop
  241. state.stop_requested = True
  242. # Set connection status to disconnected
  243. if state.conn:
  244. try:
  245. state.conn.disconnect()
  246. except:
  247. pass
  248. state.conn = None
  249. # Update the state connection status
  250. state.is_connected = False
  251. logger.info("Connection marked as disconnected due to timeout")
  252. return False
  253. def get_machine_steps(timeout=10):
  254. """
  255. Get machine steps/mm from the GRBL controller.
  256. Returns True if successful, False otherwise.
  257. """
  258. if not state.conn or not state.conn.is_connected():
  259. logger.error("Cannot get machine steps: No connection available")
  260. return False
  261. x_steps_per_mm = None
  262. y_steps_per_mm = None
  263. gear_ratio = None
  264. start_time = time.time()
  265. # Clear any pending data in the buffer
  266. try:
  267. while state.conn.in_waiting() > 0:
  268. state.conn.readline()
  269. except Exception as e:
  270. logger.warning(f"Error clearing buffer: {e}")
  271. # Send the command to request all settings
  272. try:
  273. logger.info("Requesting GRBL settings with $$ command")
  274. state.conn.send("$$\n")
  275. time.sleep(0.5) # Give GRBL a moment to process and respond
  276. except Exception as e:
  277. logger.error(f"Error sending $$ command: {e}")
  278. return False
  279. # Wait for and process responses
  280. settings_complete = False
  281. while time.time() - start_time < timeout and not settings_complete:
  282. try:
  283. # Attempt to read a line from the connection
  284. if state.conn.in_waiting() > 0:
  285. response = state.conn.readline()
  286. logger.debug(f"Raw response: {response}")
  287. # Process the line
  288. if response.strip(): # Only process non-empty lines
  289. for line in response.splitlines():
  290. line = line.strip()
  291. logger.debug(f"Config response: {line}")
  292. if line.startswith("$100="):
  293. x_steps_per_mm = float(line.split("=")[1])
  294. state.x_steps_per_mm = x_steps_per_mm
  295. logger.info(f"X steps per mm: {x_steps_per_mm}")
  296. elif line.startswith("$101="):
  297. y_steps_per_mm = float(line.split("=")[1])
  298. state.y_steps_per_mm = y_steps_per_mm
  299. logger.info(f"Y steps per mm: {y_steps_per_mm}")
  300. elif line.startswith("$131="):
  301. gear_ratio = float(line.split("=")[1])
  302. state.gear_ratio = gear_ratio
  303. logger.info(f"Gear ratio: {gear_ratio}")
  304. elif line.startswith("$22="):
  305. # $22 reports if the homing cycle is enabled
  306. # returns 0 if disabled, 1 if enabled
  307. homing = int(line.split('=')[1])
  308. state.homing = homing
  309. logger.info(f"Homing enabled: {homing}")
  310. # Check if we've received all the settings we need
  311. if x_steps_per_mm is not None and y_steps_per_mm is not None and gear_ratio is not None:
  312. settings_complete = True
  313. else:
  314. # No data waiting, small sleep to prevent CPU thrashing
  315. time.sleep(0.1)
  316. # If it's taking too long, try sending the command again after 3 seconds
  317. elapsed = time.time() - start_time
  318. if elapsed > 3 and elapsed < 4:
  319. logger.warning("No response yet, sending $$ command again")
  320. state.conn.send("$$\n")
  321. except Exception as e:
  322. logger.error(f"Error getting machine steps: {e}")
  323. time.sleep(0.5)
  324. # Process results and determine table type
  325. if settings_complete:
  326. if y_steps_per_mm == 180:
  327. state.table_type = 'dune_weaver_mini'
  328. elif y_steps_per_mm >= 320:
  329. state.table_type = 'dune_weaver_pro'
  330. elif y_steps_per_mm == 287:
  331. state.table_type = 'dune_weaver'
  332. else:
  333. state.table_type = None
  334. logger.warning(f"Unknown table type with Y steps/mm: {y_steps_per_mm}")
  335. logger.info(f"Machine type detected: {state.table_type}")
  336. return True
  337. else:
  338. missing = []
  339. if x_steps_per_mm is None: missing.append("X steps/mm")
  340. if y_steps_per_mm is None: missing.append("Y steps/mm")
  341. if gear_ratio is None: missing.append("gear ratio")
  342. logger.error(f"Failed to get all machine parameters after {timeout}s. Missing: {', '.join(missing)}")
  343. return False
  344. def home(timeout=15):
  345. """
  346. Perform homing by checking device configuration and sending the appropriate commands.
  347. Args:
  348. timeout: Maximum time in seconds to wait for homing to complete (default: 15)
  349. """
  350. global _is_homing
  351. # Check if homing is already in progress
  352. if not _homing_lock.acquire(blocking=False):
  353. logger.warning("Homing already in progress, skipping duplicate request")
  354. return False
  355. try:
  356. _is_homing = True
  357. logger.info("Starting homing procedure")
  358. # Flag to track if homing completed
  359. homing_complete = threading.Event()
  360. homing_success = False
  361. def home_internal():
  362. nonlocal homing_success
  363. try:
  364. if state.homing:
  365. logger.info("Using sensorless homing")
  366. state.conn.send("$H\n")
  367. state.conn.send("G1 Y0 F100\n")
  368. else:
  369. homing_speed = 400
  370. if state.table_type == 'dune_weaver_mini':
  371. homing_speed = 120
  372. logger.info("Sensorless homing not supported. Using crash homing")
  373. logger.info(f"Homing with speed {homing_speed}")
  374. # Run async function in new event loop
  375. loop = asyncio.new_event_loop()
  376. asyncio.set_event_loop(loop)
  377. try:
  378. if state.gear_ratio == 6.25:
  379. result = loop.run_until_complete(send_grbl_coordinates(0, - 30, homing_speed, home=True))
  380. if result == False:
  381. logger.error("Homing failed - send_grbl_coordinates returned False")
  382. homing_complete.set()
  383. return
  384. state.machine_y -= 30
  385. else:
  386. result = loop.run_until_complete(send_grbl_coordinates(0, -22, homing_speed, home=True))
  387. if result == False:
  388. logger.error("Homing failed - send_grbl_coordinates returned False")
  389. homing_complete.set()
  390. return
  391. state.machine_y -= 22
  392. finally:
  393. loop.close()
  394. state.current_theta = state.current_rho = 0
  395. homing_success = True
  396. homing_complete.set()
  397. except Exception as e:
  398. logger.error(f"Error during homing: {e}")
  399. homing_complete.set()
  400. # Start homing in a separate thread
  401. homing_thread = threading.Thread(target=home_internal)
  402. homing_thread.daemon = True
  403. homing_thread.start()
  404. # Wait for homing to complete or timeout
  405. if not homing_complete.wait(timeout):
  406. logger.error(f"Homing timeout after {timeout} seconds")
  407. # Try to stop any ongoing movement
  408. try:
  409. if state.conn and state.conn.is_connected():
  410. state.conn.send("!\n") # Send feed hold
  411. time.sleep(0.1)
  412. state.conn.send("\x18\n") # Send reset
  413. except Exception as e:
  414. logger.error(f"Error stopping movement after timeout: {e}")
  415. return False
  416. if not homing_success:
  417. logger.error("Homing failed")
  418. return False
  419. logger.info("Homing completed successfully")
  420. return True
  421. finally:
  422. # Always release the lock when done
  423. _is_homing = False
  424. _homing_lock.release()
  425. logger.debug("Homing lock released")
  426. def check_idle():
  427. """
  428. Continuously check if the device is idle (synchronous version).
  429. """
  430. logger.info("Checking idle")
  431. while True:
  432. response = get_status_response()
  433. if response and "Idle" in response:
  434. logger.info("Device is idle")
  435. # Schedule async update_machine_position in the existing event loop
  436. try:
  437. # Try to schedule in existing event loop if available
  438. try:
  439. loop = asyncio.get_running_loop()
  440. # Create a task but don't await it (fire and forget)
  441. asyncio.create_task(update_machine_position())
  442. logger.debug("Scheduled machine position update task")
  443. except RuntimeError:
  444. # No event loop running, skip machine position update
  445. logger.debug("No event loop running, skipping machine position update")
  446. except Exception as e:
  447. logger.error(f"Error scheduling machine position update: {e}")
  448. return True
  449. time.sleep(1)
  450. async def check_idle_async():
  451. """
  452. Continuously check if the device is idle (async version).
  453. """
  454. logger.info("Checking idle (async)")
  455. while True:
  456. response = await asyncio.to_thread(get_status_response)
  457. if response and "Idle" in response:
  458. logger.info("Device is idle")
  459. try:
  460. await update_machine_position()
  461. except Exception as e:
  462. logger.error(f"Error updating machine position: {e}")
  463. return True
  464. await asyncio.sleep(1)
  465. def get_machine_position(timeout=5):
  466. """
  467. Query the device for its position.
  468. """
  469. start_time = time.time()
  470. while time.time() - start_time < timeout:
  471. try:
  472. state.conn.send('?')
  473. response = state.conn.readline()
  474. logger.debug(f"Raw status response: {response}")
  475. if "MPos" in response:
  476. pos = parse_machine_position(response)
  477. if pos:
  478. machine_x, machine_y = pos
  479. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  480. return machine_x, machine_y
  481. except Exception as e:
  482. logger.error(f"Error getting machine position: {e}")
  483. return
  484. time.sleep(0.1)
  485. logger.warning("Timeout reached waiting for machine position")
  486. return None, None
  487. async def update_machine_position():
  488. if (state.conn.is_connected() if state.conn else False):
  489. try:
  490. logger.info('Saving machine position')
  491. state.machine_x, state.machine_y = await asyncio.to_thread(get_machine_position)
  492. await asyncio.to_thread(state.save)
  493. logger.info(f'Machine position saved: {state.machine_x}, {state.machine_y}')
  494. except Exception as e:
  495. logger.error(f"Error updating machine position: {e}")
  496. def restart_connection(homing=False):
  497. """
  498. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  499. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  500. The new connection is saved to state.conn.
  501. Returns:
  502. True if the connection was restarted successfully, False otherwise.
  503. """
  504. try:
  505. if (state.conn.is_connected() if state.conn else False):
  506. logger.info("Closing current connection...")
  507. state.conn.close()
  508. except Exception as e:
  509. logger.error(f"Error while closing connection: {e}")
  510. # Clear the connection reference.
  511. state.conn = None
  512. logger.info("Attempting to restart connection...")
  513. try:
  514. connect_device(homing) # This will set state.conn appropriately.
  515. if (state.conn.is_connected() if state.conn else False):
  516. logger.info("Connection restarted successfully.")
  517. return True
  518. else:
  519. logger.error("Failed to restart connection.")
  520. return False
  521. except Exception as e:
  522. logger.error(f"Error restarting connection: {e}")
  523. return False