PauseAtHeight.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from ..Script import Script
  4. from UM.Application import Application #To get the current printer's settings.
  5. from UM.Logger import Logger
  6. from typing import List, Tuple
  7. class PauseAtHeight(Script):
  8. def __init__(self) -> None:
  9. super().__init__()
  10. def getSettingDataString(self) -> str:
  11. return """{
  12. "name": "Pause at height",
  13. "key": "PauseAtHeight",
  14. "metadata": {},
  15. "version": 2,
  16. "settings":
  17. {
  18. "pause_at":
  19. {
  20. "label": "Pause at",
  21. "description": "Whether to pause at a certain height or at a certain layer.",
  22. "type": "enum",
  23. "options": {"height": "Height", "layer_no": "Layer Number"},
  24. "default_value": "height"
  25. },
  26. "pause_height":
  27. {
  28. "label": "Pause Height",
  29. "description": "At what height should the pause occur?",
  30. "unit": "mm",
  31. "type": "float",
  32. "default_value": 5.0,
  33. "minimum_value": "0",
  34. "minimum_value_warning": "0.27",
  35. "enabled": "pause_at == 'height'"
  36. },
  37. "pause_layer":
  38. {
  39. "label": "Pause Layer",
  40. "description": "At what layer should the pause occur?",
  41. "type": "int",
  42. "value": "math.floor((pause_height - 0.27) / 0.1) + 1",
  43. "minimum_value": "0",
  44. "minimum_value_warning": "1",
  45. "enabled": "pause_at == 'layer_no'"
  46. },
  47. "pause_method":
  48. {
  49. "label": "Method",
  50. "description": "The method or gcode command to use for pausing.",
  51. "type": "enum",
  52. "options": {"marlin": "Marlin (M0)", "griffin": "Griffin (M0, firmware retract)", "bq": "BQ (M25)", "reprap": "RepRap (M226)", "repetier": "Repetier/OctoPrint (@pause)"},
  53. "default_value": "marlin",
  54. "value": "\\\"griffin\\\" if machine_gcode_flavor==\\\"Griffin\\\" else \\\"reprap\\\" if machine_gcode_flavor==\\\"RepRap (RepRap)\\\" else \\\"repetier\\\" if machine_gcode_flavor==\\\"Repetier\\\" else \\\"bq\\\" if \\\"BQ\\\" in machine_name or \\\"Flying Bear Ghost 4S\\\" in machine_name else \\\"marlin\\\""
  55. },
  56. "disarm_timeout":
  57. {
  58. "label": "Disarm timeout",
  59. "description": "After this time steppers are going to disarm (meaning that they can easily lose their positions). Set this to 0 if you don't want to set any duration.",
  60. "type": "int",
  61. "value": "0",
  62. "minimum_value": "0",
  63. "minimum_value_warning": "0",
  64. "maximum_value_warning": "1800",
  65. "unit": "s"
  66. },
  67. "head_park_enabled":
  68. {
  69. "label": "Park Print",
  70. "description": "Instruct the head to move to a safe location when pausing. Leave this unchecked if your printer handles parking for you.",
  71. "type": "bool",
  72. "default_value": true,
  73. "enabled": "pause_method != \\\"griffin\\\""
  74. },
  75. "head_park_x":
  76. {
  77. "label": "Park Print Head X",
  78. "description": "What X location does the head move to when pausing.",
  79. "unit": "mm",
  80. "type": "float",
  81. "default_value": 190,
  82. "enabled": "head_park_enabled and pause_method != \\\"griffin\\\""
  83. },
  84. "head_park_y":
  85. {
  86. "label": "Park Print Head Y",
  87. "description": "What Y location does the head move to when pausing.",
  88. "unit": "mm",
  89. "type": "float",
  90. "default_value": 190,
  91. "enabled": "head_park_enabled and pause_method != \\\"griffin\\\""
  92. },
  93. "head_move_z":
  94. {
  95. "label": "Head move Z",
  96. "description": "The Height of Z-axis retraction before parking.",
  97. "unit": "mm",
  98. "type": "float",
  99. "default_value": 15.0,
  100. "enabled": "head_park_enabled and pause_method == \\\"repetier\\\""
  101. },
  102. "retraction_amount":
  103. {
  104. "label": "Retraction",
  105. "description": "How much filament must be retracted at pause.",
  106. "unit": "mm",
  107. "type": "float",
  108. "default_value": 0,
  109. "enabled": "pause_method != \\\"griffin\\\""
  110. },
  111. "retraction_speed":
  112. {
  113. "label": "Retraction Speed",
  114. "description": "How fast to retract the filament.",
  115. "unit": "mm/s",
  116. "type": "float",
  117. "default_value": 25,
  118. "enabled": "pause_method not in [\\\"griffin\\\", \\\"repetier\\\"]"
  119. },
  120. "extrude_amount":
  121. {
  122. "label": "Extrude Amount",
  123. "description": "How much filament should be extruded after pause. This is needed when doing a material change on Ultimaker2's to compensate for the retraction after the change. In that case 128+ is recommended.",
  124. "unit": "mm",
  125. "type": "float",
  126. "default_value": 0,
  127. "enabled": "pause_method != \\\"griffin\\\""
  128. },
  129. "extrude_speed":
  130. {
  131. "label": "Extrude Speed",
  132. "description": "How fast to extrude the material after pause.",
  133. "unit": "mm/s",
  134. "type": "float",
  135. "default_value": 3.3333,
  136. "enabled": "pause_method not in [\\\"griffin\\\", \\\"repetier\\\"]"
  137. },
  138. "redo_layer":
  139. {
  140. "label": "Redo Layer",
  141. "description": "Redo the last layer before the pause, to get the filament flowing again after having oozed a bit during the pause.",
  142. "type": "bool",
  143. "default_value": false
  144. },
  145. "standby_temperature":
  146. {
  147. "label": "Standby Temperature",
  148. "description": "Change the temperature during the pause.",
  149. "unit": "°C",
  150. "type": "int",
  151. "default_value": 0,
  152. "enabled": "pause_method not in [\\\"griffin\\\", \\\"repetier\\\"]"
  153. },
  154. "display_text":
  155. {
  156. "label": "Display Text",
  157. "description": "Text that should appear on the display while paused. If left empty, there will not be any message.",
  158. "type": "str",
  159. "default_value": "",
  160. "enabled": "pause_method != \\\"repetier\\\""
  161. },
  162. "machine_name":
  163. {
  164. "label": "Machine Type",
  165. "description": "The name of your 3D printer model. This setting is controlled by the script and will not be visible.",
  166. "default_value": "Unknown",
  167. "type": "str",
  168. "enabled": false
  169. },
  170. "machine_gcode_flavor":
  171. {
  172. "label": "G-code flavor",
  173. "description": "The type of g-code to be generated. This setting is controlled by the script and will not be visible.",
  174. "type": "enum",
  175. "options":
  176. {
  177. "RepRap (Marlin/Sprinter)": "Marlin",
  178. "RepRap (Volumetric)": "Marlin (Volumetric)",
  179. "RepRap (RepRap)": "RepRap",
  180. "UltiGCode": "Ultimaker 2",
  181. "Griffin": "Griffin",
  182. "Makerbot": "Makerbot",
  183. "BFB": "Bits from Bytes",
  184. "MACH3": "Mach3",
  185. "Repetier": "Repetier"
  186. },
  187. "default_value": "RepRap (Marlin/Sprinter)",
  188. "enabled": false
  189. },
  190. "custom_gcode_before_pause":
  191. {
  192. "label": "G-code Before Pause",
  193. "description": "Any custom g-code to run before the pause, for example, M300 S440 P200 to beep.",
  194. "type": "str",
  195. "default_value": ""
  196. },
  197. "custom_gcode_after_pause":
  198. {
  199. "label": "G-code After Pause",
  200. "description": "Any custom g-code to run after the pause, for example, M300 S440 P200 to beep.",
  201. "type": "str",
  202. "default_value": ""
  203. }
  204. }
  205. }"""
  206. ## Copy machine name and gcode flavor from global stack so we can use their value in the script stack
  207. def initialize(self) -> None:
  208. super().initialize()
  209. global_container_stack = Application.getInstance().getGlobalContainerStack()
  210. if global_container_stack is None or self._instance is None:
  211. return
  212. for key in ["machine_name", "machine_gcode_flavor"]:
  213. self._instance.setProperty(key, "value", global_container_stack.getProperty(key, "value"))
  214. ## Get the X and Y values for a layer (will be used to get X and Y of the
  215. # layer after the pause).
  216. def getNextXY(self, layer: str) -> Tuple[float, float]:
  217. """Get the X and Y values for a layer (will be used to get X and Y of the layer after the pause)."""
  218. lines = layer.split("\n")
  219. for line in lines:
  220. if line.startswith(("G0", "G1", "G2", "G3")):
  221. if self.getValue(line, "X") is not None and self.getValue(line, "Y") is not None:
  222. x = self.getValue(line, "X")
  223. y = self.getValue(line, "Y")
  224. return x, y
  225. return 0, 0
  226. def execute(self, data: List[str]) -> List[str]:
  227. """Inserts the pause commands.
  228. :param data: List of layers.
  229. :return: New list of layers.
  230. """
  231. pause_at = self.getSettingValueByKey("pause_at")
  232. pause_height = self.getSettingValueByKey("pause_height")
  233. pause_layer = self.getSettingValueByKey("pause_layer")
  234. disarm_timeout = self.getSettingValueByKey("disarm_timeout")
  235. retraction_amount = self.getSettingValueByKey("retraction_amount")
  236. retraction_speed = self.getSettingValueByKey("retraction_speed")
  237. extrude_amount = self.getSettingValueByKey("extrude_amount")
  238. extrude_speed = self.getSettingValueByKey("extrude_speed")
  239. park_enabled = self.getSettingValueByKey("head_park_enabled")
  240. park_x = self.getSettingValueByKey("head_park_x")
  241. park_y = self.getSettingValueByKey("head_park_y")
  242. move_z = self.getSettingValueByKey("head_move_z")
  243. layers_started = False
  244. redo_layer = self.getSettingValueByKey("redo_layer")
  245. standby_temperature = self.getSettingValueByKey("standby_temperature")
  246. firmware_retract = Application.getInstance().getGlobalContainerStack().getProperty("machine_firmware_retract", "value")
  247. control_temperatures = Application.getInstance().getGlobalContainerStack().getProperty("machine_nozzle_temp_enabled", "value")
  248. initial_layer_height = Application.getInstance().getGlobalContainerStack().getProperty("layer_height_0", "value")
  249. display_text = self.getSettingValueByKey("display_text")
  250. gcode_before = self.getSettingValueByKey("custom_gcode_before_pause")
  251. gcode_after = self.getSettingValueByKey("custom_gcode_after_pause")
  252. pause_method = self.getSettingValueByKey("pause_method")
  253. pause_command = {
  254. "marlin": self.putValue(M = 0),
  255. "griffin": self.putValue(M = 0),
  256. "bq": self.putValue(M = 25),
  257. "reprap": self.putValue(M = 226),
  258. "repetier": self.putValue("@pause now change filament and press continue printing")
  259. }[pause_method]
  260. # T = ExtruderManager.getInstance().getActiveExtruderStack().getProperty("material_print_temperature", "value")
  261. # use offset to calculate the current height: <current_height> = <current_z> - <layer_0_z>
  262. layer_0_z = 0
  263. current_z = 0
  264. current_height = 0
  265. current_layer = 0
  266. current_extrusion_f = 0
  267. got_first_g_cmd_on_layer_0 = False
  268. current_t = 0 #Tracks the current extruder for tracking the target temperature.
  269. target_temperature = {} #Tracks the current target temperature for each extruder.
  270. nbr_negative_layers = 0
  271. for index, layer in enumerate(data):
  272. lines = layer.split("\n")
  273. # Scroll each line of instruction for each layer in the G-code
  274. for line in lines:
  275. # Fist positive layer reached
  276. if ";LAYER:0" in line:
  277. layers_started = True
  278. # Count nbr of negative layers (raft)
  279. elif ";LAYER:-" in line:
  280. nbr_negative_layers += 1
  281. #Track the latest printing temperature in order to resume at the correct temperature.
  282. if line.startswith("T"):
  283. current_t = self.getValue(line, "T")
  284. m = self.getValue(line, "M")
  285. if m is not None and (m == 104 or m == 109) and self.getValue(line, "S") is not None:
  286. extruder = current_t
  287. if self.getValue(line, "T") is not None:
  288. extruder = self.getValue(line, "T")
  289. target_temperature[extruder] = self.getValue(line, "S")
  290. if not layers_started:
  291. continue
  292. # Look for the feed rate of an extrusion instruction
  293. if self.getValue(line, "F") is not None and self.getValue(line, "E") is not None:
  294. current_extrusion_f = self.getValue(line, "F")
  295. # If a Z instruction is in the line, read the current Z
  296. if self.getValue(line, "Z") is not None:
  297. current_z = self.getValue(line, "Z")
  298. if pause_at == "height":
  299. # Ignore if the line is not G1 or G0
  300. if self.getValue(line, "G") != 1 and self.getValue(line, "G") != 0:
  301. continue
  302. # This block is executed once, the first time there is a G
  303. # command, to get the z offset (z for first positive layer)
  304. if not got_first_g_cmd_on_layer_0:
  305. layer_0_z = current_z - initial_layer_height
  306. got_first_g_cmd_on_layer_0 = True
  307. current_height = current_z - layer_0_z
  308. if current_height < pause_height:
  309. continue # Scan the enitre layer, z-changes are not always on the same/first line.
  310. # Pause at layer
  311. else:
  312. if not line.startswith(";LAYER:"):
  313. continue
  314. current_layer = line[len(";LAYER:"):]
  315. try:
  316. current_layer = int(current_layer)
  317. # Couldn't cast to int. Something is wrong with this
  318. # g-code data
  319. except ValueError:
  320. continue
  321. if current_layer < pause_layer - nbr_negative_layers:
  322. continue
  323. prev_layer = data[index - 1]
  324. prev_lines = prev_layer.split("\n")
  325. current_e = 0.
  326. # Access last layer, browse it backwards to find
  327. # last extruder absolute position
  328. for prevLine in reversed(prev_lines):
  329. current_e = self.getValue(prevLine, "E", -1)
  330. if current_e >= 0:
  331. break
  332. # and also find last X,Y
  333. for prevLine in reversed(prev_lines):
  334. if prevLine.startswith(("G0", "G1", "G2", "G3")):
  335. if self.getValue(prevLine, "X") is not None and self.getValue(prevLine, "Y") is not None:
  336. x = self.getValue(prevLine, "X")
  337. y = self.getValue(prevLine, "Y")
  338. break
  339. # Maybe redo the last layer.
  340. if redo_layer:
  341. prev_layer = data[index - 1]
  342. layer = prev_layer + layer
  343. # Get extruder's absolute position at the
  344. # beginning of the redone layer.
  345. # see https://github.com/nallath/PostProcessingPlugin/issues/55
  346. # Get X and Y from the next layer (better position for
  347. # the nozzle)
  348. x, y = self.getNextXY(layer)
  349. prev_lines = prev_layer.split("\n")
  350. for lin in prev_lines:
  351. new_e = self.getValue(lin, "E", current_e)
  352. if new_e != current_e:
  353. current_e = new_e
  354. break
  355. prepend_gcode = ";TYPE:CUSTOM\n"
  356. prepend_gcode += ";added code by post processing\n"
  357. prepend_gcode += ";script: PauseAtHeight.py\n"
  358. if pause_at == "height":
  359. prepend_gcode += ";current z: {z}\n".format(z = current_z)
  360. prepend_gcode += ";current height: {height}\n".format(height = current_height)
  361. else:
  362. prepend_gcode += ";current layer: {layer}\n".format(layer = current_layer)
  363. if pause_method == "repetier":
  364. #Retraction
  365. prepend_gcode += self.putValue(M = 83) + " ; switch to relative E values for any needed retraction\n"
  366. if retraction_amount != 0:
  367. prepend_gcode += self.putValue(G = 1, E = -retraction_amount, F = 6000) + "\n"
  368. if park_enabled:
  369. #Move the head away
  370. prepend_gcode += self.putValue(G = 1, Z = current_z + 1, F = 300) + " ; move up a millimeter to get out of the way\n"
  371. prepend_gcode += self.putValue(G = 1, X = park_x, Y = park_y, F = 9000) + "\n"
  372. if current_z < move_z:
  373. prepend_gcode += self.putValue(G = 1, Z = current_z + move_z, F = 300) + "\n"
  374. #Disable the E steppers
  375. prepend_gcode += self.putValue(M = 84, E = 0) + "\n"
  376. elif pause_method != "griffin":
  377. # Retraction
  378. prepend_gcode += self.putValue(M = 83) + " ; switch to relative E values for any needed retraction\n"
  379. if retraction_amount != 0:
  380. if firmware_retract: #Can't set the distance directly to what the user wants. We have to choose ourselves.
  381. retraction_count = 1 if control_temperatures else 3 #Retract more if we don't control the temperature.
  382. for i in range(retraction_count):
  383. prepend_gcode += self.putValue(G = 10) + "\n"
  384. else:
  385. prepend_gcode += self.putValue(G = 1, E = -retraction_amount, F = retraction_speed * 60) + "\n"
  386. if park_enabled:
  387. # Move the head away
  388. prepend_gcode += self.putValue(G = 1, Z = current_z + 1, F = 300) + " ; move up a millimeter to get out of the way\n"
  389. # This line should be ok
  390. prepend_gcode += self.putValue(G = 1, X = park_x, Y = park_y, F = 9000) + "\n"
  391. if current_z < 15:
  392. prepend_gcode += self.putValue(G = 1, Z = 15, F = 300) + " ; too close to bed--move to at least 15mm\n"
  393. if control_temperatures:
  394. # Set extruder standby temperature
  395. prepend_gcode += self.putValue(M = 104, S = standby_temperature) + " ; standby temperature\n"
  396. if display_text:
  397. prepend_gcode += "M117 " + display_text + "\n"
  398. # Set the disarm timeout
  399. if disarm_timeout > 0:
  400. prepend_gcode += self.putValue(M = 18, S = disarm_timeout) + " ; Set the disarm timeout\n"
  401. # Set a custom GCODE section before pause
  402. if gcode_before:
  403. prepend_gcode += gcode_before + "\n"
  404. # Wait till the user continues printing
  405. prepend_gcode += pause_command + " ; Do the actual pause\n"
  406. # Set a custom GCODE section before pause
  407. if gcode_after:
  408. prepend_gcode += gcode_after + "\n"
  409. if pause_method == "repetier":
  410. #Push the filament back,
  411. if retraction_amount != 0:
  412. prepend_gcode += self.putValue(G = 1, E = retraction_amount, F = 6000) + "\n"
  413. # Optionally extrude material
  414. if extrude_amount != 0:
  415. prepend_gcode += self.putValue(G = 1, E = extrude_amount, F = 200) + "\n"
  416. prepend_gcode += self.putValue("@info wait for cleaning nozzle from previous filament") + "\n"
  417. prepend_gcode += self.putValue("@pause remove the waste filament from parking area and press continue printing") + "\n"
  418. # and retract again, the properly primes the nozzle when changing filament.
  419. if retraction_amount != 0:
  420. prepend_gcode += self.putValue(G = 1, E = -retraction_amount, F = 6000) + "\n"
  421. #Move the head back
  422. if park_enabled:
  423. prepend_gcode += self.putValue(G = 1, X = x, Y = y, F = 9000) + "\n"
  424. prepend_gcode += self.putValue(G = 1, Z = current_z, F = 300) + "\n"
  425. if retraction_amount != 0:
  426. prepend_gcode += self.putValue(G = 1, E = retraction_amount, F = 6000) + "\n"
  427. if current_extrusion_f != 0:
  428. prepend_gcode += self.putValue(G = 1, F = current_extrusion_f) + " ; restore extrusion feedrate\n"
  429. else:
  430. Logger.log("w", "No previous feedrate found in gcode, feedrate for next layer(s) might be incorrect")
  431. prepend_gcode += self.putValue(M = 82) + "\n"
  432. # reset extrude value to pre pause value
  433. prepend_gcode += self.putValue(G = 92, E = current_e) + "\n"
  434. elif pause_method != "griffin":
  435. if control_temperatures:
  436. # Set extruder resume temperature
  437. prepend_gcode += self.putValue(M = 109, S = int(target_temperature.get(current_t, 0))) + " ; resume temperature\n"
  438. # Push the filament back,
  439. if retraction_amount != 0:
  440. prepend_gcode += self.putValue(G = 1, E = retraction_amount, F = retraction_speed * 60) + "\n"
  441. # Optionally extrude material
  442. if extrude_amount != 0:
  443. prepend_gcode += self.putValue(G = 1, E = extrude_amount, F = extrude_speed * 60) + "\n"
  444. # and retract again, the properly primes the nozzle
  445. # when changing filament.
  446. if retraction_amount != 0:
  447. prepend_gcode += self.putValue(G = 1, E = -retraction_amount, F = retraction_speed * 60) + "\n"
  448. # Move the head back
  449. if park_enabled:
  450. if current_z < 15:
  451. prepend_gcode += self.putValue(G = 1, Z = current_z, F = 300) + "\n"
  452. prepend_gcode += self.putValue(G = 1, X = x, Y = y, F = 9000) + "\n"
  453. prepend_gcode += self.putValue(G = 1, Z = current_z, F = 300) + " ; move back down to resume height\n"
  454. if retraction_amount != 0:
  455. if firmware_retract: #Can't set the distance directly to what the user wants. We have to choose ourselves.
  456. retraction_count = 1 if control_temperatures else 3 #Retract more if we don't control the temperature.
  457. for i in range(retraction_count):
  458. prepend_gcode += self.putValue(G = 11) + "\n"
  459. else:
  460. prepend_gcode += self.putValue(G = 1, E = retraction_amount, F = retraction_speed * 60) + "\n"
  461. if current_extrusion_f != 0:
  462. prepend_gcode += self.putValue(G = 1, F = current_extrusion_f) + " ; restore extrusion feedrate\n"
  463. else:
  464. Logger.log("w", "No previous feedrate found in gcode, feedrate for next layer(s) might be incorrect")
  465. extrusion_mode_string = "absolute"
  466. extrusion_mode_numeric = 82
  467. relative_extrusion = Application.getInstance().getGlobalContainerStack().getProperty("relative_extrusion", "value")
  468. if relative_extrusion:
  469. extrusion_mode_string = "relative"
  470. extrusion_mode_numeric = 83
  471. prepend_gcode += self.putValue(M = extrusion_mode_numeric) + " ; switch back to " + extrusion_mode_string + " E values\n"
  472. # reset extrude value to pre pause value
  473. prepend_gcode += self.putValue(G = 92, E = current_e) + "\n"
  474. elif redo_layer:
  475. # All other options reset the E value to what it was before the pause because E things were added.
  476. # If it's not yet reset, it still needs to be reset if there were any redo layers.
  477. prepend_gcode += self.putValue(G = 92, E = current_e) + "\n"
  478. layer = prepend_gcode + layer
  479. # Override the data of this layer with the
  480. # modified data
  481. data[index] = layer
  482. return data
  483. return data