connection_manager.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. from modules.led.led_controller import effect_loading, effect_idle, effect_connected, LEDController
  10. logger = logging.getLogger(__name__)
  11. IGNORE_PORTS = ['/dev/cu.debug-console', '/dev/cu.Bluetooth-Incoming-Port']
  12. ###############################################################################
  13. # Connection Abstraction
  14. ###############################################################################
  15. class BaseConnection:
  16. """Abstract base class for a connection."""
  17. def send(self, data: str) -> None:
  18. raise NotImplementedError
  19. def flush(self) -> None:
  20. raise NotImplementedError
  21. def readline(self) -> str:
  22. raise NotImplementedError
  23. def in_waiting(self) -> int:
  24. raise NotImplementedError
  25. def is_connected(self) -> bool:
  26. raise NotImplementedError
  27. def close(self) -> None:
  28. raise NotImplementedError
  29. ###############################################################################
  30. # Serial Connection Implementation
  31. ###############################################################################
  32. class SerialConnection(BaseConnection):
  33. def __init__(self, port: str, baudrate: int = 115200, timeout: int = 2):
  34. self.port = port
  35. self.baudrate = baudrate
  36. self.timeout = timeout
  37. self.lock = threading.RLock()
  38. logger.info(f'Connecting to Serial port {port}')
  39. self.ser = serial.Serial(port, baudrate, timeout=timeout)
  40. state.port = port
  41. logger.info(f'Connected to Serial port {port}')
  42. def send(self, data: str) -> None:
  43. with self.lock:
  44. self.ser.write(data.encode())
  45. self.ser.flush()
  46. def flush(self) -> None:
  47. with self.lock:
  48. self.ser.flush()
  49. def readline(self) -> str:
  50. with self.lock:
  51. return self.ser.readline().decode().strip()
  52. def in_waiting(self) -> int:
  53. with self.lock:
  54. return self.ser.in_waiting
  55. def is_connected(self) -> bool:
  56. return self.ser is not None and self.ser.is_open
  57. def close(self) -> None:
  58. update_machine_position()
  59. with self.lock:
  60. if self.ser.is_open:
  61. self.ser.close()
  62. # Release the lock resources
  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 = None
  103. def list_serial_ports():
  104. """Return a list of available serial ports."""
  105. ports = serial.tools.list_ports.comports()
  106. available_ports = [port.device for port in ports if port.device not in IGNORE_PORTS]
  107. logger.debug(f"Available serial ports: {available_ports}")
  108. return available_ports
  109. def device_init(homing=True):
  110. try:
  111. if get_machine_steps():
  112. 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}")
  113. except:
  114. logger.fatal("Not GRBL firmware")
  115. pass
  116. machine_x, machine_y = get_machine_position()
  117. if machine_x != state.machine_x or machine_y != state.machine_y:
  118. logger.info(f'x, y; {machine_x}, {machine_y}')
  119. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  120. if homing:
  121. home()
  122. else:
  123. logger.info('Machine position known, skipping home')
  124. logger.info(f'Theta: {state.current_theta}, rho: {state.current_rho}')
  125. logger.info(f'x, y; {machine_x}, {machine_y}')
  126. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  127. time.sleep(2) # Allow time for the connection to establish
  128. try:
  129. if get_machine_steps():
  130. 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}")
  131. return True
  132. except:
  133. logger.fatal("Not GRBL firmware")
  134. return False
  135. def connect_device(homing=True):
  136. if state.wled_ip:
  137. state.led_controller = LEDController(state.wled_ip)
  138. effect_loading(state.led_controller)
  139. ports = list_serial_ports()
  140. if state.port and state.port in ports:
  141. state.conn = SerialConnection(state.port)
  142. elif ports:
  143. state.conn = SerialConnection(ports[0])
  144. else:
  145. logger.warning("No serial ports found. Falling back to WebSocket.")
  146. # state.conn = WebSocketConnection('ws://fluidnc.local:81')
  147. return
  148. if (state.conn.is_connected() if state.conn else False):
  149. device_init(homing)
  150. if state.led_controller:
  151. effect_connected(state.led_controller)
  152. def get_status_response() -> str:
  153. """
  154. Send a status query ('?') and return the response if available.
  155. """
  156. while True:
  157. try:
  158. state.conn.send('?')
  159. response = state.conn.readline()
  160. if "MPos" in response:
  161. logger.debug(f"Status response: {response}")
  162. return response
  163. except Exception as e:
  164. logger.error(f"Error getting status response: {e}")
  165. return False
  166. time.sleep(1)
  167. def parse_machine_position(response: str):
  168. """
  169. Parse the work position (MPos) from a status response.
  170. Expected format: "<...|MPos:-994.869,-321.861,0.000|...>"
  171. Returns a tuple (work_x, work_y) if found, else None.
  172. """
  173. if "MPos:" not in response:
  174. return None
  175. try:
  176. wpos_section = next((part for part in response.split("|") if part.startswith("MPos:")), None)
  177. if wpos_section:
  178. wpos_str = wpos_section.split(":", 1)[1]
  179. wpos_values = wpos_str.split(",")
  180. work_x = float(wpos_values[0])
  181. work_y = float(wpos_values[1])
  182. return work_x, work_y
  183. except Exception as e:
  184. logger.error(f"Error parsing work position: {e}")
  185. return None
  186. def send_grbl_coordinates(x, y, speed=600, timeout=2, home=False):
  187. """
  188. Send a G-code command to FluidNC and wait for an 'ok' response.
  189. """
  190. logger.debug(f"Sending G-code: X{x} Y{y} at F{speed}")
  191. while True:
  192. try:
  193. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  194. state.conn.send(gcode + "\n")
  195. logger.debug(f"Sent command: {gcode}")
  196. start_time = time.time()
  197. while time.time() - start_time < timeout:
  198. response = state.conn.readline()
  199. logger.debug(f"Response: {response}")
  200. if response.lower() == "ok":
  201. logger.debug("Command execution confirmed.")
  202. return
  203. except Exception as e:
  204. logger.warning(f"No 'ok' received for X{x} Y{y}, speed {speed}. Retrying in 1s...")
  205. time.sleep(0.1)
  206. def get_machine_steps(timeout=10):
  207. """
  208. Send "$$" to retrieve machine settings and update state.
  209. Returns True if the expected configuration is received, or False if it times out.
  210. """
  211. if not (state.conn.is_connected() if state.conn else False):
  212. logger.error("Connection is not established.")
  213. return False
  214. # Send the command once
  215. state.conn.send("$$\n")
  216. start_time = time.time()
  217. x_steps_per_mm = y_steps_per_mm = gear_ratio = None
  218. while time.time() - start_time < timeout:
  219. try:
  220. # Attempt to read a line from the connection
  221. response = state.conn.readline()
  222. logger.debug(response)
  223. for line in response.splitlines():
  224. logger.debug(f"Config response: {line}")
  225. if line.startswith("$100="):
  226. x_steps_per_mm = float(line.split("=")[1])
  227. state.x_steps_per_mm = x_steps_per_mm
  228. elif line.startswith("$101="):
  229. y_steps_per_mm = float(line.split("=")[1])
  230. state.y_steps_per_mm = y_steps_per_mm
  231. elif line.startswith("$131="):
  232. gear_ratio = float(line.split("=")[1])
  233. state.gear_ratio = gear_ratio
  234. elif line.startswith("$22="):
  235. # $22 reports if the homing cycle is enabled
  236. # returns 0 if disabled, 1 if enabled
  237. homing = int(line.split('=')[1])
  238. state.homing = homing
  239. # If all parameters are received, exit early
  240. if x_steps_per_mm is not None and y_steps_per_mm is not None and gear_ratio is not None:
  241. return True
  242. except Exception as e:
  243. logger.error(f"Error getting machine steps: {e}")
  244. return False
  245. # Use a smaller sleep to poll more frequently
  246. time.sleep(0.1)
  247. logger.error("Timeout reached waiting for machine steps")
  248. return False
  249. def home():
  250. """
  251. Perform homing by checking device configuration and sending the appropriate commands.
  252. """
  253. if state.homing:
  254. logger.info("Using sensorless homing")
  255. state.conn.send("$H\n")
  256. state.conn.send("G1 Y0 F100\n")
  257. else:
  258. logger.info("Sensorless homing not supported. Using crash homing")
  259. logger.info(f"Homing with speed {state.speed}")
  260. if state.gear_ratio == 6.25:
  261. send_grbl_coordinates(0, - 30, state.speed, home=True)
  262. state.machine_y -= 30
  263. else:
  264. send_grbl_coordinates(0, -22, state.speed, home=True)
  265. state.machine_y -= 22
  266. state.current_theta = state.current_rho = 0
  267. def check_idle():
  268. """
  269. Continuously check if the device is idle.
  270. """
  271. logger.info("Checking idle")
  272. while True:
  273. response = get_status_response()
  274. if response and "Idle" in response:
  275. logger.info("Device is idle")
  276. update_machine_position()
  277. return True
  278. time.sleep(1)
  279. def get_machine_position(timeout=5):
  280. """
  281. Query the device for its position.
  282. """
  283. start_time = time.time()
  284. while time.time() - start_time < timeout:
  285. try:
  286. state.conn.send('?')
  287. response = state.conn.readline()
  288. logger.debug(f"Raw status response: {response}")
  289. if "MPos" in response:
  290. pos = parse_machine_position(response)
  291. if pos:
  292. machine_x, machine_y = pos
  293. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  294. return machine_x, machine_y
  295. except Exception as e:
  296. logger.error(f"Error getting machine position: {e}")
  297. return
  298. time.sleep(0.1)
  299. logger.warning("Timeout reached waiting for machine position")
  300. return None, None
  301. def update_machine_position():
  302. if (state.conn.is_connected() if state.conn else False):
  303. logger.info('Saving machine position')
  304. state.machine_x, state.machine_y = get_machine_position()
  305. state.save()
  306. logger.info(f'Machine position saved: {state.machine_x}, {state.machine_y}')
  307. def restart_connection(homing=False):
  308. """
  309. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  310. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  311. The new connection is saved to state.conn.
  312. Returns:
  313. True if the connection was restarted successfully, False otherwise.
  314. """
  315. try:
  316. if (state.conn.is_connected() if state.conn else False):
  317. logger.info("Closing current connection...")
  318. state.conn.close()
  319. except Exception as e:
  320. logger.error(f"Error while closing connection: {e}")
  321. # Clear the connection reference.
  322. state.conn = None
  323. logger.info("Attempting to restart connection...")
  324. try:
  325. connect_device(homing) # This will set state.conn appropriately.
  326. if (state.conn.is_connected() if state.conn else False):
  327. logger.info("Connection restarted successfully.")
  328. return True
  329. else:
  330. logger.error("Failed to restart connection.")
  331. return False
  332. except Exception as e:
  333. logger.error(f"Error restarting connection: {e}")
  334. return False