connection_manager.py 13 KB

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