connection_manager.py 11 KB

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