connection_manager.py 60 KB

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