1
0

connection_manager.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  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. import os
  9. from modules.core import pattern_manager
  10. from modules.core.state import state
  11. from modules.led.led_interface import LEDInterface
  12. from modules.led.idle_timeout_manager import idle_timeout_manager
  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. # Priority for auto-connect:
  182. # 1. Preferred port (user's explicit choice) if available
  183. # 2. Last used port if available
  184. # 3. First available port as fallback
  185. if state.preferred_port and state.preferred_port in ports:
  186. logger.info(f"Connecting to preferred port: {state.preferred_port}")
  187. state.conn = SerialConnection(state.preferred_port)
  188. elif state.port and state.port in ports:
  189. logger.info(f"Connecting to last used port: {state.port}")
  190. state.conn = SerialConnection(state.port)
  191. elif ports:
  192. logger.info(f"Connecting to first available port: {ports[0]}")
  193. state.conn = SerialConnection(ports[0])
  194. else:
  195. logger.error("Auto connect failed: No serial ports available")
  196. # state.conn = WebSocketConnection('ws://fluidnc.local:81')
  197. if (state.conn.is_connected() if state.conn else False):
  198. # Check for alarm state and unlock if needed before initializing
  199. if not check_and_unlock_alarm():
  200. logger.error("Failed to unlock device from alarm state")
  201. # Still proceed with device_init but log the issue
  202. device_init(homing)
  203. # Show connected effect, then transition to configured idle effect
  204. if state.led_controller:
  205. logger.info("Showing LED connected effect (green flash)")
  206. state.led_controller.effect_connected()
  207. # Set the configured idle effect after connection
  208. logger.info(f"Setting LED to idle effect: {state.dw_led_idle_effect}")
  209. state.led_controller.effect_idle(state.dw_led_idle_effect)
  210. _start_idle_led_timeout()
  211. def check_and_unlock_alarm():
  212. """
  213. Check if GRBL is in alarm state and unlock it with $X if needed.
  214. Uses $A command to log detailed alarm information before unlocking.
  215. Returns True if device is ready (unlocked or no alarm), False on error.
  216. """
  217. try:
  218. logger.info("Checking device status for alarm state...")
  219. # Send status query
  220. state.conn.send('?\n')
  221. time.sleep(0.1)
  222. # Read response with timeout
  223. max_attempts = 5
  224. response = None
  225. for attempt in range(max_attempts):
  226. if state.conn.in_waiting() > 0:
  227. response = state.conn.readline()
  228. logger.debug(f"Status response: {response}")
  229. break
  230. time.sleep(0.1)
  231. if not response:
  232. logger.warning("No status response received, proceeding anyway")
  233. return True
  234. # Check for alarm state
  235. if "Alarm" in response:
  236. logger.warning(f"Device in ALARM state: {response}")
  237. # Query alarm details with $A command
  238. logger.info("Querying alarm details with $A command...")
  239. state.conn.send('$A\n')
  240. time.sleep(0.2)
  241. # Read and log alarm details
  242. for attempt in range(max_attempts):
  243. if state.conn.in_waiting() > 0:
  244. alarm_details = state.conn.readline()
  245. logger.warning(f"Alarm details: {alarm_details}")
  246. break
  247. time.sleep(0.1)
  248. # Send unlock command
  249. logger.info("Sending $X to unlock...")
  250. state.conn.send('$X\n')
  251. time.sleep(0.5)
  252. # Verify unlock succeeded
  253. state.conn.send('?\n')
  254. time.sleep(0.1)
  255. verify_response = state.conn.readline()
  256. logger.debug(f"Verification response: {verify_response}")
  257. if "Alarm" in verify_response:
  258. logger.error("Failed to unlock device from alarm state")
  259. return False
  260. else:
  261. logger.info("Device successfully unlocked")
  262. return True
  263. else:
  264. logger.info("Device not in alarm state, proceeding normally")
  265. return True
  266. except Exception as e:
  267. logger.error(f"Error checking/unlocking alarm: {e}")
  268. return False
  269. def get_status_response() -> str:
  270. """
  271. Send a status query ('?') and return the response if available.
  272. """
  273. while True:
  274. try:
  275. state.conn.send('?')
  276. response = state.conn.readline()
  277. if "MPos" in response:
  278. logger.debug(f"Status response: {response}")
  279. return response
  280. except Exception as e:
  281. logger.error(f"Error getting status response: {e}")
  282. return False
  283. time.sleep(1)
  284. def parse_machine_position(response: str):
  285. """
  286. Parse the work position (MPos) from a status response.
  287. Expected format: "<...|MPos:-994.869,-321.861,0.000|...>"
  288. Returns a tuple (work_x, work_y) if found, else None.
  289. """
  290. if "MPos:" not in response:
  291. return None
  292. try:
  293. wpos_section = next((part for part in response.split("|") if part.startswith("MPos:")), None)
  294. if wpos_section:
  295. wpos_str = wpos_section.split(":", 1)[1]
  296. wpos_values = wpos_str.split(",")
  297. work_x = float(wpos_values[0])
  298. work_y = float(wpos_values[1])
  299. return work_x, work_y
  300. except Exception as e:
  301. logger.error(f"Error parsing work position: {e}")
  302. return None
  303. async def send_grbl_coordinates(x, y, speed=600, timeout=2, home=False):
  304. """
  305. Send a G-code command to FluidNC and wait for an 'ok' response.
  306. If no response after set timeout, sets state to stop and disconnects.
  307. """
  308. logger.debug(f"Sending G-code: X{x} Y{y} at F{speed}")
  309. # Track overall attempt time
  310. overall_start_time = time.time()
  311. while True:
  312. try:
  313. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  314. # Use asyncio.to_thread for both send and receive operations to avoid blocking
  315. await asyncio.to_thread(state.conn.send, gcode + "\n")
  316. logger.debug(f"Sent command: {gcode}")
  317. start_time = time.time()
  318. while True:
  319. # Use asyncio.to_thread for blocking I/O operations
  320. response = await asyncio.to_thread(state.conn.readline)
  321. logger.debug(f"Response: {response}")
  322. if response.lower() == "ok":
  323. logger.debug("Command execution confirmed.")
  324. return
  325. except Exception as e:
  326. # Store the error string inside the exception block
  327. error_str = str(e)
  328. logger.warning(f"Error sending command: {error_str}")
  329. # Immediately return for device not configured errors
  330. if "Device not configured" in error_str or "Errno 6" in error_str:
  331. logger.error(f"Device configuration error detected: {error_str}")
  332. state.stop_requested = True
  333. state.conn = None
  334. state.is_connected = False
  335. logger.info("Connection marked as disconnected due to device error")
  336. return False
  337. logger.warning(f"No 'ok' received for X{x} Y{y}, speed {speed}. Retrying...")
  338. await asyncio.sleep(0.1)
  339. # If we reach here, the timeout has occurred
  340. logger.error(f"Failed to receive 'ok' response after {max_total_attempt_time} seconds. Stopping and disconnecting.")
  341. # Set state to stop
  342. state.stop_requested = True
  343. # Set connection status to disconnected
  344. if state.conn:
  345. try:
  346. state.conn.disconnect()
  347. except:
  348. pass
  349. state.conn = None
  350. # Update the state connection status
  351. state.is_connected = False
  352. logger.info("Connection marked as disconnected due to timeout")
  353. return False
  354. def get_machine_steps(timeout=10):
  355. """
  356. Get machine steps/mm from the GRBL controller.
  357. Returns True if successful, False otherwise.
  358. """
  359. if not state.conn or not state.conn.is_connected():
  360. logger.error("Cannot get machine steps: No connection available")
  361. return False
  362. x_steps_per_mm = None
  363. y_steps_per_mm = None
  364. start_time = time.time()
  365. # Clear any pending data in the buffer
  366. try:
  367. while state.conn.in_waiting() > 0:
  368. state.conn.readline()
  369. except Exception as e:
  370. logger.warning(f"Error clearing buffer: {e}")
  371. # Send the command to request all settings
  372. try:
  373. logger.info("Requesting GRBL settings with $$ command")
  374. state.conn.send("$$\n")
  375. time.sleep(0.5) # Give GRBL a moment to process and respond
  376. except Exception as e:
  377. logger.error(f"Error sending $$ command: {e}")
  378. return False
  379. # Wait for and process responses
  380. settings_complete = False
  381. while time.time() - start_time < timeout and not settings_complete:
  382. try:
  383. # Attempt to read a line from the connection
  384. if state.conn.in_waiting() > 0:
  385. response = state.conn.readline()
  386. logger.debug(f"Raw response: {response}")
  387. # Process the line
  388. if response.strip(): # Only process non-empty lines
  389. for line in response.splitlines():
  390. line = line.strip()
  391. logger.debug(f"Config response: {line}")
  392. if line.startswith("$100="):
  393. x_steps_per_mm = float(line.split("=")[1])
  394. state.x_steps_per_mm = x_steps_per_mm
  395. logger.info(f"X steps per mm: {x_steps_per_mm}")
  396. elif line.startswith("$101="):
  397. y_steps_per_mm = float(line.split("=")[1])
  398. state.y_steps_per_mm = y_steps_per_mm
  399. logger.info(f"Y steps per mm: {y_steps_per_mm}")
  400. elif line.startswith("$22="):
  401. # $22 reports if the homing cycle is enabled
  402. # returns 0 if disabled, 1 if enabled
  403. homing = int(line.split('=')[1])
  404. state.homing = homing
  405. logger.info(f"Homing enabled: {homing}")
  406. # Check if we've received all the settings we need
  407. if x_steps_per_mm is not None and y_steps_per_mm is not None:
  408. settings_complete = True
  409. else:
  410. # No data waiting, small sleep to prevent CPU thrashing
  411. time.sleep(0.1)
  412. # If it's taking too long, try sending the command again after 3 seconds
  413. elapsed = time.time() - start_time
  414. if elapsed > 3 and elapsed < 4:
  415. logger.warning("No response yet, sending $$ command again")
  416. state.conn.send("$$\n")
  417. except Exception as e:
  418. logger.error(f"Error getting machine steps: {e}")
  419. time.sleep(0.5)
  420. # Process results and determine table type
  421. if settings_complete:
  422. if y_steps_per_mm == 180 and x_steps_per_mm == 256:
  423. state.table_type = 'dune_weaver_mini'
  424. elif y_steps_per_mm == 287:
  425. state.table_type = 'dune_weaver'
  426. elif y_steps_per_mm == 164:
  427. state.table_type = 'dune_weaver_mini_pro'
  428. elif y_steps_per_mm >= 320:
  429. state.table_type = 'dune_weaver_pro'
  430. else:
  431. state.table_type = None
  432. logger.warning(f"Unknown table type with Y steps/mm: {y_steps_per_mm}")
  433. # Set gear ratio based on table type (hardcoded)
  434. if state.table_type in ['dune_weaver_mini', 'dune_weaver_mini_pro']:
  435. state.gear_ratio = 6.25
  436. else:
  437. state.gear_ratio = 10
  438. # Check for environment variable override
  439. gear_ratio_override = os.getenv('GEAR_RATIO')
  440. if gear_ratio_override is not None:
  441. try:
  442. state.gear_ratio = float(gear_ratio_override)
  443. logger.info(f"Machine type detected: {state.table_type}, gear ratio: {state.gear_ratio} (from GEAR_RATIO env var)")
  444. except ValueError:
  445. logger.error(f"Invalid GEAR_RATIO env var value: {gear_ratio_override}, using default: {state.gear_ratio}")
  446. logger.info(f"Machine type detected: {state.table_type}, gear ratio: {state.gear_ratio} (hardcoded)")
  447. else:
  448. logger.info(f"Machine type detected: {state.table_type}, gear ratio: {state.gear_ratio} (hardcoded)")
  449. return True
  450. else:
  451. missing = []
  452. if x_steps_per_mm is None: missing.append("X steps/mm")
  453. if y_steps_per_mm is None: missing.append("Y steps/mm")
  454. logger.error(f"Failed to get all machine parameters after {timeout}s. Missing: {', '.join(missing)}")
  455. return False
  456. def home(timeout=90):
  457. """
  458. Perform homing sequence based on configured mode:
  459. Mode 0 (Crash):
  460. - Y axis moves -22mm (or -30mm for mini) until physical stop
  461. - Set theta=0, rho=0 (no x0 y0 command)
  462. Mode 1 (Sensor):
  463. - Send $H command to home both X and Y axes
  464. - Wait for [MSG:Homed:X] and [MSG:Homed:Y] messages
  465. - Send x0 y0 to zero positions
  466. - Set theta to compass offset, rho=0
  467. Args:
  468. timeout: Maximum time in seconds to wait for homing to complete (default: 90)
  469. """
  470. import threading
  471. import math
  472. # Check for alarm state before homing and unlock if needed
  473. if not check_and_unlock_alarm():
  474. logger.error("Failed to unlock device from alarm state, cannot proceed with homing")
  475. return False
  476. # Flag to track if homing completed
  477. homing_complete = threading.Event()
  478. homing_success = False
  479. def home_internal():
  480. nonlocal homing_success
  481. homing_speed = 400
  482. if state.table_type == 'dune_weaver_mini':
  483. homing_speed = 100
  484. try:
  485. if state.homing == 1:
  486. # Mode 1: Sensor-based homing using $H
  487. logger.info("Using sensor-based homing mode ($H)")
  488. # Clear any pending responses
  489. state.homed_x = False
  490. state.homed_y = False
  491. # Send $H command
  492. state.conn.send("$H\n")
  493. logger.info("Sent $H command, waiting for homing messages...")
  494. # Wait for [MSG:Homed:X] and [MSG:Homed:Y] messages
  495. max_wait_time = 30 # 30 seconds timeout for homing messages
  496. start_time = time.time()
  497. while (time.time() - start_time) < max_wait_time:
  498. try:
  499. response = state.conn.readline()
  500. if response:
  501. logger.debug(f"Homing response: {response}")
  502. # Check for homing messages
  503. if "[MSG:Homed:X]" in response:
  504. state.homed_x = True
  505. logger.info("Received [MSG:Homed:X]")
  506. if "[MSG:Homed:Y]" in response:
  507. state.homed_y = True
  508. logger.info("Received [MSG:Homed:Y]")
  509. # Break if we've received both messages
  510. if state.homed_x and state.homed_y:
  511. logger.info("Received both homing confirmation messages")
  512. break
  513. except Exception as e:
  514. logger.error(f"Error reading homing response: {e}")
  515. time.sleep(0.1)
  516. if not (state.homed_x and state.homed_y):
  517. logger.warning(f"Did not receive all homing messages (X:{state.homed_x}, Y:{state.homed_y})")
  518. # Wait for idle state after $H
  519. logger.info("Waiting for device to reach idle state after $H...")
  520. idle_reached = check_idle()
  521. if not idle_reached:
  522. logger.error("Device did not reach idle state after $H command")
  523. homing_complete.set()
  524. return
  525. # Send x0 y0 to zero both positions using send_grbl_coordinates
  526. logger.info(f"Zeroing positions with x0 y0 f{homing_speed}")
  527. # Run async function in new event loop
  528. loop = asyncio.new_event_loop()
  529. asyncio.set_event_loop(loop)
  530. try:
  531. # Send G1 X0 Y0 F{homing_speed}
  532. result = loop.run_until_complete(send_grbl_coordinates(0, 0, homing_speed))
  533. if result == False:
  534. logger.error("Position zeroing failed - send_grbl_coordinates returned False")
  535. homing_complete.set()
  536. return
  537. logger.info("Position zeroing completed successfully")
  538. finally:
  539. loop.close()
  540. # Wait for device to reach idle state after zeroing movement
  541. logger.info("Waiting for device to reach idle state after zeroing...")
  542. idle_reached = check_idle()
  543. if not idle_reached:
  544. logger.error("Device did not reach idle state after zeroing")
  545. homing_complete.set()
  546. return
  547. # Set current position based on compass reference point (sensor mode only)
  548. # Only set AFTER x0 y0 is confirmed and device is idle
  549. offset_radians = math.radians(state.angular_homing_offset_degrees)
  550. state.current_theta = offset_radians
  551. state.current_rho = 0
  552. logger.info(f"Sensor homing completed - theta set to {state.angular_homing_offset_degrees}° ({offset_radians:.3f} rad), rho=0")
  553. else:
  554. logger.info(f"Using crash homing mode at {homing_speed} mm/min")
  555. # Run async function in new event loop
  556. loop = asyncio.new_event_loop()
  557. asyncio.set_event_loop(loop)
  558. try:
  559. if state.table_type == 'dune_weaver_mini':
  560. result = loop.run_until_complete(send_grbl_coordinates(0, -30, homing_speed, home=True))
  561. if result == False:
  562. logger.error("Crash homing failed - send_grbl_coordinates returned False")
  563. homing_complete.set()
  564. return
  565. state.machine_y -= 30
  566. else:
  567. result = loop.run_until_complete(send_grbl_coordinates(0, -22, homing_speed, home=True))
  568. if result == False:
  569. logger.error("Crash homing failed - send_grbl_coordinates returned False")
  570. homing_complete.set()
  571. return
  572. state.machine_y -= 22
  573. finally:
  574. loop.close()
  575. # Wait for device to reach idle state after crash homing
  576. logger.info("Waiting for device to reach idle state after crash homing...")
  577. idle_reached = check_idle()
  578. if not idle_reached:
  579. logger.error("Device did not reach idle state after crash homing")
  580. homing_complete.set()
  581. return
  582. # Crash homing just sets theta and rho to 0 (no x0 y0 command)
  583. state.current_theta = 0
  584. state.current_rho = 0
  585. logger.info("Crash homing completed - theta=0, rho=0")
  586. homing_success = True
  587. homing_complete.set()
  588. except Exception as e:
  589. logger.error(f"Error during homing: {e}")
  590. homing_complete.set()
  591. # Start homing in a separate thread
  592. homing_thread = threading.Thread(target=home_internal)
  593. homing_thread.daemon = True
  594. homing_thread.start()
  595. # Wait for homing to complete or timeout
  596. if not homing_complete.wait(timeout):
  597. logger.error(f"Homing timeout after {timeout} seconds")
  598. # Try to stop any ongoing movement
  599. try:
  600. if state.conn and state.conn.is_connected():
  601. state.conn.send("!\n") # Send feed hold
  602. time.sleep(0.1)
  603. state.conn.send("\x18\n") # Send reset
  604. except Exception as e:
  605. logger.error(f"Error stopping movement after timeout: {e}")
  606. return False
  607. if not homing_success:
  608. logger.error("Homing failed")
  609. return False
  610. logger.info("Homing completed successfully")
  611. return True
  612. def check_idle():
  613. """
  614. Continuously check if the device is idle (synchronous version).
  615. """
  616. logger.info("Checking idle")
  617. while True:
  618. response = get_status_response()
  619. if response and "Idle" in response:
  620. logger.info("Device is idle")
  621. # Schedule async update_machine_position in the existing event loop
  622. try:
  623. # Try to schedule in existing event loop if available
  624. try:
  625. loop = asyncio.get_running_loop()
  626. # Create a task but don't await it (fire and forget)
  627. asyncio.create_task(update_machine_position())
  628. logger.debug("Scheduled machine position update task")
  629. except RuntimeError:
  630. # No event loop running, skip machine position update
  631. logger.debug("No event loop running, skipping machine position update")
  632. except Exception as e:
  633. logger.error(f"Error scheduling machine position update: {e}")
  634. return True
  635. time.sleep(1)
  636. async def check_idle_async():
  637. """
  638. Continuously check if the device is idle (async version).
  639. """
  640. logger.info("Checking idle (async)")
  641. while True:
  642. response = await asyncio.to_thread(get_status_response)
  643. if response and "Idle" in response:
  644. logger.info("Device is idle")
  645. try:
  646. await update_machine_position()
  647. except Exception as e:
  648. logger.error(f"Error updating machine position: {e}")
  649. return True
  650. await asyncio.sleep(1)
  651. def is_machine_idle() -> bool:
  652. """
  653. Single check to see if the machine is currently idle.
  654. Does not loop - returns immediately with current status.
  655. Returns:
  656. True if machine is idle, False otherwise
  657. """
  658. if not state.conn or not state.conn.is_connected():
  659. logger.debug("No connection - machine not idle")
  660. return False
  661. try:
  662. state.conn.send('?')
  663. response = state.conn.readline()
  664. if response and "Idle" in response:
  665. logger.debug("Machine status: Idle")
  666. return True
  667. else:
  668. logger.debug(f"Machine status: {response}")
  669. return False
  670. except Exception as e:
  671. logger.error(f"Error checking machine idle status: {e}")
  672. return False
  673. def get_machine_position(timeout=5):
  674. """
  675. Query the device for its position.
  676. """
  677. start_time = time.time()
  678. while time.time() - start_time < timeout:
  679. try:
  680. state.conn.send('?')
  681. response = state.conn.readline()
  682. logger.debug(f"Raw status response: {response}")
  683. if "MPos" in response:
  684. pos = parse_machine_position(response)
  685. if pos:
  686. machine_x, machine_y = pos
  687. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  688. return machine_x, machine_y
  689. except Exception as e:
  690. logger.error(f"Error getting machine position: {e}")
  691. return
  692. time.sleep(0.1)
  693. logger.warning("Timeout reached waiting for machine position")
  694. return None, None
  695. async def update_machine_position():
  696. if (state.conn.is_connected() if state.conn else False):
  697. try:
  698. logger.info('Saving machine position')
  699. state.machine_x, state.machine_y = await asyncio.to_thread(get_machine_position)
  700. await asyncio.to_thread(state.save)
  701. logger.info(f'Machine position saved: {state.machine_x}, {state.machine_y}')
  702. except Exception as e:
  703. logger.error(f"Error updating machine position: {e}")
  704. def restart_connection(homing=False):
  705. """
  706. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  707. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  708. The new connection is saved to state.conn.
  709. Returns:
  710. True if the connection was restarted successfully, False otherwise.
  711. """
  712. try:
  713. if (state.conn.is_connected() if state.conn else False):
  714. logger.info("Closing current connection...")
  715. state.conn.close()
  716. except Exception as e:
  717. logger.error(f"Error while closing connection: {e}")
  718. # Clear the connection reference.
  719. state.conn = None
  720. logger.info("Attempting to restart connection...")
  721. try:
  722. connect_device(homing) # This will set state.conn appropriately.
  723. if (state.conn.is_connected() if state.conn else False):
  724. logger.info("Connection restarted successfully.")
  725. return True
  726. else:
  727. logger.error("Failed to restart connection.")
  728. return False
  729. except Exception as e:
  730. logger.error(f"Error restarting connection: {e}")
  731. return False