connection_manager.py 57 KB

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