connection_manager.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. 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. If no response after 5 seconds total, sets state to stop and disconnects.
  183. """
  184. logger.debug(f"Sending G-code: X{x} Y{y} at F{speed}")
  185. # Track overall attempt time
  186. overall_start_time = time.time()
  187. max_total_attempt_time = 10 # Maximum total seconds to try
  188. while time.time() - overall_start_time < max_total_attempt_time:
  189. try:
  190. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  191. state.conn.send(gcode + "\n")
  192. logger.debug(f"Sent command: {gcode}")
  193. start_time = time.time()
  194. while time.time() - start_time < timeout and time.time() - overall_start_time < max_total_attempt_time:
  195. response = state.conn.readline()
  196. logger.debug(f"Response: {response}")
  197. if response.lower() == "ok":
  198. logger.debug("Command execution confirmed.")
  199. return
  200. except Exception as e:
  201. logger.warning(f"Error sending command: {str(e)}")
  202. # Check if we've exceeded our overall timeout
  203. if time.time() - overall_start_time >= max_total_attempt_time:
  204. break
  205. logger.warning(f"No 'ok' received for X{x} Y{y}, speed {speed}. Retrying...")
  206. time.sleep(0.1)
  207. # If we reach here, the 5-second timeout has occurred
  208. logger.error(f"Failed to receive 'ok' response after {max_total_attempt_time} seconds. Stopping and disconnecting.")
  209. # Set state to stop
  210. state.stop_requested = True
  211. # Set connection status to disconnected
  212. state.conn = None
  213. # Update the state connection status
  214. state.is_connected = False
  215. logger.info("Connection marked as disconnected due to timeout")
  216. return False
  217. def get_machine_steps(timeout=10):
  218. """
  219. Get machine steps/mm from the GRBL controller.
  220. Returns True if successful, False otherwise.
  221. """
  222. if not state.conn or not state.conn.is_connected():
  223. logger.error("Cannot get machine steps: No connection available")
  224. return False
  225. x_steps_per_mm = None
  226. y_steps_per_mm = None
  227. gear_ratio = None
  228. start_time = time.time()
  229. # Clear any pending data in the buffer
  230. try:
  231. while state.conn.in_waiting() > 0:
  232. state.conn.readline()
  233. except Exception as e:
  234. logger.warning(f"Error clearing buffer: {e}")
  235. # Send the command to request all settings
  236. try:
  237. logger.info("Requesting GRBL settings with $$ command")
  238. state.conn.send("$$\n")
  239. time.sleep(0.5) # Give GRBL a moment to process and respond
  240. except Exception as e:
  241. logger.error(f"Error sending $$ command: {e}")
  242. return False
  243. # Wait for and process responses
  244. settings_complete = False
  245. while time.time() - start_time < timeout and not settings_complete:
  246. try:
  247. # Attempt to read a line from the connection
  248. if state.conn.in_waiting() > 0:
  249. response = state.conn.readline()
  250. logger.debug(f"Raw response: {response}")
  251. # Process the line
  252. if response.strip(): # Only process non-empty lines
  253. for line in response.splitlines():
  254. line = line.strip()
  255. logger.debug(f"Config response: {line}")
  256. if line.startswith("$100="):
  257. x_steps_per_mm = float(line.split("=")[1])
  258. state.x_steps_per_mm = x_steps_per_mm
  259. logger.info(f"X steps per mm: {x_steps_per_mm}")
  260. elif line.startswith("$101="):
  261. y_steps_per_mm = float(line.split("=")[1])
  262. state.y_steps_per_mm = y_steps_per_mm
  263. logger.info(f"Y steps per mm: {y_steps_per_mm}")
  264. elif line.startswith("$131="):
  265. gear_ratio = float(line.split("=")[1])
  266. state.gear_ratio = gear_ratio
  267. logger.info(f"Gear ratio: {gear_ratio}")
  268. elif line.startswith("$22="):
  269. # $22 reports if the homing cycle is enabled
  270. # returns 0 if disabled, 1 if enabled
  271. homing = int(line.split('=')[1])
  272. state.homing = homing
  273. logger.info(f"Homing enabled: {homing}")
  274. # Check if we've received all the settings we need
  275. if x_steps_per_mm is not None and y_steps_per_mm is not None and gear_ratio is not None:
  276. settings_complete = True
  277. else:
  278. # No data waiting, small sleep to prevent CPU thrashing
  279. time.sleep(0.1)
  280. # If it's taking too long, try sending the command again after 3 seconds
  281. elapsed = time.time() - start_time
  282. if elapsed > 3 and elapsed < 4:
  283. logger.warning("No response yet, sending $$ command again")
  284. state.conn.send("$$\n")
  285. except Exception as e:
  286. logger.error(f"Error getting machine steps: {e}")
  287. time.sleep(0.5)
  288. # Process results and determine table type
  289. if settings_complete:
  290. if y_steps_per_mm == 180:
  291. state.table_type = 'dune_weaver_mini'
  292. elif y_steps_per_mm == 320:
  293. state.table_type = 'dune_weaver_pro'
  294. elif y_steps_per_mm == 287:
  295. state.table_type = 'dune_weaver'
  296. else:
  297. state.table_type = None
  298. logger.warning(f"Unknown table type with Y steps/mm: {y_steps_per_mm}")
  299. logger.info(f"Machine type detected: {state.table_type}")
  300. return True
  301. else:
  302. missing = []
  303. if x_steps_per_mm is None: missing.append("X steps/mm")
  304. if y_steps_per_mm is None: missing.append("Y steps/mm")
  305. if gear_ratio is None: missing.append("gear ratio")
  306. logger.error(f"Failed to get all machine parameters after {timeout}s. Missing: {', '.join(missing)}")
  307. return False
  308. def home():
  309. """
  310. Perform homing by checking device configuration and sending the appropriate commands.
  311. """
  312. if state.homing:
  313. logger.info("Using sensorless homing")
  314. state.conn.send("$H\n")
  315. state.conn.send("G1 Y0 F100\n")
  316. else:
  317. homing_speed = 400
  318. if state.table_type == 'dune_weaver_mini':
  319. homing_speed = 120
  320. logger.info("Sensorless homing not supported. Using crash homing")
  321. logger.info(f"Homing with speed {homing_speed}")
  322. if state.gear_ratio == 6.25:
  323. send_grbl_coordinates(0, - 30, homing_speed, home=True)
  324. state.machine_y -= 30
  325. else:
  326. send_grbl_coordinates(0, -22, homing_speed, home=True)
  327. state.machine_y -= 22
  328. state.current_theta = state.current_rho = 0
  329. def check_idle():
  330. """
  331. Continuously check if the device is idle.
  332. """
  333. logger.info("Checking idle")
  334. while True:
  335. response = get_status_response()
  336. if response and "Idle" in response:
  337. logger.info("Device is idle")
  338. update_machine_position()
  339. return True
  340. time.sleep(1)
  341. def get_machine_position(timeout=5):
  342. """
  343. Query the device for its position.
  344. """
  345. start_time = time.time()
  346. while time.time() - start_time < timeout:
  347. try:
  348. state.conn.send('?')
  349. response = state.conn.readline()
  350. logger.debug(f"Raw status response: {response}")
  351. if "MPos" in response:
  352. pos = parse_machine_position(response)
  353. if pos:
  354. machine_x, machine_y = pos
  355. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  356. return machine_x, machine_y
  357. except Exception as e:
  358. logger.error(f"Error getting machine position: {e}")
  359. return
  360. time.sleep(0.1)
  361. logger.warning("Timeout reached waiting for machine position")
  362. return None, None
  363. def update_machine_position():
  364. if (state.conn.is_connected() if state.conn else False):
  365. try:
  366. logger.info('Saving machine position')
  367. state.machine_x, state.machine_y = get_machine_position()
  368. state.save()
  369. logger.info(f'Machine position saved: {state.machine_x}, {state.machine_y}')
  370. except Exception as e:
  371. logger.error(f"Error updating machine position: {e}")
  372. def restart_connection(homing=False):
  373. """
  374. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  375. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  376. The new connection is saved to state.conn.
  377. Returns:
  378. True if the connection was restarted successfully, False otherwise.
  379. """
  380. try:
  381. if (state.conn.is_connected() if state.conn else False):
  382. logger.info("Closing current connection...")
  383. state.conn.close()
  384. except Exception as e:
  385. logger.error(f"Error while closing connection: {e}")
  386. # Clear the connection reference.
  387. state.conn = None
  388. logger.info("Attempting to restart connection...")
  389. try:
  390. connect_device(homing) # This will set state.conn appropriately.
  391. if (state.conn.is_connected() if state.conn else False):
  392. logger.info("Connection restarted successfully.")
  393. return True
  394. else:
  395. logger.error("Failed to restart connection.")
  396. return False
  397. except Exception as e:
  398. logger.error(f"Error restarting connection: {e}")
  399. return False