1
0

connection_manager.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  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 (shown in UI but not auto-selected)
  16. DEPRIORITIZED_PORTS = ['/dev/ttyS0']
  17. async def _check_table_is_idle() -> bool:
  18. """Helper function to check if table is idle."""
  19. return not state.current_playing_file or state.pause_requested
  20. def _start_idle_led_timeout():
  21. """Start idle LED timeout if enabled."""
  22. if not state.dw_led_idle_timeout_enabled or state.dw_led_idle_timeout_minutes <= 0:
  23. return
  24. logger.debug(f"Starting idle LED timeout: {state.dw_led_idle_timeout_minutes} minutes")
  25. idle_timeout_manager.start_idle_timeout(
  26. timeout_minutes=state.dw_led_idle_timeout_minutes,
  27. state=state,
  28. check_idle_callback=_check_table_is_idle
  29. )
  30. ###############################################################################
  31. # Connection Abstraction
  32. ###############################################################################
  33. class BaseConnection:
  34. """Abstract base class for a connection."""
  35. def send(self, data: str) -> None:
  36. raise NotImplementedError
  37. def flush(self) -> None:
  38. raise NotImplementedError
  39. def readline(self) -> str:
  40. raise NotImplementedError
  41. def in_waiting(self) -> int:
  42. raise NotImplementedError
  43. def is_connected(self) -> bool:
  44. raise NotImplementedError
  45. def close(self) -> None:
  46. raise NotImplementedError
  47. ###############################################################################
  48. # Serial Connection Implementation
  49. ###############################################################################
  50. class SerialConnection(BaseConnection):
  51. def __init__(self, port: str, baudrate: int = 115200, timeout: int = 2):
  52. self.port = port
  53. self.baudrate = baudrate
  54. self.timeout = timeout
  55. self.lock = threading.RLock()
  56. logger.info(f'Connecting to Serial port {port}')
  57. self.ser = serial.Serial(port, baudrate, timeout=timeout)
  58. state.port = port
  59. logger.info(f'Connected to Serial port {port}')
  60. def send(self, data: str) -> None:
  61. with self.lock:
  62. self.ser.write(data.encode())
  63. self.ser.flush()
  64. def flush(self) -> None:
  65. with self.lock:
  66. self.ser.flush()
  67. def readline(self) -> str:
  68. with self.lock:
  69. return self.ser.readline().decode().strip()
  70. def in_waiting(self) -> int:
  71. with self.lock:
  72. return self.ser.in_waiting
  73. def reset_input_buffer(self) -> None:
  74. """Clear any stale data from the serial input buffer."""
  75. with self.lock:
  76. if self.ser and self.ser.is_open:
  77. self.ser.reset_input_buffer()
  78. def is_connected(self) -> bool:
  79. return self.ser is not None and self.ser.is_open
  80. def close(self) -> None:
  81. # Save current state synchronously first (critical for position persistence)
  82. try:
  83. state.save()
  84. except Exception as e:
  85. logger.error(f"Error saving state on close: {e}")
  86. # Schedule async position update if event loop exists, otherwise skip
  87. # This avoids creating nested event loops which causes RuntimeError
  88. try:
  89. loop = asyncio.get_running_loop()
  90. # We're in async context - schedule as task (fire-and-forget)
  91. asyncio.create_task(update_machine_position())
  92. logger.debug("Scheduled async machine position update")
  93. except RuntimeError:
  94. # No running event loop - we're in sync context
  95. # Position was already saved above, skip async update to avoid nested loop
  96. logger.debug("No event loop running, skipping async position update")
  97. with self.lock:
  98. if self.ser.is_open:
  99. self.ser.close()
  100. ###############################################################################
  101. # WebSocket Connection Implementation
  102. ###############################################################################
  103. class WebSocketConnection(BaseConnection):
  104. def __init__(self, url: str, timeout: int = 5):
  105. self.url = url
  106. self.timeout = timeout
  107. self.lock = threading.RLock()
  108. self.ws = None
  109. self.connect()
  110. def connect(self):
  111. logger.info(f'Connecting to Websocket {self.url}')
  112. self.ws = websocket.create_connection(self.url, timeout=self.timeout)
  113. state.port = self.url
  114. logger.info(f'Connected to Websocket {self.url}')
  115. def send(self, data: str) -> None:
  116. with self.lock:
  117. self.ws.send(data)
  118. def flush(self) -> None:
  119. # WebSocket sends immediately; nothing to flush.
  120. pass
  121. def readline(self) -> str:
  122. with self.lock:
  123. data = self.ws.recv()
  124. # Decode bytes to string if necessary
  125. if isinstance(data, bytes):
  126. data = data.decode('utf-8')
  127. return data.strip()
  128. def in_waiting(self) -> int:
  129. return 0 # Not applicable for WebSocket
  130. def is_connected(self) -> bool:
  131. return self.ws is not None
  132. def close(self) -> None:
  133. # Save current state synchronously first (critical for position persistence)
  134. try:
  135. state.save()
  136. except Exception as e:
  137. logger.error(f"Error saving state on close: {e}")
  138. # Schedule async position update if event loop exists, otherwise skip
  139. # This avoids creating nested event loops which causes RuntimeError
  140. try:
  141. loop = asyncio.get_running_loop()
  142. # We're in async context - schedule as task (fire-and-forget)
  143. asyncio.create_task(update_machine_position())
  144. logger.debug("Scheduled async machine position update")
  145. except RuntimeError:
  146. # No running event loop - we're in sync context
  147. # Position was already saved above, skip async update to avoid nested loop
  148. logger.debug("No event loop running, skipping async position update")
  149. with self.lock:
  150. if self.ws:
  151. self.ws.close()
  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. # IMPORTANT: Query machine position BEFORE reset to determine if homing is needed
  160. # If machine wasn't power cycled, it retains position and we can skip homing
  161. # Reset ($Bye) zeroes position counters, so we must check BEFORE reset
  162. try:
  163. if get_machine_steps():
  164. 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}")
  165. else:
  166. logger.fatal("Failed to get machine steps")
  167. state.conn.close()
  168. return False
  169. except:
  170. logger.fatal("Not GRBL firmware")
  171. state.conn.close()
  172. return False
  173. # Check machine position BEFORE reset to decide if homing is needed
  174. machine_x, machine_y = get_machine_position()
  175. needs_homing = False
  176. if machine_x != state.machine_x or machine_y != state.machine_y:
  177. logger.info(f'Machine position mismatch - machine: ({machine_x}, {machine_y}), saved: ({state.machine_x}, {state.machine_y})')
  178. needs_homing = homing
  179. else:
  180. logger.info('Machine position matches saved state, skipping home')
  181. logger.info(f'Theta: {state.current_theta}, rho: {state.current_rho}')
  182. logger.info(f'Position: ({machine_x}, {machine_y})')
  183. # Now perform soft reset to ensure controller is in a clean state
  184. # This clears any pending commands and resets position counters to 0
  185. logger.info("Performing soft reset for clean controller state...")
  186. perform_soft_reset_sync()
  187. time.sleep(1) # Extra stabilization after controller restart
  188. # Reset work coordinate offsets for a clean start
  189. # This ensures we're using work coordinates (G54) starting from 0
  190. reset_work_coordinates()
  191. # Home if position was mismatched (machine may have been power cycled)
  192. if needs_homing:
  193. logger.info("Homing required due to position mismatch...")
  194. success = home()
  195. if not success:
  196. logger.error("Homing failed during device initialization")
  197. # If sensor homing failed, close connection and return False
  198. # This prevents auto-connection from completing until user takes action
  199. if state.sensor_homing_failed:
  200. logger.error("Sensor homing failed - closing connection. User must check sensor or switch to crash homing.")
  201. state.conn.close()
  202. state.conn = None
  203. return False
  204. time.sleep(2) # Allow time for the connection to establish
  205. return True
  206. def connect_device(homing=True):
  207. # Initialize LED interface based on configured provider
  208. # Note: DW LEDs are initialized at startup in main.py, so we preserve the existing controller
  209. if state.led_provider == "wled" and state.wled_ip:
  210. state.led_controller = LEDInterface(provider="wled", ip_address=state.wled_ip)
  211. elif state.led_provider == "dw_leds":
  212. # DW LEDs are already initialized in main.py at startup
  213. # Only initialize here if not already set up (e.g., reconnection scenario)
  214. if not state.led_controller or not state.led_controller.is_configured:
  215. state.led_controller = LEDInterface(
  216. provider="dw_leds",
  217. num_leds=state.dw_led_num_leds,
  218. gpio_pin=state.dw_led_gpio_pin,
  219. pixel_order=state.dw_led_pixel_order,
  220. brightness=state.dw_led_brightness / 100.0,
  221. speed=state.dw_led_speed,
  222. intensity=state.dw_led_intensity
  223. )
  224. elif state.led_provider == "hyperion" and state.hyperion_ip:
  225. state.led_controller = LEDInterface(
  226. provider="hyperion",
  227. ip_address=state.hyperion_ip,
  228. port=state.hyperion_port
  229. )
  230. elif state.led_provider == "none" or not state.led_provider:
  231. state.led_controller = None
  232. # For other cases (e.g., wled without IP), preserve existing controller
  233. # Show loading effect
  234. if state.led_controller:
  235. state.led_controller.effect_loading()
  236. ports = list_serial_ports()
  237. # Check auto-connect mode: "__auto__" or None = auto, "__none__" = disabled, else specific port
  238. if state.preferred_port == "__none__":
  239. logger.info("Auto-connect disabled by user preference")
  240. # Skip all auto-connect logic, no connection will be established
  241. # Priority for auto-connect:
  242. # 1. Preferred port (user's explicit choice) if available
  243. # 2. Last used port if available
  244. # 3. First available port as fallback
  245. elif state.preferred_port and state.preferred_port not in ("__auto__", None) and state.preferred_port in ports:
  246. logger.info(f"Connecting to preferred port: {state.preferred_port}")
  247. state.conn = SerialConnection(state.preferred_port)
  248. elif state.port and state.port in ports:
  249. logger.info(f"Connecting to last used port: {state.port}")
  250. state.conn = SerialConnection(state.port)
  251. elif ports:
  252. # Prefer non-deprioritized ports (e.g., USB serial over hardware UART)
  253. preferred_ports = [p for p in ports if p not in DEPRIORITIZED_PORTS]
  254. fallback_ports = [p for p in ports if p in DEPRIORITIZED_PORTS]
  255. if preferred_ports:
  256. logger.info(f"Connecting to first available port: {preferred_ports[0]}")
  257. state.conn = SerialConnection(preferred_ports[0])
  258. elif fallback_ports:
  259. logger.info(f"Connecting to deprioritized port (no better option): {fallback_ports[0]}")
  260. state.conn = SerialConnection(fallback_ports[0])
  261. else:
  262. logger.error("Auto connect failed: No serial ports available")
  263. # state.conn = WebSocketConnection('ws://fluidnc.local:81')
  264. if (state.conn.is_connected() if state.conn else False):
  265. # Check for alarm state and unlock if needed before initializing
  266. if not check_and_unlock_alarm():
  267. logger.error("Failed to unlock device from alarm state")
  268. # Still proceed with device_init but log the issue
  269. device_init(homing)
  270. # Show connected effect, then transition to configured idle effect
  271. if state.led_controller:
  272. logger.info("Showing LED connected effect (green flash)")
  273. state.led_controller.effect_connected()
  274. # Set the configured idle effect after connection
  275. logger.info(f"Setting LED to idle effect: {state.dw_led_idle_effect}")
  276. state.led_controller.effect_idle(state.dw_led_idle_effect)
  277. _start_idle_led_timeout()
  278. def check_and_unlock_alarm():
  279. """
  280. Check if GRBL is in alarm state and unlock it with $X if needed.
  281. Returns True if device is ready (unlocked or no alarm), False on error.
  282. Note: If sensors are physically triggered (Pn:XY), the alarm may persist
  283. but we still return True to allow homing to proceed.
  284. """
  285. try:
  286. logger.info("Checking device status for alarm state...")
  287. # Clear any pending data in buffer first
  288. while state.conn.in_waiting() > 0:
  289. state.conn.readline()
  290. # Send status query
  291. state.conn.send('?\n')
  292. time.sleep(0.2)
  293. # Read response with timeout
  294. max_attempts = 10
  295. response = None
  296. for attempt in range(max_attempts):
  297. if state.conn.in_waiting() > 0:
  298. response = state.conn.readline()
  299. logger.debug(f"Status response: {response}")
  300. if response and ('<' in response or 'Alarm' in response or 'Idle' in response):
  301. break # Got a valid status response
  302. time.sleep(0.1)
  303. if not response:
  304. logger.warning("No status response received, proceeding anyway")
  305. return True
  306. # Check for alarm state
  307. if "Alarm" in response:
  308. logger.warning(f"Device in ALARM state: {response}")
  309. # Send unlock command
  310. logger.info("Sending $X to unlock...")
  311. state.conn.send('$X\n')
  312. time.sleep(1.0) # Give more time for unlock to process
  313. # Clear buffer before verification
  314. while state.conn.in_waiting() > 0:
  315. discarded = state.conn.readline()
  316. logger.debug(f"Discarded response: {discarded}")
  317. # Verify unlock succeeded
  318. state.conn.send('?\n')
  319. time.sleep(0.3)
  320. verify_response = None
  321. for attempt in range(max_attempts):
  322. if state.conn.in_waiting() > 0:
  323. verify_response = state.conn.readline()
  324. logger.debug(f"Verification response: {verify_response}")
  325. if verify_response and '<' in verify_response:
  326. break
  327. time.sleep(0.1)
  328. if verify_response and "Alarm" in verify_response:
  329. # Check if pins are physically triggered (Pn: in response)
  330. if "Pn:" in verify_response:
  331. logger.warning(f"Alarm persists due to triggered sensors: {verify_response}")
  332. logger.warning("Proceeding anyway - homing may clear the sensor state")
  333. return True # Let homing attempt to proceed
  334. else:
  335. logger.error("Failed to unlock device from alarm state")
  336. return False
  337. else:
  338. logger.info("Device successfully unlocked")
  339. return True
  340. else:
  341. logger.info("Device not in alarm state, proceeding normally")
  342. return True
  343. except Exception as e:
  344. logger.error(f"Error checking/unlocking alarm: {e}")
  345. return False
  346. def get_status_response() -> str:
  347. """
  348. Send a status query ('?') and return the response if available.
  349. Accepts both MPos (machine position) and WPos (work position) formats
  350. depending on GRBL's $10 setting.
  351. """
  352. if state.conn is None or not state.conn.is_connected():
  353. logger.warning("Cannot get status response: no active connection")
  354. return False
  355. while True:
  356. try:
  357. state.conn.send('?')
  358. response = state.conn.readline()
  359. # Accept either MPos or WPos format (depends on GRBL $10 setting)
  360. if "MPos" in response or "WPos" in response:
  361. logger.debug(f"Status response: {response}")
  362. return response
  363. except Exception as e:
  364. logger.error(f"Error getting status response: {e}")
  365. return False
  366. time.sleep(1)
  367. def parse_machine_position(response: str):
  368. """
  369. Parse the position from a status response.
  370. Supports both MPos (machine position) and WPos (work position) formats
  371. depending on GRBL's $10 setting.
  372. Expected formats:
  373. "<...|MPos:-994.869,-321.861,0.000|...>"
  374. "<...|WPos:0.000,19.000,0.000|...>"
  375. Returns a tuple (x, y) if found, else None.
  376. """
  377. if "MPos:" not in response and "WPos:" not in response:
  378. return None
  379. try:
  380. # Try MPos first, then WPos
  381. pos_section = next((part for part in response.split("|") if part.startswith("MPos:")), None)
  382. if pos_section is None:
  383. pos_section = next((part for part in response.split("|") if part.startswith("WPos:")), None)
  384. if pos_section:
  385. pos_str = pos_section.split(":", 1)[1]
  386. pos_values = pos_str.split(",")
  387. pos_x = float(pos_values[0])
  388. pos_y = float(pos_values[1])
  389. return pos_x, pos_y
  390. except Exception as e:
  391. logger.error(f"Error parsing position: {e}")
  392. return None
  393. async def send_grbl_coordinates(x, y, speed=600, timeout=30, home=False):
  394. """
  395. Send a G-code command to FluidNC and wait for an 'ok' response.
  396. If no response after set timeout, returns False.
  397. Args:
  398. x: X coordinate
  399. y: Y coordinate
  400. speed: Feed rate in mm/min
  401. timeout: Maximum time in seconds to wait for 'ok' response
  402. home: If True, sends jog command ($J=) instead of G1
  403. Returns:
  404. True on success, False on timeout or error
  405. """
  406. logger.debug(f"Sending G-code: X{x} Y{y} at F{speed}")
  407. overall_start_time = time.time()
  408. max_retries = 3
  409. retry_count = 0
  410. while retry_count < max_retries:
  411. # Check overall timeout
  412. if time.time() - overall_start_time > timeout:
  413. logger.error(f"Timeout waiting for 'ok' response after {timeout}s")
  414. return False
  415. try:
  416. gcode = f"$J=G91 G21 Y{y:.2f} F{speed}" if home else f"G1 X{x:.2f} Y{y:.2f} F{speed}"
  417. await asyncio.to_thread(state.conn.send, gcode + "\n")
  418. logger.debug(f"Sent command: {gcode}")
  419. # Wait for 'ok' response with timeout
  420. response_start = time.time()
  421. response_timeout = min(10, timeout - (time.time() - overall_start_time))
  422. while time.time() - response_start < response_timeout:
  423. # Check overall timeout
  424. if time.time() - overall_start_time > timeout:
  425. logger.error(f"Overall timeout waiting for 'ok' response")
  426. return False
  427. response = await asyncio.to_thread(state.conn.readline)
  428. if response:
  429. logger.debug(f"Response: {response}")
  430. if response.lower().strip() == "ok":
  431. logger.debug("Command execution confirmed.")
  432. return True
  433. elif 'error' in response.lower():
  434. logger.warning(f"Got error response: {response}")
  435. # Don't immediately fail - some errors are recoverable
  436. else:
  437. await asyncio.sleep(0.05)
  438. # Response timeout for this attempt
  439. logger.warning(f"No 'ok' received for {gcode}, retrying... ({retry_count + 1}/{max_retries})")
  440. retry_count += 1
  441. await asyncio.sleep(0.2)
  442. except Exception as e:
  443. error_str = str(e)
  444. logger.warning(f"Error sending command: {error_str}")
  445. # Immediately return for device not configured errors
  446. if "Device not configured" in error_str or "Errno 6" in error_str:
  447. logger.error(f"Device configuration error detected: {error_str}")
  448. state.stop_requested = True
  449. state.conn = None
  450. state.is_connected = False
  451. logger.info("Connection marked as disconnected due to device error")
  452. return False
  453. retry_count += 1
  454. await asyncio.sleep(0.2)
  455. logger.error(f"Failed to receive 'ok' response after {max_retries} retries")
  456. return False
  457. def _detect_firmware():
  458. """
  459. Detect firmware type (FluidNC or GRBL) by sending $I command.
  460. Returns tuple: (firmware_type: str, version: str or None)
  461. firmware_type is 'fluidnc', 'grbl', or 'unknown'
  462. """
  463. if not state.conn or not state.conn.is_connected():
  464. return ('unknown', None)
  465. # Clear buffer first
  466. try:
  467. while state.conn.in_waiting() > 0:
  468. state.conn.readline()
  469. except Exception:
  470. pass
  471. try:
  472. state.conn.send("$I\n")
  473. time.sleep(0.3)
  474. firmware_type = 'unknown'
  475. version = None
  476. start_time = time.time()
  477. while time.time() - start_time < 2.0:
  478. if state.conn.in_waiting() > 0:
  479. response = state.conn.readline()
  480. if response:
  481. logger.debug(f"Firmware detection response: {response}")
  482. response_lower = response.lower()
  483. if 'fluidnc' in response_lower:
  484. firmware_type = 'fluidnc'
  485. # Try to extract version from response like "FluidNC v3.7.2"
  486. if 'v' in response_lower:
  487. parts = response.split()
  488. for part in parts:
  489. if part.lower().startswith('v') and any(c.isdigit() for c in part):
  490. version = part
  491. break
  492. break
  493. elif 'grbl' in response_lower and 'fluidnc' not in response_lower:
  494. firmware_type = 'grbl'
  495. # Try to extract version like "Grbl 1.1h"
  496. parts = response.split()
  497. for i, part in enumerate(parts):
  498. if 'grbl' in part.lower() and i + 1 < len(parts):
  499. version = parts[i + 1]
  500. break
  501. break
  502. elif response.lower().strip() == 'ok':
  503. break
  504. else:
  505. time.sleep(0.05)
  506. # Clear any remaining responses
  507. while state.conn.in_waiting() > 0:
  508. state.conn.readline()
  509. return (firmware_type, version)
  510. except Exception as e:
  511. logger.warning(f"Firmware detection failed: {e}")
  512. return ('unknown', None)
  513. def _get_steps_fluidnc():
  514. """
  515. Get steps/mm from FluidNC using individual setting queries.
  516. Returns tuple: (x_steps_per_mm, y_steps_per_mm) or (None, None) on failure.
  517. Note: Works even when device is in ALARM state (e.g., limit switch active).
  518. """
  519. x_steps = None
  520. y_steps = None
  521. # Clear buffer
  522. try:
  523. while state.conn.in_waiting() > 0:
  524. state.conn.readline()
  525. except Exception:
  526. pass
  527. # Query X steps/mm
  528. try:
  529. state.conn.send("$/axes/x/steps_per_mm\n")
  530. time.sleep(0.2)
  531. start_time = time.time()
  532. while time.time() - start_time < 2.0:
  533. if state.conn.in_waiting() > 0:
  534. response = state.conn.readline()
  535. if response:
  536. logger.debug(f"FluidNC X steps response: {response}")
  537. # Response format: "/axes/x/steps_per_mm=200.000" or similar
  538. if 'steps_per_mm=' in response:
  539. try:
  540. x_steps = float(response.split('=')[1].strip())
  541. state.x_steps_per_mm = x_steps
  542. logger.info(f"X steps per mm (FluidNC): {x_steps}")
  543. except (ValueError, IndexError) as e:
  544. logger.warning(f"Failed to parse X steps: {e}")
  545. break
  546. elif response.lower().strip() == 'ok':
  547. break
  548. elif 'error' in response.lower() or 'alarm' in response.lower():
  549. # Device may be in alarm state (e.g., limit switch active)
  550. # Log and continue - settings queries often work anyway
  551. logger.debug(f"Got error/alarm response, continuing: {response}")
  552. else:
  553. time.sleep(0.05)
  554. except Exception as e:
  555. logger.error(f"Error querying FluidNC X steps: {e}")
  556. # Clear buffer before next query
  557. try:
  558. while state.conn.in_waiting() > 0:
  559. state.conn.readline()
  560. except Exception:
  561. pass
  562. # Query Y steps/mm
  563. try:
  564. state.conn.send("$/axes/y/steps_per_mm\n")
  565. time.sleep(0.2)
  566. start_time = time.time()
  567. while time.time() - start_time < 2.0:
  568. if state.conn.in_waiting() > 0:
  569. response = state.conn.readline()
  570. if response:
  571. logger.debug(f"FluidNC Y steps response: {response}")
  572. if 'steps_per_mm=' in response:
  573. try:
  574. y_steps = float(response.split('=')[1].strip())
  575. state.y_steps_per_mm = y_steps
  576. logger.info(f"Y steps per mm (FluidNC): {y_steps}")
  577. except (ValueError, IndexError) as e:
  578. logger.warning(f"Failed to parse Y steps: {e}")
  579. break
  580. elif response.lower().strip() == 'ok':
  581. break
  582. elif 'error' in response.lower() or 'alarm' in response.lower():
  583. logger.debug(f"Got error/alarm response, continuing: {response}")
  584. else:
  585. time.sleep(0.05)
  586. except Exception as e:
  587. logger.error(f"Error querying FluidNC Y steps: {e}")
  588. # Clear buffer before homing query
  589. try:
  590. while state.conn.in_waiting() > 0:
  591. state.conn.readline()
  592. except Exception:
  593. pass
  594. # Query homing cycle setting (informational - user preference takes precedence)
  595. try:
  596. state.conn.send("$/axes/y/homing/cycle\n")
  597. time.sleep(0.2)
  598. start_time = time.time()
  599. while time.time() - start_time < 1.5:
  600. if state.conn.in_waiting() > 0:
  601. response = state.conn.readline()
  602. if response:
  603. logger.debug(f"FluidNC homing response: {response}")
  604. if 'homing/cycle=' in response:
  605. try:
  606. homing_cycle = int(float(response.split('=')[1].strip()))
  607. # cycle >= 1 means homing is enabled in firmware
  608. firmware_homing = 1 if homing_cycle >= 1 else 0
  609. logger.info(f"Firmware homing setting (cycle): {homing_cycle}, using user preference: {state.homing}")
  610. except (ValueError, IndexError):
  611. pass
  612. break
  613. elif response.lower().strip() == 'ok':
  614. break
  615. else:
  616. time.sleep(0.05)
  617. except Exception as e:
  618. logger.debug(f"Could not query FluidNC homing setting: {e}")
  619. # Clear buffer
  620. try:
  621. while state.conn.in_waiting() > 0:
  622. state.conn.readline()
  623. except Exception:
  624. pass
  625. return (x_steps, y_steps)
  626. def _get_steps_grbl():
  627. """
  628. Get steps/mm from GRBL using $$ command.
  629. Returns tuple: (x_steps_per_mm, y_steps_per_mm) or (None, None) on failure.
  630. Note: Works even when device is in ALARM state (e.g., limit switch active).
  631. $$ command typically responds with settings even during alarm.
  632. """
  633. x_steps_per_mm = None
  634. y_steps_per_mm = None
  635. max_retries = 3
  636. attempt_timeout = 4
  637. for attempt in range(max_retries):
  638. logger.info(f"Requesting GRBL settings with $$ command (attempt {attempt + 1}/{max_retries})")
  639. try:
  640. state.conn.send("$$\n")
  641. except Exception as e:
  642. logger.error(f"Error sending $$ command: {e}")
  643. continue
  644. attempt_start = time.time()
  645. got_ok = False
  646. while time.time() - attempt_start < attempt_timeout:
  647. try:
  648. response = state.conn.readline()
  649. if not response:
  650. continue
  651. logger.debug(f"Raw response: {response}")
  652. for line in response.splitlines():
  653. line = line.strip()
  654. if not line:
  655. continue
  656. logger.debug(f"Config response: {line}")
  657. if line.startswith("$100="):
  658. x_steps_per_mm = float(line.split("=")[1])
  659. state.x_steps_per_mm = x_steps_per_mm
  660. logger.info(f"X steps per mm: {x_steps_per_mm}")
  661. elif line.startswith("$101="):
  662. y_steps_per_mm = float(line.split("=")[1])
  663. state.y_steps_per_mm = y_steps_per_mm
  664. logger.info(f"Y steps per mm: {y_steps_per_mm}")
  665. elif line.startswith("$22="):
  666. firmware_homing = int(line.split('=')[1])
  667. logger.info(f"Firmware homing setting ($22): {firmware_homing}, using user preference: {state.homing}")
  668. elif line.lower() == 'ok':
  669. got_ok = True
  670. logger.debug("Received 'ok' confirmation from GRBL")
  671. elif line.lower().startswith('error') or 'alarm' in line.lower():
  672. # Device may be in alarm state (e.g., limit switch active)
  673. # Log and continue - $$ typically works anyway
  674. logger.debug(f"Got error/alarm during settings query (proceeding): {line}")
  675. if got_ok:
  676. if x_steps_per_mm is not None and y_steps_per_mm is not None:
  677. logger.info("Successfully received all GRBL settings")
  678. break
  679. else:
  680. logger.warning("Received 'ok' but missing some settings")
  681. break
  682. except Exception as e:
  683. logger.error(f"Error reading GRBL response: {e}")
  684. break
  685. if x_steps_per_mm is not None and y_steps_per_mm is not None:
  686. break
  687. if attempt < max_retries - 1:
  688. logger.warning(f"Attempt {attempt + 1} did not get all settings, retrying...")
  689. time.sleep(0.5)
  690. try:
  691. while state.conn.in_waiting() > 0:
  692. state.conn.readline()
  693. except Exception:
  694. pass
  695. return (x_steps_per_mm, y_steps_per_mm)
  696. def get_machine_steps(timeout=10):
  697. """
  698. Get machine steps/mm from the controller (FluidNC or GRBL).
  699. Returns True if successful, False otherwise.
  700. Detects firmware type first:
  701. - FluidNC: Uses targeted $/axes/x/steps_per_mm queries (more reliable)
  702. - GRBL: Falls back to $$ command with retries
  703. """
  704. if not state.conn or not state.conn.is_connected():
  705. logger.error("Cannot get machine steps: No connection available")
  706. return False
  707. # Clear any pending data in the buffer
  708. try:
  709. while state.conn.in_waiting() > 0:
  710. state.conn.readline()
  711. except Exception as e:
  712. logger.warning(f"Error clearing buffer: {e}")
  713. # Verify controller is responsive before querying
  714. try:
  715. state.conn.send("?\n")
  716. time.sleep(0.2)
  717. ready_check_attempts = 5
  718. controller_ready = False
  719. in_alarm = False
  720. for _ in range(ready_check_attempts):
  721. if state.conn.in_waiting() > 0:
  722. response = state.conn.readline()
  723. if response and ('<' in response or 'Idle' in response or 'Alarm' in response):
  724. controller_ready = True
  725. if 'Alarm' in response:
  726. in_alarm = True
  727. logger.info(f"Controller in ALARM state (likely limit switch active), proceeding with settings query: {response.strip()}")
  728. else:
  729. logger.debug(f"Controller ready, status: {response}")
  730. break
  731. time.sleep(0.1)
  732. if not controller_ready:
  733. logger.warning("Controller not responding to status query, proceeding anyway...")
  734. # Clear buffer after readiness check
  735. while state.conn.in_waiting() > 0:
  736. state.conn.readline()
  737. time.sleep(0.1)
  738. except Exception as e:
  739. logger.warning(f"Readiness check failed: {e}, proceeding anyway...")
  740. # Detect firmware type
  741. firmware_type, firmware_version = _detect_firmware()
  742. if firmware_type == 'fluidnc':
  743. if firmware_version:
  744. logger.info(f"Detected FluidNC firmware, version: {firmware_version}")
  745. else:
  746. logger.info("Detected FluidNC firmware (version unknown)")
  747. x_steps_per_mm, y_steps_per_mm = _get_steps_fluidnc()
  748. # Fallback to GRBL method if FluidNC queries failed
  749. if x_steps_per_mm is None or y_steps_per_mm is None:
  750. logger.warning("FluidNC setting queries failed, falling back to $$ command...")
  751. x_steps_per_mm, y_steps_per_mm = _get_steps_grbl()
  752. else:
  753. if firmware_type == 'grbl':
  754. if firmware_version:
  755. logger.info(f"Detected GRBL firmware, version: {firmware_version}")
  756. else:
  757. logger.info("Detected GRBL firmware (version unknown)")
  758. else:
  759. logger.info("Could not detect firmware type, using GRBL commands")
  760. x_steps_per_mm, y_steps_per_mm = _get_steps_grbl()
  761. # Process results and determine table type
  762. settings_complete = (x_steps_per_mm is not None and y_steps_per_mm is not None)
  763. if settings_complete:
  764. if y_steps_per_mm == 180 and x_steps_per_mm == 256:
  765. state.table_type = 'dune_weaver_mini'
  766. elif y_steps_per_mm == 210 and x_steps_per_mm == 256:
  767. state.table_type = 'dune_weaver_mini_pro_byj'
  768. elif y_steps_per_mm == 270 and x_steps_per_mm == 200:
  769. state.table_type = 'dune_weaver_gold'
  770. elif y_steps_per_mm == 287:
  771. state.table_type = 'dune_weaver'
  772. elif y_steps_per_mm == 164:
  773. state.table_type = 'dune_weaver_mini_pro'
  774. elif y_steps_per_mm >= 320:
  775. state.table_type = 'dune_weaver_pro'
  776. else:
  777. state.table_type = None
  778. logger.warning(f"Unknown table type with Y steps/mm: {y_steps_per_mm}")
  779. # Use override if set, otherwise use detected table type
  780. effective_table_type = state.table_type_override or state.table_type
  781. # Set gear ratio based on effective table type (hardcoded)
  782. if effective_table_type in ['dune_weaver_mini', 'dune_weaver_mini_pro', 'dune_weaver_mini_pro_byj', 'dune_weaver_gold']:
  783. state.gear_ratio = 6.25
  784. else:
  785. state.gear_ratio = 10
  786. # Check for environment variable override
  787. gear_ratio_override = os.getenv('GEAR_RATIO')
  788. if gear_ratio_override is not None:
  789. try:
  790. state.gear_ratio = float(gear_ratio_override)
  791. logger.info(f"Machine type detected: {state.table_type}, effective: {effective_table_type}, gear ratio: {state.gear_ratio} (from GEAR_RATIO env var)")
  792. except ValueError:
  793. logger.error(f"Invalid GEAR_RATIO env var value: {gear_ratio_override}, using default: {state.gear_ratio}")
  794. logger.info(f"Machine type detected: {state.table_type}, effective: {effective_table_type}, gear ratio: {state.gear_ratio} (hardcoded)")
  795. elif state.table_type_override:
  796. logger.info(f"Machine type detected: {state.table_type}, overridden to: {effective_table_type}, gear ratio: {state.gear_ratio}")
  797. else:
  798. logger.info(f"Machine type detected: {state.table_type}, gear ratio: {state.gear_ratio} (hardcoded)")
  799. return True
  800. else:
  801. missing = []
  802. if x_steps_per_mm is None: missing.append("X steps/mm")
  803. if y_steps_per_mm is None: missing.append("Y steps/mm")
  804. logger.error(f"Failed to get all machine parameters after {timeout}s. Missing: {', '.join(missing)}")
  805. return False
  806. def home(timeout=120):
  807. """
  808. Perform homing sequence based on configured mode:
  809. Mode 0 (Crash):
  810. - Y axis moves -22mm (or -30mm for mini) until physical stop
  811. - Set theta=0, rho=0 (no x0 y0 command)
  812. Mode 1 (Sensor):
  813. - Send $H command to home both X and Y axes
  814. - Wait for [MSG:Homed:X] and [MSG:Homed:Y] messages
  815. - Send x0 y0 to zero positions
  816. - Set theta to compass offset, rho=0
  817. Args:
  818. timeout: Maximum time in seconds to wait for homing to complete (default: 120)
  819. Increased from 90s to allow buffer after soft reset recovery
  820. """
  821. import threading
  822. import math
  823. # Check for alarm state before homing and unlock if needed
  824. if not check_and_unlock_alarm():
  825. logger.error("Failed to unlock device from alarm state, cannot proceed with homing")
  826. return False
  827. # Flag to track if homing completed
  828. homing_complete = threading.Event()
  829. homing_success = False
  830. def home_internal():
  831. nonlocal homing_success
  832. effective_table_type = state.table_type_override or state.table_type
  833. homing_speed = 400
  834. if effective_table_type == 'dune_weaver_mini':
  835. homing_speed = 100
  836. try:
  837. if state.homing == 1:
  838. # Mode 1: Sensor-based homing using $H
  839. logger.info("Using sensor-based homing mode ($H)")
  840. # Clear any pending responses
  841. state.homed_x = False
  842. state.homed_y = False
  843. # Clear any stale data from previous operations
  844. try:
  845. while state.conn.in_waiting() > 0:
  846. stale = state.conn.readline()
  847. logger.debug(f"Cleared stale data before homing: {stale}")
  848. except Exception:
  849. pass
  850. # Send $H command
  851. state.conn.send("$H\n")
  852. logger.info("Sent $H command, waiting for homing messages...")
  853. # Wait for [MSG:Homed:X] and [MSG:Homed:Y] messages
  854. max_wait_time = 60 # 60 seconds - boot recovery needs more time
  855. start_time = time.time()
  856. while (time.time() - start_time) < max_wait_time:
  857. try:
  858. response = state.conn.readline()
  859. if response:
  860. logger.debug(f"Homing response: {response}")
  861. # Check for homing messages
  862. if "[MSG:Homed:X]" in response:
  863. state.homed_x = True
  864. logger.info("Received [MSG:Homed:X]")
  865. if "[MSG:Homed:Y]" in response:
  866. state.homed_y = True
  867. logger.info("Received [MSG:Homed:Y]")
  868. # Break if we've received both messages
  869. if state.homed_x and state.homed_y:
  870. logger.info("Received both homing confirmation messages")
  871. break
  872. except Exception as e:
  873. logger.error(f"Error reading homing response: {e}")
  874. time.sleep(0.1)
  875. if not (state.homed_x and state.homed_y):
  876. logger.warning(f"Did not receive all homing messages (X:{state.homed_x}, Y:{state.homed_y}), unlocking and continuing...")
  877. # Unlock machine to clear any alarm state
  878. state.conn.send("$X\n")
  879. time.sleep(0.5)
  880. # Wait for idle state after $H
  881. logger.info("Waiting for device to reach idle state after $H...")
  882. idle_reached = check_idle()
  883. if not idle_reached:
  884. logger.error("Device did not reach idle state after $H command")
  885. homing_complete.set()
  886. return
  887. # If X homed but Y failed, fallback to crash homing for Y
  888. if state.homed_x and not state.homed_y:
  889. logger.warning("Sensor homing incomplete (Y failed) - falling back to crash homing")
  890. # Perform crash homing as fallback
  891. logger.info(f"Executing crash homing fallback at {homing_speed} mm/min")
  892. loop = asyncio.new_event_loop()
  893. asyncio.set_event_loop(loop)
  894. try:
  895. if effective_table_type == 'dune_weaver_mini':
  896. result = loop.run_until_complete(send_grbl_coordinates(0, -30, homing_speed, home=True))
  897. if result == False:
  898. logger.error("Crash homing fallback failed")
  899. homing_complete.set()
  900. return
  901. else:
  902. result = loop.run_until_complete(send_grbl_coordinates(0, -22, homing_speed, home=True))
  903. if result == False:
  904. logger.error("Crash homing fallback failed")
  905. homing_complete.set()
  906. return
  907. finally:
  908. loop.close()
  909. # Wait for idle after crash homing
  910. logger.info("Waiting for device to reach idle state after crash homing fallback...")
  911. idle_reached = check_idle()
  912. if not idle_reached:
  913. logger.error("Device did not reach idle state after crash homing fallback")
  914. homing_complete.set()
  915. return
  916. # Set position like crash homing does
  917. state.current_theta = 0
  918. state.current_rho = 0
  919. logger.info("Crash homing fallback completed - theta=0, rho=0")
  920. elif not state.homed_x and not state.homed_y:
  921. # Neither axis homed - this is a failure, don't proceed
  922. # Set sensor_homing_failed flag to notify UI for user action
  923. logger.error("Sensor homing failed - neither axis homed. User action required.")
  924. state.sensor_homing_failed = True
  925. homing_complete.set()
  926. return
  927. else:
  928. # Send x0 y0 to zero both positions using send_grbl_coordinates
  929. logger.info(f"Zeroing positions with x0 y0 f{homing_speed}")
  930. # Run async function in new event loop
  931. loop = asyncio.new_event_loop()
  932. asyncio.set_event_loop(loop)
  933. try:
  934. # Send G1 X0 Y0 F{homing_speed}
  935. result = loop.run_until_complete(send_grbl_coordinates(0, 0, homing_speed))
  936. if result == False:
  937. logger.error("Position zeroing failed - send_grbl_coordinates returned False")
  938. homing_complete.set()
  939. return
  940. logger.info("Position zeroing completed successfully")
  941. finally:
  942. loop.close()
  943. # Wait for device to reach idle state after zeroing movement
  944. logger.info("Waiting for device to reach idle state after zeroing...")
  945. idle_reached = check_idle()
  946. if not idle_reached:
  947. logger.error("Device did not reach idle state after zeroing")
  948. homing_complete.set()
  949. return
  950. # Set current position based on compass reference point (sensor mode only)
  951. offset_radians = math.radians(state.angular_homing_offset_degrees)
  952. state.current_theta = offset_radians
  953. state.current_rho = 0
  954. logger.info(f"Sensor homing completed - theta set to {state.angular_homing_offset_degrees}° ({offset_radians:.3f} rad), rho=0")
  955. else:
  956. logger.info(f"Using crash homing mode at {homing_speed} mm/min")
  957. # Run async function in new event loop
  958. loop = asyncio.new_event_loop()
  959. asyncio.set_event_loop(loop)
  960. try:
  961. if effective_table_type == 'dune_weaver_mini':
  962. result = loop.run_until_complete(send_grbl_coordinates(0, -30, homing_speed, home=True))
  963. if result == False:
  964. logger.error("Crash homing failed - send_grbl_coordinates returned False")
  965. homing_complete.set()
  966. return
  967. state.machine_y -= 30
  968. else:
  969. result = loop.run_until_complete(send_grbl_coordinates(0, -22, homing_speed, home=True))
  970. if result == False:
  971. logger.error("Crash homing failed - send_grbl_coordinates returned False")
  972. homing_complete.set()
  973. return
  974. state.machine_y -= 22
  975. finally:
  976. loop.close()
  977. # Wait for device to reach idle state after crash homing
  978. logger.info("Waiting for device to reach idle state after crash homing...")
  979. idle_reached = check_idle()
  980. if not idle_reached:
  981. logger.error("Device did not reach idle state after crash homing")
  982. homing_complete.set()
  983. return
  984. # Crash homing just sets theta and rho to 0 (no x0 y0 command)
  985. state.current_theta = 0
  986. state.current_rho = 0
  987. logger.info("Crash homing completed - theta=0, rho=0")
  988. # Update machine position from hardware after homing
  989. logger.info("Updating machine position after homing...")
  990. try:
  991. pos = get_machine_position()
  992. if pos and pos[0] is not None and pos[1] is not None:
  993. state.machine_x, state.machine_y = pos
  994. state.save()
  995. logger.info(f"Machine position updated after homing: X={state.machine_x}, Y={state.machine_y}")
  996. else:
  997. logger.warning("Could not get machine position after homing")
  998. except Exception as e:
  999. logger.error(f"Error updating machine position after homing: {e}")
  1000. homing_success = True
  1001. # Clear sensor_homing_failed flag on successful homing
  1002. state.sensor_homing_failed = False
  1003. homing_complete.set()
  1004. except Exception as e:
  1005. logger.error(f"Error during homing: {e}")
  1006. homing_complete.set()
  1007. # Start homing in a separate thread
  1008. homing_thread = threading.Thread(target=home_internal)
  1009. homing_thread.daemon = True
  1010. homing_thread.start()
  1011. # Wait for homing to complete or timeout
  1012. if not homing_complete.wait(timeout):
  1013. logger.error(f"Homing timeout after {timeout} seconds")
  1014. # Try to stop any ongoing movement
  1015. try:
  1016. if state.conn and state.conn.is_connected():
  1017. state.conn.send("!\n") # Send feed hold
  1018. time.sleep(0.1)
  1019. state.conn.send("\x18\n") # Send reset
  1020. except Exception as e:
  1021. logger.error(f"Error stopping movement after timeout: {e}")
  1022. return False
  1023. if not homing_success:
  1024. logger.error("Homing failed")
  1025. return False
  1026. logger.info("Homing completed successfully")
  1027. return True
  1028. def check_idle():
  1029. """
  1030. Continuously check if the device is idle (synchronous version).
  1031. """
  1032. logger.info("Checking idle")
  1033. while True:
  1034. response = get_status_response()
  1035. if response and "Idle" in response:
  1036. logger.info("Device is idle")
  1037. # Schedule async update_machine_position in the existing event loop
  1038. try:
  1039. # Try to schedule in existing event loop if available
  1040. try:
  1041. loop = asyncio.get_running_loop()
  1042. # Create a task but don't await it (fire and forget)
  1043. asyncio.create_task(update_machine_position())
  1044. logger.debug("Scheduled machine position update task")
  1045. except RuntimeError:
  1046. # No event loop running, skip machine position update
  1047. logger.debug("No event loop running, skipping machine position update")
  1048. except Exception as e:
  1049. logger.error(f"Error scheduling machine position update: {e}")
  1050. return True
  1051. time.sleep(1)
  1052. async def check_idle_async(timeout: float = 30.0):
  1053. """
  1054. Continuously check if the device is idle (async version).
  1055. Args:
  1056. timeout: Maximum seconds to wait for idle state (default 30s)
  1057. Returns:
  1058. True if device became idle, False if timeout or stop requested
  1059. """
  1060. logger.info("Checking idle (async)")
  1061. start_time = asyncio.get_event_loop().time()
  1062. while True:
  1063. # Check if stop was requested - exit early
  1064. if state.stop_requested:
  1065. logger.info("Stop requested during idle check, exiting early")
  1066. return False
  1067. # Check timeout
  1068. elapsed = asyncio.get_event_loop().time() - start_time
  1069. if elapsed > timeout:
  1070. logger.warning(f"Timeout ({timeout}s) waiting for device idle state")
  1071. return False
  1072. response = await asyncio.to_thread(get_status_response)
  1073. if response and "Idle" in response:
  1074. logger.info("Device is idle")
  1075. try:
  1076. await update_machine_position()
  1077. except Exception as e:
  1078. logger.error(f"Error updating machine position: {e}")
  1079. return True
  1080. await asyncio.sleep(1)
  1081. def is_machine_idle() -> bool:
  1082. """
  1083. Single check to see if the machine is currently idle.
  1084. Does not loop - returns immediately with current status.
  1085. Returns:
  1086. True if machine is idle, False otherwise
  1087. """
  1088. if not state.conn or not state.conn.is_connected():
  1089. logger.debug("No connection - machine not idle")
  1090. return False
  1091. try:
  1092. state.conn.send('?')
  1093. response = state.conn.readline()
  1094. if response and "Idle" in response:
  1095. logger.debug("Machine status: Idle")
  1096. return True
  1097. else:
  1098. logger.debug(f"Machine status: {response}")
  1099. return False
  1100. except Exception as e:
  1101. logger.error(f"Error checking machine idle status: {e}")
  1102. return False
  1103. def get_machine_position(timeout=5):
  1104. """
  1105. Query the device for its position.
  1106. Supports both MPos and WPos formats (depends on GRBL $10 setting).
  1107. """
  1108. start_time = time.time()
  1109. while time.time() - start_time < timeout:
  1110. try:
  1111. state.conn.send('?')
  1112. response = state.conn.readline()
  1113. logger.debug(f"Raw status response: {response}")
  1114. # Accept either MPos or WPos format
  1115. if "MPos" in response or "WPos" in response:
  1116. pos = parse_machine_position(response)
  1117. if pos:
  1118. machine_x, machine_y = pos
  1119. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  1120. return machine_x, machine_y
  1121. except Exception as e:
  1122. logger.error(f"Error getting machine position: {e}")
  1123. return
  1124. time.sleep(0.1)
  1125. logger.warning("Timeout reached waiting for machine position")
  1126. return None, None
  1127. async def update_machine_position():
  1128. if (state.conn.is_connected() if state.conn else False):
  1129. try:
  1130. logger.info('Saving machine position')
  1131. state.machine_x, state.machine_y = await asyncio.to_thread(get_machine_position)
  1132. await asyncio.to_thread(state.save)
  1133. logger.info(f'Machine position saved: {state.machine_x}, {state.machine_y}')
  1134. except Exception as e:
  1135. logger.error(f"Error updating machine position: {e}")
  1136. def perform_soft_reset_sync(max_retries: int = 5):
  1137. """
  1138. Synchronous version of soft reset for use during device initialization.
  1139. Supports both FluidNC ($Bye) and GRBL (Ctrl+X / 0x18) firmware.
  1140. Triggers a software reset which clears position counters to 0.
  1141. This is more reliable than G92 which only sets a work coordinate offset
  1142. without changing the actual machine position (MPos).
  1143. IMPORTANT: Position is only reset to (0,0) if confirmation is received.
  1144. This prevents position drift from accumulating over long operation periods.
  1145. Uses exponential backoff for retries:
  1146. - Attempt 1: 5s timeout
  1147. - Attempt 2: 7.5s timeout, 1s delay before retry
  1148. - Attempt 3: 11s timeout, 2s delay before retry
  1149. - Attempt 4: 17s timeout, 4s delay before retry
  1150. - Attempt 5: 25s timeout, 8s delay before retry
  1151. Args:
  1152. max_retries: Maximum number of reset attempts (default 5)
  1153. Returns:
  1154. True if reset confirmed, False if all attempts failed
  1155. """
  1156. if not state.conn or not state.conn.is_connected():
  1157. logger.warning("Cannot perform soft reset: no active connection")
  1158. return False
  1159. try:
  1160. # Detect firmware type to use appropriate reset command
  1161. firmware_type, version = _detect_firmware()
  1162. logger.info(f"Detected firmware: {firmware_type} {version or ''}")
  1163. logger.info(f"Performing soft reset (was: X={state.machine_x:.2f}, Y={state.machine_y:.2f})")
  1164. for attempt in range(max_retries):
  1165. # Exponential backoff: 5s * 1.5^attempt → 5s, 7.5s, 11s, 17s, 25s
  1166. timeout = 5.0 * (1.5 ** attempt)
  1167. logger.info(f"Reset attempt {attempt + 1}/{max_retries} (timeout: {timeout:.1f}s)")
  1168. # Clear any pending data first
  1169. if isinstance(state.conn, SerialConnection) and state.conn.ser:
  1170. state.conn.ser.reset_input_buffer()
  1171. # Send appropriate reset command based on firmware
  1172. if firmware_type == 'fluidnc':
  1173. # FluidNC uses $Bye for soft reset
  1174. if isinstance(state.conn, SerialConnection) and state.conn.ser:
  1175. state.conn.ser.write(b'$Bye\n')
  1176. state.conn.ser.flush()
  1177. logger.info(f"$Bye sent directly via serial to {state.port}")
  1178. else:
  1179. state.conn.send('$Bye\n')
  1180. logger.info("$Bye sent via connection abstraction")
  1181. else:
  1182. # GRBL uses Ctrl+X (0x18) for soft reset
  1183. if isinstance(state.conn, SerialConnection) and state.conn.ser:
  1184. state.conn.ser.write(b'\x18')
  1185. state.conn.ser.flush()
  1186. logger.info(f"Ctrl+X (0x18) sent directly via serial to {state.port}")
  1187. else:
  1188. state.conn.send('\x18')
  1189. logger.info("Ctrl+X (0x18) sent via connection abstraction")
  1190. # Wait for controller to fully restart
  1191. # FluidNC sequence: [MSG:INFO: Restarting] -> ... -> "Grbl 3.9 [FluidNC...]"
  1192. # GRBL sequence: "Grbl 1.1h ['$' for help]"
  1193. start_time = time.time()
  1194. reset_confirmed = False
  1195. while time.time() - start_time < timeout:
  1196. try:
  1197. response = state.conn.readline()
  1198. if response:
  1199. logger.debug(f"Reset response: {response}")
  1200. # Wait for the "Grbl" startup banner - this means fully ready
  1201. if response.startswith("Grbl") or "fluidnc" in response.lower():
  1202. reset_confirmed = True
  1203. logger.info(f"Controller restart complete: {response}")
  1204. break
  1205. except Exception:
  1206. pass
  1207. time.sleep(0.05)
  1208. if reset_confirmed:
  1209. # Small delay to let controller fully stabilize
  1210. time.sleep(0.2)
  1211. # Unlock controller in case it's in alarm state after reset
  1212. logger.info("Sending $X to unlock controller after reset")
  1213. state.conn.send("$X\n")
  1214. # Wait for ok response
  1215. unlock_start = time.time()
  1216. while time.time() - unlock_start < 1.0:
  1217. try:
  1218. response = state.conn.readline()
  1219. if response:
  1220. logger.debug(f"$X response: {response}")
  1221. if response.lower() == "ok":
  1222. logger.info("Controller unlocked")
  1223. break
  1224. except Exception:
  1225. pass
  1226. time.sleep(0.05)
  1227. # Only reset state positions when confirmation received
  1228. state.machine_x = 0.0
  1229. state.machine_y = 0.0
  1230. reset_cmd = '$Bye' if firmware_type == 'fluidnc' else 'Ctrl+X'
  1231. logger.info(f"Machine position reset to 0 via {reset_cmd} soft reset")
  1232. # Save the reset position
  1233. state.save()
  1234. logger.info(f"Machine position saved: {state.machine_x}, {state.machine_y}")
  1235. return True
  1236. # Retry after failed attempt with exponential backoff delay
  1237. if attempt < max_retries - 1:
  1238. backoff_delay = 1.0 * (2 ** attempt) # 1s, 2s, 4s, 8s
  1239. logger.warning(f"Reset attempt {attempt + 1}/{max_retries} failed, retrying in {backoff_delay:.0f}s...")
  1240. time.sleep(backoff_delay)
  1241. # All attempts failed - DO NOT reset position to prevent drift
  1242. logger.error(
  1243. f"All {max_retries} reset attempts failed - no confirmation received. "
  1244. f"Position NOT reset (still: X={state.machine_x:.2f}, Y={state.machine_y:.2f}). "
  1245. "This may indicate communication issues or controller not responding."
  1246. )
  1247. return False
  1248. except Exception as e:
  1249. logger.error(f"Error performing soft reset: {e}")
  1250. return False
  1251. async def perform_soft_reset():
  1252. """
  1253. Async version of soft reset for use in async contexts (API endpoints, pattern manager).
  1254. Wraps the sync version in a thread to avoid blocking the event loop.
  1255. """
  1256. return await asyncio.to_thread(perform_soft_reset_sync)
  1257. def reset_work_coordinates():
  1258. """
  1259. Clear all work coordinate offsets for a clean start.
  1260. This ensures the work coordinate system starts fresh on each connection,
  1261. preventing accumulated offsets from previous sessions from affecting
  1262. pattern execution.
  1263. G92.1: Clears any G92 offset (resets work coordinates to machine coordinates)
  1264. G10 L2 P1 X0 Y0: Sets G54 work offset to 0 (for completeness)
  1265. """
  1266. if not state.conn or not state.conn.is_connected():
  1267. logger.warning("Cannot reset work coordinates: no active connection")
  1268. return False
  1269. try:
  1270. logger.info("Resetting work coordinate offsets")
  1271. # Clear any stale input data first
  1272. try:
  1273. while state.conn.in_waiting() > 0:
  1274. state.conn.readline()
  1275. except Exception:
  1276. pass
  1277. # Clear G92 offset
  1278. state.conn.send("G92.1\n")
  1279. time.sleep(0.2)
  1280. # Wait for 'ok' response
  1281. start_time = time.time()
  1282. got_ok = False
  1283. while time.time() - start_time < 2.0:
  1284. if state.conn.in_waiting() > 0:
  1285. response = state.conn.readline()
  1286. if response:
  1287. logger.debug(f"G92.1 response: {response}")
  1288. if response.lower() == "ok":
  1289. got_ok = True
  1290. break
  1291. elif "error" in response.lower():
  1292. logger.warning(f"G92.1 error: {response}")
  1293. break
  1294. time.sleep(0.05)
  1295. if not got_ok:
  1296. logger.warning("Did not receive 'ok' for G92.1, continuing anyway")
  1297. # Set G54 offset to 0 (optional, for completeness)
  1298. state.conn.send("G10 L2 P1 X0 Y0\n")
  1299. time.sleep(0.2)
  1300. # Wait for 'ok' response
  1301. start_time = time.time()
  1302. got_ok = False
  1303. while time.time() - start_time < 2.0:
  1304. if state.conn.in_waiting() > 0:
  1305. response = state.conn.readline()
  1306. if response:
  1307. logger.debug(f"G10 response: {response}")
  1308. if response.lower() == "ok":
  1309. got_ok = True
  1310. break
  1311. elif "error" in response.lower():
  1312. logger.warning(f"G10 error: {response}")
  1313. break
  1314. time.sleep(0.05)
  1315. if not got_ok:
  1316. logger.warning("Did not receive 'ok' for G10 L2 P1 X0 Y0, continuing anyway")
  1317. # Reset machine_x to 0 since work coordinates now start at 0
  1318. state.machine_x = 0.0
  1319. logger.info("Work coordinates reset complete")
  1320. return True
  1321. except Exception as e:
  1322. logger.error(f"Error resetting work coordinates: {e}")
  1323. return False
  1324. def restart_connection(homing=False):
  1325. """
  1326. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  1327. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  1328. The new connection is saved to state.conn.
  1329. Returns:
  1330. True if the connection was restarted successfully, False otherwise.
  1331. """
  1332. try:
  1333. if (state.conn.is_connected() if state.conn else False):
  1334. logger.info("Closing current connection...")
  1335. state.conn.close()
  1336. except Exception as e:
  1337. logger.error(f"Error while closing connection: {e}")
  1338. # Clear the connection reference.
  1339. state.conn = None
  1340. logger.info("Attempting to restart connection...")
  1341. try:
  1342. connect_device(homing) # This will set state.conn appropriately.
  1343. if (state.conn.is_connected() if state.conn else False):
  1344. logger.info("Connection restarted successfully.")
  1345. return True
  1346. else:
  1347. logger.error("Failed to restart connection.")
  1348. return False
  1349. except Exception as e:
  1350. logger.error(f"Error restarting connection: {e}")
  1351. return False