connection_manager.py 13 KB

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