connection_manager.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  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. # Save current state synchronously first (critical for position persistence)
  75. try:
  76. state.save()
  77. except Exception as e:
  78. logger.error(f"Error saving state on close: {e}")
  79. # Schedule async position update if event loop exists, otherwise skip
  80. # This avoids creating nested event loops which causes RuntimeError
  81. try:
  82. loop = asyncio.get_running_loop()
  83. # We're in async context - schedule as task (fire-and-forget)
  84. asyncio.create_task(update_machine_position())
  85. logger.debug("Scheduled async machine position update")
  86. except RuntimeError:
  87. # No running event loop - we're in sync context
  88. # Position was already saved above, skip async update to avoid nested loop
  89. logger.debug("No event loop running, skipping async position update")
  90. with self.lock:
  91. if self.ser.is_open:
  92. self.ser.close()
  93. # Release the lock resources
  94. self.lock = None
  95. ###############################################################################
  96. # WebSocket Connection Implementation
  97. ###############################################################################
  98. class WebSocketConnection(BaseConnection):
  99. def __init__(self, url: str, timeout: int = 5):
  100. self.url = url
  101. self.timeout = timeout
  102. self.lock = threading.RLock()
  103. self.ws = None
  104. self.connect()
  105. def connect(self):
  106. logger.info(f'Connecting to Websocket {self.url}')
  107. self.ws = websocket.create_connection(self.url, timeout=self.timeout)
  108. state.port = self.url
  109. logger.info(f'Connected to Websocket {self.url}')
  110. def send(self, data: str) -> None:
  111. with self.lock:
  112. self.ws.send(data)
  113. def flush(self) -> None:
  114. # WebSocket sends immediately; nothing to flush.
  115. pass
  116. def readline(self) -> str:
  117. with self.lock:
  118. data = self.ws.recv()
  119. # Decode bytes to string if necessary
  120. if isinstance(data, bytes):
  121. data = data.decode('utf-8')
  122. return data.strip()
  123. def in_waiting(self) -> int:
  124. return 0 # Not applicable for WebSocket
  125. def is_connected(self) -> bool:
  126. return self.ws is not None
  127. def close(self) -> None:
  128. # Save current state synchronously first (critical for position persistence)
  129. try:
  130. state.save()
  131. except Exception as e:
  132. logger.error(f"Error saving state on close: {e}")
  133. # Schedule async position update if event loop exists, otherwise skip
  134. # This avoids creating nested event loops which causes RuntimeError
  135. try:
  136. loop = asyncio.get_running_loop()
  137. # We're in async context - schedule as task (fire-and-forget)
  138. asyncio.create_task(update_machine_position())
  139. logger.debug("Scheduled async machine position update")
  140. except RuntimeError:
  141. # No running event loop - we're in sync context
  142. # Position was already saved above, skip async update to avoid nested loop
  143. logger.debug("No event loop running, skipping async position update")
  144. with self.lock:
  145. if self.ws:
  146. self.ws.close()
  147. # Release the lock resources
  148. self.lock = None
  149. def list_serial_ports():
  150. """Return a list of available serial ports."""
  151. ports = serial.tools.list_ports.comports()
  152. available_ports = [port.device for port in ports if port.device not in IGNORE_PORTS]
  153. logger.debug(f"Available serial ports: {available_ports}")
  154. return available_ports
  155. def device_init(homing=True):
  156. try:
  157. if get_machine_steps():
  158. 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}")
  159. else:
  160. logger.fatal("Failed to get machine steps")
  161. state.conn.close()
  162. return False
  163. except:
  164. logger.fatal("Not GRBL firmware")
  165. state.conn.close()
  166. return False
  167. machine_x, machine_y = get_machine_position()
  168. if machine_x != state.machine_x or machine_y != state.machine_y:
  169. logger.info(f'x, y; {machine_x}, {machine_y}')
  170. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  171. if homing:
  172. success = home()
  173. if not success:
  174. logger.error("Homing failed during device initialization")
  175. else:
  176. logger.info('Machine position known, skipping home')
  177. logger.info(f'Theta: {state.current_theta}, rho: {state.current_rho}')
  178. logger.info(f'x, y; {machine_x}, {machine_y}')
  179. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  180. time.sleep(2) # Allow time for the connection to establish
  181. def connect_device(homing=True):
  182. # Initialize LED interface based on configured provider
  183. if state.led_provider == "wled" and state.wled_ip:
  184. state.led_controller = LEDInterface(provider="wled", ip_address=state.wled_ip)
  185. elif state.led_provider == "hyperion" and state.hyperion_ip:
  186. state.led_controller = LEDInterface(
  187. provider="hyperion",
  188. ip_address=state.hyperion_ip,
  189. port=state.hyperion_port
  190. )
  191. else:
  192. state.led_controller = None
  193. # Show loading effect
  194. if state.led_controller:
  195. state.led_controller.effect_loading()
  196. ports = list_serial_ports()
  197. # Priority for auto-connect:
  198. # 1. Preferred port (user's explicit choice) if available
  199. # 2. Last used port if available
  200. # 3. First available port as fallback
  201. if state.preferred_port and state.preferred_port in ports:
  202. logger.info(f"Connecting to preferred port: {state.preferred_port}")
  203. state.conn = SerialConnection(state.preferred_port)
  204. elif state.port and state.port in ports:
  205. logger.info(f"Connecting to last used port: {state.port}")
  206. state.conn = SerialConnection(state.port)
  207. elif ports:
  208. logger.info(f"Connecting to first available port: {ports[0]}")
  209. state.conn = SerialConnection(ports[0])
  210. else:
  211. logger.error("Auto connect failed: No serial ports available")
  212. # state.conn = WebSocketConnection('ws://fluidnc.local:81')
  213. if (state.conn.is_connected() if state.conn else False):
  214. # Check for alarm state and unlock if needed before initializing
  215. if not check_and_unlock_alarm():
  216. logger.error("Failed to unlock device from alarm state")
  217. # Still proceed with device_init but log the issue
  218. device_init(homing)
  219. # Show connected effect, then transition to configured idle effect
  220. if state.led_controller:
  221. logger.info("Showing LED connected effect (green flash)")
  222. state.led_controller.effect_connected()
  223. # Set the configured idle effect after connection
  224. logger.info(f"Setting LED to idle effect: {state.dw_led_idle_effect}")
  225. state.led_controller.effect_idle(state.dw_led_idle_effect)
  226. _start_idle_led_timeout()
  227. def check_and_unlock_alarm():
  228. """
  229. Check if GRBL is in alarm state and unlock it with $X if needed.
  230. Returns True if device is ready (unlocked or no alarm), False on error.
  231. Note: If sensors are physically triggered (Pn:XY), the alarm may persist
  232. but we still return True to allow homing to proceed.
  233. """
  234. try:
  235. logger.info("Checking device status for alarm state...")
  236. # Clear any pending data in buffer first
  237. while state.conn.in_waiting() > 0:
  238. state.conn.readline()
  239. # Send status query
  240. state.conn.send('?\n')
  241. time.sleep(0.2)
  242. # Read response with timeout
  243. max_attempts = 10
  244. response = None
  245. for attempt in range(max_attempts):
  246. if state.conn.in_waiting() > 0:
  247. response = state.conn.readline()
  248. logger.debug(f"Status response: {response}")
  249. if response and ('<' in response or 'Alarm' in response or 'Idle' in response):
  250. break # Got a valid status response
  251. time.sleep(0.1)
  252. if not response:
  253. logger.warning("No status response received, proceeding anyway")
  254. return True
  255. # Check for alarm state
  256. if "Alarm" in response:
  257. logger.warning(f"Device in ALARM state: {response}")
  258. # Send unlock command
  259. logger.info("Sending $X to unlock...")
  260. state.conn.send('$X\n')
  261. time.sleep(1.0) # Give more time for unlock to process
  262. # Clear buffer before verification
  263. while state.conn.in_waiting() > 0:
  264. discarded = state.conn.readline()
  265. logger.debug(f"Discarded response: {discarded}")
  266. # Verify unlock succeeded
  267. state.conn.send('?\n')
  268. time.sleep(0.3)
  269. verify_response = None
  270. for attempt in range(max_attempts):
  271. if state.conn.in_waiting() > 0:
  272. verify_response = state.conn.readline()
  273. logger.debug(f"Verification response: {verify_response}")
  274. if verify_response and '<' in verify_response:
  275. break
  276. time.sleep(0.1)
  277. if verify_response and "Alarm" in verify_response:
  278. # Check if pins are physically triggered (Pn: in response)
  279. if "Pn:" in verify_response:
  280. logger.warning(f"Alarm persists due to triggered sensors: {verify_response}")
  281. logger.warning("Proceeding anyway - homing may clear the sensor state")
  282. return True # Let homing attempt to proceed
  283. else:
  284. logger.error("Failed to unlock device from alarm state")
  285. return False
  286. else:
  287. logger.info("Device successfully unlocked")
  288. return True
  289. else:
  290. logger.info("Device not in alarm state, proceeding normally")
  291. return True
  292. except Exception as e:
  293. logger.error(f"Error checking/unlocking alarm: {e}")
  294. return False
  295. def get_status_response() -> str:
  296. """
  297. Send a status query ('?') and return the response if available.
  298. """
  299. while True:
  300. try:
  301. state.conn.send('?')
  302. response = state.conn.readline()
  303. if "MPos" in response:
  304. logger.debug(f"Status response: {response}")
  305. return response
  306. except Exception as e:
  307. logger.error(f"Error getting status response: {e}")
  308. return False
  309. time.sleep(1)
  310. def parse_machine_position(response: str):
  311. """
  312. Parse the work position (MPos) from a status response.
  313. Expected format: "<...|MPos:-994.869,-321.861,0.000|...>"
  314. Returns a tuple (work_x, work_y) if found, else None.
  315. """
  316. if "MPos:" not in response:
  317. return None
  318. try:
  319. wpos_section = next((part for part in response.split("|") if part.startswith("MPos:")), None)
  320. if wpos_section:
  321. wpos_str = wpos_section.split(":", 1)[1]
  322. wpos_values = wpos_str.split(",")
  323. work_x = float(wpos_values[0])
  324. work_y = float(wpos_values[1])
  325. return work_x, work_y
  326. except Exception as e:
  327. logger.error(f"Error parsing work position: {e}")
  328. return None
  329. async def send_grbl_coordinates(x, y, speed=600, timeout=2, home=False):
  330. """
  331. Send a G-code command to FluidNC and wait for an 'ok' response.
  332. If no response after set timeout, sets state to stop and disconnects.
  333. """
  334. logger.debug(f"Sending G-code: X{x} Y{y} at F{speed}")
  335. # Track overall attempt time
  336. overall_start_time = time.time()
  337. while True:
  338. try:
  339. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  340. # Use asyncio.to_thread for both send and receive operations to avoid blocking
  341. await asyncio.to_thread(state.conn.send, gcode + "\n")
  342. logger.debug(f"Sent command: {gcode}")
  343. start_time = time.time()
  344. while True:
  345. # Use asyncio.to_thread for blocking I/O operations
  346. response = await asyncio.to_thread(state.conn.readline)
  347. logger.debug(f"Response: {response}")
  348. if response.lower() == "ok":
  349. logger.debug("Command execution confirmed.")
  350. return
  351. except Exception as e:
  352. # Store the error string inside the exception block
  353. error_str = str(e)
  354. logger.warning(f"Error sending command: {error_str}")
  355. # Immediately return for device not configured errors
  356. if "Device not configured" in error_str or "Errno 6" in error_str:
  357. logger.error(f"Device configuration error detected: {error_str}")
  358. state.stop_requested = True
  359. state.conn = None
  360. state.is_connected = False
  361. logger.info("Connection marked as disconnected due to device error")
  362. return False
  363. logger.warning(f"No 'ok' received for X{x} Y{y}, speed {speed}. Retrying...")
  364. await asyncio.sleep(0.1)
  365. # If we reach here, the timeout has occurred
  366. logger.error(f"Failed to receive 'ok' response after {max_total_attempt_time} seconds. Stopping and disconnecting.")
  367. # Set state to stop
  368. state.stop_requested = True
  369. # Set connection status to disconnected
  370. if state.conn:
  371. try:
  372. state.conn.disconnect()
  373. except:
  374. pass
  375. state.conn = None
  376. # Update the state connection status
  377. state.is_connected = False
  378. logger.info("Connection marked as disconnected due to timeout")
  379. return False
  380. def get_machine_steps(timeout=10):
  381. """
  382. Get machine steps/mm from the GRBL controller.
  383. Returns True if successful, False otherwise.
  384. """
  385. if not state.conn or not state.conn.is_connected():
  386. logger.error("Cannot get machine steps: No connection available")
  387. return False
  388. x_steps_per_mm = None
  389. y_steps_per_mm = None
  390. start_time = time.time()
  391. # Clear any pending data in the buffer
  392. try:
  393. while state.conn.in_waiting() > 0:
  394. state.conn.readline()
  395. except Exception as e:
  396. logger.warning(f"Error clearing buffer: {e}")
  397. # Send the command to request all settings
  398. try:
  399. logger.info("Requesting GRBL settings with $$ command")
  400. state.conn.send("$$\n")
  401. time.sleep(1.0) # Give GRBL time to process and respond (ESP32/FluidNC may need longer)
  402. except Exception as e:
  403. logger.error(f"Error sending $$ command: {e}")
  404. return False
  405. # Wait for and process responses
  406. settings_complete = False
  407. last_retry_time = start_time # Track when we last sent $$ for retry logic
  408. while time.time() - start_time < timeout and not settings_complete:
  409. try:
  410. # Attempt to read a line from the connection
  411. if state.conn.in_waiting() > 0:
  412. response = state.conn.readline()
  413. logger.debug(f"Raw response: {response}")
  414. # Process the line
  415. if response.strip(): # Only process non-empty lines
  416. for line in response.splitlines():
  417. line = line.strip()
  418. logger.debug(f"Config response: {line}")
  419. if line.startswith("$100="):
  420. x_steps_per_mm = float(line.split("=")[1])
  421. state.x_steps_per_mm = x_steps_per_mm
  422. logger.info(f"X steps per mm: {x_steps_per_mm}")
  423. elif line.startswith("$101="):
  424. y_steps_per_mm = float(line.split("=")[1])
  425. state.y_steps_per_mm = y_steps_per_mm
  426. logger.info(f"Y steps per mm: {y_steps_per_mm}")
  427. elif line.startswith("$22="):
  428. # $22 reports if the homing cycle is enabled
  429. # returns 0 if disabled, 1 if enabled
  430. # Note: We only log this, we don't overwrite state.homing
  431. # because user preference (saved in state.json) should take precedence
  432. firmware_homing = int(line.split('=')[1])
  433. logger.info(f"Firmware homing setting ($22): {firmware_homing}, using user preference: {state.homing}")
  434. # Check if we've received all the settings we need
  435. if x_steps_per_mm is not None and y_steps_per_mm is not None:
  436. settings_complete = True
  437. else:
  438. # No data waiting, small sleep to prevent CPU thrashing
  439. time.sleep(0.1)
  440. # Retry every 3 seconds if no response received
  441. if time.time() - last_retry_time > 3:
  442. logger.warning("No response yet, sending $$ command again")
  443. state.conn.send("$$\n")
  444. last_retry_time = time.time()
  445. except Exception as e:
  446. logger.error(f"Error getting machine steps: {e}")
  447. time.sleep(0.5)
  448. # Process results and determine table type
  449. if settings_complete:
  450. if y_steps_per_mm == 180 and x_steps_per_mm == 256:
  451. state.table_type = 'dune_weaver_mini'
  452. elif y_steps_per_mm == 210 and x_steps_per_mm == 256:
  453. state.table_type = 'dune_weaver_mini_pro_byj'
  454. elif y_steps_per_mm == 270 and x_steps_per_mm == 200:
  455. state.table_type = 'dune_weaver_gold'
  456. elif y_steps_per_mm == 287:
  457. state.table_type = 'dune_weaver'
  458. elif y_steps_per_mm == 164:
  459. state.table_type = 'dune_weaver_mini_pro'
  460. elif y_steps_per_mm >= 320:
  461. state.table_type = 'dune_weaver_pro'
  462. else:
  463. state.table_type = None
  464. logger.warning(f"Unknown table type with Y steps/mm: {y_steps_per_mm}")
  465. # Use override if set, otherwise use detected table type
  466. effective_table_type = state.table_type_override or state.table_type
  467. # Set gear ratio based on effective table type (hardcoded)
  468. if effective_table_type in ['dune_weaver_mini', 'dune_weaver_mini_pro', 'dune_weaver_mini_pro_byj', 'dune_weaver_gold']:
  469. state.gear_ratio = 6.25
  470. else:
  471. state.gear_ratio = 10
  472. # Check for environment variable override
  473. gear_ratio_override = os.getenv('GEAR_RATIO')
  474. if gear_ratio_override is not None:
  475. try:
  476. state.gear_ratio = float(gear_ratio_override)
  477. logger.info(f"Machine type detected: {state.table_type}, effective: {effective_table_type}, gear ratio: {state.gear_ratio} (from GEAR_RATIO env var)")
  478. except ValueError:
  479. logger.error(f"Invalid GEAR_RATIO env var value: {gear_ratio_override}, using default: {state.gear_ratio}")
  480. logger.info(f"Machine type detected: {state.table_type}, effective: {effective_table_type}, gear ratio: {state.gear_ratio} (hardcoded)")
  481. elif state.table_type_override:
  482. logger.info(f"Machine type detected: {state.table_type}, overridden to: {effective_table_type}, gear ratio: {state.gear_ratio}")
  483. else:
  484. logger.info(f"Machine type detected: {state.table_type}, gear ratio: {state.gear_ratio} (hardcoded)")
  485. return True
  486. else:
  487. missing = []
  488. if x_steps_per_mm is None: missing.append("X steps/mm")
  489. if y_steps_per_mm is None: missing.append("Y steps/mm")
  490. logger.error(f"Failed to get all machine parameters after {timeout}s. Missing: {', '.join(missing)}")
  491. return False
  492. def home(timeout=90):
  493. """
  494. Perform homing sequence based on configured mode:
  495. Mode 0 (Crash):
  496. - Y axis moves -22mm (or -30mm for mini) until physical stop
  497. - Set theta=0, rho=0 (no x0 y0 command)
  498. Mode 1 (Sensor):
  499. - Send $H command to home both X and Y axes
  500. - Wait for [MSG:Homed:X] and [MSG:Homed:Y] messages
  501. - Send x0 y0 to zero positions
  502. - Set theta to compass offset, rho=0
  503. Args:
  504. timeout: Maximum time in seconds to wait for homing to complete (default: 90)
  505. """
  506. import threading
  507. import math
  508. # Check for alarm state before homing and unlock if needed
  509. if not check_and_unlock_alarm():
  510. logger.error("Failed to unlock device from alarm state, cannot proceed with homing")
  511. return False
  512. # Flag to track if homing completed
  513. homing_complete = threading.Event()
  514. homing_success = False
  515. def home_internal():
  516. nonlocal homing_success
  517. effective_table_type = state.table_type_override or state.table_type
  518. homing_speed = 400
  519. if effective_table_type == 'dune_weaver_mini':
  520. homing_speed = 100
  521. try:
  522. if state.homing == 1:
  523. # Mode 1: Sensor-based homing using $H
  524. logger.info("Using sensor-based homing mode ($H)")
  525. # Clear any pending responses
  526. state.homed_x = False
  527. state.homed_y = False
  528. # Send $H command
  529. state.conn.send("$H\n")
  530. logger.info("Sent $H command, waiting for homing messages...")
  531. # Wait for [MSG:Homed:X] and [MSG:Homed:Y] messages
  532. max_wait_time = 30 # 30 seconds timeout for homing messages
  533. start_time = time.time()
  534. while (time.time() - start_time) < max_wait_time:
  535. try:
  536. response = state.conn.readline()
  537. if response:
  538. logger.debug(f"Homing response: {response}")
  539. # Check for homing messages
  540. if "[MSG:Homed:X]" in response:
  541. state.homed_x = True
  542. logger.info("Received [MSG:Homed:X]")
  543. if "[MSG:Homed:Y]" in response:
  544. state.homed_y = True
  545. logger.info("Received [MSG:Homed:Y]")
  546. # Break if we've received both messages
  547. if state.homed_x and state.homed_y:
  548. logger.info("Received both homing confirmation messages")
  549. break
  550. except Exception as e:
  551. logger.error(f"Error reading homing response: {e}")
  552. time.sleep(0.1)
  553. if not (state.homed_x and state.homed_y):
  554. logger.warning(f"Did not receive all homing messages (X:{state.homed_x}, Y:{state.homed_y}), unlocking and continuing...")
  555. # Unlock machine to clear any alarm state
  556. state.conn.send("$X\n")
  557. time.sleep(0.5)
  558. # Wait for idle state after $H
  559. logger.info("Waiting for device to reach idle state after $H...")
  560. idle_reached = check_idle()
  561. if not idle_reached:
  562. logger.error("Device did not reach idle state after $H command")
  563. homing_complete.set()
  564. return
  565. # Send x0 y0 to zero both positions using send_grbl_coordinates
  566. logger.info(f"Zeroing positions with x0 y0 f{homing_speed}")
  567. # Run async function in new event loop
  568. loop = asyncio.new_event_loop()
  569. asyncio.set_event_loop(loop)
  570. try:
  571. # Send G1 X0 Y0 F{homing_speed}
  572. result = loop.run_until_complete(send_grbl_coordinates(0, 0, homing_speed))
  573. if result == False:
  574. logger.error("Position zeroing failed - send_grbl_coordinates returned False")
  575. homing_complete.set()
  576. return
  577. logger.info("Position zeroing completed successfully")
  578. finally:
  579. loop.close()
  580. # Wait for device to reach idle state after zeroing movement
  581. logger.info("Waiting for device to reach idle state after zeroing...")
  582. idle_reached = check_idle()
  583. if not idle_reached:
  584. logger.error("Device did not reach idle state after zeroing")
  585. homing_complete.set()
  586. return
  587. # Set current position based on compass reference point (sensor mode only)
  588. # Only set AFTER x0 y0 is confirmed and device is idle
  589. offset_radians = math.radians(state.angular_homing_offset_degrees)
  590. state.current_theta = offset_radians
  591. state.current_rho = 0
  592. logger.info(f"Sensor homing completed - theta set to {state.angular_homing_offset_degrees}° ({offset_radians:.3f} rad), rho=0")
  593. else:
  594. logger.info(f"Using crash homing mode at {homing_speed} mm/min")
  595. # Run async function in new event loop
  596. loop = asyncio.new_event_loop()
  597. asyncio.set_event_loop(loop)
  598. try:
  599. if effective_table_type == 'dune_weaver_mini':
  600. result = loop.run_until_complete(send_grbl_coordinates(0, -30, homing_speed, home=True))
  601. if result == False:
  602. logger.error("Crash homing failed - send_grbl_coordinates returned False")
  603. homing_complete.set()
  604. return
  605. state.machine_y -= 30
  606. else:
  607. result = loop.run_until_complete(send_grbl_coordinates(0, -22, homing_speed, home=True))
  608. if result == False:
  609. logger.error("Crash homing failed - send_grbl_coordinates returned False")
  610. homing_complete.set()
  611. return
  612. state.machine_y -= 22
  613. finally:
  614. loop.close()
  615. # Wait for device to reach idle state after crash homing
  616. logger.info("Waiting for device to reach idle state after crash homing...")
  617. idle_reached = check_idle()
  618. if not idle_reached:
  619. logger.error("Device did not reach idle state after crash homing")
  620. homing_complete.set()
  621. return
  622. # Crash homing just sets theta and rho to 0 (no x0 y0 command)
  623. state.current_theta = 0
  624. state.current_rho = 0
  625. logger.info("Crash homing completed - theta=0, rho=0")
  626. # Update machine position from hardware after homing
  627. logger.info("Updating machine position after homing...")
  628. try:
  629. pos = get_machine_position()
  630. if pos and pos[0] is not None and pos[1] is not None:
  631. state.machine_x, state.machine_y = pos
  632. state.save()
  633. logger.info(f"Machine position updated after homing: X={state.machine_x}, Y={state.machine_y}")
  634. else:
  635. logger.warning("Could not get machine position after homing")
  636. except Exception as e:
  637. logger.error(f"Error updating machine position after homing: {e}")
  638. homing_success = True
  639. homing_complete.set()
  640. except Exception as e:
  641. logger.error(f"Error during homing: {e}")
  642. homing_complete.set()
  643. # Start homing in a separate thread
  644. homing_thread = threading.Thread(target=home_internal)
  645. homing_thread.daemon = True
  646. homing_thread.start()
  647. # Wait for homing to complete or timeout
  648. if not homing_complete.wait(timeout):
  649. logger.error(f"Homing timeout after {timeout} seconds")
  650. # Try to stop any ongoing movement
  651. try:
  652. if state.conn and state.conn.is_connected():
  653. state.conn.send("!\n") # Send feed hold
  654. time.sleep(0.1)
  655. state.conn.send("\x18\n") # Send reset
  656. except Exception as e:
  657. logger.error(f"Error stopping movement after timeout: {e}")
  658. return False
  659. if not homing_success:
  660. logger.error("Homing failed")
  661. return False
  662. logger.info("Homing completed successfully")
  663. return True
  664. def check_idle():
  665. """
  666. Continuously check if the device is idle (synchronous version).
  667. """
  668. logger.info("Checking idle")
  669. while True:
  670. response = get_status_response()
  671. if response and "Idle" in response:
  672. logger.info("Device is idle")
  673. # Schedule async update_machine_position in the existing event loop
  674. try:
  675. # Try to schedule in existing event loop if available
  676. try:
  677. loop = asyncio.get_running_loop()
  678. # Create a task but don't await it (fire and forget)
  679. asyncio.create_task(update_machine_position())
  680. logger.debug("Scheduled machine position update task")
  681. except RuntimeError:
  682. # No event loop running, skip machine position update
  683. logger.debug("No event loop running, skipping machine position update")
  684. except Exception as e:
  685. logger.error(f"Error scheduling machine position update: {e}")
  686. return True
  687. time.sleep(1)
  688. async def check_idle_async():
  689. """
  690. Continuously check if the device is idle (async version).
  691. """
  692. logger.info("Checking idle (async)")
  693. while True:
  694. response = await asyncio.to_thread(get_status_response)
  695. if response and "Idle" in response:
  696. logger.info("Device is idle")
  697. try:
  698. await update_machine_position()
  699. except Exception as e:
  700. logger.error(f"Error updating machine position: {e}")
  701. return True
  702. await asyncio.sleep(1)
  703. def is_machine_idle() -> bool:
  704. """
  705. Single check to see if the machine is currently idle.
  706. Does not loop - returns immediately with current status.
  707. Returns:
  708. True if machine is idle, False otherwise
  709. """
  710. if not state.conn or not state.conn.is_connected():
  711. logger.debug("No connection - machine not idle")
  712. return False
  713. try:
  714. state.conn.send('?')
  715. response = state.conn.readline()
  716. if response and "Idle" in response:
  717. logger.debug("Machine status: Idle")
  718. return True
  719. else:
  720. logger.debug(f"Machine status: {response}")
  721. return False
  722. except Exception as e:
  723. logger.error(f"Error checking machine idle status: {e}")
  724. return False
  725. def get_machine_position(timeout=5):
  726. """
  727. Query the device for its position.
  728. """
  729. start_time = time.time()
  730. while time.time() - start_time < timeout:
  731. try:
  732. state.conn.send('?')
  733. response = state.conn.readline()
  734. logger.debug(f"Raw status response: {response}")
  735. if "MPos" in response:
  736. pos = parse_machine_position(response)
  737. if pos:
  738. machine_x, machine_y = pos
  739. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  740. return machine_x, machine_y
  741. except Exception as e:
  742. logger.error(f"Error getting machine position: {e}")
  743. return
  744. time.sleep(0.1)
  745. logger.warning("Timeout reached waiting for machine position")
  746. return None, None
  747. async def update_machine_position():
  748. if (state.conn.is_connected() if state.conn else False):
  749. try:
  750. logger.info('Saving machine position')
  751. state.machine_x, state.machine_y = await asyncio.to_thread(get_machine_position)
  752. await asyncio.to_thread(state.save)
  753. logger.info(f'Machine position saved: {state.machine_x}, {state.machine_y}')
  754. except Exception as e:
  755. logger.error(f"Error updating machine position: {e}")
  756. def restart_connection(homing=False):
  757. """
  758. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  759. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  760. The new connection is saved to state.conn.
  761. Returns:
  762. True if the connection was restarted successfully, False otherwise.
  763. """
  764. try:
  765. if (state.conn.is_connected() if state.conn else False):
  766. logger.info("Closing current connection...")
  767. state.conn.close()
  768. except Exception as e:
  769. logger.error(f"Error while closing connection: {e}")
  770. # Clear the connection reference.
  771. state.conn = None
  772. logger.info("Attempting to restart connection...")
  773. try:
  774. connect_device(homing) # This will set state.conn appropriately.
  775. if (state.conn.is_connected() if state.conn else False):
  776. logger.info("Connection restarted successfully.")
  777. return True
  778. else:
  779. logger.error("Failed to restart connection.")
  780. return False
  781. except Exception as e:
  782. logger.error(f"Error restarting connection: {e}")
  783. return False