connection_manager.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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_interface import LEDInterface
  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. # Initialize LED interface based on configured provider
  151. if state.led_provider == "wled" and state.wled_ip:
  152. state.led_controller = LEDInterface(provider="wled", ip_address=state.wled_ip)
  153. elif state.led_provider == "hyperion" and state.hyperion_ip:
  154. state.led_controller = LEDInterface(
  155. provider="hyperion",
  156. ip_address=state.hyperion_ip,
  157. port=state.hyperion_port
  158. )
  159. else:
  160. state.led_controller = None
  161. # Show loading effect
  162. if state.led_controller:
  163. state.led_controller.effect_loading()
  164. ports = list_serial_ports()
  165. if state.port and state.port in ports:
  166. state.conn = SerialConnection(state.port)
  167. elif ports:
  168. state.conn = SerialConnection(ports[0])
  169. else:
  170. logger.error("Auto connect failed.")
  171. # state.conn = WebSocketConnection('ws://fluidnc.local:81')
  172. if (state.conn.is_connected() if state.conn else False):
  173. # Check for alarm state and unlock if needed before initializing
  174. if not check_and_unlock_alarm():
  175. logger.error("Failed to unlock device from alarm state")
  176. # Still proceed with device_init but log the issue
  177. device_init(homing)
  178. # Show connected effect, then transition to configured idle effect
  179. if state.led_controller:
  180. logger.info("Showing LED connected effect (green flash)")
  181. state.led_controller.effect_connected()
  182. # Set the configured idle effect after connection
  183. logger.info(f"Setting LED to idle effect: {state.dw_led_idle_effect}")
  184. state.led_controller.effect_idle(state.dw_led_idle_effect)
  185. def check_and_unlock_alarm():
  186. """
  187. Check if GRBL is in alarm state and unlock it with $X if needed.
  188. Returns True if device is ready (unlocked or no alarm), False on error.
  189. """
  190. try:
  191. logger.info("Checking device status for alarm state...")
  192. # Send status query
  193. state.conn.send('?\n')
  194. time.sleep(0.1)
  195. # Read response with timeout
  196. max_attempts = 5
  197. response = None
  198. for attempt in range(max_attempts):
  199. if state.conn.in_waiting() > 0:
  200. response = state.conn.readline()
  201. logger.debug(f"Status response: {response}")
  202. break
  203. time.sleep(0.1)
  204. if not response:
  205. logger.warning("No status response received, proceeding anyway")
  206. return True
  207. # Check for alarm state
  208. if "Alarm" in response:
  209. logger.warning(f"Device in ALARM state: {response}")
  210. logger.info("Sending $X to unlock...")
  211. # Send unlock command
  212. state.conn.send('$X\n')
  213. time.sleep(0.5)
  214. # Verify unlock succeeded
  215. state.conn.send('?\n')
  216. time.sleep(0.1)
  217. verify_response = state.conn.readline()
  218. logger.debug(f"Verification response: {verify_response}")
  219. if "Alarm" in verify_response:
  220. logger.error("Failed to unlock device from alarm state")
  221. return False
  222. else:
  223. logger.info("Device successfully unlocked")
  224. return True
  225. else:
  226. logger.info("Device not in alarm state, proceeding normally")
  227. return True
  228. except Exception as e:
  229. logger.error(f"Error checking/unlocking alarm: {e}")
  230. return False
  231. def get_status_response() -> str:
  232. """
  233. Send a status query ('?') and return the response if available.
  234. """
  235. while True:
  236. try:
  237. state.conn.send('?')
  238. response = state.conn.readline()
  239. if "MPos" in response:
  240. logger.debug(f"Status response: {response}")
  241. return response
  242. except Exception as e:
  243. logger.error(f"Error getting status response: {e}")
  244. return False
  245. time.sleep(1)
  246. def parse_machine_position(response: str):
  247. """
  248. Parse the work position (MPos) from a status response.
  249. Expected format: "<...|MPos:-994.869,-321.861,0.000|...>"
  250. Returns a tuple (work_x, work_y) if found, else None.
  251. """
  252. if "MPos:" not in response:
  253. return None
  254. try:
  255. wpos_section = next((part for part in response.split("|") if part.startswith("MPos:")), None)
  256. if wpos_section:
  257. wpos_str = wpos_section.split(":", 1)[1]
  258. wpos_values = wpos_str.split(",")
  259. work_x = float(wpos_values[0])
  260. work_y = float(wpos_values[1])
  261. return work_x, work_y
  262. except Exception as e:
  263. logger.error(f"Error parsing work position: {e}")
  264. return None
  265. async def send_grbl_coordinates(x, y, speed=600, timeout=2, home=False):
  266. """
  267. Send a G-code command to FluidNC and wait for an 'ok' response.
  268. If no response after set timeout, sets state to stop and disconnects.
  269. """
  270. logger.debug(f"Sending G-code: X{x} Y{y} at F{speed}")
  271. # Track overall attempt time
  272. overall_start_time = time.time()
  273. while True:
  274. try:
  275. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  276. # Use asyncio.to_thread for both send and receive operations to avoid blocking
  277. await asyncio.to_thread(state.conn.send, gcode + "\n")
  278. logger.debug(f"Sent command: {gcode}")
  279. start_time = time.time()
  280. while True:
  281. # Use asyncio.to_thread for blocking I/O operations
  282. response = await asyncio.to_thread(state.conn.readline)
  283. logger.debug(f"Response: {response}")
  284. if response.lower() == "ok":
  285. logger.debug("Command execution confirmed.")
  286. return
  287. except Exception as e:
  288. # Store the error string inside the exception block
  289. error_str = str(e)
  290. logger.warning(f"Error sending command: {error_str}")
  291. # Immediately return for device not configured errors
  292. if "Device not configured" in error_str or "Errno 6" in error_str:
  293. logger.error(f"Device configuration error detected: {error_str}")
  294. state.stop_requested = True
  295. state.conn = None
  296. state.is_connected = False
  297. logger.info("Connection marked as disconnected due to device error")
  298. return False
  299. logger.warning(f"No 'ok' received for X{x} Y{y}, speed {speed}. Retrying...")
  300. await asyncio.sleep(0.1)
  301. # If we reach here, the timeout has occurred
  302. logger.error(f"Failed to receive 'ok' response after {max_total_attempt_time} seconds. Stopping and disconnecting.")
  303. # Set state to stop
  304. state.stop_requested = True
  305. # Set connection status to disconnected
  306. if state.conn:
  307. try:
  308. state.conn.disconnect()
  309. except:
  310. pass
  311. state.conn = None
  312. # Update the state connection status
  313. state.is_connected = False
  314. logger.info("Connection marked as disconnected due to timeout")
  315. return False
  316. def get_machine_steps(timeout=10):
  317. """
  318. Get machine steps/mm from the GRBL controller.
  319. Returns True if successful, False otherwise.
  320. """
  321. if not state.conn or not state.conn.is_connected():
  322. logger.error("Cannot get machine steps: No connection available")
  323. return False
  324. x_steps_per_mm = None
  325. y_steps_per_mm = None
  326. gear_ratio = None
  327. start_time = time.time()
  328. # Clear any pending data in the buffer
  329. try:
  330. while state.conn.in_waiting() > 0:
  331. state.conn.readline()
  332. except Exception as e:
  333. logger.warning(f"Error clearing buffer: {e}")
  334. # Send the command to request all settings
  335. try:
  336. logger.info("Requesting GRBL settings with $$ command")
  337. state.conn.send("$$\n")
  338. time.sleep(0.5) # Give GRBL a moment to process and respond
  339. except Exception as e:
  340. logger.error(f"Error sending $$ command: {e}")
  341. return False
  342. # Wait for and process responses
  343. settings_complete = False
  344. while time.time() - start_time < timeout and not settings_complete:
  345. try:
  346. # Attempt to read a line from the connection
  347. if state.conn.in_waiting() > 0:
  348. response = state.conn.readline()
  349. logger.debug(f"Raw response: {response}")
  350. # Process the line
  351. if response.strip(): # Only process non-empty lines
  352. for line in response.splitlines():
  353. line = line.strip()
  354. logger.debug(f"Config response: {line}")
  355. if line.startswith("$100="):
  356. x_steps_per_mm = float(line.split("=")[1])
  357. state.x_steps_per_mm = x_steps_per_mm
  358. logger.info(f"X steps per mm: {x_steps_per_mm}")
  359. elif line.startswith("$101="):
  360. y_steps_per_mm = float(line.split("=")[1])
  361. state.y_steps_per_mm = y_steps_per_mm
  362. logger.info(f"Y steps per mm: {y_steps_per_mm}")
  363. elif line.startswith("$131="):
  364. gear_ratio = float(line.split("=")[1])
  365. state.gear_ratio = gear_ratio
  366. logger.info(f"Gear ratio: {gear_ratio}")
  367. elif line.startswith("$22="):
  368. # $22 reports if the homing cycle is enabled
  369. # returns 0 if disabled, 1 if enabled
  370. homing = int(line.split('=')[1])
  371. state.homing = homing
  372. logger.info(f"Homing enabled: {homing}")
  373. # Check if we've received all the settings we need
  374. if x_steps_per_mm is not None and y_steps_per_mm is not None and gear_ratio is not None:
  375. settings_complete = True
  376. else:
  377. # No data waiting, small sleep to prevent CPU thrashing
  378. time.sleep(0.1)
  379. # If it's taking too long, try sending the command again after 3 seconds
  380. elapsed = time.time() - start_time
  381. if elapsed > 3 and elapsed < 4:
  382. logger.warning("No response yet, sending $$ command again")
  383. state.conn.send("$$\n")
  384. except Exception as e:
  385. logger.error(f"Error getting machine steps: {e}")
  386. time.sleep(0.5)
  387. # Process results and determine table type
  388. if settings_complete:
  389. if y_steps_per_mm == 180:
  390. state.table_type = 'dune_weaver_mini'
  391. elif y_steps_per_mm >= 320:
  392. state.table_type = 'dune_weaver_pro'
  393. elif y_steps_per_mm == 287:
  394. state.table_type = 'dune_weaver'
  395. else:
  396. state.table_type = None
  397. logger.warning(f"Unknown table type with Y steps/mm: {y_steps_per_mm}")
  398. logger.info(f"Machine type detected: {state.table_type}")
  399. return True
  400. else:
  401. missing = []
  402. if x_steps_per_mm is None: missing.append("X steps/mm")
  403. if y_steps_per_mm is None: missing.append("Y steps/mm")
  404. if gear_ratio is None: missing.append("gear ratio")
  405. logger.error(f"Failed to get all machine parameters after {timeout}s. Missing: {', '.join(missing)}")
  406. return False
  407. def home(timeout=15):
  408. """
  409. Perform homing by checking device configuration and sending the appropriate commands.
  410. Args:
  411. timeout: Maximum time in seconds to wait for homing to complete (default: 15)
  412. """
  413. import threading
  414. # Flag to track if homing completed
  415. homing_complete = threading.Event()
  416. homing_success = False
  417. def home_internal():
  418. nonlocal homing_success
  419. try:
  420. if state.homing:
  421. logger.info("Using sensorless homing")
  422. state.conn.send("$H\n")
  423. state.conn.send("G1 Y0 F100\n")
  424. else:
  425. homing_speed = 400
  426. if state.table_type == 'dune_weaver_mini':
  427. homing_speed = 120
  428. logger.info("Sensorless homing not supported. Using crash homing")
  429. logger.info(f"Homing with speed {homing_speed}")
  430. # Run async function in new event loop
  431. loop = asyncio.new_event_loop()
  432. asyncio.set_event_loop(loop)
  433. try:
  434. if state.table_type == 'dune_weaver_mini':
  435. result = loop.run_until_complete(send_grbl_coordinates(0, - 30, homing_speed, home=True))
  436. if result == False:
  437. logger.error("Homing failed - send_grbl_coordinates returned False")
  438. homing_complete.set()
  439. return
  440. state.machine_y -= 30
  441. else:
  442. result = loop.run_until_complete(send_grbl_coordinates(0, -22, homing_speed, home=True))
  443. if result == False:
  444. logger.error("Homing failed - send_grbl_coordinates returned False")
  445. homing_complete.set()
  446. return
  447. state.machine_y -= 22
  448. finally:
  449. loop.close()
  450. # Wait for device to reach idle state after homing
  451. logger.info("Waiting for device to reach idle state after homing...")
  452. idle_reached = check_idle()
  453. if idle_reached:
  454. state.current_rho = 0
  455. if not state.current_theta:
  456. state.current_theta = 0
  457. homing_success = True
  458. logger.info("Homing completed and device is idle")
  459. else:
  460. logger.error("Device did not reach idle state after homing")
  461. homing_complete.set()
  462. except Exception as e:
  463. logger.error(f"Error during homing: {e}")
  464. homing_complete.set()
  465. # Start homing in a separate thread
  466. homing_thread = threading.Thread(target=home_internal)
  467. homing_thread.daemon = True
  468. homing_thread.start()
  469. # Wait for homing to complete or timeout
  470. if not homing_complete.wait(timeout):
  471. logger.error(f"Homing timeout after {timeout} seconds")
  472. # Try to stop any ongoing movement
  473. try:
  474. if state.conn and state.conn.is_connected():
  475. state.conn.send("!\n") # Send feed hold
  476. time.sleep(0.1)
  477. state.conn.send("\x18\n") # Send reset
  478. except Exception as e:
  479. logger.error(f"Error stopping movement after timeout: {e}")
  480. return False
  481. if not homing_success:
  482. logger.error("Homing failed")
  483. return False
  484. logger.info("Homing completed successfully")
  485. return True
  486. def check_idle():
  487. """
  488. Continuously check if the device is idle (synchronous version).
  489. """
  490. logger.info("Checking idle")
  491. while True:
  492. response = get_status_response()
  493. if response and "Idle" in response:
  494. logger.info("Device is idle")
  495. # Schedule async update_machine_position in the existing event loop
  496. try:
  497. # Try to schedule in existing event loop if available
  498. try:
  499. loop = asyncio.get_running_loop()
  500. # Create a task but don't await it (fire and forget)
  501. asyncio.create_task(update_machine_position())
  502. logger.debug("Scheduled machine position update task")
  503. except RuntimeError:
  504. # No event loop running, skip machine position update
  505. logger.debug("No event loop running, skipping machine position update")
  506. except Exception as e:
  507. logger.error(f"Error scheduling machine position update: {e}")
  508. return True
  509. time.sleep(1)
  510. async def check_idle_async():
  511. """
  512. Continuously check if the device is idle (async version).
  513. """
  514. logger.info("Checking idle (async)")
  515. while True:
  516. response = await asyncio.to_thread(get_status_response)
  517. if response and "Idle" in response:
  518. logger.info("Device is idle")
  519. try:
  520. await update_machine_position()
  521. except Exception as e:
  522. logger.error(f"Error updating machine position: {e}")
  523. return True
  524. await asyncio.sleep(1)
  525. def get_machine_position(timeout=5):
  526. """
  527. Query the device for its position.
  528. """
  529. start_time = time.time()
  530. while time.time() - start_time < timeout:
  531. try:
  532. state.conn.send('?')
  533. response = state.conn.readline()
  534. logger.debug(f"Raw status response: {response}")
  535. if "MPos" in response:
  536. pos = parse_machine_position(response)
  537. if pos:
  538. machine_x, machine_y = pos
  539. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  540. return machine_x, machine_y
  541. except Exception as e:
  542. logger.error(f"Error getting machine position: {e}")
  543. return
  544. time.sleep(0.1)
  545. logger.warning("Timeout reached waiting for machine position")
  546. return None, None
  547. async def update_machine_position():
  548. if (state.conn.is_connected() if state.conn else False):
  549. try:
  550. logger.info('Saving machine position')
  551. state.machine_x, state.machine_y = await asyncio.to_thread(get_machine_position)
  552. await asyncio.to_thread(state.save)
  553. logger.info(f'Machine position saved: {state.machine_x}, {state.machine_y}')
  554. except Exception as e:
  555. logger.error(f"Error updating machine position: {e}")
  556. def restart_connection(homing=False):
  557. """
  558. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  559. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  560. The new connection is saved to state.conn.
  561. Returns:
  562. True if the connection was restarted successfully, False otherwise.
  563. """
  564. try:
  565. if (state.conn.is_connected() if state.conn else False):
  566. logger.info("Closing current connection...")
  567. state.conn.close()
  568. except Exception as e:
  569. logger.error(f"Error while closing connection: {e}")
  570. # Clear the connection reference.
  571. state.conn = None
  572. logger.info("Attempting to restart connection...")
  573. try:
  574. connect_device(homing) # This will set state.conn appropriately.
  575. if (state.conn.is_connected() if state.conn else False):
  576. logger.info("Connection restarted successfully.")
  577. return True
  578. else:
  579. logger.error("Failed to restart connection.")
  580. return False
  581. except Exception as e:
  582. logger.error(f"Error restarting connection: {e}")
  583. return False