connection_manager.py 13 KB

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