serial_manager.py 9.6 KB

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