connection_manager.py 14 KB

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