connection_manager.py 30 KB

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