50_inst_per_sec.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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._distance_in_mm = 0.0 # type float
  91. self._estimated_exec_time_in_ms = 0.0 # type: float
  92. self._cmd_process_function_map = {
  93. "G": self._handle_g,
  94. "M": self._handle_m,
  95. "T": self._handle_t,
  96. }
  97. self._is_comment = False # type: bool
  98. self._is_empty = False # type: bool
  99. #Fields taken from CuraEngine's implementation.
  100. self._recalculate = False
  101. self._accelerate_until = 0
  102. self._decelerate_after = 0
  103. self._initial_feedrate = 0
  104. self._final_feedrate = 0
  105. self._entry_speed = 0
  106. self._max_entry_speed =0
  107. self._nominal_length = False
  108. self._nominal_feedrate = 0
  109. self._max_travel = 0
  110. self._distance = 0
  111. self._acceleration = 0
  112. self._delta = [0, 0, 0]
  113. self._abs_delta = [0, 0, 0]
  114. ## Calculate the velocity-time trapezoid function for this move.
  115. #
  116. # Each move has a three-part function mapping time to velocity.
  117. def calculate_trapezoid(self, entry_factor, exit_factor):
  118. initial_feedrate = self._nominal_feedrate * entry_factor
  119. final_feedrate = self._nominal_feedrate * exit_factor
  120. #How far are we accelerating and how far are we decelerating?
  121. accelerate_distance = calc_acceleration_distance(initial_feedrate, self._nominal_feedrate, self._acceleration)
  122. decelerate_distance = calc_acceleration_distance(self._nominal_feedrate, final_feedrate, -self._acceleration)
  123. plateau_distance = self._distance - accelerate_distance - decelerate_distance #And how far in between at max speed?
  124. #Is the plateau negative size? That means no cruising, and we'll have to
  125. #use intersection_distance to calculate when to abort acceleration and
  126. #start braking in order to reach the final_rate exactly at the end of
  127. #this command.
  128. if plateau_distance < 0:
  129. accelerate_distance = calc_intersection_distance(initial_feedrate, final_feedrate, self._acceleration, self._distance)
  130. accelerate_distance = max(accelerate_distance, 0) #Due to rounding errors.
  131. accelerate_distance = min(accelerate_distance, self._distance)
  132. plateau_distance = 0
  133. self._accelerate_until = accelerate_distance
  134. self._decelerate_after = accelerate_distance + plateau_distance
  135. self._initial_feedrate = initial_feedrate
  136. self._final_feedrate = final_feedrate
  137. @property
  138. def is_command(self) -> bool:
  139. return not self._is_comment and not self._is_empty
  140. @property
  141. def estimated_exec_time_in_ms(self) -> float:
  142. return self._estimated_exec_time_in_ms
  143. def __str__(self) -> str:
  144. if self._is_comment or self._is_empty:
  145. return self._cmd_str
  146. distance_in_mm = round(self._distance_in_mm, 5)
  147. info = "d=%s t=%s" % (distance_in_mm, self._estimated_exec_time_in_ms)
  148. return self._cmd_str.strip() + " ; --- " + info + os.linesep
  149. ## Estimates the execution time of this command and calculates the state
  150. # after this command is executed.
  151. def parse(self) -> None:
  152. line = self._cmd_str.strip()
  153. if not line:
  154. self._is_empty = True
  155. return
  156. if line.startswith(";"):
  157. self._is_comment = True
  158. return
  159. # Remove comment
  160. line = line.split(";", 1)[0].strip()
  161. parts = line.split(" ")
  162. cmd_code, cmd_num = get_code_and_num(parts[0])
  163. cmd_num = int(cmd_num)
  164. func = self._cmd_process_function_map.get(cmd_code)
  165. if func is None:
  166. print("!!! no handle function for command type [%s]" % cmd_code)
  167. return
  168. func(cmd_num, parts)
  169. def _handle_g(self, cmd_num: int, parts: List[str]) -> None:
  170. self._estimated_exec_time_in_ms = 0.0
  171. # G10: Retract. Make this behave as if it's a retraction of 25mm.
  172. if cmd_num == 10:
  173. #TODO: If already retracted, this shouldn't add anything to the time.
  174. cmd_num = 1
  175. parts = ["G1", "E" + str(buf.current_position[3] - 25)]
  176. # G11: Unretract. Make this behave as if it's an unretraction of 25mm.
  177. elif cmd_num == 11:
  178. #TODO: If already unretracted, this shouldn't add anything to the time.
  179. cmd_num = 1
  180. parts = ["G1", "E" + str(buf.current_position[3] + 25)]
  181. # G0 and G1: Move
  182. if cmd_num in (0, 1):
  183. # Move
  184. if len(parts) > 0:
  185. value_dict = get_value_dict(parts[1:])
  186. new_position = copy.deepcopy(buf.current_position)
  187. new_position[0] = value_dict.get("X", new_position[0])
  188. new_position[1] = value_dict.get("Y", new_position[1])
  189. new_position[2] = value_dict.get("Z", new_position[2])
  190. new_position[3] = value_dict.get("E", new_position[3])
  191. distance = calc_distance(buf.current_position, new_position)
  192. self._distance_in_mm = distance
  193. self._delta = [
  194. new_position[0] - buf.current_position[0],
  195. new_position[1] - buf.current_position[1],
  196. new_position[2] - buf.current_position[2],
  197. new_position[3] - buf.current_position[3]
  198. ]
  199. self._abs_delta = [abs(x) for x in self._delta]
  200. self._max_travel = max(self._abs_delta)
  201. if self._max_travel > 0:
  202. feedrate = buf.current_feedrate
  203. if "F" in value_dict:
  204. feedrate = value_dict["F"]
  205. if feedrate < MACHINE_MINIMUM_FEEDRATE:
  206. feedrate = MACHINE_MINIMUM_FEEDRATE
  207. self._nominal_feedrate = feedrate
  208. self._distance = math.sqrt(self._abs_delta[0] ** 2 + self._abs_delta[1] ** 2 + self._abs_delta[2] ** 2)
  209. if self._distance == 0:
  210. self._distance = self._abs_delta[3]
  211. current_feedrate = [d * feedrate / self._distance for d in self._delta]
  212. current_abs_feedrate = [abs(f) for f in current_feedrate]
  213. feedrate_factor = min(1.0, MACHINE_MAX_FEEDRATE_X)
  214. feedrate_factor = min(feedrate_factor, MACHINE_MAX_FEEDRATE_Y)
  215. feedrate_factor = min(feedrate_factor, buf.max_z_feedrate)
  216. feedrate_factor = min(feedrate_factor, MACHINE_MAX_FEEDRATE_E)
  217. #TODO: XY_FREQUENCY_LIMIT
  218. current_feedrate = [f * feedrate_factor for f in current_feedrate]
  219. current_abs_feedrate = [f * feedrate_factor for f in current_abs_feedrate]
  220. self._nominal_feedrate *= feedrate_factor
  221. self._acceleration = MACHINE_ACCELERATION
  222. max_accelerations = [MACHINE_MAX_ACCELERATION_X, MACHINE_MAX_ACCELERATION_Y, MACHINE_MAX_ACCELERATION_Z, MACHINE_MAX_ACCELERATION_E]
  223. for n in range(len(max_accelerations)):
  224. if self._acceleration * self._abs_delta[n] / self._distance > max_accelerations[n]:
  225. self._acceleration = max_accelerations[n]
  226. vmax_junction = MACHINE_MAX_JERK_XY / 2
  227. vmax_junction_factor = 1.0
  228. if current_abs_feedrate[2] > buf.max_z_jerk / 2:
  229. vmax_junction = min(vmax_junction, buf.max_z_jerk)
  230. if current_abs_feedrate[3] > buf.max_e_jerk / 2:
  231. vmax_junction = min(vmax_junction, buf.max_e_jerk)
  232. vmax_junction = min(vmax_junction, self._nominal_feedrate)
  233. safe_speed = vmax_junction
  234. if buf.previous_nominal_feedrate > 0.0001:
  235. xy_jerk = math.sqrt((current_feedrate[0] - buf.previous_feedrate[0]) ** 2 + (current_feedrate[1] - buf.previous_feedrate[1]) ** 2)
  236. vmax_junction = self._nominal_feedrate
  237. if xy_jerk > MACHINE_MAX_JERK_XY:
  238. vmax_junction_factor = MACHINE_MAX_JERK_XY / xy_jerk
  239. if abs(current_feedrate[2] - buf.previous_feedrate[2]) > MACHINE_MAX_JERK_Z:
  240. vmax_junction_factor = min(vmax_junction_factor, (MACHINE_MAX_JERK_Z / abs(current_feedrate[2] - buf.previous_feedrate[2])))
  241. if abs(current_feedrate[3] - buf.previous_feedrate[3]) > MACHINE_MAX_JERK_E:
  242. vmax_junction_factor = min(vmax_junction_factor, (MACHINE_MAX_JERK_E / abs(current_feedrate[3] - buf.previous_feedrate[3])))
  243. vmax_junction = min(buf.previous_nominal_feedrate, vmax_junction * vmax_junction_factor) #Limit speed to max previous speed.
  244. self._max_entry_speed = vmax_junction
  245. v_allowable = calc_max_allowable_speed(-self._acceleration, MINIMUM_PLANNER_SPEED, self._distance)
  246. self._entry_speed = min(vmax_junction, v_allowable)
  247. self._nominal_length = self._nominal_feedrate <= v_allowable
  248. self._recalculate = True
  249. buf.previous_feedrate = current_feedrate
  250. buf.previous_nominal_feedrate = self._nominal_feedrate
  251. buf.current_position = new_position
  252. self.calculate_trapezoid(self._entry_speed / self._nominal_feedrate, safe_speed / self._nominal_feedrate)
  253. self._estimated_exec_time_in_ms = -1 #Signal that we need to include this in our second pass.
  254. # G4: Dwell, pause the machine for a period of time.
  255. elif cmd_num == 4:
  256. # Pnnn is time to wait in milliseconds (P0 wait until all previous moves are finished)
  257. cmd, num = get_code_and_num(parts[1])
  258. num = float(num)
  259. if cmd == "P":
  260. if num > 0:
  261. self._estimated_exec_time_in_ms = num
  262. def _handle_m(self, cmd_num: int, parts: List[str]) -> None:
  263. self._estimated_exec_time_in_ms = 0.0
  264. # M203: Set maximum feedrate. Only Z is supported. Assume 0 execution time.
  265. if cmd_num == 203:
  266. value_dict = get_value_dict(parts[1:])
  267. buf.max_z_feedrate = value_dict.get("Z", buf.max_z_feedrate)
  268. # M204: Set default acceleration. Assume 0 execution time.
  269. if cmd_num == 204:
  270. value_dict = get_value_dict(parts[1:])
  271. buf.acceleration = value_dict.get("S", buf.acceleration)
  272. # M205: Advanced settings, we only set jerks for Griffin. Assume 0 execution time.
  273. if cmd_num == 205:
  274. value_dict = get_value_dict(parts[1:])
  275. buf.max_xy_jerk = value_dict.get("XY", buf.max_xy_jerk)
  276. buf.max_z_jerk = value_dict.get("Z", buf.max_z_jerk)
  277. buf.max_e_jerk = value_dict.get("E", buf.max_e_jerk)
  278. def _handle_t(self, cmd_num: int, parts: List[str]) -> None:
  279. # Tn: Switching extruder. Assume 0 seconds. Actually more like 2.
  280. self._estimated_exec_time_in_ms = 0.0
  281. class CommandBuffer:
  282. def __init__(self, all_lines: List[str],
  283. buffer_filling_rate: float = DEFAULT_BUFFER_FILLING_RATE_IN_C_PER_MS,
  284. buffer_size: int = DEFAULT_BUFFER_SIZE
  285. ) -> None:
  286. self._all_lines = all_lines
  287. self._all_commands = list()
  288. self._buffer_filling_rate = buffer_filling_rate # type: float
  289. self._buffer_size = buffer_size # type: int
  290. self.acceleration = 3000
  291. self.current_position = [0, 0, 0, 0]
  292. self.current_feedrate = 0
  293. self.max_xy_jerk = MACHINE_MAX_JERK_XY
  294. self.max_z_jerk = MACHINE_MAX_JERK_Z
  295. self.max_e_jerk = MACHINE_MAX_JERK_E
  296. self.max_z_feedrate = MACHINE_MAX_FEEDRATE_Z
  297. # If the buffer can depletes less than this amount time, it can be filled up in time.
  298. lower_bound_buffer_depletion_time = self._buffer_size / self._buffer_filling_rate # type: float
  299. self._detection_time_frame = lower_bound_buffer_depletion_time
  300. self._code_count_limit = self._buffer_size
  301. self.previous_feedrate = [0, 0, 0, 0]
  302. self.previous_nominal_feedrate = 0
  303. print("Time Frame: %s" % self._detection_time_frame)
  304. print("Code Limit: %s" % self._code_count_limit)
  305. self._bad_frame_ranges = []
  306. def process(self) -> None:
  307. cmd0_idx = 0
  308. total_frame_time_in_ms = 0.0
  309. cmd_count = 0
  310. for idx, line in enumerate(self._all_lines):
  311. cmd = Command(line)
  312. cmd.parse()
  313. if not cmd.is_command:
  314. continue
  315. self._all_commands.append(cmd)
  316. #Second pass: Reverse kernel.
  317. kernel_commands = [None, None, None]
  318. for cmd in reversed(self._all_commands):
  319. if cmd.estimated_exec_time_in_ms >= 0:
  320. continue #Not a movement command.
  321. kernel_commands[2] = kernel_commands[1]
  322. kernel_commands[1] = kernel_commands[0]
  323. kernel_commands[0] = cmd
  324. self.reverse_pass_kernel(kernel_commands[0], kernel_commands[1], kernel_commands[2])
  325. #Third pass: Forward kernel.
  326. kernel_commands = [None, None, None]
  327. for cmd in self._all_commands:
  328. if cmd.estimated_exec_time_in_ms >= 0:
  329. continue #Not a movement command.
  330. kernel_commands[2] = kernel_commands[1]
  331. kernel_commands[1] = kernel_commands[0]
  332. kernel_commands[0] = cmd
  333. self.forward_pass_kernel(kernel_commands[0], kernel_commands[1], kernel_commands[2])
  334. self.forward_pass_kernel(kernel_commands[1], kernel_commands[2], None)
  335. #Fourth pass: Recalculate the commands that have _recalculate set.
  336. previous = None
  337. current = None
  338. for current in self._all_commands:
  339. if current.estimated_exec_time_in_ms >= 0:
  340. continue #Not a movement command.
  341. if previous:
  342. #Recalculate if current command entry or exit junction speed has changed.
  343. if previous._recalculate or current._recalculate:
  344. #Note: Entry and exit factors always >0 by all previous logic operators.
  345. previous.calculate_trapezoid(previous._entry_speed / previous._nominal_feedrate, current._entry_speed / previous._nominal_feedrate)
  346. previous._recalculate = False
  347. previous = current
  348. if current is not None:
  349. current.calculate_trapezoid(current._entry_speed / current._nominal_feedrate, MINIMUM_PLANNER_SPEED / current._nominal_feedrate)
  350. current._recalculate = False
  351. #Fifth pass: Compute time for movement commands.
  352. for cmd in self._all_commands:
  353. if cmd.estimated_exec_time_in_ms >= 0:
  354. continue #Not a movement command.
  355. plateau_distance = cmd._decelerate_after - cmd._accelerate_until
  356. cmd.estimated_exec_time_in_ms = calc_acceleration_time_from_distance(cmd._initial_feedrate, cmd._accelerate_until, cmd._acceleration)
  357. cmd.estimated_exec_time_in_ms += plateau_distance / cmd._nominal_feedrate
  358. cmd.estimated_exec_time_in_ms += calc_acceleration_time_from_distance(cmd._final_feedrate, (cmd._distancd - cmd._decelerate_after), cmd._acceleration)
  359. for idx, cmd in enumerate(self._all_commands):
  360. cmd_count += 1
  361. if idx > cmd0_idx or idx == 0:
  362. total_frame_time_in_ms += cmd.estimated_exec_time_in_ms
  363. if total_frame_time_in_ms > 1000.0:
  364. # Find the next starting command which makes the total execution time of the frame to be less than
  365. # 1 second.
  366. cmd0_idx += 1
  367. total_frame_time_in_ms -= self._all_commands[cmd0_idx].estimated_exec_time_in_ms
  368. cmd_count -= 1
  369. while total_frame_time_in_ms > 1000.0:
  370. cmd0_idx += 1
  371. total_frame_time_in_ms -= self._all_commands[cmd0_idx].estimated_exec_time_in_ms
  372. cmd_count -= 1
  373. # If within the current time frame the code count exceeds the limit, record that.
  374. if total_frame_time_in_ms <= self._detection_time_frame and cmd_count > self._code_count_limit:
  375. need_to_append = True
  376. if self._bad_frame_ranges:
  377. last_item = self._bad_frame_ranges[-1]
  378. if last_item["start_line"] == cmd0_idx:
  379. last_item["end_line"] = idx
  380. last_item["cmd_count"] = cmd_count
  381. last_item["time_in_ms"] = total_frame_time_in_ms
  382. need_to_append = False
  383. if need_to_append:
  384. self._bad_frame_ranges.append({"start_line": cmd0_idx,
  385. "end_line": idx,
  386. "cmd_count": cmd_count,
  387. "time_in_ms": total_frame_time_in_ms})
  388. def reverse_pass_kernel(self, previous: Optional[Command], current: Optional[Command], next: Optional[Command]) -> None:
  389. if not previous:
  390. return
  391. #If entry speed is already at the maximum entry speed, no need to
  392. #recheck. The command is cruising. If not, the command is in state of
  393. #acceleration or deceleration. Reset entry speed to maximum and check
  394. #for maximum allowable speed reductions to ensure maximum possible
  395. #planned speed.
  396. if current._entry_speed != current._max_entry_speed:
  397. #If nominal length is true, max junction speed is guaranteed to be
  398. #reached. Only compute for max allowable speed if block is
  399. #decelerating and nominal length is false.
  400. if not current._nominal_length and current._max_entry_speed > next._max_entry_speed:
  401. current._entry_speed = min(current._max_entry_speed, calc_max_allowable_speed(-current._acceleration, next._entry_speed, current._distance))
  402. else:
  403. current._entry_speed = current._max_entry_speed
  404. current._recalculate = True
  405. def forward_pass_kernel(self, previous: Optional[Command], current: Optional[Command], next: Optional[Command]) -> None:
  406. if not previous:
  407. return
  408. #If the previous command is an acceleration command, but it is not long
  409. #enough to complete the full speed change within the command, we need to
  410. #adjust the entry speed accordingly. Entry speeds have already been
  411. #reset, maximised and reverse planned by the reverse planner. If nominal
  412. #length is set, max junction speed is guaranteed to be reached. No need
  413. #to recheck.
  414. if not previous._nominal_length:
  415. if previous._entry_speed < current._entry_speed:
  416. entry_speed = min(current._entry_speed, calc_max_allowable_speed(-previous._acceleration, previous._entry_speed, previous._distance))
  417. if current._entry_speed != entry_speed:
  418. current._entry_speed = entry_speed
  419. current._recalculate = True
  420. def to_file(self, file_name: str) -> None:
  421. all_lines = [str(c) for c in self._all_commands]
  422. with open(file_name, "w", encoding = "utf-8") as f:
  423. f.writelines(all_lines)
  424. def report(self) -> None:
  425. for item in self._bad_frame_ranges:
  426. print("!!!!! potential bad frame from line %s to %s, code count = %s, in %s ms" % (
  427. item["start_line"], item["end_line"], item["cmd_count"], round(item["time_in_ms"], 4)))
  428. if __name__ == "__main__":
  429. if len(sys.argv) != 3:
  430. print("Usage: <input gcode> <output gcode>")
  431. sys.exit(1)
  432. in_filename = sys.argv[1]
  433. out_filename = sys.argv[2]
  434. with open(in_filename, "r", encoding = "utf-8") as f:
  435. all_lines = f.readlines()
  436. buf = CommandBuffer(all_lines)
  437. buf.process()
  438. buf.to_file(out_filename)
  439. buf.report()