serial_manager.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. import serial
  2. import serial.tools.list_ports
  3. import threading
  4. import time
  5. import logging
  6. from dune_weaver_flask.modules.core.state import state
  7. logger = logging.getLogger(__name__)
  8. # Global variables
  9. ser = None
  10. ser_port = None
  11. serial_lock = threading.RLock()
  12. IGNORE_PORTS = ['/dev/cu.debug-console', '/dev/cu.Bluetooth-Incoming-Port']
  13. # Device information
  14. arduino_table_name = None
  15. arduino_driver_type = 'Unknown'
  16. firmware_version = 'Unknown'
  17. def list_serial_ports():
  18. """Return a list of available serial ports."""
  19. ports = serial.tools.list_ports.comports()
  20. available_ports = [port.device for port in ports if port.device not in IGNORE_PORTS]
  21. logger.debug(f"Available serial ports: {available_ports}")
  22. return available_ports
  23. def get_machine_steps():
  24. """
  25. Send "$$" to the serial port to retrieve machine settings and return values for $100 and $101.
  26. Returns two floats: x_steps_per_mm and y_steps_per_mm, or (None, None) if not found.
  27. """
  28. if not is_connected():
  29. logger.error("Serial connection is not established.")
  30. return None, None
  31. while True:
  32. with serial_lock:
  33. ser.write("$$\n".encode())
  34. ser.flush()
  35. time.sleep(1) # Allow time for response
  36. x_steps_per_mm = None
  37. y_steps_per_mm = None
  38. gear_ratio = None
  39. while ser.in_waiting > 0:
  40. line = ser.readline().decode().strip()
  41. logger.debug(f"Config response: {line}")
  42. if line.startswith("$100="):
  43. x_steps_per_mm = float(line.split("=")[1])
  44. state.x_steps_per_mm = x_steps_per_mm
  45. elif line.startswith("$101="):
  46. y_steps_per_mm = float(line.split("=")[1])
  47. state.y_steps_per_mm = y_steps_per_mm
  48. elif line.startswith("$131="):
  49. gear_ratio = float(line.split("=")[1])
  50. state.gear_ratio = gear_ratio
  51. if x_steps_per_mm is not None and y_steps_per_mm is not None and gear_ratio is not None:
  52. return True
  53. def device_init():
  54. try:
  55. if get_machine_steps():
  56. 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}")
  57. except:
  58. logger.fatal("Not GRBL firmware")
  59. pass
  60. machine_x, machine_y = get_machine_position()
  61. if not machine_x or not machine_y or machine_x != state.machine_x or machine_y != state.machine_y:
  62. logger.info(f'x, y; {machine_x}, {machine_y}')
  63. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  64. home()
  65. else:
  66. logger.info('Machine position known, skipping home')
  67. logger.info(f'Theta: {state.current_theta}, rho: {state.current_rho}')
  68. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  69. time.sleep(2) # Allow time for the connection to establish
  70. try:
  71. if get_machine_steps():
  72. 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}")
  73. return True
  74. except:
  75. logger.info("Not GRBL firmware")
  76. return False
  77. def connect_to_serial(port=None, baudrate=115200):
  78. """Automatically connect to the first available serial port or a specified port with a timeout."""
  79. global ser, ser_port, arduino_table_name, arduino_driver_type, firmware_version
  80. timeout = 5 # Timeout in seconds
  81. start_time = time.time()
  82. while time.time() - start_time < timeout:
  83. try:
  84. if port is None:
  85. ports = list_serial_ports()
  86. if not ports:
  87. logger.warning("No serial port connected")
  88. time.sleep(1) # Wait before retrying
  89. continue # Retry connecting
  90. port = ports[0] # Auto-select the first available port
  91. with serial_lock:
  92. if ser and ser.is_open:
  93. ser.close()
  94. ser = serial.Serial(port, baudrate, timeout=2) # Timeout for individual serial operations
  95. ser_port = port
  96. # Check if connection is established by trying a quick command
  97. try:
  98. ser.write(b"?\r") # Example GRBL command
  99. response = ser.readline().decode('utf-8').strip()
  100. if response: # Check if we get any response
  101. logger.info(f"Connected to serial port: {port}")
  102. device_init()
  103. break # Exit the loop, connection successful
  104. else:
  105. logger.warning("No response from serial port. Retrying...")
  106. ser.close() # Close the port before retrying
  107. time.sleep(1) # Wait before retrying
  108. continue
  109. except serial.SerialException as e:
  110. logger.warning(f"Serial exception during test command: {e}. Retrying...")
  111. ser.close()
  112. time.sleep(1)
  113. continue
  114. except Exception as e:
  115. logger.exception(f"Unexpected error during connection test: {e}")
  116. ser.close()
  117. time.sleep(1)
  118. continue
  119. except serial.SerialException as e:
  120. logger.error(f"Failed to connect to serial port {port}: {e}")
  121. ser_port = None
  122. time.sleep(1) # Wait before retrying
  123. continue # Retry connecting
  124. else: # If the loop finishes without breaking (timeout)
  125. logger.error(f"Timeout reached. Could not connect to a serial port after {timeout} seconds.")
  126. return False
  127. def disconnect_serial():
  128. """Disconnect the current serial connection."""
  129. global ser, ser_port
  130. if ser and ser.is_open:
  131. logger.info("Disconnecting serial connection")
  132. ser.close()
  133. ser = None
  134. ser_port = None
  135. def restart_serial(port, baudrate=115200):
  136. """Restart the serial connection."""
  137. logger.info(f"Restarting serial connection on port {port}")
  138. disconnect_serial()
  139. return connect_to_serial(port, baudrate)
  140. def is_connected():
  141. """Check if serial connection is established and open."""
  142. return ser is not None and ser.is_open
  143. def get_port():
  144. """Get the current serial port."""
  145. return ser_port
  146. def get_status_response():
  147. """
  148. Send a status query ('?') and return the response string if available.
  149. This helper centralizes the query logic used throughout the module.
  150. """
  151. while True:
  152. with serial_lock:
  153. ser.write('?'.encode())
  154. ser.flush()
  155. while ser.in_waiting > 0:
  156. response = ser.readline().decode().strip()
  157. if "MPos" in response:
  158. logger.debug(f"Status response: {response}")
  159. return response
  160. time.sleep(1)
  161. def parse_machine_position(response):
  162. """
  163. Parse the work position (MPos) from a status response.
  164. Expected format: "<...|MPos:-994.869,-321.861,0.000|...>"
  165. Returns a tuple (work_x, work_y) if found, else None.
  166. """
  167. if "MPos:" not in response:
  168. return None
  169. try:
  170. wpos_section = next((part for part in response.split("|") if part.startswith("MPos:")), None)
  171. if wpos_section:
  172. wpos_str = wpos_section.split(":", 1)[1]
  173. wpos_values = wpos_str.split(",")
  174. work_x = float(wpos_values[0])
  175. work_y = float(wpos_values[1])
  176. return work_x, work_y
  177. except Exception as e:
  178. logger.error(f"Error parsing work position: {e}")
  179. return None
  180. def parse_buffer_info(response):
  181. """
  182. Parse the planner and serial buffer info from a status response.
  183. Expected format: "<...|Bf:15,128|...>"
  184. Returns a dictionary with keys 'planner_buffer' and 'serial_buffer' if found, else None.
  185. """
  186. if "|Bf:" in response:
  187. try:
  188. buffer_section = response.split("|Bf:")[1].split("|")[0]
  189. planner_buffer, serial_buffer = map(int, buffer_section.split(","))
  190. return {"planner_buffer": planner_buffer, "serial_buffer": serial_buffer}
  191. except ValueError:
  192. logger.warning("Failed to parse buffer info from response")
  193. return None
  194. def send_grbl_coordinates(x, y, speed=600, timeout=2, home=False):
  195. """
  196. Send a G-code command to FluidNC and wait up to timeout seconds for an 'ok' response.
  197. If no 'ok' is received, retry every retry_interval seconds until successful.
  198. """
  199. logger.debug(f"Sending G-code: X{x} Y{y} at F{speed}")
  200. while True:
  201. with serial_lock:
  202. if home:
  203. gcode = f"$J=G91 Y{y} F{speed}"
  204. else:
  205. gcode = f"G1 X{x} Y{y} F{speed}"
  206. ser.write(f"{gcode}\n".encode())
  207. ser.flush()
  208. logger.debug(f"Sent command: {gcode}")
  209. start_time = time.time()
  210. while time.time() - start_time < timeout:
  211. if ser.in_waiting > 0:
  212. response = ser.readline().decode().strip()
  213. logger.debug(f"Response: {response}")
  214. if response.lower() == "ok":
  215. logger.debug("Command execution confirmed.")
  216. return # Exit function when 'ok' is received
  217. logger.warning(f"No 'ok' received for X{x} Y{y}. Retrying in 1s...")
  218. time.sleep(1)
  219. def home(retry = 0):
  220. logger.info(f"Homing with speed {state.speed}")
  221. # Check config for sensorless homing
  222. with serial_lock:
  223. ser.flush()
  224. ser.write("$config\n".encode())
  225. response = ser.readline().decode().strip().lower()
  226. logger.debug(f"Config response: {response}")
  227. if "sensorless" in response:
  228. logger.info("Using sensorless homing")
  229. with serial_lock:
  230. ser.write("$H\n".encode())
  231. ser.write("G1 Y0 F100\n".encode())
  232. ser.flush()
  233. # we check that we actually got a valid response, if not, we try again a couple of times
  234. elif "filename" in response:
  235. logger.info("Using crash homing")
  236. send_grbl_coordinates(0, -110/5, state.speed, home=True)
  237. # error:3 means that the controller is running grbl, which doesn't support $config
  238. # we just use crash homing for grbl
  239. elif "error:3" in response:
  240. logger.info("Grbl detected, Using crash homing")
  241. send_grbl_coordinates(0, -110/5, state.speed, home=True)
  242. else:
  243. # we wait a bit and cal again increasing retry times
  244. # if we are over the third retry, we give up
  245. if retry < 3:
  246. time.sleep(1)
  247. home(retry+1)
  248. return
  249. else:
  250. # after 3 retries we're still not getting a good response
  251. # raise an exception
  252. raise Exception("Couldn't get a valid response for homing after 3 retries")
  253. state.current_theta = state.current_rho = 0
  254. update_machine_position()
  255. def check_idle():
  256. """
  257. Continuously check if the machine is in the 'Idle' state.
  258. """
  259. logger.info("Checking idle")
  260. while True:
  261. response = get_status_response()
  262. if response and "Idle" in response:
  263. logger.info("Table is idle")
  264. update_machine_position()
  265. return True # Exit once 'Idle' is confirmed
  266. time.sleep(1)
  267. def get_machine_position(timeout=3):
  268. """
  269. Send status queries for up to `timeout` seconds to obtain a valid machine (work) position.
  270. Returns a tuple (machine_x, machine_y) if a valid response is received,
  271. otherwise returns (None, None) after timeout.
  272. """
  273. start_time = time.time()
  274. while time.time() - start_time < timeout:
  275. with serial_lock:
  276. ser.write('?'.encode())
  277. ser.flush()
  278. # Check if there is any response available
  279. while ser.in_waiting > 0:
  280. response = ser.readline().decode().strip()
  281. logger.debug(f"Raw status response: {response}")
  282. if "MPos" in response:
  283. pos = parse_machine_position(response)
  284. if pos:
  285. machine_x, machine_y = pos
  286. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  287. return machine_x, machine_y
  288. # Short sleep before trying again
  289. time.sleep(0.1)
  290. logger.warning("Timeout reached waiting for machine position")
  291. return None, None
  292. def update_machine_position():
  293. state.machine_x, state.machine_y = get_machine_position()
  294. state.save()