serial_manager.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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 connect_to_serial(port=None, baudrate=115200):
  54. """Automatically connect to the first available serial port or a specified port."""
  55. global ser, ser_port, arduino_table_name, arduino_driver_type, firmware_version
  56. try:
  57. if port is None:
  58. ports = list_serial_ports()
  59. if not ports:
  60. logger.warning("No serial port connected")
  61. return False
  62. port = ports[0] # Auto-select the first available port
  63. with serial_lock:
  64. if ser and ser.is_open:
  65. ser.close()
  66. ser = serial.Serial(port, baudrate, timeout=2)
  67. ser_port = port
  68. try:
  69. if get_machine_steps():
  70. 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}")
  71. except:
  72. logger.fatal("Not GRBL firmware")
  73. pass
  74. machine_x, machine_y = get_machine_position()
  75. if not machine_x or not machine_y or machine_x != state.machine_x or machine_y != state.machine_y:
  76. logger.info(f'x, y; {machine_x}, {machine_y}')
  77. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  78. home()
  79. else:
  80. logger.info('Machine position known, skipping home')
  81. logger.info(f'Theta: {state.current_theta}, rho: {state.current_rho}')
  82. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  83. logger.info(f"Connected to serial port: {port}")
  84. time.sleep(2) # Allow time for the connection to establish
  85. try:
  86. if get_machine_steps():
  87. 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}")
  88. return True
  89. except:
  90. logger.info("Not GRBL firmware")
  91. return False
  92. except serial.SerialException as e:
  93. logger.error(f"Failed to connect to serial port {port}: {e}")
  94. ser_port = None
  95. logger.error("Max retries reached. Could not connect to a serial port.")
  96. return False
  97. def disconnect_serial():
  98. """Disconnect the current serial connection."""
  99. global ser, ser_port
  100. if ser and ser.is_open:
  101. logger.info("Disconnecting serial connection")
  102. ser.close()
  103. ser = None
  104. ser_port = None
  105. def restart_serial(port, baudrate=115200):
  106. """Restart the serial connection."""
  107. logger.info(f"Restarting serial connection on port {port}")
  108. disconnect_serial()
  109. return connect_to_serial(port, baudrate)
  110. def is_connected():
  111. """Check if serial connection is established and open."""
  112. return ser is not None and ser.is_open
  113. def get_port():
  114. """Get the current serial port."""
  115. return ser_port
  116. def get_status_response():
  117. """
  118. Send a status query ('?') and return the response string if available.
  119. This helper centralizes the query logic used throughout the module.
  120. """
  121. while True:
  122. with serial_lock:
  123. ser.write('?'.encode())
  124. ser.flush()
  125. while ser.in_waiting > 0:
  126. response = ser.readline().decode().strip()
  127. if "MPos" in response:
  128. logger.debug(f"Status response: {response}")
  129. return response
  130. time.sleep(1)
  131. def parse_machine_position(response):
  132. """
  133. Parse the work position (MPos) from a status response.
  134. Expected format: "<...|MPos:-994.869,-321.861,0.000|...>"
  135. Returns a tuple (work_x, work_y) if found, else None.
  136. """
  137. if "MPos:" not in response:
  138. return None
  139. try:
  140. wpos_section = next((part for part in response.split("|") if part.startswith("MPos:")), None)
  141. if wpos_section:
  142. wpos_str = wpos_section.split(":", 1)[1]
  143. wpos_values = wpos_str.split(",")
  144. work_x = float(wpos_values[0])
  145. work_y = float(wpos_values[1])
  146. return work_x, work_y
  147. except Exception as e:
  148. logger.error(f"Error parsing work position: {e}")
  149. return None
  150. def parse_buffer_info(response):
  151. """
  152. Parse the planner and serial buffer info from a status response.
  153. Expected format: "<...|Bf:15,128|...>"
  154. Returns a dictionary with keys 'planner_buffer' and 'serial_buffer' if found, else None.
  155. """
  156. if "|Bf:" in response:
  157. try:
  158. buffer_section = response.split("|Bf:")[1].split("|")[0]
  159. planner_buffer, serial_buffer = map(int, buffer_section.split(","))
  160. return {"planner_buffer": planner_buffer, "serial_buffer": serial_buffer}
  161. except ValueError:
  162. logger.warning("Failed to parse buffer info from response")
  163. return None
  164. def send_grbl_coordinates(x, y, speed=600, timeout=2, home=False):
  165. """
  166. Send a G-code command to FluidNC and wait up to timeout seconds for an 'ok' response.
  167. If no 'ok' is received, retry every retry_interval seconds until successful.
  168. """
  169. logger.debug(f"Sending G-code: X{x} Y{y} at F{speed}")
  170. while True:
  171. with serial_lock:
  172. if home:
  173. gcode = f"$J=G91 Y{y} F{speed}"
  174. else:
  175. gcode = f"G1 X{x} Y{y} F{speed}"
  176. ser.write(f"{gcode}\n".encode())
  177. ser.flush()
  178. logger.debug(f"Sent command: {gcode}")
  179. start_time = time.time()
  180. while time.time() - start_time < timeout:
  181. if ser.in_waiting > 0:
  182. response = ser.readline().decode().strip()
  183. logger.debug(f"Response: {response}")
  184. if response.lower() == "ok":
  185. logger.debug("Command execution confirmed.")
  186. return # Exit function when 'ok' is received
  187. logger.warning(f"No 'ok' received for X{x} Y{y}. Retrying in 1s...")
  188. time.sleep(1)
  189. def home(retry = 0):
  190. logger.info(f"Homing with speed {state.speed}")
  191. # Check config for sensorless homing
  192. with serial_lock:
  193. ser.flush()
  194. ser.write("$config\n".encode())
  195. response = ser.readline().decode().strip().lower()
  196. logger.debug(f"Config response: {response}")
  197. if "sensorless" in response:
  198. logger.info("Using sensorless homing")
  199. with serial_lock:
  200. ser.write("$H\n".encode())
  201. ser.write("G1 Y0 F100\n".encode())
  202. ser.flush()
  203. # we check that we actually got a valid response, if not, we try again a couple of times
  204. elif "filename" in response:
  205. logger.info("Using brute-force homing")
  206. send_grbl_coordinates(0, -110/5, state.speed, home=True)
  207. # error:3 means that the controller is running grbl, which doesn't support $config
  208. # we just use brute force homing for grbl
  209. elif "error:3" in response:
  210. logger.info("Grbl detected, Using brute-force homing")
  211. send_grbl_coordinates(0, -110/5, state.speed, home=True)
  212. else:
  213. # we wait a bit and cal again increasing retry times
  214. # if we are over the third retry, we give up
  215. if retry < 3:
  216. time.sleep(1)
  217. home(retry+1)
  218. return
  219. else:
  220. # after 3 retries we're still not getting a good response
  221. # raise an exception
  222. raise Exception("Couldn't get a valid response for homing after 3 retries")
  223. state.current_theta = state.current_rho = 0
  224. update_machine_position()
  225. def check_idle():
  226. """
  227. Continuously check if the machine is in the 'Idle' state.
  228. """
  229. logger.info("Checking idle")
  230. while True:
  231. response = get_status_response()
  232. if response and "Idle" in response:
  233. logger.info("Table is idle")
  234. update_machine_position()
  235. return True # Exit once 'Idle' is confirmed
  236. time.sleep(1)
  237. def get_machine_position(timeout=3):
  238. """
  239. Send status queries for up to `timeout` seconds to obtain a valid machine (work) position.
  240. Returns a tuple (machine_x, machine_y) if a valid response is received,
  241. otherwise returns (None, None) after timeout.
  242. """
  243. start_time = time.time()
  244. while time.time() - start_time < timeout:
  245. with serial_lock:
  246. ser.write('?'.encode())
  247. ser.flush()
  248. # Check if there is any response available
  249. while ser.in_waiting > 0:
  250. response = ser.readline().decode().strip()
  251. logger.debug(f"Raw status response: {response}")
  252. if "MPos" in response:
  253. pos = parse_machine_position(response)
  254. if pos:
  255. machine_x, machine_y = pos
  256. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  257. return machine_x, machine_y
  258. # Short sleep before trying again
  259. time.sleep(0.1)
  260. logger.warning("Timeout reached waiting for machine position")
  261. return None, None
  262. def update_machine_position():
  263. state.machine_x, state.machine_y = get_machine_position()
  264. state.save()