connection_manager.py 39 KB

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