connection_manager.py 17 KB

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