connection_manager.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  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 import pattern_manager
  9. from modules.core.state import state
  10. from modules.led.led_interface import LEDInterface
  11. from modules.led.idle_timeout_manager import idle_timeout_manager
  12. from modules.connection.reed_switch import ReedSwitchMonitor
  13. logger = logging.getLogger(__name__)
  14. IGNORE_PORTS = ['/dev/cu.debug-console', '/dev/cu.Bluetooth-Incoming-Port']
  15. async def _check_table_is_idle() -> bool:
  16. """Helper function to check if table is idle."""
  17. return not state.current_playing_file or state.pause_requested
  18. def _start_idle_led_timeout():
  19. """Start idle LED timeout if enabled."""
  20. if not state.dw_led_idle_timeout_enabled or state.dw_led_idle_timeout_minutes <= 0:
  21. return
  22. logger.debug(f"Starting idle LED timeout: {state.dw_led_idle_timeout_minutes} minutes")
  23. idle_timeout_manager.start_idle_timeout(
  24. timeout_minutes=state.dw_led_idle_timeout_minutes,
  25. state=state,
  26. check_idle_callback=_check_table_is_idle
  27. )
  28. ###############################################################################
  29. # Connection Abstraction
  30. ###############################################################################
  31. class BaseConnection:
  32. """Abstract base class for a connection."""
  33. def send(self, data: str) -> None:
  34. raise NotImplementedError
  35. def flush(self) -> None:
  36. raise NotImplementedError
  37. def readline(self) -> str:
  38. raise NotImplementedError
  39. def in_waiting(self) -> int:
  40. raise NotImplementedError
  41. def is_connected(self) -> bool:
  42. raise NotImplementedError
  43. def close(self) -> None:
  44. raise NotImplementedError
  45. ###############################################################################
  46. # Serial Connection Implementation
  47. ###############################################################################
  48. class SerialConnection(BaseConnection):
  49. def __init__(self, port: str, baudrate: int = 115200, timeout: int = 2):
  50. self.port = port
  51. self.baudrate = baudrate
  52. self.timeout = timeout
  53. self.lock = threading.RLock()
  54. logger.info(f'Connecting to Serial port {port}')
  55. self.ser = serial.Serial(port, baudrate, timeout=timeout)
  56. state.port = port
  57. logger.info(f'Connected to Serial port {port}')
  58. def send(self, data: str) -> None:
  59. with self.lock:
  60. self.ser.write(data.encode())
  61. self.ser.flush()
  62. def flush(self) -> None:
  63. with self.lock:
  64. self.ser.flush()
  65. def readline(self) -> str:
  66. with self.lock:
  67. return self.ser.readline().decode().strip()
  68. def in_waiting(self) -> int:
  69. with self.lock:
  70. return self.ser.in_waiting
  71. def is_connected(self) -> bool:
  72. return self.ser is not None and self.ser.is_open
  73. def close(self) -> None:
  74. # Run async update_machine_position in sync context
  75. try:
  76. loop = asyncio.new_event_loop()
  77. asyncio.set_event_loop(loop)
  78. loop.run_until_complete(update_machine_position())
  79. loop.close()
  80. except Exception as e:
  81. logger.error(f"Error updating machine position on close: {e}")
  82. with self.lock:
  83. if self.ser.is_open:
  84. self.ser.close()
  85. # Release the lock resources
  86. self.lock = None
  87. ###############################################################################
  88. # WebSocket Connection Implementation
  89. ###############################################################################
  90. class WebSocketConnection(BaseConnection):
  91. def __init__(self, url: str, timeout: int = 5):
  92. self.url = url
  93. self.timeout = timeout
  94. self.lock = threading.RLock()
  95. self.ws = None
  96. self.connect()
  97. def connect(self):
  98. logger.info(f'Connecting to Websocket {self.url}')
  99. self.ws = websocket.create_connection(self.url, timeout=self.timeout)
  100. state.port = self.url
  101. logger.info(f'Connected to Websocket {self.url}')
  102. def send(self, data: str) -> None:
  103. with self.lock:
  104. self.ws.send(data)
  105. def flush(self) -> None:
  106. # WebSocket sends immediately; nothing to flush.
  107. pass
  108. def readline(self) -> str:
  109. with self.lock:
  110. data = self.ws.recv()
  111. # Decode bytes to string if necessary
  112. if isinstance(data, bytes):
  113. data = data.decode('utf-8')
  114. return data.strip()
  115. def in_waiting(self) -> int:
  116. return 0 # Not applicable for WebSocket
  117. def is_connected(self) -> bool:
  118. return self.ws is not None
  119. def close(self) -> None:
  120. # Run async update_machine_position in sync context
  121. try:
  122. loop = asyncio.new_event_loop()
  123. asyncio.set_event_loop(loop)
  124. loop.run_until_complete(update_machine_position())
  125. loop.close()
  126. except Exception as e:
  127. logger.error(f"Error updating machine position on close: {e}")
  128. with self.lock:
  129. if self.ws:
  130. self.ws.close()
  131. # Release the lock resources
  132. self.lock = None
  133. def list_serial_ports():
  134. """Return a list of available serial ports."""
  135. ports = serial.tools.list_ports.comports()
  136. available_ports = [port.device for port in ports if port.device not in IGNORE_PORTS]
  137. logger.debug(f"Available serial ports: {available_ports}")
  138. return available_ports
  139. def device_init(homing=True):
  140. try:
  141. if get_machine_steps():
  142. 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}")
  143. else:
  144. logger.fatal("Failed to get machine steps")
  145. state.conn.close()
  146. return False
  147. except:
  148. logger.fatal("Not GRBL firmware")
  149. state.conn.close()
  150. return False
  151. machine_x, machine_y = get_machine_position()
  152. if machine_x != state.machine_x or machine_y != state.machine_y:
  153. logger.info(f'x, y; {machine_x}, {machine_y}')
  154. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  155. if homing:
  156. success = home()
  157. if not success:
  158. logger.error("Homing failed during device initialization")
  159. else:
  160. logger.info('Machine position known, skipping home')
  161. logger.info(f'Theta: {state.current_theta}, rho: {state.current_rho}')
  162. logger.info(f'x, y; {machine_x}, {machine_y}')
  163. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  164. time.sleep(2) # Allow time for the connection to establish
  165. def connect_device(homing=True):
  166. # Initialize LED interface based on configured provider
  167. if state.led_provider == "wled" and state.wled_ip:
  168. state.led_controller = LEDInterface(provider="wled", ip_address=state.wled_ip)
  169. elif state.led_provider == "hyperion" and state.hyperion_ip:
  170. state.led_controller = LEDInterface(
  171. provider="hyperion",
  172. ip_address=state.hyperion_ip,
  173. port=state.hyperion_port
  174. )
  175. else:
  176. state.led_controller = None
  177. # Show loading effect
  178. if state.led_controller:
  179. state.led_controller.effect_loading()
  180. ports = list_serial_ports()
  181. if state.port and state.port in ports:
  182. state.conn = SerialConnection(state.port)
  183. elif ports:
  184. state.conn = SerialConnection(ports[0])
  185. else:
  186. logger.error("Auto connect failed.")
  187. # state.conn = WebSocketConnection('ws://fluidnc.local:81')
  188. if (state.conn.is_connected() if state.conn else False):
  189. # Check for alarm state and unlock if needed before initializing
  190. if not check_and_unlock_alarm():
  191. logger.error("Failed to unlock device from alarm state")
  192. # Still proceed with device_init but log the issue
  193. device_init(homing)
  194. # Show connected effect, then transition to configured idle effect
  195. if state.led_controller:
  196. logger.info("Showing LED connected effect (green flash)")
  197. state.led_controller.effect_connected()
  198. # Set the configured idle effect after connection
  199. logger.info(f"Setting LED to idle effect: {state.dw_led_idle_effect}")
  200. state.led_controller.effect_idle(state.dw_led_idle_effect)
  201. _start_idle_led_timeout()
  202. def check_and_unlock_alarm():
  203. """
  204. Check if GRBL is in alarm state and unlock it with $X if needed.
  205. Uses $A command to log detailed alarm information before unlocking.
  206. Returns True if device is ready (unlocked or no alarm), False on error.
  207. """
  208. try:
  209. logger.info("Checking device status for alarm state...")
  210. # Send status query
  211. state.conn.send('?\n')
  212. time.sleep(0.1)
  213. # Read response with timeout
  214. max_attempts = 5
  215. response = None
  216. for attempt in range(max_attempts):
  217. if state.conn.in_waiting() > 0:
  218. response = state.conn.readline()
  219. logger.debug(f"Status response: {response}")
  220. break
  221. time.sleep(0.1)
  222. if not response:
  223. logger.warning("No status response received, proceeding anyway")
  224. return True
  225. # Check for alarm state
  226. if "Alarm" in response:
  227. logger.warning(f"Device in ALARM state: {response}")
  228. # Query alarm details with $A command
  229. logger.info("Querying alarm details with $A command...")
  230. state.conn.send('$A\n')
  231. time.sleep(0.2)
  232. # Read and log alarm details
  233. for attempt in range(max_attempts):
  234. if state.conn.in_waiting() > 0:
  235. alarm_details = state.conn.readline()
  236. logger.warning(f"Alarm details: {alarm_details}")
  237. break
  238. time.sleep(0.1)
  239. # Send unlock command
  240. logger.info("Sending $X to unlock...")
  241. state.conn.send('$X\n')
  242. time.sleep(0.5)
  243. # Verify unlock succeeded
  244. state.conn.send('?\n')
  245. time.sleep(0.1)
  246. verify_response = state.conn.readline()
  247. logger.debug(f"Verification response: {verify_response}")
  248. if "Alarm" in verify_response:
  249. logger.error("Failed to unlock device from alarm state")
  250. return False
  251. else:
  252. logger.info("Device successfully unlocked")
  253. return True
  254. else:
  255. logger.info("Device not in alarm state, proceeding normally")
  256. return True
  257. except Exception as e:
  258. logger.error(f"Error checking/unlocking alarm: {e}")
  259. return False
  260. def get_status_response() -> str:
  261. """
  262. Send a status query ('?') and return the response if available.
  263. """
  264. while True:
  265. try:
  266. state.conn.send('?')
  267. response = state.conn.readline()
  268. if "MPos" in response:
  269. logger.debug(f"Status response: {response}")
  270. return response
  271. except Exception as e:
  272. logger.error(f"Error getting status response: {e}")
  273. return False
  274. time.sleep(1)
  275. def parse_machine_position(response: str):
  276. """
  277. Parse the work position (MPos) from a status response.
  278. Expected format: "<...|MPos:-994.869,-321.861,0.000|...>"
  279. Returns a tuple (work_x, work_y) if found, else None.
  280. """
  281. if "MPos:" not in response:
  282. return None
  283. try:
  284. wpos_section = next((part for part in response.split("|") if part.startswith("MPos:")), None)
  285. if wpos_section:
  286. wpos_str = wpos_section.split(":", 1)[1]
  287. wpos_values = wpos_str.split(",")
  288. work_x = float(wpos_values[0])
  289. work_y = float(wpos_values[1])
  290. return work_x, work_y
  291. except Exception as e:
  292. logger.error(f"Error parsing work position: {e}")
  293. return None
  294. async def send_grbl_coordinates(x, y, speed=600, timeout=2, home=False):
  295. """
  296. Send a G-code command to FluidNC and wait for an 'ok' response.
  297. If no response after set timeout, sets state to stop and disconnects.
  298. """
  299. logger.debug(f"Sending G-code: X{x} Y{y} at F{speed}")
  300. # Track overall attempt time
  301. overall_start_time = time.time()
  302. while True:
  303. try:
  304. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  305. # Use asyncio.to_thread for both send and receive operations to avoid blocking
  306. await asyncio.to_thread(state.conn.send, gcode + "\n")
  307. logger.debug(f"Sent command: {gcode}")
  308. start_time = time.time()
  309. while True:
  310. # Use asyncio.to_thread for blocking I/O operations
  311. response = await asyncio.to_thread(state.conn.readline)
  312. logger.debug(f"Response: {response}")
  313. if response.lower() == "ok":
  314. logger.debug("Command execution confirmed.")
  315. return
  316. except Exception as e:
  317. # Store the error string inside the exception block
  318. error_str = str(e)
  319. logger.warning(f"Error sending command: {error_str}")
  320. # Immediately return for device not configured errors
  321. if "Device not configured" in error_str or "Errno 6" in error_str:
  322. logger.error(f"Device configuration error detected: {error_str}")
  323. state.stop_requested = True
  324. state.conn = None
  325. state.is_connected = False
  326. logger.info("Connection marked as disconnected due to device error")
  327. return False
  328. logger.warning(f"No 'ok' received for X{x} Y{y}, speed {speed}. Retrying...")
  329. await asyncio.sleep(0.1)
  330. # If we reach here, the timeout has occurred
  331. logger.error(f"Failed to receive 'ok' response after {max_total_attempt_time} seconds. Stopping and disconnecting.")
  332. # Set state to stop
  333. state.stop_requested = True
  334. # Set connection status to disconnected
  335. if state.conn:
  336. try:
  337. state.conn.disconnect()
  338. except:
  339. pass
  340. state.conn = None
  341. # Update the state connection status
  342. state.is_connected = False
  343. logger.info("Connection marked as disconnected due to timeout")
  344. return False
  345. def get_machine_steps(timeout=10):
  346. """
  347. Get machine steps/mm from the GRBL controller.
  348. Returns True if successful, False otherwise.
  349. """
  350. if not state.conn or not state.conn.is_connected():
  351. logger.error("Cannot get machine steps: No connection available")
  352. return False
  353. x_steps_per_mm = None
  354. y_steps_per_mm = None
  355. gear_ratio = None
  356. start_time = time.time()
  357. # Clear any pending data in the buffer
  358. try:
  359. while state.conn.in_waiting() > 0:
  360. state.conn.readline()
  361. except Exception as e:
  362. logger.warning(f"Error clearing buffer: {e}")
  363. # Send the command to request all settings
  364. try:
  365. logger.info("Requesting GRBL settings with $$ command")
  366. state.conn.send("$$\n")
  367. time.sleep(0.5) # Give GRBL a moment to process and respond
  368. except Exception as e:
  369. logger.error(f"Error sending $$ command: {e}")
  370. return False
  371. # Wait for and process responses
  372. settings_complete = False
  373. while time.time() - start_time < timeout and not settings_complete:
  374. try:
  375. # Attempt to read a line from the connection
  376. if state.conn.in_waiting() > 0:
  377. response = state.conn.readline()
  378. logger.debug(f"Raw response: {response}")
  379. # Process the line
  380. if response.strip(): # Only process non-empty lines
  381. for line in response.splitlines():
  382. line = line.strip()
  383. logger.debug(f"Config response: {line}")
  384. if line.startswith("$100="):
  385. x_steps_per_mm = float(line.split("=")[1])
  386. state.x_steps_per_mm = x_steps_per_mm
  387. logger.info(f"X steps per mm: {x_steps_per_mm}")
  388. elif line.startswith("$101="):
  389. y_steps_per_mm = float(line.split("=")[1])
  390. state.y_steps_per_mm = y_steps_per_mm
  391. logger.info(f"Y steps per mm: {y_steps_per_mm}")
  392. elif line.startswith("$131="):
  393. gear_ratio = float(line.split("=")[1])
  394. state.gear_ratio = gear_ratio
  395. logger.info(f"Gear ratio: {gear_ratio}")
  396. elif line.startswith("$22="):
  397. # $22 reports if the homing cycle is enabled
  398. # returns 0 if disabled, 1 if enabled
  399. homing = int(line.split('=')[1])
  400. state.homing = homing
  401. logger.info(f"Homing enabled: {homing}")
  402. # Check if we've received all the settings we need
  403. if x_steps_per_mm is not None and y_steps_per_mm is not None and gear_ratio is not None:
  404. settings_complete = True
  405. else:
  406. # No data waiting, small sleep to prevent CPU thrashing
  407. time.sleep(0.1)
  408. # If it's taking too long, try sending the command again after 3 seconds
  409. elapsed = time.time() - start_time
  410. if elapsed > 3 and elapsed < 4:
  411. logger.warning("No response yet, sending $$ command again")
  412. state.conn.send("$$\n")
  413. except Exception as e:
  414. logger.error(f"Error getting machine steps: {e}")
  415. time.sleep(0.5)
  416. # Process results and determine table type
  417. if settings_complete:
  418. if y_steps_per_mm == 180:
  419. state.table_type = 'dune_weaver_mini'
  420. elif y_steps_per_mm >= 320:
  421. state.table_type = 'dune_weaver_pro'
  422. elif y_steps_per_mm == 287:
  423. state.table_type = 'dune_weaver'
  424. elif y_steps_per_mm == 164:
  425. state.table_type == 'dune_weaver_mini_pro'
  426. else:
  427. state.table_type = None
  428. logger.warning(f"Unknown table type with Y steps/mm: {y_steps_per_mm}")
  429. logger.info(f"Machine type detected: {state.table_type}")
  430. return True
  431. else:
  432. missing = []
  433. if x_steps_per_mm is None: missing.append("X steps/mm")
  434. if y_steps_per_mm is None: missing.append("Y steps/mm")
  435. if gear_ratio is None: missing.append("gear ratio")
  436. logger.error(f"Failed to get all machine parameters after {timeout}s. Missing: {', '.join(missing)}")
  437. return False
  438. def home(timeout=90):
  439. """
  440. Perform homing by checking device configuration and sending the appropriate commands.
  441. Args:
  442. timeout: Maximum time in seconds to wait for homing to complete (default: 60)
  443. """
  444. import threading
  445. # Check for alarm state before homing and unlock if needed
  446. if not check_and_unlock_alarm():
  447. logger.error("Failed to unlock device from alarm state, cannot proceed with homing")
  448. return False
  449. # Flag to track if homing completed
  450. homing_complete = threading.Event()
  451. homing_success = False
  452. def home_internal():
  453. nonlocal homing_success
  454. try:
  455. if state.homing:
  456. logger.info("Using sensorless homing")
  457. state.conn.send("$H\n")
  458. state.conn.send("G1 Y0 F100\n")
  459. else:
  460. homing_speed = 400
  461. if state.table_type == 'dune_weaver_mini':
  462. homing_speed = 120
  463. logger.info("Sensorless homing not supported. Using crash homing")
  464. logger.info(f"Homing with speed {homing_speed}")
  465. # Run async function in new event loop
  466. loop = asyncio.new_event_loop()
  467. asyncio.set_event_loop(loop)
  468. try:
  469. if state.table_type == 'dune_weaver_mini':
  470. result = loop.run_until_complete(send_grbl_coordinates(0, - 30, homing_speed, home=True))
  471. if result == False:
  472. logger.error("Homing failed - send_grbl_coordinates returned False")
  473. homing_complete.set()
  474. return
  475. state.machine_y -= 30
  476. else:
  477. result = loop.run_until_complete(send_grbl_coordinates(0, -22, homing_speed, home=True))
  478. if result == False:
  479. logger.error("Homing failed - send_grbl_coordinates returned False")
  480. homing_complete.set()
  481. return
  482. state.machine_y -= 22
  483. finally:
  484. loop.close()
  485. # Wait for device to reach idle state after homing
  486. logger.info("Waiting for device to reach idle state after homing...")
  487. idle_reached = check_idle()
  488. if not idle_reached:
  489. logger.error("Device did not reach idle state after homing")
  490. homing_complete.set()
  491. return
  492. else:
  493. state.current_theta = state.current_rho = 0
  494. # Perform Desert Compass calibration if enabled (Raspberry Pi only)
  495. if state.angular_homing_enabled:
  496. logger.info("Starting Desert Compass calibration sequence")
  497. try:
  498. # Initialize reed switch monitor with configured GPIO pin and invert state
  499. gpio_pin = state.angular_homing_gpio_pin
  500. invert_state = state.angular_homing_invert_state
  501. logger.info(f"Desert Compass: Using GPIO pin {gpio_pin} for reed switch (invert_state={invert_state})")
  502. reed_switch = ReedSwitchMonitor(gpio_pin=gpio_pin, invert_state=invert_state)
  503. try:
  504. # Reset theta first
  505. logger.info("Desert Compass: Resetting theta before calibration")
  506. asyncio.run(pattern_manager.reset_theta())
  507. # Move radial arm to perimeter (theta=0, rho=1.0)
  508. logger.info("Desert Compass: Moving radial arm to perimeter (theta=0, rho=1.0)")
  509. asyncio.run(pattern_manager.move_polar(0, 1.0, homing_speed))
  510. idle_reached = check_idle()
  511. if not idle_reached:
  512. logger.error("Desert Compass: Device did not reach idle state after moving to perimeter")
  513. homing_complete.set()
  514. return
  515. # Wait 1 second for stabilization
  516. logger.info("Desert Compass: Waiting for stabilization...")
  517. time.sleep(1)
  518. # Perform angular rotation until reed switch is triggered
  519. logger.info("Desert Compass: Rotating around perimeter to find reference point")
  520. increment = 0.1 # Small angular increment in radians
  521. current_theta = 0
  522. max_theta = 6.28 # One full rotation (2*pi)
  523. reed_switch_triggered = False
  524. while current_theta < max_theta:
  525. # Move to next position
  526. current_theta += increment
  527. asyncio.run(pattern_manager.move_polar(current_theta, 1.0, homing_speed))
  528. # Small delay to allow reed switch to settle after movement
  529. time.sleep(0.5)
  530. # Check reed switch AFTER movement completes
  531. if reed_switch.is_triggered():
  532. logger.info(f"Desert Compass: Reed switch triggered at theta={current_theta}")
  533. reed_switch_triggered = True
  534. break
  535. if not reed_switch_triggered:
  536. logger.warning("Desert Compass: Completed full rotation without reed switch trigger")
  537. # Set theta to the offset value (accounting for sensor placement)
  538. # If offset is 0, this is the true reference position
  539. # If offset is non-zero, the sensor is physically placed at that angle
  540. # Convert degrees to radians for internal use
  541. import math
  542. offset_radians = math.radians(state.angular_homing_offset_degrees)
  543. state.current_theta = offset_radians
  544. state.current_rho = 1
  545. logger.info(f"Desert Compass: Calibration completed - theta set to {state.angular_homing_offset_degrees}° ({offset_radians:.3f} radians)")
  546. finally:
  547. reed_switch.cleanup()
  548. except Exception as e:
  549. logger.error(f"Error during Desert Compass calibration: {e}")
  550. # Continue with normal homing completion even if Desert Compass calibration fails
  551. homing_success = True
  552. logger.info("Homing completed and device is idle")
  553. homing_complete.set()
  554. except Exception as e:
  555. logger.error(f"Error during homing: {e}")
  556. homing_complete.set()
  557. # Start homing in a separate thread
  558. homing_thread = threading.Thread(target=home_internal)
  559. homing_thread.daemon = True
  560. homing_thread.start()
  561. # Wait for homing to complete or timeout
  562. if not homing_complete.wait(timeout):
  563. logger.error(f"Homing timeout after {timeout} seconds")
  564. # Try to stop any ongoing movement
  565. try:
  566. if state.conn and state.conn.is_connected():
  567. state.conn.send("!\n") # Send feed hold
  568. time.sleep(0.1)
  569. state.conn.send("\x18\n") # Send reset
  570. except Exception as e:
  571. logger.error(f"Error stopping movement after timeout: {e}")
  572. return False
  573. if not homing_success:
  574. logger.error("Homing failed")
  575. return False
  576. logger.info("Homing completed successfully")
  577. return True
  578. def check_idle():
  579. """
  580. Continuously check if the device is idle (synchronous version).
  581. """
  582. logger.info("Checking idle")
  583. while True:
  584. response = get_status_response()
  585. if response and "Idle" in response:
  586. logger.info("Device is idle")
  587. # Schedule async update_machine_position in the existing event loop
  588. try:
  589. # Try to schedule in existing event loop if available
  590. try:
  591. loop = asyncio.get_running_loop()
  592. # Create a task but don't await it (fire and forget)
  593. asyncio.create_task(update_machine_position())
  594. logger.debug("Scheduled machine position update task")
  595. except RuntimeError:
  596. # No event loop running, skip machine position update
  597. logger.debug("No event loop running, skipping machine position update")
  598. except Exception as e:
  599. logger.error(f"Error scheduling machine position update: {e}")
  600. return True
  601. time.sleep(1)
  602. async def check_idle_async():
  603. """
  604. Continuously check if the device is idle (async version).
  605. """
  606. logger.info("Checking idle (async)")
  607. while True:
  608. response = await asyncio.to_thread(get_status_response)
  609. if response and "Idle" in response:
  610. logger.info("Device is idle")
  611. try:
  612. await update_machine_position()
  613. except Exception as e:
  614. logger.error(f"Error updating machine position: {e}")
  615. return True
  616. await asyncio.sleep(1)
  617. def get_machine_position(timeout=5):
  618. """
  619. Query the device for its position.
  620. """
  621. start_time = time.time()
  622. while time.time() - start_time < timeout:
  623. try:
  624. state.conn.send('?')
  625. response = state.conn.readline()
  626. logger.debug(f"Raw status response: {response}")
  627. if "MPos" in response:
  628. pos = parse_machine_position(response)
  629. if pos:
  630. machine_x, machine_y = pos
  631. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  632. return machine_x, machine_y
  633. except Exception as e:
  634. logger.error(f"Error getting machine position: {e}")
  635. return
  636. time.sleep(0.1)
  637. logger.warning("Timeout reached waiting for machine position")
  638. return None, None
  639. async def update_machine_position():
  640. if (state.conn.is_connected() if state.conn else False):
  641. try:
  642. logger.info('Saving machine position')
  643. state.machine_x, state.machine_y = await asyncio.to_thread(get_machine_position)
  644. await asyncio.to_thread(state.save)
  645. logger.info(f'Machine position saved: {state.machine_x}, {state.machine_y}')
  646. except Exception as e:
  647. logger.error(f"Error updating machine position: {e}")
  648. def restart_connection(homing=False):
  649. """
  650. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  651. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  652. The new connection is saved to state.conn.
  653. Returns:
  654. True if the connection was restarted successfully, False otherwise.
  655. """
  656. try:
  657. if (state.conn.is_connected() if state.conn else False):
  658. logger.info("Closing current connection...")
  659. state.conn.close()
  660. except Exception as e:
  661. logger.error(f"Error while closing connection: {e}")
  662. # Clear the connection reference.
  663. state.conn = None
  664. logger.info("Attempting to restart connection...")
  665. try:
  666. connect_device(homing) # This will set state.conn appropriately.
  667. if (state.conn.is_connected() if state.conn else False):
  668. logger.info("Connection restarted successfully.")
  669. return True
  670. else:
  671. logger.error("Failed to restart connection.")
  672. return False
  673. except Exception as e:
  674. logger.error(f"Error restarting connection: {e}")
  675. return False