connection_manager.py 26 KB

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