connection_manager.py 22 KB

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