connection_manager.py 23 KB

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