connection_manager.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. import threading
  2. import time
  3. import logging
  4. import serial
  5. import serial.tools.list_ports
  6. import websocket
  7. from dune_weaver_flask.modules.core.state import state
  8. logger = logging.getLogger(__name__)
  9. IGNORE_PORTS = ['/dev/cu.debug-console', '/dev/cu.Bluetooth-Incoming-Port']
  10. ###############################################################################
  11. # Connection Abstraction
  12. ###############################################################################
  13. class BaseConnection:
  14. """Abstract base class for a connection."""
  15. def send(self, data: str) -> None:
  16. raise NotImplementedError
  17. def flush(self) -> None:
  18. raise NotImplementedError
  19. def readline(self) -> str:
  20. raise NotImplementedError
  21. def in_waiting(self) -> int:
  22. raise NotImplementedError
  23. def is_connected(self) -> bool:
  24. raise NotImplementedError
  25. def close(self) -> None:
  26. raise NotImplementedError
  27. ###############################################################################
  28. # Serial Connection Implementation
  29. ###############################################################################
  30. class SerialConnection(BaseConnection):
  31. def __init__(self, port: str, baudrate: int = 115200, timeout: int = 2):
  32. self.port = port
  33. self.baudrate = baudrate
  34. self.timeout = timeout
  35. self.lock = threading.RLock()
  36. logger.info(f'Connecting to Serial port {port}')
  37. self.ser = serial.Serial(port, baudrate, timeout=timeout)
  38. state.port = port
  39. logger.info(f'Connected to Serial port {port}')
  40. def send(self, data: str) -> None:
  41. with self.lock:
  42. self.ser.write(data.encode())
  43. self.ser.flush()
  44. def flush(self) -> None:
  45. with self.lock:
  46. self.ser.flush()
  47. def readline(self) -> str:
  48. with self.lock:
  49. return self.ser.readline().decode().strip()
  50. def in_waiting(self) -> int:
  51. with self.lock:
  52. return self.ser.in_waiting
  53. def is_connected(self) -> bool:
  54. return self.ser is not None and self.ser.is_open
  55. def close(self) -> None:
  56. with self.lock:
  57. if self.ser.is_open:
  58. self.ser.close()
  59. ###############################################################################
  60. # WebSocket Connection Implementation
  61. ###############################################################################
  62. class WebSocketConnection(BaseConnection):
  63. def __init__(self, url: str, timeout: int = 5):
  64. self.url = url
  65. self.timeout = timeout
  66. self.lock = threading.RLock()
  67. self.ws = None
  68. self.connect()
  69. def connect(self):
  70. logger.info(f'Connecting to Websocket {self.url}')
  71. self.ws = websocket.create_connection(self.url, timeout=self.timeout)
  72. state.port = self.url
  73. logger.info(f'Connected to Websocket {self.url}')
  74. def send(self, data: str) -> None:
  75. with self.lock:
  76. self.ws.send(data)
  77. def flush(self) -> None:
  78. # WebSocket sends immediately; nothing to flush.
  79. pass
  80. def readline(self) -> str:
  81. with self.lock:
  82. data = self.ws.recv()
  83. # Decode bytes to string if necessary
  84. if isinstance(data, bytes):
  85. data = data.decode('utf-8')
  86. return data.strip()
  87. def in_waiting(self) -> int:
  88. return 0 # Not applicable for WebSocket
  89. def is_connected(self) -> bool:
  90. return self.ws is not None
  91. def close(self) -> None:
  92. with self.lock:
  93. if self.ws:
  94. self.ws.close()
  95. def list_serial_ports():
  96. """Return a list of available serial ports."""
  97. ports = serial.tools.list_ports.comports()
  98. available_ports = [port.device for port in ports if port.device not in IGNORE_PORTS]
  99. logger.debug(f"Available serial ports: {available_ports}")
  100. return available_ports
  101. def device_init(home=True):
  102. try:
  103. if get_machine_steps():
  104. 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}")
  105. except:
  106. logger.fatal("Not GRBL firmware")
  107. pass
  108. machine_x, machine_y = get_machine_position()
  109. if machine_x != state.machine_x or machine_y != state.machine_y:
  110. logger.info(f'x, y; {machine_x}, {machine_y}')
  111. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  112. if home:
  113. home()
  114. else:
  115. logger.info('Machine position known, skipping home')
  116. logger.info(f'Theta: {state.current_theta}, rho: {state.current_rho}')
  117. logger.info(f'x, y; {machine_x}, {machine_y}')
  118. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  119. time.sleep(2) # Allow time for the connection to establish
  120. try:
  121. if get_machine_steps():
  122. logger.info(f"x_steps_per_mm: {state.x_steps_per_mm}, x_steps_per_mm: {state.y_steps_per_mm}, gear_ratio: {state.gear_ratio}")
  123. return True
  124. except:
  125. logger.fatal("Not GRBL firmware")
  126. return False
  127. def connect_device(home=True):
  128. ports = list_serial_ports()
  129. if not ports:
  130. state.conn = WebSocketConnection('ws://fluidnc.local:81')
  131. else:
  132. state.conn = SerialConnection(ports[0])
  133. if state.conn.is_connected():
  134. device_init(home)
  135. def get_status_response() -> str:
  136. """
  137. Send a status query ('?') and return the response if available.
  138. """
  139. while True:
  140. try:
  141. state.conn.send('?')
  142. response = state.conn.readline()
  143. if "MPos" in response:
  144. logger.debug(f"Status response: {response}")
  145. return response
  146. except Exception as e:
  147. logger.error(f"Error getting status response: {e}")
  148. return False
  149. time.sleep(1)
  150. def parse_machine_position(response: str):
  151. """
  152. Parse the work position (MPos) from a status response.
  153. Expected format: "<...|MPos:-994.869,-321.861,0.000|...>"
  154. Returns a tuple (work_x, work_y) if found, else None.
  155. """
  156. if "MPos:" not in response:
  157. return None
  158. try:
  159. wpos_section = next((part for part in response.split("|") if part.startswith("MPos:")), None)
  160. if wpos_section:
  161. wpos_str = wpos_section.split(":", 1)[1]
  162. wpos_values = wpos_str.split(",")
  163. work_x = float(wpos_values[0])
  164. work_y = float(wpos_values[1])
  165. return work_x, work_y
  166. except Exception as e:
  167. logger.error(f"Error parsing work position: {e}")
  168. return None
  169. def send_grbl_coordinates(x, y, speed=600, timeout=2, home=False):
  170. """
  171. Send a G-code command to FluidNC and wait for an 'ok' response.
  172. """
  173. logger.debug(f"Sending G-code: X{x} Y{y} at F{speed}")
  174. while True:
  175. try:
  176. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  177. state.conn.send(gcode + "\n")
  178. logger.debug(f"Sent command: {gcode}")
  179. start_time = time.time()
  180. while time.time() - start_time < timeout:
  181. response = state.conn.readline()
  182. logger.debug(f"Response: {response}")
  183. if response.lower() == "ok":
  184. logger.debug("Command execution confirmed.")
  185. return
  186. except Exception as e:
  187. logger.warning(f"No 'ok' received for X{x} Y{y}, speed {speed}. Retrying in 1s...")
  188. time.sleep(0.1)
  189. def get_machine_steps(timeout=10):
  190. """
  191. Send "$$" to retrieve machine settings and update state.
  192. Returns True if the expected configuration is received, or False if it times out.
  193. """
  194. if not state.conn.is_connected():
  195. logger.error("Connection is not established.")
  196. return False
  197. # Send the command once
  198. state.conn.send("$$\n")
  199. start_time = time.time()
  200. x_steps_per_mm = y_steps_per_mm = gear_ratio = None
  201. while time.time() - start_time < timeout:
  202. try:
  203. # Attempt to read a line from the connection
  204. response = state.conn.readline()
  205. logger.debug(response)
  206. for line in response.splitlines():
  207. logger.debug(f"Config response: {line}")
  208. if line.startswith("$100="):
  209. x_steps_per_mm = float(line.split("=")[1])
  210. state.x_steps_per_mm = x_steps_per_mm
  211. elif line.startswith("$101="):
  212. y_steps_per_mm = float(line.split("=")[1])
  213. state.y_steps_per_mm = y_steps_per_mm
  214. elif line.startswith("$131="):
  215. gear_ratio = float(line.split("=")[1])
  216. state.gear_ratio = gear_ratio
  217. # If all parameters are received, exit early
  218. if x_steps_per_mm is not None and y_steps_per_mm is not None and gear_ratio is not None:
  219. return True
  220. except Exception as e:
  221. logger.error(f"Error getting machine steps: {e}")
  222. return False
  223. # Use a smaller sleep to poll more frequently
  224. time.sleep(0.1)
  225. logger.error("Timeout reached waiting for machine steps")
  226. return False
  227. def home():
  228. """
  229. Perform homing by checking device configuration and sending the appropriate commands.
  230. """
  231. try:
  232. state.conn.send("$config\n")
  233. response = state.conn.readline().strip().lower()
  234. logger.debug(f"Config response: {response}")
  235. except Exception as e:
  236. logger.error(f"Error during homing config: {e}")
  237. response = ""
  238. if "sensorless" in response:
  239. logger.info("Using sensorless homing")
  240. state.conn.send("$H\n")
  241. state.conn.send("G1 Y0 F100\n")
  242. else:
  243. logger.info("Sensorless homing not supported. Using crash homing")
  244. logger.info(f"Homing with speed 300")
  245. send_grbl_coordinates(0, -22, 300, home=True)
  246. state.current_theta = state.current_rho = 0
  247. update_machine_position()
  248. state.save()
  249. def check_idle():
  250. """
  251. Continuously check if the device is idle.
  252. """
  253. logger.info("Checking idle")
  254. while True:
  255. response = get_status_response()
  256. if response and "Idle" in response:
  257. logger.info("Device is idle")
  258. update_machine_position()
  259. return True
  260. time.sleep(1)
  261. def get_machine_position(timeout=5):
  262. """
  263. Query the device for its position.
  264. """
  265. start_time = time.time()
  266. while time.time() - start_time < timeout:
  267. try:
  268. state.conn.send('?')
  269. response = state.conn.readline()
  270. logger.debug(f"Raw status response: {response}")
  271. if "MPos" in response:
  272. pos = parse_machine_position(response)
  273. if pos:
  274. machine_x, machine_y = pos
  275. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  276. return machine_x, machine_y
  277. except Exception as e:
  278. logger.error(f"Error getting machine position: {e}")
  279. time.sleep(0.1)
  280. logger.warning("Timeout reached waiting for machine position")
  281. return None, None
  282. def update_machine_position():
  283. state.machine_x, state.machine_y = get_machine_position()
  284. state.save()
  285. def restart_connection(home=False):
  286. """
  287. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  288. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  289. The new connection is saved to state.conn.
  290. Returns:
  291. True if the connection was restarted successfully, False otherwise.
  292. """
  293. try:
  294. if state.conn and state.conn.is_connected():
  295. logger.info("Closing current connection...")
  296. state.conn.close()
  297. except Exception as e:
  298. logger.error(f"Error while closing connection: {e}")
  299. # Clear the connection reference.
  300. state.conn = None
  301. logger.info("Attempting to restart connection...")
  302. try:
  303. connect_device(home=False) # This will set state.conn appropriately.
  304. if state.conn and state.conn.is_connected():
  305. logger.info("Connection restarted successfully.")
  306. return True
  307. else:
  308. logger.error("Failed to restart connection.")
  309. return False
  310. except Exception as e:
  311. logger.error(f"Error restarting connection: {e}")
  312. return False