connection_manager.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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.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 state.port and state.port in ports:
  133. state.conn = SerialConnection(state.port)
  134. elif ports:
  135. state.conn = SerialConnection(ports[0])
  136. else:
  137. logger.warning("No serial ports found. Falling back to WebSocket.")
  138. # state.conn = WebSocketConnection('ws://fluidnc.local:81')
  139. return
  140. if (state.conn.is_connected() if state.conn else False):
  141. device_init(homing)
  142. def get_status_response() -> str:
  143. """
  144. Send a status query ('?') and return the response if available.
  145. """
  146. while True:
  147. try:
  148. state.conn.send('?')
  149. response = state.conn.readline()
  150. if "MPos" in response:
  151. logger.debug(f"Status response: {response}")
  152. return response
  153. except Exception as e:
  154. logger.error(f"Error getting status response: {e}")
  155. return False
  156. time.sleep(1)
  157. def parse_machine_position(response: str):
  158. """
  159. Parse the work position (MPos) from a status response.
  160. Expected format: "<...|MPos:-994.869,-321.861,0.000|...>"
  161. Returns a tuple (work_x, work_y) if found, else None.
  162. """
  163. if "MPos:" not in response:
  164. return None
  165. try:
  166. wpos_section = next((part for part in response.split("|") if part.startswith("MPos:")), None)
  167. if wpos_section:
  168. wpos_str = wpos_section.split(":", 1)[1]
  169. wpos_values = wpos_str.split(",")
  170. work_x = float(wpos_values[0])
  171. work_y = float(wpos_values[1])
  172. return work_x, work_y
  173. except Exception as e:
  174. logger.error(f"Error parsing work position: {e}")
  175. return None
  176. def send_grbl_coordinates(x, y, speed=600, timeout=2, home=False):
  177. """
  178. Send a G-code command to FluidNC and wait for an 'ok' response.
  179. """
  180. logger.debug(f"Sending G-code: X{x} Y{y} at F{speed}")
  181. while True:
  182. try:
  183. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  184. state.conn.send(gcode + "\n")
  185. logger.debug(f"Sent command: {gcode}")
  186. start_time = time.time()
  187. while time.time() - start_time < timeout:
  188. response = state.conn.readline()
  189. logger.debug(f"Response: {response}")
  190. if response.lower() == "ok":
  191. logger.debug("Command execution confirmed.")
  192. return
  193. except Exception as e:
  194. logger.warning(f"No 'ok' received for X{x} Y{y}, speed {speed}. Retrying in 1s...")
  195. time.sleep(0.1)
  196. def get_machine_steps(timeout=10):
  197. """
  198. Send "$$" to retrieve machine settings and update state.
  199. Returns True if the expected configuration is received, or False if it times out.
  200. """
  201. if not (state.conn.is_connected() if state.conn else False):
  202. logger.error("Connection is not established.")
  203. return False
  204. # Send the command once
  205. state.conn.send("$$\n")
  206. start_time = time.time()
  207. x_steps_per_mm = y_steps_per_mm = gear_ratio = None
  208. while time.time() - start_time < timeout:
  209. try:
  210. # Attempt to read a line from the connection
  211. response = state.conn.readline()
  212. logger.debug(response)
  213. for line in response.splitlines():
  214. logger.debug(f"Config response: {line}")
  215. if line.startswith("$100="):
  216. x_steps_per_mm = float(line.split("=")[1])
  217. state.x_steps_per_mm = x_steps_per_mm
  218. elif line.startswith("$101="):
  219. y_steps_per_mm = float(line.split("=")[1])
  220. state.y_steps_per_mm = y_steps_per_mm
  221. elif line.startswith("$131="):
  222. gear_ratio = float(line.split("=")[1])
  223. state.gear_ratio = gear_ratio
  224. elif line.startswith("$22="):
  225. # $22 reports if the homing cycle is enabled
  226. # returns 0 if disabled, 1 if enabled
  227. homing = int(line.split('=')[1])
  228. state.homing = homing
  229. # If all parameters are received, exit early
  230. if x_steps_per_mm is not None and y_steps_per_mm is not None and gear_ratio is not None:
  231. return True
  232. except Exception as e:
  233. logger.error(f"Error getting machine steps: {e}")
  234. return False
  235. # Use a smaller sleep to poll more frequently
  236. time.sleep(0.1)
  237. logger.error("Timeout reached waiting for machine steps")
  238. return False
  239. def home():
  240. """
  241. Perform homing by checking device configuration and sending the appropriate commands.
  242. """
  243. if state.homing:
  244. logger.info("Using sensorless homing")
  245. state.conn.send("$H\n")
  246. state.conn.send("G1 Y0 F100\n")
  247. else:
  248. logger.info("Sensorless homing not supported. Using crash homing")
  249. logger.info(f"Homing with speed {state.speed}")
  250. if state.gear_ratio == 6.25:
  251. send_grbl_coordinates(0, - 30, state.speed, home=True)
  252. state.machine_y -= 30
  253. else:
  254. send_grbl_coordinates(0, -22, state.speed, home=True)
  255. state.machine_y -= 22
  256. state.current_theta = state.current_rho = 0
  257. def check_idle():
  258. """
  259. Continuously check if the device is idle.
  260. """
  261. logger.info("Checking idle")
  262. while True:
  263. response = get_status_response()
  264. if response and "Idle" in response:
  265. logger.info("Device is idle")
  266. update_machine_position()
  267. return True
  268. time.sleep(1)
  269. def get_machine_position(timeout=5):
  270. """
  271. Query the device for its position.
  272. """
  273. start_time = time.time()
  274. while time.time() - start_time < timeout:
  275. try:
  276. state.conn.send('?')
  277. response = state.conn.readline()
  278. logger.debug(f"Raw status response: {response}")
  279. if "MPos" in response:
  280. pos = parse_machine_position(response)
  281. if pos:
  282. machine_x, machine_y = pos
  283. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  284. return machine_x, machine_y
  285. except Exception as e:
  286. logger.error(f"Error getting machine position: {e}")
  287. return
  288. time.sleep(0.1)
  289. logger.warning("Timeout reached waiting for machine position")
  290. return None, None
  291. def update_machine_position():
  292. if (state.conn.is_connected() if state.conn else False):
  293. logger.info('Saving machine position')
  294. state.machine_x, state.machine_y = get_machine_position()
  295. state.save()
  296. logger.info(f'Machine position: {state.machine_x}, {state.machine_y}')
  297. def restart_connection(homing=False):
  298. """
  299. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  300. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  301. The new connection is saved to state.conn.
  302. Returns:
  303. True if the connection was restarted successfully, False otherwise.
  304. """
  305. try:
  306. if (state.conn.is_connected() if state.conn else False):
  307. logger.info("Closing current connection...")
  308. state.conn.close()
  309. except Exception as e:
  310. logger.error(f"Error while closing connection: {e}")
  311. # Clear the connection reference.
  312. state.conn = None
  313. logger.info("Attempting to restart connection...")
  314. try:
  315. connect_device(homing) # This will set state.conn appropriately.
  316. if (state.conn.is_connected() if state.conn else False):
  317. logger.info("Connection restarted successfully.")
  318. return True
  319. else:
  320. logger.error("Failed to restart connection.")
  321. return False
  322. except Exception as e:
  323. logger.error(f"Error restarting connection: {e}")
  324. return False