connection_manager.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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. try:
  402. # Reset theta first
  403. logger.info("Resetting theta before angular homing")
  404. asyncio.run(pattern_manager.reset_theta())
  405. # Move radial arm to perimeter (theta=0, rho=1.0)
  406. logger.info("Moving radial arm to perimeter (theta=0, rho=1.0)")
  407. asyncio.run(pattern_manager.move_polar(0, 1.0, homing_speed))
  408. idle_reached = check_idle()
  409. if not idle_reached:
  410. logger.error("Device did not reach idle state after moving to perimeter")
  411. homing_complete.set()
  412. return
  413. # Wait 1 second for stabilization
  414. logger.info("Waiting for stabilization...")
  415. time.sleep(1)
  416. # Perform angular rotation until reed switch is triggered
  417. logger.info("Rotating around perimeter to find home position")
  418. increment = 0.1 # Small angular increment in radians
  419. current_theta = 0
  420. max_theta = 6.28 # One full rotation (2*pi)
  421. reed_switch_triggered = False
  422. while current_theta < max_theta:
  423. # Move to next position
  424. current_theta += increment
  425. asyncio.run(pattern_manager.move_polar(current_theta, 1.0, homing_speed))
  426. # Small delay to allow reed switch to settle after movement
  427. time.sleep(0.5)
  428. # Check reed switch AFTER movement completes
  429. if reed_switch.is_triggered():
  430. logger.info(f"Reed switch triggered at theta={current_theta}")
  431. reed_switch_triggered = True
  432. break
  433. if not reed_switch_triggered:
  434. logger.warning("Completed full rotation without reed switch trigger")
  435. # Set theta to 0 at this position (home position)
  436. state.current_theta = 0
  437. state.current_rho = 1
  438. logger.info("Angular homing completed - theta set to 0")
  439. finally:
  440. reed_switch.cleanup()
  441. except Exception as e:
  442. logger.error(f"Error during angular homing: {e}")
  443. # Continue with normal homing completion even if angular homing fails
  444. homing_success = True
  445. logger.info("Homing completed and device is idle")
  446. homing_complete.set()
  447. except Exception as e:
  448. logger.error(f"Error during homing: {e}")
  449. homing_complete.set()
  450. # Start homing in a separate thread
  451. homing_thread = threading.Thread(target=home_internal)
  452. homing_thread.daemon = True
  453. homing_thread.start()
  454. # Wait for homing to complete or timeout
  455. if not homing_complete.wait(timeout):
  456. logger.error(f"Homing timeout after {timeout} seconds")
  457. # Try to stop any ongoing movement
  458. try:
  459. if state.conn and state.conn.is_connected():
  460. state.conn.send("!\n") # Send feed hold
  461. time.sleep(0.1)
  462. state.conn.send("\x18\n") # Send reset
  463. except Exception as e:
  464. logger.error(f"Error stopping movement after timeout: {e}")
  465. return False
  466. if not homing_success:
  467. logger.error("Homing failed")
  468. return False
  469. logger.info("Homing completed successfully")
  470. return True
  471. def check_idle():
  472. """
  473. Continuously check if the device is idle (synchronous version).
  474. """
  475. logger.info("Checking idle")
  476. while True:
  477. response = get_status_response()
  478. if response and "Idle" in response:
  479. logger.info("Device is idle")
  480. # Schedule async update_machine_position in the existing event loop
  481. try:
  482. # Try to schedule in existing event loop if available
  483. try:
  484. loop = asyncio.get_running_loop()
  485. # Create a task but don't await it (fire and forget)
  486. asyncio.create_task(update_machine_position())
  487. logger.debug("Scheduled machine position update task")
  488. except RuntimeError:
  489. # No event loop running, skip machine position update
  490. logger.debug("No event loop running, skipping machine position update")
  491. except Exception as e:
  492. logger.error(f"Error scheduling machine position update: {e}")
  493. return True
  494. time.sleep(1)
  495. async def check_idle_async():
  496. """
  497. Continuously check if the device is idle (async version).
  498. """
  499. logger.info("Checking idle (async)")
  500. while True:
  501. response = await asyncio.to_thread(get_status_response)
  502. if response and "Idle" in response:
  503. logger.info("Device is idle")
  504. try:
  505. await update_machine_position()
  506. except Exception as e:
  507. logger.error(f"Error updating machine position: {e}")
  508. return True
  509. await asyncio.sleep(1)
  510. def get_machine_position(timeout=5):
  511. """
  512. Query the device for its position.
  513. """
  514. start_time = time.time()
  515. while time.time() - start_time < timeout:
  516. try:
  517. state.conn.send('?')
  518. response = state.conn.readline()
  519. logger.debug(f"Raw status response: {response}")
  520. if "MPos" in response:
  521. pos = parse_machine_position(response)
  522. if pos:
  523. machine_x, machine_y = pos
  524. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  525. return machine_x, machine_y
  526. except Exception as e:
  527. logger.error(f"Error getting machine position: {e}")
  528. return
  529. time.sleep(0.1)
  530. logger.warning("Timeout reached waiting for machine position")
  531. return None, None
  532. async def update_machine_position():
  533. if (state.conn.is_connected() if state.conn else False):
  534. try:
  535. logger.info('Saving machine position')
  536. state.machine_x, state.machine_y = await asyncio.to_thread(get_machine_position)
  537. await asyncio.to_thread(state.save)
  538. logger.info(f'Machine position saved: {state.machine_x}, {state.machine_y}')
  539. except Exception as e:
  540. logger.error(f"Error updating machine position: {e}")
  541. def restart_connection(homing=False):
  542. """
  543. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  544. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  545. The new connection is saved to state.conn.
  546. Returns:
  547. True if the connection was restarted successfully, False otherwise.
  548. """
  549. try:
  550. if (state.conn.is_connected() if state.conn else False):
  551. logger.info("Closing current connection...")
  552. state.conn.close()
  553. except Exception as e:
  554. logger.error(f"Error while closing connection: {e}")
  555. # Clear the connection reference.
  556. state.conn = None
  557. logger.info("Attempting to restart connection...")
  558. try:
  559. connect_device(homing) # This will set state.conn appropriately.
  560. if (state.conn.is_connected() if state.conn else False):
  561. logger.info("Connection restarted successfully.")
  562. return True
  563. else:
  564. logger.error("Failed to restart connection.")
  565. return False
  566. except Exception as e:
  567. logger.error(f"Error restarting connection: {e}")
  568. return False