connection_manager.py 14 KB

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