connection_manager.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. import threading
  2. import time
  3. import logging
  4. import serial
  5. import serial.tools.list_ports
  6. import websocket
  7. from modules.core.state import state
  8. from modules.led.led_controller import effect_loading, effect_idle, effect_connected, LEDController
  9. logger = logging.getLogger(__name__)
  10. IGNORE_PORTS = ['/dev/cu.debug-console', '/dev/cu.Bluetooth-Incoming-Port']
  11. ###############################################################################
  12. # Connection Abstraction
  13. ###############################################################################
  14. class BaseConnection:
  15. """Abstract base class for a connection."""
  16. def send(self, data: str) -> None:
  17. raise NotImplementedError
  18. def flush(self) -> None:
  19. raise NotImplementedError
  20. def readline(self) -> str:
  21. raise NotImplementedError
  22. def in_waiting(self) -> int:
  23. raise NotImplementedError
  24. def is_connected(self) -> bool:
  25. raise NotImplementedError
  26. def close(self) -> None:
  27. raise NotImplementedError
  28. ###############################################################################
  29. # Serial Connection Implementation
  30. ###############################################################################
  31. class SerialConnection(BaseConnection):
  32. def __init__(self, port: str, baudrate: int = 115200, timeout: int = 2):
  33. self.port = port
  34. self.baudrate = baudrate
  35. self.timeout = timeout
  36. self.lock = threading.RLock()
  37. logger.info(f'Connecting to Serial port {port}')
  38. self.ser = serial.Serial(port, baudrate, timeout=timeout)
  39. state.port = port
  40. logger.info(f'Connected to Serial port {port}')
  41. def send(self, data: str) -> None:
  42. with self.lock:
  43. self.ser.write(data.encode())
  44. self.ser.flush()
  45. def flush(self) -> None:
  46. with self.lock:
  47. self.ser.flush()
  48. def readline(self) -> str:
  49. with self.lock:
  50. return self.ser.readline().decode().strip()
  51. def in_waiting(self) -> int:
  52. with self.lock:
  53. return self.ser.in_waiting
  54. def is_connected(self) -> bool:
  55. return self.ser is not None and self.ser.is_open
  56. def close(self) -> None:
  57. update_machine_position()
  58. with self.lock:
  59. if self.ser.is_open:
  60. self.ser.close()
  61. # Release the lock resources
  62. self.lock = None
  63. ###############################################################################
  64. # WebSocket Connection Implementation
  65. ###############################################################################
  66. class WebSocketConnection(BaseConnection):
  67. def __init__(self, url: str, timeout: int = 5):
  68. self.url = url
  69. self.timeout = timeout
  70. self.lock = threading.RLock()
  71. self.ws = None
  72. self.connect()
  73. def connect(self):
  74. logger.info(f'Connecting to Websocket {self.url}')
  75. self.ws = websocket.create_connection(self.url, timeout=self.timeout)
  76. state.port = self.url
  77. logger.info(f'Connected to Websocket {self.url}')
  78. def send(self, data: str) -> None:
  79. with self.lock:
  80. self.ws.send(data)
  81. def flush(self) -> None:
  82. # WebSocket sends immediately; nothing to flush.
  83. pass
  84. def readline(self) -> str:
  85. with self.lock:
  86. data = self.ws.recv()
  87. # Decode bytes to string if necessary
  88. if isinstance(data, bytes):
  89. data = data.decode('utf-8')
  90. return data.strip()
  91. def in_waiting(self) -> int:
  92. return 0 # Not applicable for WebSocket
  93. def is_connected(self) -> bool:
  94. return self.ws is not None
  95. def close(self) -> None:
  96. update_machine_position()
  97. with self.lock:
  98. if self.ws:
  99. self.ws.close()
  100. # Release the lock resources
  101. self.lock = None
  102. def list_serial_ports():
  103. """Return a list of available serial ports."""
  104. ports = serial.tools.list_ports.comports()
  105. available_ports = [port.device for port in ports if port.device not in IGNORE_PORTS]
  106. logger.debug(f"Available serial ports: {available_ports}")
  107. return available_ports
  108. def device_init(homing=True):
  109. try:
  110. if get_machine_steps():
  111. 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}")
  112. else:
  113. logger.fatal("Failed to get machine steps")
  114. state.conn.close()
  115. return False
  116. except:
  117. logger.fatal("Not GRBL firmware")
  118. state.conn.close()
  119. return False
  120. machine_x, machine_y = get_machine_position()
  121. if machine_x != state.machine_x or machine_y != state.machine_y:
  122. logger.info(f'x, y; {machine_x}, {machine_y}')
  123. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  124. if homing:
  125. success = home()
  126. if not success:
  127. logger.error("Homing failed during device initialization")
  128. else:
  129. logger.info('Machine position known, skipping home')
  130. logger.info(f'Theta: {state.current_theta}, rho: {state.current_rho}')
  131. logger.info(f'x, y; {machine_x}, {machine_y}')
  132. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  133. time.sleep(2) # Allow time for the connection to establish
  134. def connect_device(homing=True):
  135. if state.wled_ip:
  136. state.led_controller = LEDController(state.wled_ip)
  137. effect_loading(state.led_controller)
  138. ports = list_serial_ports()
  139. if state.port and state.port in ports:
  140. state.conn = SerialConnection(state.port)
  141. elif ports:
  142. state.conn = SerialConnection(ports[0])
  143. else:
  144. logger.error("Auto connect failed.")
  145. # state.conn = WebSocketConnection('ws://fluidnc.local:81')
  146. if (state.conn.is_connected() if state.conn else False):
  147. device_init(homing)
  148. if state.led_controller:
  149. effect_connected(state.led_controller)
  150. def get_status_response() -> str:
  151. """
  152. Send a status query ('?') and return the response if available.
  153. """
  154. while True:
  155. try:
  156. state.conn.send('?')
  157. response = state.conn.readline()
  158. if "MPos" in response:
  159. logger.debug(f"Status response: {response}")
  160. return response
  161. except Exception as e:
  162. logger.error(f"Error getting status response: {e}")
  163. return False
  164. time.sleep(1)
  165. def parse_machine_position(response: str):
  166. """
  167. Parse the work position (MPos) from a status response.
  168. Expected format: "<...|MPos:-994.869,-321.861,0.000|...>"
  169. Returns a tuple (work_x, work_y) if found, else None.
  170. """
  171. if "MPos:" not in response:
  172. return None
  173. try:
  174. wpos_section = next((part for part in response.split("|") if part.startswith("MPos:")), None)
  175. if wpos_section:
  176. wpos_str = wpos_section.split(":", 1)[1]
  177. wpos_values = wpos_str.split(",")
  178. work_x = float(wpos_values[0])
  179. work_y = float(wpos_values[1])
  180. return work_x, work_y
  181. except Exception as e:
  182. logger.error(f"Error parsing work position: {e}")
  183. return None
  184. def send_grbl_coordinates(x, y, speed=600, timeout=2, home=False):
  185. """
  186. Send a G-code command to FluidNC and wait for an 'ok' response.
  187. If no response after set timeout, sets state to stop and disconnects.
  188. """
  189. logger.debug(f"Sending G-code: X{x} Y{y} at F{speed}")
  190. # Track overall attempt time
  191. overall_start_time = time.time()
  192. while True:
  193. try:
  194. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  195. state.conn.send(gcode + "\n")
  196. logger.debug(f"Sent command: {gcode}")
  197. start_time = time.time()
  198. while True:
  199. response = state.conn.readline()
  200. logger.debug(f"Response: {response}")
  201. if response.lower() == "ok":
  202. logger.debug("Command execution confirmed.")
  203. return
  204. except Exception as e:
  205. # Store the error string inside the exception block
  206. error_str = str(e)
  207. logger.warning(f"Error sending command: {error_str}")
  208. # Immediately return for device not configured errors
  209. if "Device not configured" in error_str or "Errno 6" in error_str:
  210. logger.error(f"Device configuration error detected: {error_str}")
  211. state.stop_requested = True
  212. state.conn = None
  213. state.is_connected = False
  214. logger.info("Connection marked as disconnected due to device error")
  215. return False
  216. logger.warning(f"No 'ok' received for X{x} Y{y}, speed {speed}. Retrying...")
  217. time.sleep(0.1)
  218. # If we reach here, the timeout has occurred
  219. logger.error(f"Failed to receive 'ok' response after {max_total_attempt_time} seconds. Stopping and disconnecting.")
  220. # Set state to stop
  221. state.stop_requested = True
  222. # Set connection status to disconnected
  223. if state.conn:
  224. try:
  225. state.conn.disconnect()
  226. except:
  227. pass
  228. state.conn = None
  229. # Update the state connection status
  230. state.is_connected = False
  231. logger.info("Connection marked as disconnected due to timeout")
  232. return False
  233. def get_machine_steps(timeout=10):
  234. """
  235. Get machine steps/mm from the GRBL controller.
  236. Returns True if successful, False otherwise.
  237. """
  238. if not state.conn or not state.conn.is_connected():
  239. logger.error("Cannot get machine steps: No connection available")
  240. return False
  241. x_steps_per_mm = None
  242. y_steps_per_mm = None
  243. gear_ratio = None
  244. start_time = time.time()
  245. # Clear any pending data in the buffer
  246. try:
  247. while state.conn.in_waiting() > 0:
  248. state.conn.readline()
  249. except Exception as e:
  250. logger.warning(f"Error clearing buffer: {e}")
  251. # Send the command to request all settings
  252. try:
  253. logger.info("Requesting GRBL settings with $$ command")
  254. state.conn.send("$$\n")
  255. time.sleep(0.5) # Give GRBL a moment to process and respond
  256. except Exception as e:
  257. logger.error(f"Error sending $$ command: {e}")
  258. return False
  259. # Wait for and process responses
  260. settings_complete = False
  261. while time.time() - start_time < timeout and not settings_complete:
  262. try:
  263. # Attempt to read a line from the connection
  264. if state.conn.in_waiting() > 0:
  265. response = state.conn.readline()
  266. logger.debug(f"Raw response: {response}")
  267. # Process the line
  268. if response.strip(): # Only process non-empty lines
  269. for line in response.splitlines():
  270. line = line.strip()
  271. logger.debug(f"Config response: {line}")
  272. if line.startswith("$100="):
  273. x_steps_per_mm = float(line.split("=")[1])
  274. state.x_steps_per_mm = x_steps_per_mm
  275. logger.info(f"X steps per mm: {x_steps_per_mm}")
  276. elif line.startswith("$101="):
  277. y_steps_per_mm = float(line.split("=")[1])
  278. state.y_steps_per_mm = y_steps_per_mm
  279. logger.info(f"Y steps per mm: {y_steps_per_mm}")
  280. elif line.startswith("$131="):
  281. gear_ratio = float(line.split("=")[1])
  282. state.gear_ratio = gear_ratio
  283. logger.info(f"Gear ratio: {gear_ratio}")
  284. elif line.startswith("$22="):
  285. # $22 reports if the homing cycle is enabled
  286. # returns 0 if disabled, 1 if enabled
  287. homing = int(line.split('=')[1])
  288. state.homing = homing
  289. logger.info(f"Homing enabled: {homing}")
  290. # Check if we've received all the settings we need
  291. if x_steps_per_mm is not None and y_steps_per_mm is not None and gear_ratio is not None:
  292. settings_complete = True
  293. else:
  294. # No data waiting, small sleep to prevent CPU thrashing
  295. time.sleep(0.1)
  296. # If it's taking too long, try sending the command again after 3 seconds
  297. elapsed = time.time() - start_time
  298. if elapsed > 3 and elapsed < 4:
  299. logger.warning("No response yet, sending $$ command again")
  300. state.conn.send("$$\n")
  301. except Exception as e:
  302. logger.error(f"Error getting machine steps: {e}")
  303. time.sleep(0.5)
  304. # Process results and determine table type
  305. if settings_complete:
  306. if y_steps_per_mm == 180:
  307. state.table_type = 'dune_weaver_mini'
  308. elif y_steps_per_mm >= 320:
  309. state.table_type = 'dune_weaver_pro'
  310. elif y_steps_per_mm == 287:
  311. state.table_type = 'dune_weaver'
  312. else:
  313. state.table_type = None
  314. logger.warning(f"Unknown table type with Y steps/mm: {y_steps_per_mm}")
  315. logger.info(f"Machine type detected: {state.table_type}")
  316. return True
  317. else:
  318. missing = []
  319. if x_steps_per_mm is None: missing.append("X steps/mm")
  320. if y_steps_per_mm is None: missing.append("Y steps/mm")
  321. if gear_ratio is None: missing.append("gear ratio")
  322. logger.error(f"Failed to get all machine parameters after {timeout}s. Missing: {', '.join(missing)}")
  323. return False
  324. def home(timeout=15):
  325. """
  326. Perform homing by checking device configuration and sending the appropriate commands.
  327. Args:
  328. timeout: Maximum time in seconds to wait for homing to complete (default: 15)
  329. """
  330. import threading
  331. # Flag to track if homing completed
  332. homing_complete = threading.Event()
  333. homing_success = False
  334. def home_internal():
  335. nonlocal homing_success
  336. try:
  337. if state.homing:
  338. logger.info("Using sensorless homing")
  339. state.conn.send("$H\n")
  340. state.conn.send("G1 Y0 F100\n")
  341. else:
  342. homing_speed = 400
  343. if state.table_type == 'dune_weaver_mini':
  344. homing_speed = 120
  345. logger.info("Sensorless homing not supported. Using crash homing")
  346. logger.info(f"Homing with speed {homing_speed}")
  347. if state.gear_ratio == 6.25:
  348. result = send_grbl_coordinates(0, - 30, homing_speed, home=True)
  349. if result == False:
  350. logger.error("Homing failed - send_grbl_coordinates returned False")
  351. homing_complete.set()
  352. return
  353. state.machine_y -= 30
  354. else:
  355. result = send_grbl_coordinates(0, -22, homing_speed, home=True)
  356. if result == False:
  357. logger.error("Homing failed - send_grbl_coordinates returned False")
  358. homing_complete.set()
  359. return
  360. state.machine_y -= 22
  361. state.current_theta = state.current_rho = 0
  362. homing_success = True
  363. homing_complete.set()
  364. except Exception as e:
  365. logger.error(f"Error during homing: {e}")
  366. homing_complete.set()
  367. # Start homing in a separate thread
  368. homing_thread = threading.Thread(target=home_internal)
  369. homing_thread.daemon = True
  370. homing_thread.start()
  371. # Wait for homing to complete or timeout
  372. if not homing_complete.wait(timeout):
  373. logger.error(f"Homing timeout after {timeout} seconds")
  374. # Try to stop any ongoing movement
  375. try:
  376. if state.conn and state.conn.is_connected():
  377. state.conn.send("!\n") # Send feed hold
  378. time.sleep(0.1)
  379. state.conn.send("\x18\n") # Send reset
  380. except Exception as e:
  381. logger.error(f"Error stopping movement after timeout: {e}")
  382. return False
  383. if not homing_success:
  384. logger.error("Homing failed")
  385. return False
  386. logger.info("Homing completed successfully")
  387. return True
  388. def check_idle():
  389. """
  390. Continuously check if the device is idle.
  391. """
  392. logger.info("Checking idle")
  393. while True:
  394. response = get_status_response()
  395. if response and "Idle" in response:
  396. logger.info("Device is idle")
  397. update_machine_position()
  398. return True
  399. time.sleep(1)
  400. def get_machine_position(timeout=5):
  401. """
  402. Query the device for its position.
  403. """
  404. start_time = time.time()
  405. while time.time() - start_time < timeout:
  406. try:
  407. state.conn.send('?')
  408. response = state.conn.readline()
  409. logger.debug(f"Raw status response: {response}")
  410. if "MPos" in response:
  411. pos = parse_machine_position(response)
  412. if pos:
  413. machine_x, machine_y = pos
  414. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  415. return machine_x, machine_y
  416. except Exception as e:
  417. logger.error(f"Error getting machine position: {e}")
  418. return
  419. time.sleep(0.1)
  420. logger.warning("Timeout reached waiting for machine position")
  421. return None, None
  422. def update_machine_position():
  423. if (state.conn.is_connected() if state.conn else False):
  424. try:
  425. logger.info('Saving machine position')
  426. state.machine_x, state.machine_y = get_machine_position()
  427. state.save()
  428. logger.info(f'Machine position saved: {state.machine_x}, {state.machine_y}')
  429. except Exception as e:
  430. logger.error(f"Error updating machine position: {e}")
  431. def restart_connection(homing=False):
  432. """
  433. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  434. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  435. The new connection is saved to state.conn.
  436. Returns:
  437. True if the connection was restarted successfully, False otherwise.
  438. """
  439. try:
  440. if (state.conn.is_connected() if state.conn else False):
  441. logger.info("Closing current connection...")
  442. state.conn.close()
  443. except Exception as e:
  444. logger.error(f"Error while closing connection: {e}")
  445. # Clear the connection reference.
  446. state.conn = None
  447. logger.info("Attempting to restart connection...")
  448. try:
  449. connect_device(homing) # This will set state.conn appropriately.
  450. if (state.conn.is_connected() if state.conn else False):
  451. logger.info("Connection restarted successfully.")
  452. return True
  453. else:
  454. logger.error("Failed to restart connection.")
  455. return False
  456. except Exception as e:
  457. logger.error(f"Error restarting connection: {e}")
  458. return False