connection_manager.py 19 KB

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