50_inst_per_sec.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import copy
  4. import math
  5. import os
  6. import sys
  7. import random
  8. from typing import Dict, List, Optional, Tuple
  9. # ====================================
  10. # Constants and Default Values
  11. # ====================================
  12. DEFAULT_BUFFER_FILLING_RATE_IN_C_PER_MS = 50.0 / 1000.0 # The buffer filling rate in #commands/ms
  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
  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_in_ms = 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_in_ms)
  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_in_ms = 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 = value_dict.get("F", buf.current_feedrate)
  187. self._delta = [
  188. new_position[0] - buf.current_position[0],
  189. new_position[1] - buf.current_position[1],
  190. new_position[2] - buf.current_position[2],
  191. new_position[3] - buf.current_position[3]
  192. ]
  193. self._abs_delta = [abs(x) for x in self._delta]
  194. self._max_travel = max(self._abs_delta)
  195. if self._max_travel > 0:
  196. feedrate = float(value_dict.get("F", buf.current_feedrate))
  197. if feedrate < MACHINE_MINIMUM_FEEDRATE:
  198. feedrate = MACHINE_MINIMUM_FEEDRATE
  199. self._nominal_feedrate = feedrate
  200. self._distance = math.sqrt(self._abs_delta[0] ** 2 + self._abs_delta[1] ** 2 + self._abs_delta[2] ** 2)
  201. if self._distance == 0:
  202. self._distance = self._abs_delta[3]
  203. current_feedrate = [d * feedrate / self._distance for d in self._delta]
  204. current_abs_feedrate = [abs(f) for f in current_feedrate]
  205. feedrate_factor = min(1.0, MACHINE_MAX_FEEDRATE_X)
  206. feedrate_factor = min(feedrate_factor, MACHINE_MAX_FEEDRATE_Y)
  207. feedrate_factor = min(feedrate_factor, buf.max_z_feedrate)
  208. feedrate_factor = min(feedrate_factor, MACHINE_MAX_FEEDRATE_E)
  209. #TODO: XY_FREQUENCY_LIMIT
  210. current_feedrate = [f * feedrate_factor for f in current_feedrate]
  211. current_abs_feedrate = [f * feedrate_factor for f in current_abs_feedrate]
  212. self._nominal_feedrate *= feedrate_factor
  213. self._acceleration = MACHINE_ACCELERATION
  214. max_accelerations = [MACHINE_MAX_ACCELERATION_X, MACHINE_MAX_ACCELERATION_Y, MACHINE_MAX_ACCELERATION_Z, MACHINE_MAX_ACCELERATION_E]
  215. for n in range(len(max_accelerations)):
  216. if self._acceleration * self._abs_delta[n] / self._distance > max_accelerations[n]:
  217. self._acceleration = max_accelerations[n]
  218. vmax_junction = MACHINE_MAX_JERK_XY / 2
  219. vmax_junction_factor = 1.0
  220. if current_abs_feedrate[2] > buf.max_z_jerk / 2:
  221. vmax_junction = min(vmax_junction, buf.max_z_jerk)
  222. if current_abs_feedrate[3] > buf.max_e_jerk / 2:
  223. vmax_junction = min(vmax_junction, buf.max_e_jerk)
  224. vmax_junction = min(vmax_junction, self._nominal_feedrate)
  225. safe_speed = vmax_junction
  226. if buf.previous_nominal_feedrate > 0.0001:
  227. xy_jerk = math.sqrt((current_feedrate[0] - buf.previous_feedrate[0]) ** 2 + (current_feedrate[1] - buf.previous_feedrate[1]) ** 2)
  228. vmax_junction = self._nominal_feedrate
  229. if xy_jerk > MACHINE_MAX_JERK_XY:
  230. vmax_junction_factor = MACHINE_MAX_JERK_XY / xy_jerk
  231. if abs(current_feedrate[2] - buf.previous_feedrate[2]) > MACHINE_MAX_JERK_Z:
  232. vmax_junction_factor = min(vmax_junction_factor, (MACHINE_MAX_JERK_Z / abs(current_feedrate[2] - buf.previous_feedrate[2])))
  233. if abs(current_feedrate[3] - buf.previous_feedrate[3]) > MACHINE_MAX_JERK_E:
  234. vmax_junction_factor = min(vmax_junction_factor, (MACHINE_MAX_JERK_E / abs(current_feedrate[3] - buf.previous_feedrate[3])))
  235. vmax_junction = min(buf.previous_nominal_feedrate, vmax_junction * vmax_junction_factor) #Limit speed to max previous speed.
  236. self._max_entry_speed = vmax_junction
  237. v_allowable = calc_max_allowable_speed(-self._acceleration, MINIMUM_PLANNER_SPEED, self._distance)
  238. self._entry_speed = min(vmax_junction, v_allowable)
  239. self._nominal_length = self._nominal_feedrate <= v_allowable
  240. self._recalculate = True
  241. buf.previous_feedrate = current_feedrate
  242. buf.previous_nominal_feedrate = self._nominal_feedrate
  243. buf.current_position = new_position
  244. self.calculate_trapezoid(self._entry_speed / self._nominal_feedrate, safe_speed / self._nominal_feedrate)
  245. self.estimated_exec_time_in_ms = -1 #Signal that we need to include this in our second pass.
  246. # G4: Dwell, pause the machine for a period of time.
  247. elif cmd_num == 4:
  248. # Pnnn is time to wait in milliseconds (P0 wait until all previous moves are finished)
  249. cmd, num = get_code_and_num(parts[1])
  250. num = float(num)
  251. if cmd == "P":
  252. if num > 0:
  253. self.estimated_exec_time_in_ms = num
  254. def _handle_m(self, cmd_num: int, parts: List[str]) -> None:
  255. self.estimated_exec_time_in_ms = 0.0
  256. # M203: Set maximum feedrate. Only Z is supported. Assume 0 execution time.
  257. if cmd_num == 203:
  258. value_dict = get_value_dict(parts[1:])
  259. buf.max_z_feedrate = value_dict.get("Z", buf.max_z_feedrate)
  260. # M204: Set default acceleration. Assume 0 execution time.
  261. if cmd_num == 204:
  262. value_dict = get_value_dict(parts[1:])
  263. buf.acceleration = value_dict.get("S", buf.acceleration)
  264. # M205: Advanced settings, we only set jerks for Griffin. Assume 0 execution time.
  265. if cmd_num == 205:
  266. value_dict = get_value_dict(parts[1:])
  267. buf.max_xy_jerk = value_dict.get("XY", buf.max_xy_jerk)
  268. buf.max_z_jerk = value_dict.get("Z", buf.max_z_jerk)
  269. buf.max_e_jerk = value_dict.get("E", buf.max_e_jerk)
  270. def _handle_t(self, cmd_num: int, parts: List[str]) -> None:
  271. # Tn: Switching extruder. Assume 0 seconds. Actually more like 2.
  272. self.estimated_exec_time_in_ms = 0.0
  273. class CommandBuffer:
  274. def __init__(self, all_lines: List[str],
  275. buffer_filling_rate: float = DEFAULT_BUFFER_FILLING_RATE_IN_C_PER_MS,
  276. buffer_size: int = DEFAULT_BUFFER_SIZE
  277. ) -> None:
  278. self._all_lines = all_lines
  279. self._all_commands = list()
  280. self._buffer_filling_rate = buffer_filling_rate # type: float
  281. self._buffer_size = buffer_size # type: int
  282. self.acceleration = 3000
  283. self.current_position = [0, 0, 0, 0]
  284. self.current_feedrate = 0
  285. self.max_xy_jerk = MACHINE_MAX_JERK_XY
  286. self.max_z_jerk = MACHINE_MAX_JERK_Z
  287. self.max_e_jerk = MACHINE_MAX_JERK_E
  288. self.max_z_feedrate = MACHINE_MAX_FEEDRATE_Z
  289. # If the buffer can depletes less than this amount time, it can be filled up in time.
  290. lower_bound_buffer_depletion_time = self._buffer_size / self._buffer_filling_rate # type: float
  291. self._detection_time_frame = lower_bound_buffer_depletion_time
  292. self._code_count_limit = self._buffer_size
  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. cmd0_idx = 0
  300. total_frame_time_in_ms = 0.0
  301. cmd_count = 0
  302. for idx, line in enumerate(self._all_lines):
  303. cmd = Command(line)
  304. cmd.parse()
  305. if not cmd.is_command:
  306. continue
  307. self._all_commands.append(cmd)
  308. #Second pass: Reverse kernel.
  309. kernel_commands = [None, None, None]
  310. for cmd in reversed(self._all_commands):
  311. if cmd.estimated_exec_time_in_ms >= 0:
  312. continue #Not a movement command.
  313. kernel_commands[2] = kernel_commands[1]
  314. kernel_commands[1] = kernel_commands[0]
  315. kernel_commands[0] = cmd
  316. self.reverse_pass_kernel(kernel_commands[0], kernel_commands[1], kernel_commands[2])
  317. #Third pass: Forward kernel.
  318. kernel_commands = [None, None, None]
  319. for cmd in self._all_commands:
  320. if cmd.estimated_exec_time_in_ms >= 0:
  321. continue #Not a movement command.
  322. kernel_commands[0] = kernel_commands[1]
  323. kernel_commands[1] = kernel_commands[2]
  324. kernel_commands[2] = cmd
  325. self.forward_pass_kernel(kernel_commands[0], kernel_commands[1], kernel_commands[2])
  326. self.forward_pass_kernel(kernel_commands[1], kernel_commands[2], None)
  327. #Fourth pass: Recalculate the commands that have _recalculate set.
  328. previous = None
  329. current = None
  330. for current in self._all_commands:
  331. if current.estimated_exec_time_in_ms >= 0:
  332. current = None
  333. continue #Not a movement command.
  334. if previous:
  335. #Recalculate if current command entry or exit junction speed has changed.
  336. if previous._recalculate or current._recalculate:
  337. #Note: Entry and exit factors always >0 by all previous logic operators.
  338. previous.calculate_trapezoid(previous._entry_speed / previous._nominal_feedrate, current._entry_speed / previous._nominal_feedrate)
  339. previous._recalculate = False
  340. previous = current
  341. if current is not None and current.estimated_exec_time_in_ms >= 0:
  342. current.calculate_trapezoid(current._entry_speed / current._nominal_feedrate, MINIMUM_PLANNER_SPEED / current._nominal_feedrate)
  343. current._recalculate = False
  344. #Fifth pass: Compute time for movement commands.
  345. for cmd in self._all_commands:
  346. if cmd.estimated_exec_time_in_ms >= 0:
  347. continue #Not a movement command.
  348. plateau_distance = cmd._decelerate_after - cmd._accelerate_until
  349. cmd.estimated_exec_time_in_ms = calc_acceleration_time_from_distance(cmd._initial_feedrate, cmd._accelerate_until, cmd._acceleration)
  350. cmd.estimated_exec_time_in_ms += plateau_distance / cmd._nominal_feedrate
  351. cmd.estimated_exec_time_in_ms += calc_acceleration_time_from_distance(cmd._final_feedrate, (cmd._distancd - cmd._decelerate_after), cmd._acceleration)
  352. for idx, cmd in enumerate(self._all_commands):
  353. cmd_count += 1
  354. if idx > cmd0_idx or idx == 0:
  355. total_frame_time_in_ms += cmd.estimated_exec_time_in_ms
  356. if total_frame_time_in_ms > 1000.0:
  357. # Find the next starting command which makes the total execution time of the frame to be less than
  358. # 1 second.
  359. cmd0_idx += 1
  360. total_frame_time_in_ms -= self._all_commands[cmd0_idx].estimated_exec_time_in_ms
  361. cmd_count -= 1
  362. while total_frame_time_in_ms > 1000.0:
  363. cmd0_idx += 1
  364. total_frame_time_in_ms -= self._all_commands[cmd0_idx].estimated_exec_time_in_ms
  365. cmd_count -= 1
  366. # If within the current time frame the code count exceeds the limit, record that.
  367. if total_frame_time_in_ms <= self._detection_time_frame and cmd_count > self._code_count_limit:
  368. need_to_append = True
  369. if self._bad_frame_ranges:
  370. last_item = self._bad_frame_ranges[-1]
  371. if last_item["start_line"] == cmd0_idx:
  372. last_item["end_line"] = idx
  373. last_item["cmd_count"] = cmd_count
  374. last_item["time_in_ms"] = total_frame_time_in_ms
  375. need_to_append = False
  376. if need_to_append:
  377. self._bad_frame_ranges.append({"start_line": cmd0_idx,
  378. "end_line": idx,
  379. "cmd_count": cmd_count,
  380. "time_in_ms": total_frame_time_in_ms})
  381. def reverse_pass_kernel(self, previous: Optional[Command], current: Optional[Command], next: Optional[Command]) -> None:
  382. if not current or not next:
  383. return
  384. #If entry speed is already at the maximum entry speed, no need to
  385. #recheck. The command is cruising. If not, the command is in state of
  386. #acceleration or deceleration. Reset entry speed to maximum and check
  387. #for maximum allowable speed reductions to ensure maximum possible
  388. #planned speed.
  389. if current._entry_speed != current._max_entry_speed:
  390. #If nominal length is true, max junction speed is guaranteed to be
  391. #reached. Only compute for max allowable speed if block is
  392. #decelerating and nominal length is false.
  393. if not current._nominal_length and current._max_entry_speed > next._max_entry_speed:
  394. current._entry_speed = min(current._max_entry_speed, calc_max_allowable_speed(-current._acceleration, next._entry_speed, current._distance))
  395. else:
  396. current._entry_speed = current._max_entry_speed
  397. current._recalculate = True
  398. def forward_pass_kernel(self, previous: Optional[Command], current: Optional[Command], next: Optional[Command]) -> None:
  399. if not previous:
  400. return
  401. #If the previous command is an acceleration command, but it is not long
  402. #enough to complete the full speed change within the command, we need to
  403. #adjust the entry speed accordingly. Entry speeds have already been
  404. #reset, maximised and reverse planned by the reverse planner. If nominal
  405. #length is set, max junction speed is guaranteed to be reached. No need
  406. #to recheck.
  407. if not previous._nominal_length:
  408. if previous._entry_speed < current._entry_speed:
  409. entry_speed = min(current._entry_speed, calc_max_allowable_speed(-previous._acceleration, previous._entry_speed, previous._distance))
  410. if current._entry_speed != entry_speed:
  411. current._entry_speed = entry_speed
  412. current._recalculate = True
  413. def to_file(self, file_name: str) -> None:
  414. all_lines = [str(c) for c in self._all_commands]
  415. with open(file_name, "w", encoding = "utf-8") as f:
  416. f.writelines(all_lines)
  417. def report(self) -> None:
  418. for item in self._bad_frame_ranges:
  419. print("!!!!! potential bad frame from line %s to %s, code count = %s, in %s ms" % (
  420. item["start_line"], item["end_line"], item["cmd_count"], round(item["time_in_ms"], 4)))
  421. if __name__ == "__main__":
  422. if len(sys.argv) != 3:
  423. print("Usage: <input gcode> <output gcode>")
  424. sys.exit(1)
  425. in_filename = sys.argv[1]
  426. out_filename = sys.argv[2]
  427. with open(in_filename, "r", encoding = "utf-8") as f:
  428. all_lines = f.readlines()
  429. buf = CommandBuffer(all_lines)
  430. buf.process()
  431. buf.to_file(out_filename)
  432. buf.report()