1
0

connection_manager.py 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583
  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.state import state
  10. from modules.led.led_interface import LEDInterface
  11. from modules.led.idle_timeout_manager import idle_timeout_manager
  12. logger = logging.getLogger(__name__)
  13. IGNORE_PORTS = ['/dev/cu.debug-console', '/dev/cu.Bluetooth-Incoming-Port', '/dev/ttyS0']
  14. # Ports to deprioritize during auto-connect (shown in UI but not auto-selected)
  15. DEPRIORITIZED_PORTS = ['/dev/ttyS0']
  16. async def _check_table_is_idle() -> bool:
  17. """Helper function to check if table is idle."""
  18. return not state.current_playing_file or state.pause_requested
  19. def _start_idle_led_timeout():
  20. """Start idle LED timeout if enabled."""
  21. if not state.dw_led_idle_timeout_enabled or state.dw_led_idle_timeout_minutes <= 0:
  22. return
  23. logger.debug(f"Starting idle LED timeout: {state.dw_led_idle_timeout_minutes} minutes")
  24. idle_timeout_manager.start_idle_timeout(
  25. timeout_minutes=state.dw_led_idle_timeout_minutes,
  26. state=state,
  27. check_idle_callback=_check_table_is_idle
  28. )
  29. ###############################################################################
  30. # Connection Abstraction
  31. ###############################################################################
  32. class BaseConnection:
  33. """Abstract base class for a connection."""
  34. def send(self, data: str) -> None:
  35. raise NotImplementedError
  36. def flush(self) -> None:
  37. raise NotImplementedError
  38. def readline(self) -> str:
  39. raise NotImplementedError
  40. def in_waiting(self) -> int:
  41. raise NotImplementedError
  42. def is_connected(self) -> bool:
  43. raise NotImplementedError
  44. def close(self) -> None:
  45. raise NotImplementedError
  46. ###############################################################################
  47. # Serial Connection Implementation
  48. ###############################################################################
  49. class SerialConnection(BaseConnection):
  50. def __init__(self, port: str, baudrate: int = 115200, timeout: int = 2):
  51. self.port = port
  52. self.baudrate = baudrate
  53. self.timeout = timeout
  54. self.lock = threading.RLock()
  55. logger.info(f'Connecting to Serial port {port}')
  56. self.ser = serial.Serial(port, baudrate, timeout=timeout)
  57. state.port = port
  58. logger.info(f'Connected to Serial port {port}')
  59. def send(self, data: str) -> None:
  60. with self.lock:
  61. self.ser.write(data.encode())
  62. self.ser.flush()
  63. def flush(self) -> None:
  64. with self.lock:
  65. self.ser.flush()
  66. def readline(self) -> str:
  67. with self.lock:
  68. return self.ser.readline().decode().strip()
  69. def in_waiting(self) -> int:
  70. with self.lock:
  71. return self.ser.in_waiting
  72. def reset_input_buffer(self) -> None:
  73. """Clear any stale data from the serial input buffer."""
  74. with self.lock:
  75. if self.ser and self.ser.is_open:
  76. self.ser.reset_input_buffer()
  77. def is_connected(self) -> bool:
  78. return self.ser is not None and self.ser.is_open
  79. def close(self) -> None:
  80. # Save current state synchronously first (critical for position persistence)
  81. try:
  82. state.save()
  83. except Exception as e:
  84. logger.error(f"Error saving state on close: {e}")
  85. # Schedule async position update if event loop exists, otherwise skip
  86. # This avoids creating nested event loops which causes RuntimeError
  87. try:
  88. asyncio.get_running_loop()
  89. # We're in async context - schedule as task (fire-and-forget)
  90. asyncio.create_task(update_machine_position())
  91. logger.debug("Scheduled async machine position update")
  92. except RuntimeError:
  93. # No running event loop - we're in sync context
  94. # Position was already saved above, skip async update to avoid nested loop
  95. logger.debug("No event loop running, skipping async position update")
  96. with self.lock:
  97. if self.ser.is_open:
  98. self.ser.close()
  99. ###############################################################################
  100. # WebSocket Connection Implementation
  101. ###############################################################################
  102. class WebSocketConnection(BaseConnection):
  103. def __init__(self, url: str, timeout: int = 5):
  104. self.url = url
  105. self.timeout = timeout
  106. self.lock = threading.RLock()
  107. self.ws = None
  108. self.connect()
  109. def connect(self):
  110. logger.info(f'Connecting to Websocket {self.url}')
  111. self.ws = websocket.create_connection(self.url, timeout=self.timeout)
  112. state.port = self.url
  113. logger.info(f'Connected to Websocket {self.url}')
  114. def send(self, data: str) -> None:
  115. with self.lock:
  116. self.ws.send(data)
  117. def flush(self) -> None:
  118. # WebSocket sends immediately; nothing to flush.
  119. pass
  120. def readline(self) -> str:
  121. with self.lock:
  122. data = self.ws.recv()
  123. # Decode bytes to string if necessary
  124. if isinstance(data, bytes):
  125. data = data.decode('utf-8')
  126. return data.strip()
  127. def in_waiting(self) -> int:
  128. return 0 # Not applicable for WebSocket
  129. def is_connected(self) -> bool:
  130. return self.ws is not None
  131. def close(self) -> None:
  132. # Save current state synchronously first (critical for position persistence)
  133. try:
  134. state.save()
  135. except Exception as e:
  136. logger.error(f"Error saving state on close: {e}")
  137. # Schedule async position update if event loop exists, otherwise skip
  138. # This avoids creating nested event loops which causes RuntimeError
  139. try:
  140. asyncio.get_running_loop()
  141. # We're in async context - schedule as task (fire-and-forget)
  142. asyncio.create_task(update_machine_position())
  143. logger.debug("Scheduled async machine position update")
  144. except RuntimeError:
  145. # No running event loop - we're in sync context
  146. # Position was already saved above, skip async update to avoid nested loop
  147. logger.debug("No event loop running, skipping async position update")
  148. with self.lock:
  149. if self.ws:
  150. self.ws.close()
  151. self.ws = 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. # 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 Exception:
  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("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. logger.info(f"Firmware homing setting (cycle): {homing_cycle}, using user preference: {state.homing}")
  609. except (ValueError, IndexError):
  610. pass
  611. break
  612. elif response.lower().strip() == 'ok':
  613. break
  614. else:
  615. time.sleep(0.05)
  616. except Exception as e:
  617. logger.debug(f"Could not query FluidNC homing setting: {e}")
  618. # Clear buffer
  619. try:
  620. while state.conn.in_waiting() > 0:
  621. state.conn.readline()
  622. except Exception:
  623. pass
  624. return (x_steps, y_steps)
  625. def _get_steps_grbl():
  626. """
  627. Get steps/mm from GRBL using $$ command.
  628. Returns tuple: (x_steps_per_mm, y_steps_per_mm) or (None, None) on failure.
  629. Note: Works even when device is in ALARM state (e.g., limit switch active).
  630. $$ command typically responds with settings even during alarm.
  631. """
  632. x_steps_per_mm = None
  633. y_steps_per_mm = None
  634. max_retries = 3
  635. attempt_timeout = 4
  636. for attempt in range(max_retries):
  637. logger.info(f"Requesting GRBL settings with $$ command (attempt {attempt + 1}/{max_retries})")
  638. try:
  639. state.conn.send("$$\n")
  640. except Exception as e:
  641. logger.error(f"Error sending $$ command: {e}")
  642. continue
  643. attempt_start = time.time()
  644. got_ok = False
  645. while time.time() - attempt_start < attempt_timeout:
  646. try:
  647. response = state.conn.readline()
  648. if not response:
  649. continue
  650. logger.debug(f"Raw response: {response}")
  651. for line in response.splitlines():
  652. line = line.strip()
  653. if not line:
  654. continue
  655. logger.debug(f"Config response: {line}")
  656. if line.startswith("$100="):
  657. x_steps_per_mm = float(line.split("=")[1])
  658. state.x_steps_per_mm = x_steps_per_mm
  659. logger.info(f"X steps per mm: {x_steps_per_mm}")
  660. elif line.startswith("$101="):
  661. y_steps_per_mm = float(line.split("=")[1])
  662. state.y_steps_per_mm = y_steps_per_mm
  663. logger.info(f"Y steps per mm: {y_steps_per_mm}")
  664. elif line.startswith("$22="):
  665. firmware_homing = int(line.split('=')[1])
  666. logger.info(f"Firmware homing setting ($22): {firmware_homing}, using user preference: {state.homing}")
  667. elif line.lower() == 'ok':
  668. got_ok = True
  669. logger.debug("Received 'ok' confirmation from GRBL")
  670. elif line.lower().startswith('error') or 'alarm' in line.lower():
  671. # Device may be in alarm state (e.g., limit switch active)
  672. # Log and continue - $$ typically works anyway
  673. logger.debug(f"Got error/alarm during settings query (proceeding): {line}")
  674. if got_ok:
  675. if x_steps_per_mm is not None and y_steps_per_mm is not None:
  676. logger.info("Successfully received all GRBL settings")
  677. break
  678. else:
  679. logger.warning("Received 'ok' but missing some settings")
  680. break
  681. except Exception as e:
  682. logger.error(f"Error reading GRBL response: {e}")
  683. break
  684. if x_steps_per_mm is not None and y_steps_per_mm is not None:
  685. break
  686. if attempt < max_retries - 1:
  687. logger.warning(f"Attempt {attempt + 1} did not get all settings, retrying...")
  688. time.sleep(0.5)
  689. try:
  690. while state.conn.in_waiting() > 0:
  691. state.conn.readline()
  692. except Exception:
  693. pass
  694. return (x_steps_per_mm, y_steps_per_mm)
  695. def get_machine_steps(timeout=10):
  696. """
  697. Get machine steps/mm from the controller (FluidNC or GRBL).
  698. Returns True if successful, False otherwise.
  699. Detects firmware type first:
  700. - FluidNC: Uses targeted $/axes/x/steps_per_mm queries (more reliable)
  701. - GRBL: Falls back to $$ command with retries
  702. """
  703. if not state.conn or not state.conn.is_connected():
  704. logger.error("Cannot get machine steps: No connection available")
  705. return False
  706. # Clear any pending data in the buffer
  707. try:
  708. while state.conn.in_waiting() > 0:
  709. state.conn.readline()
  710. except Exception as e:
  711. logger.warning(f"Error clearing buffer: {e}")
  712. # Verify controller is responsive before querying
  713. try:
  714. state.conn.send("?\n")
  715. time.sleep(0.2)
  716. ready_check_attempts = 5
  717. controller_ready = False
  718. for _ in range(ready_check_attempts):
  719. if state.conn.in_waiting() > 0:
  720. response = state.conn.readline()
  721. if response and ('<' in response or 'Idle' in response or 'Alarm' in response):
  722. controller_ready = True
  723. if 'Alarm' in response:
  724. logger.info(f"Controller in ALARM state (likely limit switch active), proceeding with settings query: {response.strip()}")
  725. else:
  726. logger.debug(f"Controller ready, status: {response}")
  727. break
  728. time.sleep(0.1)
  729. if not controller_ready:
  730. logger.warning("Controller not responding to status query, proceeding anyway...")
  731. # Clear buffer after readiness check
  732. while state.conn.in_waiting() > 0:
  733. state.conn.readline()
  734. time.sleep(0.1)
  735. except Exception as e:
  736. logger.warning(f"Readiness check failed: {e}, proceeding anyway...")
  737. # Detect firmware type
  738. firmware_type, firmware_version = _detect_firmware()
  739. if firmware_type == 'fluidnc':
  740. if firmware_version:
  741. logger.info(f"Detected FluidNC firmware, version: {firmware_version}")
  742. else:
  743. logger.info("Detected FluidNC firmware (version unknown)")
  744. x_steps_per_mm, y_steps_per_mm = _get_steps_fluidnc()
  745. # Fallback to GRBL method if FluidNC queries failed
  746. if x_steps_per_mm is None or y_steps_per_mm is None:
  747. logger.warning("FluidNC setting queries failed, falling back to $$ command...")
  748. x_steps_per_mm, y_steps_per_mm = _get_steps_grbl()
  749. else:
  750. if firmware_type == 'grbl':
  751. if firmware_version:
  752. logger.info(f"Detected GRBL firmware, version: {firmware_version}")
  753. else:
  754. logger.info("Detected GRBL firmware (version unknown)")
  755. else:
  756. logger.info("Could not detect firmware type, using GRBL commands")
  757. x_steps_per_mm, y_steps_per_mm = _get_steps_grbl()
  758. # Process results and determine table type
  759. settings_complete = (x_steps_per_mm is not None and y_steps_per_mm is not None)
  760. if settings_complete:
  761. if y_steps_per_mm == 180 and x_steps_per_mm == 256:
  762. state.table_type = 'dune_weaver_mini'
  763. elif y_steps_per_mm == 210 and x_steps_per_mm == 256:
  764. state.table_type = 'dune_weaver_mini_pro_byj'
  765. elif (y_steps_per_mm == 270 or y_steps_per_mm == 250) and x_steps_per_mm == 200:
  766. state.table_type = 'dune_weaver_gold'
  767. elif y_steps_per_mm == 287:
  768. state.table_type = 'dune_weaver'
  769. elif y_steps_per_mm == 164:
  770. state.table_type = 'dune_weaver_mini_pro'
  771. elif y_steps_per_mm >= 320:
  772. state.table_type = 'dune_weaver_pro'
  773. else:
  774. state.table_type = None
  775. logger.warning(f"Unknown table type with Y steps/mm: {y_steps_per_mm}")
  776. # Use override if set, otherwise use detected table type
  777. effective_table_type = state.table_type_override or state.table_type
  778. # Set gear ratio based on effective table type (hardcoded)
  779. if effective_table_type in ['dune_weaver_mini', 'dune_weaver_mini_pro', 'dune_weaver_mini_pro_byj', 'dune_weaver_gold']:
  780. state.gear_ratio = 6.25
  781. else:
  782. state.gear_ratio = 10
  783. # Check for environment variable override
  784. gear_ratio_override = os.getenv('GEAR_RATIO')
  785. if gear_ratio_override is not None:
  786. try:
  787. state.gear_ratio = float(gear_ratio_override)
  788. logger.info(f"Machine type detected: {state.table_type}, effective: {effective_table_type}, gear ratio: {state.gear_ratio} (from GEAR_RATIO env var)")
  789. except ValueError:
  790. logger.error(f"Invalid GEAR_RATIO env var value: {gear_ratio_override}, using default: {state.gear_ratio}")
  791. logger.info(f"Machine type detected: {state.table_type}, effective: {effective_table_type}, gear ratio: {state.gear_ratio} (hardcoded)")
  792. elif state.table_type_override:
  793. logger.info(f"Machine type detected: {state.table_type}, overridden to: {effective_table_type}, gear ratio: {state.gear_ratio}")
  794. else:
  795. logger.info(f"Machine type detected: {state.table_type}, gear ratio: {state.gear_ratio} (hardcoded)")
  796. return True
  797. else:
  798. missing = []
  799. if x_steps_per_mm is None:
  800. missing.append("X steps/mm")
  801. if y_steps_per_mm is None:
  802. missing.append("Y steps/mm")
  803. logger.error(f"Failed to get all machine parameters after {timeout}s. Missing: {', '.join(missing)}")
  804. return False
  805. def home(timeout=120):
  806. """
  807. Perform homing sequence based on configured mode:
  808. Mode 0 (Crash):
  809. - Y axis moves -22mm (or -30mm for mini) until physical stop
  810. - Set theta=0, rho=0 (no x0 y0 command)
  811. Mode 1 (Sensor):
  812. - Send $H command to home both X and Y axes
  813. - Wait for [MSG:Homed:X] and [MSG:Homed:Y] messages
  814. - Send x0 y0 to zero positions
  815. - Set theta to compass offset, rho=0
  816. Args:
  817. timeout: Maximum time in seconds to wait for homing to complete (default: 120)
  818. Increased from 90s to allow buffer after soft reset recovery
  819. """
  820. import threading
  821. import math
  822. # Check for alarm state before homing and unlock if needed
  823. if not check_and_unlock_alarm():
  824. logger.error("Failed to unlock device from alarm state, cannot proceed with homing")
  825. return False
  826. # Flag to track if homing completed
  827. homing_complete = threading.Event()
  828. homing_success = False
  829. def home_internal():
  830. nonlocal homing_success
  831. effective_table_type = state.table_type_override or state.table_type
  832. homing_speed = 400
  833. if effective_table_type == 'dune_weaver_mini':
  834. homing_speed = 100
  835. try:
  836. if state.homing == 1:
  837. # Mode 1: Sensor-based homing using $H
  838. logger.info("Using sensor-based homing mode ($H)")
  839. # Clear any pending responses
  840. state.homed_x = False
  841. state.homed_y = False
  842. # Clear any stale data from previous operations
  843. try:
  844. while state.conn.in_waiting() > 0:
  845. stale = state.conn.readline()
  846. logger.debug(f"Cleared stale data before homing: {stale}")
  847. except Exception:
  848. pass
  849. # Send $H command
  850. state.conn.send("$H\n")
  851. logger.info("Sent $H command, waiting for homing messages...")
  852. # Wait for [MSG:Homed:X] and [MSG:Homed:Y] messages
  853. max_wait_time = 60 # 60 seconds - boot recovery needs more time
  854. start_time = time.time()
  855. while (time.time() - start_time) < max_wait_time:
  856. try:
  857. response = state.conn.readline()
  858. if response:
  859. logger.debug(f"Homing response: {response}")
  860. # Check for homing messages
  861. if "[MSG:Homed:X]" in response:
  862. state.homed_x = True
  863. logger.info("Received [MSG:Homed:X]")
  864. if "[MSG:Homed:Y]" in response:
  865. state.homed_y = True
  866. logger.info("Received [MSG:Homed:Y]")
  867. # Break if we've received both messages
  868. if state.homed_x and state.homed_y:
  869. logger.info("Received both homing confirmation messages")
  870. break
  871. except Exception as e:
  872. logger.error(f"Error reading homing response: {e}")
  873. time.sleep(0.1)
  874. if not (state.homed_x and state.homed_y):
  875. logger.warning(f"Did not receive all homing messages (X:{state.homed_x}, Y:{state.homed_y}), unlocking and continuing...")
  876. # Unlock machine to clear any alarm state
  877. state.conn.send("$X\n")
  878. time.sleep(0.5)
  879. # Wait for idle state after $H
  880. logger.info("Waiting for device to reach idle state after $H...")
  881. idle_reached = check_idle()
  882. if not idle_reached:
  883. logger.error("Device did not reach idle state after $H command")
  884. homing_complete.set()
  885. return
  886. # If X homed but Y failed, fallback to crash homing for Y
  887. if state.homed_x and not state.homed_y:
  888. logger.warning("Sensor homing incomplete (Y failed) - falling back to crash homing")
  889. # Perform crash homing as fallback
  890. logger.info(f"Executing crash homing fallback at {homing_speed} mm/min")
  891. loop = asyncio.new_event_loop()
  892. asyncio.set_event_loop(loop)
  893. try:
  894. if effective_table_type == 'dune_weaver_mini':
  895. result = loop.run_until_complete(send_grbl_coordinates(0, -30, homing_speed, home=True))
  896. if not result:
  897. logger.error("Crash homing fallback failed")
  898. homing_complete.set()
  899. return
  900. else:
  901. result = loop.run_until_complete(send_grbl_coordinates(0, -22, homing_speed, home=True))
  902. if not result:
  903. logger.error("Crash homing fallback failed")
  904. homing_complete.set()
  905. return
  906. finally:
  907. loop.close()
  908. # Wait for idle after crash homing
  909. logger.info("Waiting for device to reach idle state after crash homing fallback...")
  910. idle_reached = check_idle()
  911. if not idle_reached:
  912. logger.error("Device did not reach idle state after crash homing fallback")
  913. homing_complete.set()
  914. return
  915. # Set position like crash homing does
  916. state.current_theta = 0
  917. state.current_rho = 0
  918. logger.info("Crash homing fallback completed - theta=0, rho=0")
  919. elif not state.homed_x and not state.homed_y:
  920. # Neither axis homed - this is a failure, don't proceed
  921. # Set sensor_homing_failed flag to notify UI for user action
  922. logger.error("Sensor homing failed - neither axis homed. User action required.")
  923. state.sensor_homing_failed = True
  924. homing_complete.set()
  925. return
  926. else:
  927. # Send x0 y0 to zero both positions using send_grbl_coordinates
  928. logger.info(f"Zeroing positions with x0 y0 f{homing_speed}")
  929. # Run async function in new event loop
  930. loop = asyncio.new_event_loop()
  931. asyncio.set_event_loop(loop)
  932. try:
  933. # Send G1 X0 Y0 F{homing_speed}
  934. result = loop.run_until_complete(send_grbl_coordinates(0, 0, homing_speed))
  935. if not result:
  936. logger.error("Position zeroing failed - send_grbl_coordinates returned False")
  937. homing_complete.set()
  938. return
  939. logger.info("Position zeroing completed successfully")
  940. finally:
  941. loop.close()
  942. # Wait for device to reach idle state after zeroing movement
  943. logger.info("Waiting for device to reach idle state after zeroing...")
  944. idle_reached = check_idle()
  945. if not idle_reached:
  946. logger.error("Device did not reach idle state after zeroing")
  947. homing_complete.set()
  948. return
  949. # Set current position based on compass reference point (sensor mode only)
  950. offset_radians = math.radians(state.angular_homing_offset_degrees)
  951. state.current_theta = offset_radians
  952. state.current_rho = 0
  953. logger.info(f"Sensor homing completed - theta set to {state.angular_homing_offset_degrees}° ({offset_radians:.3f} rad), rho=0")
  954. else:
  955. logger.info(f"Using crash homing mode at {homing_speed} mm/min")
  956. # Run async function in new event loop
  957. loop = asyncio.new_event_loop()
  958. asyncio.set_event_loop(loop)
  959. try:
  960. if effective_table_type == 'dune_weaver_mini':
  961. result = loop.run_until_complete(send_grbl_coordinates(0, -30, homing_speed, home=True))
  962. if not result:
  963. logger.error("Crash homing failed - send_grbl_coordinates returned False")
  964. homing_complete.set()
  965. return
  966. state.machine_y -= 30
  967. else:
  968. result = loop.run_until_complete(send_grbl_coordinates(0, -22, homing_speed, home=True))
  969. if not result:
  970. logger.error("Crash homing failed - send_grbl_coordinates returned False")
  971. homing_complete.set()
  972. return
  973. state.machine_y -= 22
  974. finally:
  975. loop.close()
  976. # Wait for device to reach idle state after crash homing
  977. logger.info("Waiting for device to reach idle state after crash homing...")
  978. idle_reached = check_idle()
  979. if not idle_reached:
  980. logger.error("Device did not reach idle state after crash homing")
  981. homing_complete.set()
  982. return
  983. # Crash homing just sets theta and rho to 0 (no x0 y0 command)
  984. state.current_theta = 0
  985. state.current_rho = 0
  986. logger.info("Crash homing completed - theta=0, rho=0")
  987. # Update machine position from hardware after homing
  988. logger.info("Updating machine position after homing...")
  989. try:
  990. pos = get_machine_position()
  991. if pos and pos[0] is not None and pos[1] is not None:
  992. state.machine_x, state.machine_y = pos
  993. state.save()
  994. logger.info(f"Machine position updated after homing: X={state.machine_x}, Y={state.machine_y}")
  995. else:
  996. logger.warning("Could not get machine position after homing")
  997. except Exception as e:
  998. logger.error(f"Error updating machine position after homing: {e}")
  999. homing_success = True
  1000. # Clear sensor_homing_failed flag on successful homing
  1001. state.sensor_homing_failed = False
  1002. homing_complete.set()
  1003. except Exception as e:
  1004. logger.error(f"Error during homing: {e}")
  1005. homing_complete.set()
  1006. # Start homing in a separate thread
  1007. homing_thread = threading.Thread(target=home_internal)
  1008. homing_thread.daemon = True
  1009. homing_thread.start()
  1010. # Wait for homing to complete or timeout
  1011. if not homing_complete.wait(timeout):
  1012. logger.error(f"Homing timeout after {timeout} seconds")
  1013. # Try to stop any ongoing movement
  1014. try:
  1015. if state.conn and state.conn.is_connected():
  1016. state.conn.send("!\n") # Send feed hold
  1017. time.sleep(0.1)
  1018. state.conn.send("\x18\n") # Send reset
  1019. except Exception as e:
  1020. logger.error(f"Error stopping movement after timeout: {e}")
  1021. return False
  1022. if not homing_success:
  1023. logger.error("Homing failed")
  1024. return False
  1025. logger.info("Homing completed successfully")
  1026. return True
  1027. def check_idle():
  1028. """
  1029. Continuously check if the device is idle (synchronous version).
  1030. """
  1031. logger.info("Checking idle")
  1032. while True:
  1033. response = get_status_response()
  1034. if response and "Idle" in response:
  1035. logger.info("Device is idle")
  1036. # Schedule async update_machine_position in the existing event loop
  1037. try:
  1038. # Try to schedule in existing event loop if available
  1039. try:
  1040. asyncio.get_running_loop()
  1041. # Create a task but don't await it (fire and forget)
  1042. asyncio.create_task(update_machine_position())
  1043. logger.debug("Scheduled machine position update task")
  1044. except RuntimeError:
  1045. # No event loop running, skip machine position update
  1046. logger.debug("No event loop running, skipping machine position update")
  1047. except Exception as e:
  1048. logger.error(f"Error scheduling machine position update: {e}")
  1049. return True
  1050. time.sleep(1)
  1051. async def check_idle_async(timeout: float = 30.0):
  1052. """
  1053. Continuously check if the device is idle (async version).
  1054. Args:
  1055. timeout: Maximum seconds to wait for idle state (default 30s)
  1056. Returns:
  1057. True if device became idle, False if timeout or stop requested
  1058. """
  1059. logger.info("Checking idle (async)")
  1060. start_time = asyncio.get_event_loop().time()
  1061. while True:
  1062. # Check if stop was requested - exit early
  1063. if state.stop_requested:
  1064. logger.info("Stop requested during idle check, exiting early")
  1065. return False
  1066. # Check timeout
  1067. elapsed = asyncio.get_event_loop().time() - start_time
  1068. if elapsed > timeout:
  1069. logger.warning(f"Timeout ({timeout}s) waiting for device idle state")
  1070. return False
  1071. response = await asyncio.to_thread(get_status_response)
  1072. if response and "Idle" in response:
  1073. logger.info("Device is idle")
  1074. try:
  1075. await update_machine_position()
  1076. except Exception as e:
  1077. logger.error(f"Error updating machine position: {e}")
  1078. return True
  1079. await asyncio.sleep(1)
  1080. def is_machine_idle() -> bool:
  1081. """
  1082. Single check to see if the machine is currently idle.
  1083. Does not loop - returns immediately with current status.
  1084. Returns:
  1085. True if machine is idle, False otherwise
  1086. """
  1087. if not state.conn or not state.conn.is_connected():
  1088. logger.debug("No connection - machine not idle")
  1089. return False
  1090. try:
  1091. state.conn.send('?')
  1092. response = state.conn.readline()
  1093. if response and "Idle" in response:
  1094. logger.debug("Machine status: Idle")
  1095. return True
  1096. else:
  1097. logger.debug(f"Machine status: {response}")
  1098. return False
  1099. except Exception as e:
  1100. logger.error(f"Error checking machine idle status: {e}")
  1101. return False
  1102. def get_machine_position(timeout=5):
  1103. """
  1104. Query the device for its position.
  1105. Supports both MPos and WPos formats (depends on GRBL $10 setting).
  1106. """
  1107. start_time = time.time()
  1108. while time.time() - start_time < timeout:
  1109. try:
  1110. state.conn.send('?')
  1111. response = state.conn.readline()
  1112. logger.debug(f"Raw status response: {response}")
  1113. # Accept either MPos or WPos format
  1114. if "MPos" in response or "WPos" in response:
  1115. pos = parse_machine_position(response)
  1116. if pos:
  1117. machine_x, machine_y = pos
  1118. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  1119. return machine_x, machine_y
  1120. except Exception as e:
  1121. logger.error(f"Error getting machine position: {e}")
  1122. return
  1123. time.sleep(0.1)
  1124. logger.warning("Timeout reached waiting for machine position")
  1125. return None, None
  1126. async def update_machine_position():
  1127. if (state.conn.is_connected() if state.conn else False):
  1128. try:
  1129. logger.info('Saving machine position')
  1130. state.machine_x, state.machine_y = await asyncio.to_thread(get_machine_position)
  1131. await asyncio.to_thread(state.save)
  1132. logger.info(f'Machine position saved: {state.machine_x}, {state.machine_y}')
  1133. except Exception as e:
  1134. logger.error(f"Error updating machine position: {e}")
  1135. def perform_soft_reset_sync(max_retries: int = 5):
  1136. """
  1137. Synchronous version of soft reset for use during device initialization.
  1138. Supports both FluidNC ($Bye) and GRBL (Ctrl+X / 0x18) firmware.
  1139. Triggers a software reset which clears position counters to 0.
  1140. This is more reliable than G92 which only sets a work coordinate offset
  1141. without changing the actual machine position (MPos).
  1142. IMPORTANT: Position is only reset to (0,0) if confirmation is received.
  1143. This prevents position drift from accumulating over long operation periods.
  1144. Uses exponential backoff for retries:
  1145. - Attempt 1: 5s timeout
  1146. - Attempt 2: 7.5s timeout, 1s delay before retry
  1147. - Attempt 3: 11s timeout, 2s delay before retry
  1148. - Attempt 4: 17s timeout, 4s delay before retry
  1149. - Attempt 5: 25s timeout, 8s delay before retry
  1150. Args:
  1151. max_retries: Maximum number of reset attempts (default 5)
  1152. Returns:
  1153. True if reset confirmed, False if all attempts failed
  1154. """
  1155. if not state.conn or not state.conn.is_connected():
  1156. logger.warning("Cannot perform soft reset: no active connection")
  1157. return False
  1158. try:
  1159. # Detect firmware type to use appropriate reset command
  1160. firmware_type, version = _detect_firmware()
  1161. logger.info(f"Detected firmware: {firmware_type} {version or ''}")
  1162. logger.info(f"Performing soft reset (was: X={state.machine_x:.2f}, Y={state.machine_y:.2f})")
  1163. for attempt in range(max_retries):
  1164. # Exponential backoff: 5s * 1.5^attempt → 5s, 7.5s, 11s, 17s, 25s
  1165. timeout = 5.0 * (1.5 ** attempt)
  1166. logger.info(f"Reset attempt {attempt + 1}/{max_retries} (timeout: {timeout:.1f}s)")
  1167. # Clear any pending data first
  1168. if isinstance(state.conn, SerialConnection):
  1169. state.conn.reset_input_buffer()
  1170. # Send appropriate reset command based on firmware
  1171. if firmware_type == 'fluidnc':
  1172. # FluidNC uses $Bye for soft reset
  1173. state.conn.send('$Bye\n')
  1174. logger.info(f"$Bye sent to {state.port}")
  1175. else:
  1176. # GRBL uses Ctrl+X (0x18) for soft reset
  1177. state.conn.send('\x18')
  1178. logger.info(f"Ctrl+X (0x18) sent to {state.port}")
  1179. # Wait for controller to fully restart
  1180. # FluidNC sequence: [MSG:INFO: Restarting] -> ... -> "Grbl 3.9 [FluidNC...]"
  1181. # GRBL sequence: "Grbl 1.1h ['$' for help]"
  1182. start_time = time.time()
  1183. reset_confirmed = False
  1184. while time.time() - start_time < timeout:
  1185. try:
  1186. response = state.conn.readline()
  1187. if response:
  1188. logger.debug(f"Reset response: {response}")
  1189. # Wait for the "Grbl" startup banner - this means fully ready
  1190. if response.startswith("Grbl") or "fluidnc" in response.lower():
  1191. reset_confirmed = True
  1192. logger.info(f"Controller restart complete: {response}")
  1193. break
  1194. except Exception:
  1195. pass
  1196. time.sleep(0.05)
  1197. if reset_confirmed:
  1198. # Small delay to let controller fully stabilize
  1199. time.sleep(0.2)
  1200. # Unlock controller in case it's in alarm state after reset
  1201. logger.info("Sending $X to unlock controller after reset")
  1202. state.conn.send("$X\n")
  1203. # Wait for ok response
  1204. unlock_start = time.time()
  1205. while time.time() - unlock_start < 1.0:
  1206. try:
  1207. response = state.conn.readline()
  1208. if response:
  1209. logger.debug(f"$X response: {response}")
  1210. if response.lower() == "ok":
  1211. logger.info("Controller unlocked")
  1212. break
  1213. except Exception:
  1214. pass
  1215. time.sleep(0.05)
  1216. # Only reset state positions when confirmation received
  1217. state.machine_x = 0.0
  1218. state.machine_y = 0.0
  1219. reset_cmd = '$Bye' if firmware_type == 'fluidnc' else 'Ctrl+X'
  1220. logger.info(f"Machine position reset to 0 via {reset_cmd} soft reset")
  1221. # Save the reset position
  1222. state.save()
  1223. logger.info(f"Machine position saved: {state.machine_x}, {state.machine_y}")
  1224. return True
  1225. # Retry after failed attempt with exponential backoff delay
  1226. if attempt < max_retries - 1:
  1227. backoff_delay = 1.0 * (2 ** attempt) # 1s, 2s, 4s, 8s
  1228. logger.warning(f"Reset attempt {attempt + 1}/{max_retries} failed, retrying in {backoff_delay:.0f}s...")
  1229. time.sleep(backoff_delay)
  1230. # All attempts failed - DO NOT reset position to prevent drift
  1231. logger.error(
  1232. f"All {max_retries} reset attempts failed - no confirmation received. "
  1233. f"Position NOT reset (still: X={state.machine_x:.2f}, Y={state.machine_y:.2f}). "
  1234. "This may indicate communication issues or controller not responding."
  1235. )
  1236. return False
  1237. except Exception as e:
  1238. logger.error(f"Error performing soft reset: {e}")
  1239. return False
  1240. async def perform_soft_reset():
  1241. """
  1242. Async version of soft reset for use in async contexts (API endpoints, pattern manager).
  1243. Wraps the sync version in a thread to avoid blocking the event loop.
  1244. """
  1245. return await asyncio.to_thread(perform_soft_reset_sync)
  1246. def reset_work_coordinates():
  1247. """
  1248. Clear all work coordinate offsets for a clean start.
  1249. This ensures the work coordinate system starts fresh on each connection,
  1250. preventing accumulated offsets from previous sessions from affecting
  1251. pattern execution.
  1252. G92.1: Clears any G92 offset (resets work coordinates to machine coordinates)
  1253. G10 L2 P1 X0 Y0: Sets G54 work offset to 0 (for completeness)
  1254. """
  1255. if not state.conn or not state.conn.is_connected():
  1256. logger.warning("Cannot reset work coordinates: no active connection")
  1257. return False
  1258. try:
  1259. logger.info("Resetting work coordinate offsets")
  1260. # Clear any stale input data first
  1261. try:
  1262. while state.conn.in_waiting() > 0:
  1263. state.conn.readline()
  1264. except Exception:
  1265. pass
  1266. # Clear G92 offset
  1267. state.conn.send("G92.1\n")
  1268. time.sleep(0.2)
  1269. # Wait for 'ok' response
  1270. start_time = time.time()
  1271. got_ok = False
  1272. while time.time() - start_time < 2.0:
  1273. if state.conn.in_waiting() > 0:
  1274. response = state.conn.readline()
  1275. if response:
  1276. logger.debug(f"G92.1 response: {response}")
  1277. if response.lower() == "ok":
  1278. got_ok = True
  1279. break
  1280. elif "error" in response.lower():
  1281. logger.warning(f"G92.1 error: {response}")
  1282. break
  1283. time.sleep(0.05)
  1284. if not got_ok:
  1285. logger.warning("Did not receive 'ok' for G92.1, continuing anyway")
  1286. # Set G54 offset to 0 (optional, for completeness)
  1287. state.conn.send("G10 L2 P1 X0 Y0\n")
  1288. time.sleep(0.2)
  1289. # Wait for 'ok' response
  1290. start_time = time.time()
  1291. got_ok = False
  1292. while time.time() - start_time < 2.0:
  1293. if state.conn.in_waiting() > 0:
  1294. response = state.conn.readline()
  1295. if response:
  1296. logger.debug(f"G10 response: {response}")
  1297. if response.lower() == "ok":
  1298. got_ok = True
  1299. break
  1300. elif "error" in response.lower():
  1301. logger.warning(f"G10 error: {response}")
  1302. break
  1303. time.sleep(0.05)
  1304. if not got_ok:
  1305. logger.warning("Did not receive 'ok' for G10 L2 P1 X0 Y0, continuing anyway")
  1306. # Reset machine_x to 0 since work coordinates now start at 0
  1307. state.machine_x = 0.0
  1308. logger.info("Work coordinates reset complete")
  1309. return True
  1310. except Exception as e:
  1311. logger.error(f"Error resetting work coordinates: {e}")
  1312. return False
  1313. def restart_connection(homing=False):
  1314. """
  1315. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  1316. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  1317. The new connection is saved to state.conn.
  1318. Returns:
  1319. True if the connection was restarted successfully, False otherwise.
  1320. """
  1321. try:
  1322. if (state.conn.is_connected() if state.conn else False):
  1323. logger.info("Closing current connection...")
  1324. state.conn.close()
  1325. except Exception as e:
  1326. logger.error(f"Error while closing connection: {e}")
  1327. # Clear the connection reference.
  1328. state.conn = None
  1329. logger.info("Attempting to restart connection...")
  1330. try:
  1331. connect_device(homing) # This will set state.conn appropriately.
  1332. if (state.conn.is_connected() if state.conn else False):
  1333. logger.info("Connection restarted successfully.")
  1334. return True
  1335. else:
  1336. logger.error("Failed to restart connection.")
  1337. return False
  1338. except Exception as e:
  1339. logger.error(f"Error restarting connection: {e}")
  1340. return False