connection_manager.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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
  175. if state.led_controller:
  176. state.led_controller.effect_connected()
  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. import threading
  360. # Flag to track if homing completed
  361. homing_complete = threading.Event()
  362. homing_success = False
  363. def home_internal():
  364. nonlocal homing_success
  365. try:
  366. if state.homing:
  367. logger.info("Using sensorless homing")
  368. state.conn.send("$H\n")
  369. state.conn.send("G1 Y0 F100\n")
  370. else:
  371. homing_speed = 400
  372. if state.table_type == 'dune_weaver_mini':
  373. homing_speed = 120
  374. logger.info("Sensorless homing not supported. Using crash homing")
  375. logger.info(f"Homing with speed {homing_speed}")
  376. # Run async function in new event loop
  377. loop = asyncio.new_event_loop()
  378. asyncio.set_event_loop(loop)
  379. try:
  380. if state.gear_ratio == 6.25:
  381. result = loop.run_until_complete(send_grbl_coordinates(0, - 30, homing_speed, home=True))
  382. if result == False:
  383. logger.error("Homing failed - send_grbl_coordinates returned False")
  384. homing_complete.set()
  385. return
  386. state.machine_y -= 30
  387. else:
  388. result = loop.run_until_complete(send_grbl_coordinates(0, -22, 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 -= 22
  394. finally:
  395. loop.close()
  396. state.current_theta = state.current_rho = 0
  397. homing_success = True
  398. homing_complete.set()
  399. except Exception as e:
  400. logger.error(f"Error during homing: {e}")
  401. homing_complete.set()
  402. # Start homing in a separate thread
  403. homing_thread = threading.Thread(target=home_internal)
  404. homing_thread.daemon = True
  405. homing_thread.start()
  406. # Wait for homing to complete or timeout
  407. if not homing_complete.wait(timeout):
  408. logger.error(f"Homing timeout after {timeout} seconds")
  409. # Try to stop any ongoing movement
  410. try:
  411. if state.conn and state.conn.is_connected():
  412. state.conn.send("!\n") # Send feed hold
  413. time.sleep(0.1)
  414. state.conn.send("\x18\n") # Send reset
  415. except Exception as e:
  416. logger.error(f"Error stopping movement after timeout: {e}")
  417. return False
  418. if not homing_success:
  419. logger.error("Homing failed")
  420. return False
  421. logger.info("Homing completed successfully")
  422. return True
  423. def check_idle():
  424. """
  425. Continuously check if the device is idle (synchronous version).
  426. """
  427. logger.info("Checking idle")
  428. while True:
  429. response = get_status_response()
  430. if response and "Idle" in response:
  431. logger.info("Device is idle")
  432. # Schedule async update_machine_position in the existing event loop
  433. try:
  434. # Try to schedule in existing event loop if available
  435. try:
  436. loop = asyncio.get_running_loop()
  437. # Create a task but don't await it (fire and forget)
  438. asyncio.create_task(update_machine_position())
  439. logger.debug("Scheduled machine position update task")
  440. except RuntimeError:
  441. # No event loop running, skip machine position update
  442. logger.debug("No event loop running, skipping machine position update")
  443. except Exception as e:
  444. logger.error(f"Error scheduling machine position update: {e}")
  445. return True
  446. time.sleep(1)
  447. async def check_idle_async():
  448. """
  449. Continuously check if the device is idle (async version).
  450. """
  451. logger.info("Checking idle (async)")
  452. while True:
  453. response = await asyncio.to_thread(get_status_response)
  454. if response and "Idle" in response:
  455. logger.info("Device is idle")
  456. try:
  457. await update_machine_position()
  458. except Exception as e:
  459. logger.error(f"Error updating machine position: {e}")
  460. return True
  461. await asyncio.sleep(1)
  462. def get_machine_position(timeout=5):
  463. """
  464. Query the device for its position.
  465. """
  466. start_time = time.time()
  467. while time.time() - start_time < timeout:
  468. try:
  469. state.conn.send('?')
  470. response = state.conn.readline()
  471. logger.debug(f"Raw status response: {response}")
  472. if "MPos" in response:
  473. pos = parse_machine_position(response)
  474. if pos:
  475. machine_x, machine_y = pos
  476. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  477. return machine_x, machine_y
  478. except Exception as e:
  479. logger.error(f"Error getting machine position: {e}")
  480. return
  481. time.sleep(0.1)
  482. logger.warning("Timeout reached waiting for machine position")
  483. return None, None
  484. async def update_machine_position():
  485. if (state.conn.is_connected() if state.conn else False):
  486. try:
  487. logger.info('Saving machine position')
  488. state.machine_x, state.machine_y = await asyncio.to_thread(get_machine_position)
  489. await asyncio.to_thread(state.save)
  490. logger.info(f'Machine position saved: {state.machine_x}, {state.machine_y}')
  491. except Exception as e:
  492. logger.error(f"Error updating machine position: {e}")
  493. def restart_connection(homing=False):
  494. """
  495. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  496. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  497. The new connection is saved to state.conn.
  498. Returns:
  499. True if the connection was restarted successfully, False otherwise.
  500. """
  501. try:
  502. if (state.conn.is_connected() if state.conn else False):
  503. logger.info("Closing current connection...")
  504. state.conn.close()
  505. except Exception as e:
  506. logger.error(f"Error while closing connection: {e}")
  507. # Clear the connection reference.
  508. state.conn = None
  509. logger.info("Attempting to restart connection...")
  510. try:
  511. connect_device(homing) # This will set state.conn appropriately.
  512. if (state.conn.is_connected() if state.conn else False):
  513. logger.info("Connection restarted successfully.")
  514. return True
  515. else:
  516. logger.error("Failed to restart connection.")
  517. return False
  518. except Exception as e:
  519. logger.error(f"Error restarting connection: {e}")
  520. return False