1
0

connection_manager.py 23 KB

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