check_gcode_buffer.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2018 Ultimaker B.V.
  3. # Cura is released under the terms of the LGPLv3 or higher.
  4. import copy
  5. import math
  6. import os
  7. import sys
  8. from typing import Dict, List, Optional, Tuple
  9. # ====================================
  10. # Constants and Default Values
  11. # ====================================
  12. DEFAULT_BUFFER_FILLING_RATE_IN_C_PER_S = 50.0 # The buffer filling rate in #commands/s
  13. DEFAULT_BUFFER_SIZE = 15 # The buffer size in #commands
  14. MINIMUM_PLANNER_SPEED = 0.05
  15. #Setting values for Ultimaker S5.
  16. MACHINE_MAX_FEEDRATE_X = 300
  17. MACHINE_MAX_FEEDRATE_Y = 300
  18. MACHINE_MAX_FEEDRATE_Z = 40
  19. MACHINE_MAX_FEEDRATE_E = 45
  20. MACHINE_MAX_ACCELERATION_X = 9000
  21. MACHINE_MAX_ACCELERATION_Y = 9000
  22. MACHINE_MAX_ACCELERATION_Z = 100
  23. MACHINE_MAX_ACCELERATION_E = 10000
  24. MACHINE_MAX_JERK_XY = 20
  25. MACHINE_MAX_JERK_Z = 0.4
  26. MACHINE_MAX_JERK_E = 5
  27. MACHINE_MINIMUM_FEEDRATE = 0.001
  28. MACHINE_ACCELERATION = 3000
  29. ## Gets the code and number from the given g-code line.
  30. def get_code_and_num(gcode_line: str) -> Tuple[str, str]:
  31. gcode_line = gcode_line.strip()
  32. cmd_code = gcode_line[0].upper()
  33. cmd_num = str(gcode_line[1:])
  34. return cmd_code, cmd_num
  35. ## Fetches arguments such as X1 Y2 Z3 from the given part list and returns a
  36. # dict.
  37. def get_value_dict(parts: List[str]) -> Dict[str, str]:
  38. value_dict = {}
  39. for p in parts:
  40. p = p.strip()
  41. if not p:
  42. continue
  43. code, num = get_code_and_num(p)
  44. value_dict[code] = num
  45. return value_dict
  46. # ============================
  47. # Math Functions - Begin
  48. # ============================
  49. def calc_distance(pos1, pos2):
  50. delta = {k: pos1[k] - pos2[k] for k in pos1}
  51. distance = 0
  52. for value in delta.values():
  53. distance += value ** 2
  54. distance = math.sqrt(distance)
  55. return distance
  56. ## Given the initial speed, the target speed, and the acceleration, calculate
  57. # the distance that's neede for the acceleration to finish.
  58. def calc_acceleration_distance(init_speed: float, target_speed: float, acceleration: float) -> float:
  59. if acceleration == 0:
  60. return 0.0
  61. return (target_speed ** 2 - init_speed ** 2) / (2 * acceleration)
  62. ## Gives the time it needs to accelerate from an initial speed to reach a final
  63. # distance.
  64. def calc_acceleration_time_from_distance(initial_feedrate: float, distance: float, acceleration: float) -> float:
  65. discriminant = initial_feedrate ** 2 - 2 * acceleration * -distance
  66. #If the discriminant is negative, we're moving in the wrong direction.
  67. #Making the discriminant 0 then gives the extremum of the parabola instead of the intersection.
  68. discriminant = max(0, discriminant)
  69. return (-initial_feedrate + math.sqrt(discriminant)) / acceleration
  70. ## Calculates the point at which you must start braking.
  71. #
  72. # This gives the distance from the start of a line at which you must start
  73. # decelerating (at a rate of `-acceleration`) if you started at speed
  74. # `initial_feedrate` and accelerated until this point and want to end at the
  75. # `final_feedrate` after a total travel of `distance`. This can be used to
  76. # compute the intersection point between acceleration and deceleration in the
  77. # cases where the trapezoid has no plateau (i.e. never reaches maximum speed).
  78. def calc_intersection_distance(initial_feedrate: float, final_feedrate: float, acceleration: float, distance: float) -> float:
  79. if acceleration == 0:
  80. return 0
  81. return (2 * acceleration * distance - initial_feedrate * initial_feedrate + final_feedrate * final_feedrate) / (4 * acceleration)
  82. ## Calculates the maximum speed that is allowed at this point when you must be
  83. # able to reach target_velocity using the acceleration within the allotted
  84. # distance.
  85. def calc_max_allowable_speed(acceleration: float, target_velocity: float, distance: float) -> float:
  86. return math.sqrt(target_velocity * target_velocity - 2 * acceleration * distance)
  87. class Command:
  88. def __init__(self, cmd_str: str) -> None:
  89. self._cmd_str = cmd_str # type: str
  90. self.estimated_exec_time = 0.0 # type: float
  91. self._cmd_process_function_map = {
  92. "G": self._handle_g,
  93. "M": self._handle_m,
  94. "T": self._handle_t,
  95. }
  96. self._is_comment = False # type: bool
  97. self._is_empty = False # type: bool
  98. #Fields taken from CuraEngine's implementation.
  99. self._recalculate = False
  100. self._accelerate_until = 0
  101. self._decelerate_after = 0
  102. self._initial_feedrate = 0
  103. self._final_feedrate = 0
  104. self._entry_speed = 0
  105. self._max_entry_speed =0
  106. self._nominal_length = False
  107. self._nominal_feedrate = 0
  108. self._max_travel = 0
  109. self._distance = 0
  110. self._acceleration = 0
  111. self._delta = [0, 0, 0]
  112. self._abs_delta = [0, 0, 0]
  113. ## Calculate the velocity-time trapezoid function for this move.
  114. #
  115. # Each move has a three-part function mapping time to velocity.
  116. def calculate_trapezoid(self, entry_factor, exit_factor):
  117. initial_feedrate = self._nominal_feedrate * entry_factor
  118. final_feedrate = self._nominal_feedrate * exit_factor
  119. #How far are we accelerating and how far are we decelerating?
  120. accelerate_distance = calc_acceleration_distance(initial_feedrate, self._nominal_feedrate, self._acceleration)
  121. decelerate_distance = calc_acceleration_distance(self._nominal_feedrate, final_feedrate, -self._acceleration)
  122. plateau_distance = self._distance - accelerate_distance - decelerate_distance #And how far in between at max speed?
  123. #Is the plateau negative size? That means no cruising, and we'll have to
  124. #use intersection_distance to calculate when to abort acceleration and
  125. #start braking in order to reach the final_rate exactly at the end of
  126. #this command.
  127. if plateau_distance < 0:
  128. accelerate_distance = calc_intersection_distance(initial_feedrate, final_feedrate, self._acceleration, self._distance)
  129. accelerate_distance = max(accelerate_distance, 0) #Due to rounding errors.
  130. accelerate_distance = min(accelerate_distance, self._distance)
  131. plateau_distance = 0
  132. self._accelerate_until = accelerate_distance
  133. self._decelerate_after = accelerate_distance + plateau_distance
  134. self._initial_feedrate = initial_feedrate
  135. self._final_feedrate = final_feedrate
  136. @property
  137. def is_command(self) -> bool:
  138. return not self._is_comment and not self._is_empty
  139. def __str__(self) -> str:
  140. if self._is_comment or self._is_empty:
  141. return self._cmd_str
  142. info = "t=%s" % (self.estimated_exec_time)
  143. return self._cmd_str.strip() + " ; --- " + info + os.linesep
  144. ## Estimates the execution time of this command and calculates the state
  145. # after this command is executed.
  146. def parse(self) -> None:
  147. line = self._cmd_str.strip()
  148. if not line:
  149. self._is_empty = True
  150. return
  151. if line.startswith(";"):
  152. self._is_comment = True
  153. return
  154. # Remove comment
  155. line = line.split(";", 1)[0].strip()
  156. parts = line.split(" ")
  157. cmd_code, cmd_num = get_code_and_num(parts[0])
  158. cmd_num = int(cmd_num)
  159. func = self._cmd_process_function_map.get(cmd_code)
  160. if func is None:
  161. print("!!! no handle function for command type [%s]" % cmd_code)
  162. return
  163. func(cmd_num, parts)
  164. def _handle_g(self, cmd_num: int, parts: List[str]) -> None:
  165. self.estimated_exec_time = 0.0
  166. # G10: Retract. Make this behave as if it's a retraction of 25mm.
  167. if cmd_num == 10:
  168. #TODO: If already retracted, this shouldn't add anything to the time.
  169. cmd_num = 1
  170. parts = ["G1", "E" + str(buf.current_position[3] - 25)]
  171. # G11: Unretract. Make this behave as if it's an unretraction of 25mm.
  172. elif cmd_num == 11:
  173. #TODO: If already unretracted, this shouldn't add anything to the time.
  174. cmd_num = 1
  175. parts = ["G1", "E" + str(buf.current_position[3] + 25)]
  176. # G0 and G1: Move
  177. if cmd_num in (0, 1):
  178. # Move
  179. if len(parts) > 0:
  180. value_dict = get_value_dict(parts[1:])
  181. new_position = copy.deepcopy(buf.current_position)
  182. new_position[0] = float(value_dict.get("X", new_position[0]))
  183. new_position[1] = float(value_dict.get("Y", new_position[1]))
  184. new_position[2] = float(value_dict.get("Z", new_position[2]))
  185. new_position[3] = float(value_dict.get("E", new_position[3]))
  186. buf.current_feedrate = float(value_dict.get("F", buf.current_feedrate * 60.0)) / 60.0
  187. if buf.current_feedrate < MACHINE_MINIMUM_FEEDRATE:
  188. buf.current_feedrate = MACHINE_MINIMUM_FEEDRATE
  189. self._delta = [
  190. new_position[0] - buf.current_position[0],
  191. new_position[1] - buf.current_position[1],
  192. new_position[2] - buf.current_position[2],
  193. new_position[3] - buf.current_position[3]
  194. ]
  195. self._abs_delta = [abs(x) for x in self._delta]
  196. self._max_travel = max(self._abs_delta)
  197. if self._max_travel > 0:
  198. self._nominal_feedrate = buf.current_feedrate
  199. self._distance = math.sqrt(self._abs_delta[0] ** 2 + self._abs_delta[1] ** 2 + self._abs_delta[2] ** 2)
  200. if self._distance == 0:
  201. self._distance = self._abs_delta[3]
  202. current_feedrate = [d * self._nominal_feedrate / self._distance for d in self._delta]
  203. current_abs_feedrate = [abs(f) for f in current_feedrate]
  204. feedrate_factor = min(1.0, MACHINE_MAX_FEEDRATE_X)
  205. feedrate_factor = min(feedrate_factor, MACHINE_MAX_FEEDRATE_Y)
  206. feedrate_factor = min(feedrate_factor, buf.max_z_feedrate)
  207. feedrate_factor = min(feedrate_factor, MACHINE_MAX_FEEDRATE_E)
  208. #TODO: XY_FREQUENCY_LIMIT
  209. current_feedrate = [f * feedrate_factor for f in current_feedrate]
  210. current_abs_feedrate = [f * feedrate_factor for f in current_abs_feedrate]
  211. self._nominal_feedrate *= feedrate_factor
  212. self._acceleration = MACHINE_ACCELERATION
  213. max_accelerations = [MACHINE_MAX_ACCELERATION_X, MACHINE_MAX_ACCELERATION_Y, MACHINE_MAX_ACCELERATION_Z, MACHINE_MAX_ACCELERATION_E]
  214. for n in range(len(max_accelerations)):
  215. if self._acceleration * self._abs_delta[n] / self._distance > max_accelerations[n]:
  216. self._acceleration = max_accelerations[n]
  217. vmax_junction = MACHINE_MAX_JERK_XY / 2
  218. vmax_junction_factor = 1.0
  219. if current_abs_feedrate[2] > buf.max_z_jerk / 2:
  220. vmax_junction = min(vmax_junction, buf.max_z_jerk)
  221. if current_abs_feedrate[3] > buf.max_e_jerk / 2:
  222. vmax_junction = min(vmax_junction, buf.max_e_jerk)
  223. vmax_junction = min(vmax_junction, self._nominal_feedrate)
  224. safe_speed = vmax_junction
  225. if buf.previous_nominal_feedrate > 0.0001:
  226. xy_jerk = math.sqrt((current_feedrate[0] - buf.previous_feedrate[0]) ** 2 + (current_feedrate[1] - buf.previous_feedrate[1]) ** 2)
  227. vmax_junction = self._nominal_feedrate
  228. if xy_jerk > MACHINE_MAX_JERK_XY:
  229. vmax_junction_factor = MACHINE_MAX_JERK_XY / xy_jerk
  230. if abs(current_feedrate[2] - buf.previous_feedrate[2]) > MACHINE_MAX_JERK_Z:
  231. vmax_junction_factor = min(vmax_junction_factor, (MACHINE_MAX_JERK_Z / abs(current_feedrate[2] - buf.previous_feedrate[2])))
  232. if abs(current_feedrate[3] - buf.previous_feedrate[3]) > MACHINE_MAX_JERK_E:
  233. vmax_junction_factor = min(vmax_junction_factor, (MACHINE_MAX_JERK_E / abs(current_feedrate[3] - buf.previous_feedrate[3])))
  234. vmax_junction = min(buf.previous_nominal_feedrate, vmax_junction * vmax_junction_factor) #Limit speed to max previous speed.
  235. self._max_entry_speed = vmax_junction
  236. v_allowable = calc_max_allowable_speed(-self._acceleration, MINIMUM_PLANNER_SPEED, self._distance)
  237. self._entry_speed = min(vmax_junction, v_allowable)
  238. self._nominal_length = self._nominal_feedrate <= v_allowable
  239. self._recalculate = True
  240. buf.previous_feedrate = current_feedrate
  241. buf.previous_nominal_feedrate = self._nominal_feedrate
  242. buf.current_position = new_position
  243. self.calculate_trapezoid(self._entry_speed / self._nominal_feedrate, safe_speed / self._nominal_feedrate)
  244. self.estimated_exec_time = -1 #Signal that we need to include this in our second pass.
  245. # G4: Dwell, pause the machine for a period of time.
  246. elif cmd_num == 4:
  247. # Pnnn is time to wait in milliseconds (P0 wait until all previous moves are finished)
  248. cmd, num = get_code_and_num(parts[1])
  249. num = float(num)
  250. if cmd == "P":
  251. if num > 0:
  252. self.estimated_exec_time = num
  253. def _handle_m(self, cmd_num: int, parts: List[str]) -> None:
  254. self.estimated_exec_time = 0.0
  255. # M203: Set maximum feedrate. Only Z is supported. Assume 0 execution time.
  256. if cmd_num == 203:
  257. value_dict = get_value_dict(parts[1:])
  258. buf.max_z_feedrate = value_dict.get("Z", buf.max_z_feedrate)
  259. # M204: Set default acceleration. Assume 0 execution time.
  260. if cmd_num == 204:
  261. value_dict = get_value_dict(parts[1:])
  262. buf.acceleration = value_dict.get("S", buf.acceleration)
  263. # M205: Advanced settings, we only set jerks for Griffin. Assume 0 execution time.
  264. if cmd_num == 205:
  265. value_dict = get_value_dict(parts[1:])
  266. buf.max_xy_jerk = value_dict.get("XY", buf.max_xy_jerk)
  267. buf.max_z_jerk = value_dict.get("Z", buf.max_z_jerk)
  268. buf.max_e_jerk = value_dict.get("E", buf.max_e_jerk)
  269. def _handle_t(self, cmd_num: int, parts: List[str]) -> None:
  270. # Tn: Switching extruder. Assume 0 seconds. Actually more like 2.
  271. self.estimated_exec_time = 0.0
  272. class CommandBuffer:
  273. def __init__(self, all_lines: List[str],
  274. buffer_filling_rate: float = DEFAULT_BUFFER_FILLING_RATE_IN_C_PER_S,
  275. buffer_size: int = DEFAULT_BUFFER_SIZE
  276. ) -> None:
  277. self._all_lines = all_lines
  278. self._all_commands = list()
  279. self._buffer_filling_rate = buffer_filling_rate # type: float
  280. self._buffer_size = buffer_size # type: int
  281. self.acceleration = 3000
  282. self.current_position = [0, 0, 0, 0]
  283. self.current_feedrate = 0
  284. self.max_xy_jerk = MACHINE_MAX_JERK_XY
  285. self.max_z_jerk = MACHINE_MAX_JERK_Z
  286. self.max_e_jerk = MACHINE_MAX_JERK_E
  287. self.max_z_feedrate = MACHINE_MAX_FEEDRATE_Z
  288. # If the buffer can depletes less than this amount time, it can be filled up in time.
  289. lower_bound_buffer_depletion_time = self._buffer_size / self._buffer_filling_rate # type: float
  290. self._detection_time_frame = lower_bound_buffer_depletion_time
  291. self._code_count_limit = self._buffer_size
  292. self.total_time = 0.0
  293. self.previous_feedrate = [0, 0, 0, 0]
  294. self.previous_nominal_feedrate = 0
  295. print("Time Frame: %s" % self._detection_time_frame)
  296. print("Code Limit: %s" % self._code_count_limit)
  297. self._bad_frame_ranges = []
  298. def process(self) -> None:
  299. buf.total_time = 0.0
  300. cmd0_idx = 0
  301. total_frame_time = 0.0
  302. cmd_count = 0
  303. for idx, line in enumerate(self._all_lines):
  304. cmd = Command(line)
  305. cmd.parse()
  306. if not cmd.is_command:
  307. continue
  308. self._all_commands.append(cmd)
  309. #Second pass: Reverse kernel.
  310. kernel_commands = [None, None, None]
  311. for cmd in reversed(self._all_commands):
  312. if cmd.estimated_exec_time >= 0:
  313. continue #Not a movement command.
  314. kernel_commands[2] = kernel_commands[1]
  315. kernel_commands[1] = kernel_commands[0]
  316. kernel_commands[0] = cmd
  317. self.reverse_pass_kernel(kernel_commands[0], kernel_commands[1], kernel_commands[2])
  318. #Third pass: Forward kernel.
  319. kernel_commands = [None, None, None]
  320. for cmd in self._all_commands:
  321. if cmd.estimated_exec_time >= 0:
  322. continue #Not a movement command.
  323. kernel_commands[0] = kernel_commands[1]
  324. kernel_commands[1] = kernel_commands[2]
  325. kernel_commands[2] = cmd
  326. self.forward_pass_kernel(kernel_commands[0], kernel_commands[1], kernel_commands[2])
  327. self.forward_pass_kernel(kernel_commands[1], kernel_commands[2], None)
  328. #Fourth pass: Recalculate the commands that have _recalculate set.
  329. previous = None
  330. current = None
  331. for current in self._all_commands:
  332. if current.estimated_exec_time >= 0:
  333. current = None
  334. continue #Not a movement command.
  335. if previous:
  336. #Recalculate if current command entry or exit junction speed has changed.
  337. if previous._recalculate or current._recalculate:
  338. #Note: Entry and exit factors always >0 by all previous logic operators.
  339. previous.calculate_trapezoid(previous._entry_speed / previous._nominal_feedrate, current._entry_speed / previous._nominal_feedrate)
  340. previous._recalculate = False
  341. previous = current
  342. if current is not None and current.estimated_exec_time >= 0:
  343. current.calculate_trapezoid(current._entry_speed / current._nominal_feedrate, MINIMUM_PLANNER_SPEED / current._nominal_feedrate)
  344. current._recalculate = False
  345. #Fifth pass: Compute time for movement commands.
  346. for cmd in self._all_commands:
  347. if cmd.estimated_exec_time >= 0:
  348. continue #Not a movement command.
  349. plateau_distance = cmd._decelerate_after - cmd._accelerate_until
  350. cmd.estimated_exec_time = calc_acceleration_time_from_distance(cmd._initial_feedrate, cmd._accelerate_until, cmd._acceleration)
  351. cmd.estimated_exec_time += plateau_distance / cmd._nominal_feedrate
  352. cmd.estimated_exec_time += calc_acceleration_time_from_distance(cmd._final_feedrate, (cmd._distance - cmd._decelerate_after), cmd._acceleration)
  353. for idx, cmd in enumerate(self._all_commands):
  354. cmd_count += 1
  355. if idx > cmd0_idx or idx == 0:
  356. buf.total_time += cmd.estimated_exec_time
  357. total_frame_time += cmd.estimated_exec_time
  358. if total_frame_time > 1:
  359. # Find the next starting command which makes the total execution time of the frame to be less than
  360. # 1 second.
  361. cmd0_idx += 1
  362. total_frame_time -= self._all_commands[cmd0_idx].estimated_exec_time
  363. cmd_count -= 1
  364. while total_frame_time > 1:
  365. cmd0_idx += 1
  366. total_frame_time -= self._all_commands[cmd0_idx].estimated_exec_time
  367. cmd_count -= 1
  368. # If within the current time frame the code count exceeds the limit, record that.
  369. if total_frame_time <= self._detection_time_frame and cmd_count > self._code_count_limit:
  370. need_to_append = True
  371. if self._bad_frame_ranges:
  372. last_item = self._bad_frame_ranges[-1]
  373. if last_item["start_line"] == cmd0_idx:
  374. last_item["end_line"] = idx
  375. last_item["cmd_count"] = cmd_count
  376. last_item["time"] = total_frame_time
  377. need_to_append = False
  378. if need_to_append:
  379. self._bad_frame_ranges.append({"start_line": cmd0_idx,
  380. "end_line": idx,
  381. "cmd_count": cmd_count,
  382. "time": total_frame_time})
  383. def reverse_pass_kernel(self, previous: Optional[Command], current: Optional[Command], next: Optional[Command]) -> None:
  384. if not current or not next:
  385. return
  386. #If entry speed is already at the maximum entry speed, no need to
  387. #recheck. The command is cruising. If not, the command is in state of
  388. #acceleration or deceleration. Reset entry speed to maximum and check
  389. #for maximum allowable speed reductions to ensure maximum possible
  390. #planned speed.
  391. if current._entry_speed != current._max_entry_speed:
  392. #If nominal length is true, max junction speed is guaranteed to be
  393. #reached. Only compute for max allowable speed if block is
  394. #decelerating and nominal length is false.
  395. if not current._nominal_length and current._max_entry_speed > next._max_entry_speed:
  396. current._entry_speed = min(current._max_entry_speed, calc_max_allowable_speed(-current._acceleration, next._entry_speed, current._distance))
  397. else:
  398. current._entry_speed = current._max_entry_speed
  399. current._recalculate = True
  400. def forward_pass_kernel(self, previous: Optional[Command], current: Optional[Command], next: Optional[Command]) -> None:
  401. if not previous:
  402. return
  403. #If the previous command is an acceleration command, but it is not long
  404. #enough to complete the full speed change within the command, we need to
  405. #adjust the entry speed accordingly. Entry speeds have already been
  406. #reset, maximised and reverse planned by the reverse planner. If nominal
  407. #length is set, max junction speed is guaranteed to be reached. No need
  408. #to recheck.
  409. if not previous._nominal_length:
  410. if previous._entry_speed < current._entry_speed:
  411. entry_speed = min(current._entry_speed, calc_max_allowable_speed(-previous._acceleration, previous._entry_speed, previous._distance))
  412. if current._entry_speed != entry_speed:
  413. current._entry_speed = entry_speed
  414. current._recalculate = True
  415. def to_file(self, file_name: str) -> None:
  416. all_lines = [str(c) for c in self._all_commands]
  417. with open(file_name, "w", encoding = "utf-8") as f:
  418. f.writelines(all_lines)
  419. f.write(";---TOTAL ESTIMATED TIME:" + str(self.total_time))
  420. def report(self) -> None:
  421. for item in self._bad_frame_ranges:
  422. print("Potential buffer underrun from line {start_line} to {end_line}, code count = {code_count}, in {time}s ({speed} cmd/s)".format(
  423. start_line = item["start_line"],
  424. end_line = item["end_line"],
  425. code_count = item["cmd_count"],
  426. time = round(item["time"], 4),
  427. speed = round(item["cmd_count"] / item["time"], 2)))
  428. print("Total predicted number of buffer underruns:", len(self._bad_frame_ranges))
  429. if __name__ == "__main__":
  430. if len(sys.argv) < 2 or 3 < len(sys.argv):
  431. print("Usage: <input gcode> [output gcode]")
  432. sys.exit(1)
  433. in_filename = sys.argv[1]
  434. out_filename = None
  435. if len(sys.argv) == 3:
  436. out_filename = sys.argv[2]
  437. with open(in_filename, "r", encoding = "utf-8") as f:
  438. all_lines = f.readlines()
  439. buf = CommandBuffer(all_lines)
  440. buf.process()
  441. # Output annotated gcode is optional
  442. if out_filename is not None:
  443. buf.to_file(out_filename)
  444. buf.report()