connection_manager.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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. from modules.core.state import state
  9. from modules.led.led_controller import effect_loading, effect_idle, effect_connected, LEDController
  10. from modules.connection.reed_switch import ReedSwitchMonitor
  11. logger = logging.getLogger(__name__)
  12. IGNORE_PORTS = ['/dev/cu.debug-console', '/dev/cu.Bluetooth-Incoming-Port']
  13. ###############################################################################
  14. # Connection Abstraction
  15. ###############################################################################
  16. class BaseConnection:
  17. """Abstract base class for a connection."""
  18. def send(self, data: str) -> None:
  19. raise NotImplementedError
  20. def flush(self) -> None:
  21. raise NotImplementedError
  22. def readline(self) -> str:
  23. raise NotImplementedError
  24. def in_waiting(self) -> int:
  25. raise NotImplementedError
  26. def is_connected(self) -> bool:
  27. raise NotImplementedError
  28. def close(self) -> None:
  29. raise NotImplementedError
  30. ###############################################################################
  31. # Serial Connection Implementation
  32. ###############################################################################
  33. class SerialConnection(BaseConnection):
  34. def __init__(self, port: str, baudrate: int = 115200, timeout: int = 2):
  35. self.port = port
  36. self.baudrate = baudrate
  37. self.timeout = timeout
  38. self.lock = threading.RLock()
  39. logger.info(f'Connecting to Serial port {port}')
  40. self.ser = serial.Serial(port, baudrate, timeout=timeout)
  41. state.port = port
  42. logger.info(f'Connected to Serial port {port}')
  43. def send(self, data: str) -> None:
  44. with self.lock:
  45. self.ser.write(data.encode())
  46. self.ser.flush()
  47. def flush(self) -> None:
  48. with self.lock:
  49. self.ser.flush()
  50. def readline(self) -> str:
  51. with self.lock:
  52. return self.ser.readline().decode().strip()
  53. def in_waiting(self) -> int:
  54. with self.lock:
  55. return self.ser.in_waiting
  56. def is_connected(self) -> bool:
  57. return self.ser is not None and self.ser.is_open
  58. def close(self) -> None:
  59. # Run async update_machine_position in sync context
  60. try:
  61. loop = asyncio.new_event_loop()
  62. asyncio.set_event_loop(loop)
  63. loop.run_until_complete(update_machine_position())
  64. loop.close()
  65. except Exception as e:
  66. logger.error(f"Error updating machine position on close: {e}")
  67. with self.lock:
  68. if self.ser.is_open:
  69. self.ser.close()
  70. # Release the lock resources
  71. self.lock = None
  72. ###############################################################################
  73. # WebSocket Connection Implementation
  74. ###############################################################################
  75. class WebSocketConnection(BaseConnection):
  76. def __init__(self, url: str, timeout: int = 5):
  77. self.url = url
  78. self.timeout = timeout
  79. self.lock = threading.RLock()
  80. self.ws = None
  81. self.connect()
  82. def connect(self):
  83. logger.info(f'Connecting to Websocket {self.url}')
  84. self.ws = websocket.create_connection(self.url, timeout=self.timeout)
  85. state.port = self.url
  86. logger.info(f'Connected to Websocket {self.url}')
  87. def send(self, data: str) -> None:
  88. with self.lock:
  89. self.ws.send(data)
  90. def flush(self) -> None:
  91. # WebSocket sends immediately; nothing to flush.
  92. pass
  93. def readline(self) -> str:
  94. with self.lock:
  95. data = self.ws.recv()
  96. # Decode bytes to string if necessary
  97. if isinstance(data, bytes):
  98. data = data.decode('utf-8')
  99. return data.strip()
  100. def in_waiting(self) -> int:
  101. return 0 # Not applicable for WebSocket
  102. def is_connected(self) -> bool:
  103. return self.ws is not None
  104. def close(self) -> None:
  105. # Run async update_machine_position in sync context
  106. try:
  107. loop = asyncio.new_event_loop()
  108. asyncio.set_event_loop(loop)
  109. loop.run_until_complete(update_machine_position())
  110. loop.close()
  111. except Exception as e:
  112. logger.error(f"Error updating machine position on close: {e}")
  113. with self.lock:
  114. if self.ws:
  115. self.ws.close()
  116. # Release the lock resources
  117. self.lock = None
  118. def list_serial_ports():
  119. """Return a list of available serial ports."""
  120. ports = serial.tools.list_ports.comports()
  121. available_ports = [port.device for port in ports if port.device not in IGNORE_PORTS]
  122. logger.debug(f"Available serial ports: {available_ports}")
  123. return available_ports
  124. def device_init(homing=True):
  125. try:
  126. if get_machine_steps():
  127. 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}")
  128. else:
  129. logger.fatal("Failed to get machine steps")
  130. state.conn.close()
  131. return False
  132. except:
  133. logger.fatal("Not GRBL firmware")
  134. state.conn.close()
  135. return False
  136. machine_x, machine_y = get_machine_position()
  137. if machine_x != state.machine_x or machine_y != state.machine_y:
  138. logger.info(f'x, y; {machine_x}, {machine_y}')
  139. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  140. if homing:
  141. success = home()
  142. if not success:
  143. logger.error("Homing failed during device initialization")
  144. else:
  145. logger.info('Machine position known, skipping home')
  146. logger.info(f'Theta: {state.current_theta}, rho: {state.current_rho}')
  147. logger.info(f'x, y; {machine_x}, {machine_y}')
  148. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  149. time.sleep(2) # Allow time for the connection to establish
  150. def connect_device(homing=True):
  151. if state.wled_ip:
  152. state.led_controller = LEDController(state.wled_ip)
  153. effect_loading(state.led_controller)
  154. ports = list_serial_ports()
  155. if state.port and state.port in ports:
  156. state.conn = SerialConnection(state.port)
  157. elif ports:
  158. state.conn = SerialConnection(ports[0])
  159. else:
  160. logger.error("Auto connect failed.")
  161. # state.conn = WebSocketConnection('ws://fluidnc.local:81')
  162. if (state.conn.is_connected() if state.conn else False):
  163. device_init(homing)
  164. if state.led_controller:
  165. effect_connected(state.led_controller)
  166. def get_status_response() -> str:
  167. """
  168. Send a status query ('?') and return the response if available.
  169. """
  170. while True:
  171. try:
  172. state.conn.send('?')
  173. response = state.conn.readline()
  174. if "MPos" in response:
  175. logger.debug(f"Status response: {response}")
  176. return response
  177. except Exception as e:
  178. logger.error(f"Error getting status response: {e}")
  179. return False
  180. time.sleep(1)
  181. def parse_machine_position(response: str):
  182. """
  183. Parse the work position (MPos) from a status response.
  184. Expected format: "<...|MPos:-994.869,-321.861,0.000|...>"
  185. Returns a tuple (work_x, work_y) if found, else None.
  186. """
  187. if "MPos:" not in response:
  188. return None
  189. try:
  190. wpos_section = next((part for part in response.split("|") if part.startswith("MPos:")), None)
  191. if wpos_section:
  192. wpos_str = wpos_section.split(":", 1)[1]
  193. wpos_values = wpos_str.split(",")
  194. work_x = float(wpos_values[0])
  195. work_y = float(wpos_values[1])
  196. return work_x, work_y
  197. except Exception as e:
  198. logger.error(f"Error parsing work position: {e}")
  199. return None
  200. async def send_grbl_coordinates(x, y, speed=600, timeout=2, home=False):
  201. """
  202. Send a G-code command to FluidNC and wait for an 'ok' response.
  203. If no response after set timeout, sets state to stop and disconnects.
  204. """
  205. logger.debug(f"Sending G-code: X{x} Y{y} at F{speed}")
  206. # Track overall attempt time
  207. overall_start_time = time.time()
  208. while True:
  209. try:
  210. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  211. # Use asyncio.to_thread for both send and receive operations to avoid blocking
  212. await asyncio.to_thread(state.conn.send, gcode + "\n")
  213. logger.debug(f"Sent command: {gcode}")
  214. start_time = time.time()
  215. while True:
  216. # Use asyncio.to_thread for blocking I/O operations
  217. response = await asyncio.to_thread(state.conn.readline)
  218. logger.debug(f"Response: {response}")
  219. if response.lower() == "ok":
  220. logger.debug("Command execution confirmed.")
  221. return
  222. except Exception as e:
  223. # Store the error string inside the exception block
  224. error_str = str(e)
  225. logger.warning(f"Error sending command: {error_str}")
  226. # Immediately return for device not configured errors
  227. if "Device not configured" in error_str or "Errno 6" in error_str:
  228. logger.error(f"Device configuration error detected: {error_str}")
  229. state.stop_requested = True
  230. state.conn = None
  231. state.is_connected = False
  232. logger.info("Connection marked as disconnected due to device error")
  233. return False
  234. logger.warning(f"No 'ok' received for X{x} Y{y}, speed {speed}. Retrying...")
  235. await asyncio.sleep(0.1)
  236. # If we reach here, the timeout has occurred
  237. logger.error(f"Failed to receive 'ok' response after {max_total_attempt_time} seconds. Stopping and disconnecting.")
  238. # Set state to stop
  239. state.stop_requested = True
  240. # Set connection status to disconnected
  241. if state.conn:
  242. try:
  243. state.conn.disconnect()
  244. except:
  245. pass
  246. state.conn = None
  247. # Update the state connection status
  248. state.is_connected = False
  249. logger.info("Connection marked as disconnected due to timeout")
  250. return False
  251. def get_machine_steps(timeout=10):
  252. """
  253. Get machine steps/mm from the GRBL controller.
  254. Returns True if successful, False otherwise.
  255. """
  256. if not state.conn or not state.conn.is_connected():
  257. logger.error("Cannot get machine steps: No connection available")
  258. return False
  259. x_steps_per_mm = None
  260. y_steps_per_mm = None
  261. gear_ratio = None
  262. start_time = time.time()
  263. # Clear any pending data in the buffer
  264. try:
  265. while state.conn.in_waiting() > 0:
  266. state.conn.readline()
  267. except Exception as e:
  268. logger.warning(f"Error clearing buffer: {e}")
  269. # Send the command to request all settings
  270. try:
  271. logger.info("Requesting GRBL settings with $$ command")
  272. state.conn.send("$$\n")
  273. time.sleep(0.5) # Give GRBL a moment to process and respond
  274. except Exception as e:
  275. logger.error(f"Error sending $$ command: {e}")
  276. return False
  277. # Wait for and process responses
  278. settings_complete = False
  279. while time.time() - start_time < timeout and not settings_complete:
  280. try:
  281. # Attempt to read a line from the connection
  282. if state.conn.in_waiting() > 0:
  283. response = state.conn.readline()
  284. logger.debug(f"Raw response: {response}")
  285. # Process the line
  286. if response.strip(): # Only process non-empty lines
  287. for line in response.splitlines():
  288. line = line.strip()
  289. logger.debug(f"Config response: {line}")
  290. if line.startswith("$100="):
  291. x_steps_per_mm = float(line.split("=")[1])
  292. state.x_steps_per_mm = x_steps_per_mm
  293. logger.info(f"X steps per mm: {x_steps_per_mm}")
  294. elif line.startswith("$101="):
  295. y_steps_per_mm = float(line.split("=")[1])
  296. state.y_steps_per_mm = y_steps_per_mm
  297. logger.info(f"Y steps per mm: {y_steps_per_mm}")
  298. elif line.startswith("$131="):
  299. gear_ratio = float(line.split("=")[1])
  300. state.gear_ratio = gear_ratio
  301. logger.info(f"Gear ratio: {gear_ratio}")
  302. elif line.startswith("$22="):
  303. # $22 reports if the homing cycle is enabled
  304. # returns 0 if disabled, 1 if enabled
  305. homing = int(line.split('=')[1])
  306. state.homing = homing
  307. logger.info(f"Homing enabled: {homing}")
  308. # Check if we've received all the settings we need
  309. if x_steps_per_mm is not None and y_steps_per_mm is not None and gear_ratio is not None:
  310. settings_complete = True
  311. else:
  312. # No data waiting, small sleep to prevent CPU thrashing
  313. time.sleep(0.1)
  314. # If it's taking too long, try sending the command again after 3 seconds
  315. elapsed = time.time() - start_time
  316. if elapsed > 3 and elapsed < 4:
  317. logger.warning("No response yet, sending $$ command again")
  318. state.conn.send("$$\n")
  319. except Exception as e:
  320. logger.error(f"Error getting machine steps: {e}")
  321. time.sleep(0.5)
  322. # Process results and determine table type
  323. if settings_complete:
  324. if y_steps_per_mm == 180:
  325. state.table_type = 'dune_weaver_mini'
  326. elif y_steps_per_mm >= 320:
  327. state.table_type = 'dune_weaver_pro'
  328. elif y_steps_per_mm == 287:
  329. state.table_type = 'dune_weaver'
  330. else:
  331. state.table_type = None
  332. logger.warning(f"Unknown table type with Y steps/mm: {y_steps_per_mm}")
  333. logger.info(f"Machine type detected: {state.table_type}")
  334. return True
  335. else:
  336. missing = []
  337. if x_steps_per_mm is None: missing.append("X steps/mm")
  338. if y_steps_per_mm is None: missing.append("Y steps/mm")
  339. if gear_ratio is None: missing.append("gear ratio")
  340. logger.error(f"Failed to get all machine parameters after {timeout}s. Missing: {', '.join(missing)}")
  341. return False
  342. def home(timeout=15):
  343. """
  344. Perform homing by checking device configuration and sending the appropriate commands.
  345. Args:
  346. timeout: Maximum time in seconds to wait for homing to complete (default: 15)
  347. """
  348. import threading
  349. # Flag to track if homing completed
  350. homing_complete = threading.Event()
  351. homing_success = False
  352. def home_internal():
  353. nonlocal homing_success
  354. try:
  355. if state.homing:
  356. logger.info("Using sensorless homing")
  357. state.conn.send("$H\n")
  358. state.conn.send("G1 Y0 F100\n")
  359. else:
  360. homing_speed = 400
  361. if state.table_type == 'dune_weaver_mini':
  362. homing_speed = 120
  363. logger.info("Sensorless homing not supported. Using crash homing")
  364. logger.info(f"Homing with speed {homing_speed}")
  365. # Run async function in new event loop
  366. loop = asyncio.new_event_loop()
  367. asyncio.set_event_loop(loop)
  368. try:
  369. if state.gear_ratio == 6.25:
  370. result = loop.run_until_complete(send_grbl_coordinates(0, - 30, homing_speed, home=True))
  371. if result == False:
  372. logger.error("Homing failed - send_grbl_coordinates returned False")
  373. homing_complete.set()
  374. return
  375. state.machine_y -= 30
  376. else:
  377. result = loop.run_until_complete(send_grbl_coordinates(0, -22, homing_speed, home=True))
  378. if result == False:
  379. logger.error("Homing failed - send_grbl_coordinates returned False")
  380. homing_complete.set()
  381. return
  382. state.machine_y -= 22
  383. finally:
  384. loop.close()
  385. # Wait for device to reach idle state after homing
  386. logger.info("Waiting for device to reach idle state after homing...")
  387. idle_reached = check_idle()
  388. if not idle_reached:
  389. logger.error("Device did not reach idle state after homing")
  390. homing_complete.set()
  391. return
  392. # Perform angular homing if enabled (Raspberry Pi only)
  393. if state.angular_homing_enabled:
  394. logger.info("Starting angular homing sequence")
  395. try:
  396. # Initialize reed switch monitor
  397. reed_switch = ReedSwitchMonitor(gpio_pin=18)
  398. if not reed_switch.is_raspberry_pi:
  399. logger.warning("Angular homing is enabled but not running on Raspberry Pi. Skipping angular homing.")
  400. else:
  401. # Move radial arm to perimeter
  402. logger.info("Moving radial arm to perimeter (y20)")
  403. loop = asyncio.new_event_loop()
  404. asyncio.set_event_loop(loop)
  405. try:
  406. result = loop.run_until_complete(send_grbl_coordinates(0, 20, 400, home=False))
  407. if result == False:
  408. logger.error("Failed to move to perimeter for angular homing")
  409. homing_complete.set()
  410. return
  411. state.machine_y += 20
  412. # Wait for idle
  413. idle_reached = check_idle()
  414. if not idle_reached:
  415. logger.error("Device did not reach idle state after moving to perimeter")
  416. homing_complete.set()
  417. return
  418. # Import pattern_manager here to avoid circular import
  419. from modules.core import pattern_manager
  420. # Perform angular rotation until reed switch is triggered
  421. logger.info("Rotating around perimeter to find home position (6.28 radians)")
  422. # We'll do this in small increments to check the reed switch
  423. # One full rotation is 2*pi (6.28) radians
  424. increment = 0.1 # Small angular increment
  425. current_theta = 0
  426. max_theta = 6.28 # One full rotation
  427. while current_theta < max_theta:
  428. # Check reed switch
  429. if reed_switch.is_triggered():
  430. logger.info(f"Reed switch triggered at theta={current_theta}")
  431. break
  432. # Move to next position
  433. current_theta += increment
  434. result = loop.run_until_complete(
  435. asyncio.to_thread(
  436. pattern_manager.motion_controller._move_polar_sync,
  437. current_theta,
  438. 1.0, # rho = 1.0 (perimeter)
  439. 400 # speed
  440. )
  441. )
  442. # Small delay to allow reed switch to settle
  443. time.sleep(0.05)
  444. if current_theta >= max_theta:
  445. logger.warning("Completed full rotation without reed switch trigger")
  446. # Set theta to 0 at this position
  447. state.current_theta = 0
  448. logger.info("Angular homing completed")
  449. finally:
  450. loop.close()
  451. reed_switch.cleanup()
  452. except Exception as e:
  453. logger.error(f"Error during angular homing: {e}")
  454. # Continue with normal homing completion even if angular homing fails
  455. state.current_theta = state.current_rho = 0
  456. homing_success = True
  457. logger.info("Homing completed and device is idle")
  458. homing_complete.set()
  459. except Exception as e:
  460. logger.error(f"Error during homing: {e}")
  461. homing_complete.set()
  462. # Start homing in a separate thread
  463. homing_thread = threading.Thread(target=home_internal)
  464. homing_thread.daemon = True
  465. homing_thread.start()
  466. # Wait for homing to complete or timeout
  467. if not homing_complete.wait(timeout):
  468. logger.error(f"Homing timeout after {timeout} seconds")
  469. # Try to stop any ongoing movement
  470. try:
  471. if state.conn and state.conn.is_connected():
  472. state.conn.send("!\n") # Send feed hold
  473. time.sleep(0.1)
  474. state.conn.send("\x18\n") # Send reset
  475. except Exception as e:
  476. logger.error(f"Error stopping movement after timeout: {e}")
  477. return False
  478. if not homing_success:
  479. logger.error("Homing failed")
  480. return False
  481. logger.info("Homing completed successfully")
  482. return True
  483. def check_idle():
  484. """
  485. Continuously check if the device is idle (synchronous version).
  486. """
  487. logger.info("Checking idle")
  488. while True:
  489. response = get_status_response()
  490. if response and "Idle" in response:
  491. logger.info("Device is idle")
  492. # Schedule async update_machine_position in the existing event loop
  493. try:
  494. # Try to schedule in existing event loop if available
  495. try:
  496. loop = asyncio.get_running_loop()
  497. # Create a task but don't await it (fire and forget)
  498. asyncio.create_task(update_machine_position())
  499. logger.debug("Scheduled machine position update task")
  500. except RuntimeError:
  501. # No event loop running, skip machine position update
  502. logger.debug("No event loop running, skipping machine position update")
  503. except Exception as e:
  504. logger.error(f"Error scheduling machine position update: {e}")
  505. return True
  506. time.sleep(1)
  507. async def check_idle_async():
  508. """
  509. Continuously check if the device is idle (async version).
  510. """
  511. logger.info("Checking idle (async)")
  512. while True:
  513. response = await asyncio.to_thread(get_status_response)
  514. if response and "Idle" in response:
  515. logger.info("Device is idle")
  516. try:
  517. await update_machine_position()
  518. except Exception as e:
  519. logger.error(f"Error updating machine position: {e}")
  520. return True
  521. await asyncio.sleep(1)
  522. def get_machine_position(timeout=5):
  523. """
  524. Query the device for its position.
  525. """
  526. start_time = time.time()
  527. while time.time() - start_time < timeout:
  528. try:
  529. state.conn.send('?')
  530. response = state.conn.readline()
  531. logger.debug(f"Raw status response: {response}")
  532. if "MPos" in response:
  533. pos = parse_machine_position(response)
  534. if pos:
  535. machine_x, machine_y = pos
  536. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  537. return machine_x, machine_y
  538. except Exception as e:
  539. logger.error(f"Error getting machine position: {e}")
  540. return
  541. time.sleep(0.1)
  542. logger.warning("Timeout reached waiting for machine position")
  543. return None, None
  544. async def update_machine_position():
  545. if (state.conn.is_connected() if state.conn else False):
  546. try:
  547. logger.info('Saving machine position')
  548. state.machine_x, state.machine_y = await asyncio.to_thread(get_machine_position)
  549. await asyncio.to_thread(state.save)
  550. logger.info(f'Machine position saved: {state.machine_x}, {state.machine_y}')
  551. except Exception as e:
  552. logger.error(f"Error updating machine position: {e}")
  553. def restart_connection(homing=False):
  554. """
  555. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  556. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  557. The new connection is saved to state.conn.
  558. Returns:
  559. True if the connection was restarted successfully, False otherwise.
  560. """
  561. try:
  562. if (state.conn.is_connected() if state.conn else False):
  563. logger.info("Closing current connection...")
  564. state.conn.close()
  565. except Exception as e:
  566. logger.error(f"Error while closing connection: {e}")
  567. # Clear the connection reference.
  568. state.conn = None
  569. logger.info("Attempting to restart connection...")
  570. try:
  571. connect_device(homing) # This will set state.conn appropriately.
  572. if (state.conn.is_connected() if state.conn else False):
  573. logger.info("Connection restarted successfully.")
  574. return True
  575. else:
  576. logger.error("Failed to restart connection.")
  577. return False
  578. except Exception as e:
  579. logger.error(f"Error restarting connection: {e}")
  580. return False