ChangeAtZ.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  1. # ChangeAtZ script - Change printing parameters at a given height
  2. # This script is the successor of the TweakAtZ plugin for legacy Cura.
  3. # It contains code from the TweakAtZ plugin V1.0-V4.x and from the ExampleScript by Jaime van Kessel, Ultimaker B.V.
  4. # It runs with the PostProcessingPlugin which is released under the terms of the AGPLv3 or higher.
  5. # This script is licensed under the Creative Commons - Attribution - Share Alike (CC BY-SA) terms
  6. # Authors of the ChangeAtZ plugin / script:
  7. # Written by Steven Morlock, smorloc@gmail.com
  8. # Modified by Ricardo Gomez, ricardoga@otulook.com, to add Bed Temperature and make it work with Cura_13.06.04+
  9. # Modified by Stefan Heule, Dim3nsioneer@gmx.ch since V3.0 (see changelog below)
  10. # Modified by Jaime van Kessel (Ultimaker), j.vankessel@ultimaker.com to make it work for 15.10 / 2.x
  11. # Modified by Ruben Dulek (Ultimaker), r.dulek@ultimaker.com, to debug.
  12. # Modified by Wes Hanney, https://github.com/novamxd, Retract Length + Speed, Clean up
  13. # history / changelog:
  14. # V3.0.1: TweakAtZ-state default 1 (i.e. the plugin works without any TweakAtZ comment)
  15. # V3.1: Recognizes UltiGCode and deactivates value reset, fan speed added, alternatively layer no. to tweak at,
  16. # extruder three temperature disabled by "#Ex3"
  17. # V3.1.1: Bugfix reset flow rate
  18. # V3.1.2: Bugfix disable TweakAtZ on Cool Head Lift
  19. # V3.2: Flow rate for specific extruder added (only for 2 extruders), bugfix parser,
  20. # added speed reset at the end of the print
  21. # V4.0: Progress bar, tweaking over multiple layers, M605&M606 implemented, reset after one layer option,
  22. # extruder three code removed, tweaking print speed, save call of Publisher class,
  23. # uses previous value from other plugins also on UltiGCode
  24. # V4.0.1: Bugfix for doubled G1 commands
  25. # V4.0.2: Uses Cura progress bar instead of its own
  26. # V4.0.3: Bugfix for cool head lift (contributed by luisonoff)
  27. # V4.9.91: First version for Cura 15.06.x and PostProcessingPlugin
  28. # V4.9.92: Modifications for Cura 15.10
  29. # V4.9.93: Minor bugfixes (input settings) / documentation
  30. # V4.9.94: Bugfix Combobox-selection; remove logger
  31. # V5.0: Bugfix for fall back after one layer and doubled G0 commands when using print speed tweak, Initial version for Cura 2.x
  32. # V5.0.1: Bugfix for calling unknown property 'bedTemp' of previous settings storage and unknown variable 'speed'
  33. # V5.1: API Changes included for use with Cura 2.2
  34. # V5.2.0: Wes Hanney. Added support for changing Retract Length and Speed. Removed layer spread option. Fixed issue of cumulative ChangeZ
  35. # mods so they can now properly be stacked on top of each other. Applied code refactoring to clean up various coding styles. Added comments.
  36. # Broke up functions for clarity. Split up class so it can be debugged outside of Cura.
  37. # V5.2.1: Wes Hanney. Added support for firmware based retractions. Fixed issue of properly restoring previous values in single layer option.
  38. # Added support for outputting changes to LCD (untested). Added type hints to most functions and variables. Added more comments. Created GCodeCommand
  39. # class for better detection of G1 vs G10 or G11 commands, and accessing arguments. Moved most GCode methods to GCodeCommand class. Improved wording
  40. # of Single Layer vs Keep Layer to better reflect what was happening.
  41. # Uses -
  42. # M220 S<factor in percent> - set speed factor override percentage
  43. # M221 S<factor in percent> - set flow factor override percentage
  44. # M221 S<factor in percent> T<0-#toolheads> - set flow factor override percentage for single extruder
  45. # M104 S<temp> T<0-#toolheads> - set extruder <T> to target temperature <S>
  46. # M140 S<temp> - set bed target temperature
  47. # M106 S<PWM> - set fan speed to target speed <S>
  48. # M207 S<mm> F<mm/m> - set the retract length <S> or feed rate <F>
  49. # M117 - output the current changes
  50. from typing import List, Dict
  51. from ..Script import Script
  52. import re
  53. # this was broken up into a separate class so the main ChangeZ script could be debugged outside of Cura
  54. class ChangeAtZ(Script):
  55. version = "5.2.1"
  56. def getSettingDataString(self):
  57. return """{
  58. "name": "ChangeAtZ """ + self.version + """(Experimental)",
  59. "key": "ChangeAtZ",
  60. "metadata": {},
  61. "version": 2,
  62. "settings": {
  63. "caz_enabled": {
  64. "label": "Enabled",
  65. "description": "Allows adding multiple ChangeZ mods and disabling them as needed.",
  66. "type": "bool",
  67. "default_value": true
  68. },
  69. "a_trigger": {
  70. "label": "Trigger",
  71. "description": "Trigger at height or at layer no.",
  72. "type": "enum",
  73. "options": {
  74. "height": "Height",
  75. "layer_no": "Layer No."
  76. },
  77. "default_value": "height"
  78. },
  79. "b_targetZ": {
  80. "label": "Change Height",
  81. "description": "Z height to change at",
  82. "unit": "mm",
  83. "type": "float",
  84. "default_value": 5.0,
  85. "minimum_value": "0",
  86. "minimum_value_warning": "0.1",
  87. "maximum_value_warning": "230",
  88. "enabled": "a_trigger == 'height'"
  89. },
  90. "b_targetL": {
  91. "label": "Change Layer",
  92. "description": "Layer no. to change at",
  93. "unit": "",
  94. "type": "int",
  95. "default_value": 1,
  96. "minimum_value": "-100",
  97. "minimum_value_warning": "-1",
  98. "enabled": "a_trigger == 'layer_no'"
  99. },
  100. "c_behavior": {
  101. "label": "Apply To",
  102. "description": "Target Layer + Subsequent Layers is good for testing changes between ranges of layers, ex: Layer 0 to 10 or 0mm to 5mm. Single layer is good for testing changes at a single layer, ex: at Layer 10 or 5mm only.",
  103. "type": "enum",
  104. "options": {
  105. "keep_value": "Target Layer + Subsequent Layers",
  106. "single_layer": "Target Layer Only"
  107. },
  108. "default_value": "keep_value"
  109. },
  110. "caz_output_to_display": {
  111. "label": "Output to Display",
  112. "description": "Displays the current changes to the LCD",
  113. "type": "bool",
  114. "default_value": false
  115. },
  116. "e1_Change_speed": {
  117. "label": "Change Speed",
  118. "description": "Select if total speed (print and travel) has to be changed",
  119. "type": "bool",
  120. "default_value": false
  121. },
  122. "e2_speed": {
  123. "label": "Speed",
  124. "description": "New total speed (print and travel)",
  125. "unit": "%",
  126. "type": "int",
  127. "default_value": 100,
  128. "minimum_value": "1",
  129. "minimum_value_warning": "10",
  130. "maximum_value_warning": "200",
  131. "enabled": "e1_Change_speed"
  132. },
  133. "f1_Change_printspeed": {
  134. "label": "Change Print Speed",
  135. "description": "Select if print speed has to be changed",
  136. "type": "bool",
  137. "default_value": false
  138. },
  139. "f2_printspeed": {
  140. "label": "Print Speed",
  141. "description": "New print speed",
  142. "unit": "%",
  143. "type": "int",
  144. "default_value": 100,
  145. "minimum_value": "1",
  146. "minimum_value_warning": "10",
  147. "maximum_value_warning": "200",
  148. "enabled": "f1_Change_printspeed"
  149. },
  150. "g1_Change_flowrate": {
  151. "label": "Change Flow Rate",
  152. "description": "Select if flow rate has to be changed",
  153. "type": "bool",
  154. "default_value": false
  155. },
  156. "g2_flowrate": {
  157. "label": "Flow Rate",
  158. "description": "New Flow rate",
  159. "unit": "%",
  160. "type": "int",
  161. "default_value": 100,
  162. "minimum_value": "1",
  163. "minimum_value_warning": "10",
  164. "maximum_value_warning": "200",
  165. "enabled": "g1_Change_flowrate"
  166. },
  167. "g3_Change_flowrateOne": {
  168. "label": "Change Flow Rate 1",
  169. "description": "Select if first extruder flow rate has to be changed",
  170. "type": "bool",
  171. "default_value": false
  172. },
  173. "g4_flowrateOne": {
  174. "label": "Flow Rate One",
  175. "description": "New Flow rate Extruder 1",
  176. "unit": "%",
  177. "type": "int",
  178. "default_value": 100,
  179. "minimum_value": "1",
  180. "minimum_value_warning": "10",
  181. "maximum_value_warning": "200",
  182. "enabled": "g3_Change_flowrateOne"
  183. },
  184. "g5_Change_flowrateTwo": {
  185. "label": "Change Flow Rate 2",
  186. "description": "Select if second extruder flow rate has to be changed",
  187. "type": "bool",
  188. "default_value": false
  189. },
  190. "g6_flowrateTwo": {
  191. "label": "Flow Rate two",
  192. "description": "New Flow rate Extruder 2",
  193. "unit": "%",
  194. "type": "int",
  195. "default_value": 100,
  196. "minimum_value": "1",
  197. "minimum_value_warning": "10",
  198. "maximum_value_warning": "200",
  199. "enabled": "g5_Change_flowrateTwo"
  200. },
  201. "h1_Change_bedTemp": {
  202. "label": "Change Bed Temp",
  203. "description": "Select if Bed Temperature has to be changed",
  204. "type": "bool",
  205. "default_value": false
  206. },
  207. "h2_bedTemp": {
  208. "label": "Bed Temp",
  209. "description": "New Bed Temperature",
  210. "unit": "C",
  211. "type": "float",
  212. "default_value": 60,
  213. "minimum_value": "0",
  214. "minimum_value_warning": "30",
  215. "maximum_value_warning": "120",
  216. "enabled": "h1_Change_bedTemp"
  217. },
  218. "i1_Change_extruderOne": {
  219. "label": "Change Extruder 1 Temp",
  220. "description": "Select if First Extruder Temperature has to be changed",
  221. "type": "bool",
  222. "default_value": false
  223. },
  224. "i2_extruderOne": {
  225. "label": "Extruder 1 Temp",
  226. "description": "New First Extruder Temperature",
  227. "unit": "C",
  228. "type": "float",
  229. "default_value": 190,
  230. "minimum_value": "0",
  231. "minimum_value_warning": "160",
  232. "maximum_value_warning": "250",
  233. "enabled": "i1_Change_extruderOne"
  234. },
  235. "i3_Change_extruderTwo": {
  236. "label": "Change Extruder 2 Temp",
  237. "description": "Select if Second Extruder Temperature has to be changed",
  238. "type": "bool",
  239. "default_value": false
  240. },
  241. "i4_extruderTwo": {
  242. "label": "Extruder 2 Temp",
  243. "description": "New Second Extruder Temperature",
  244. "unit": "C",
  245. "type": "float",
  246. "default_value": 190,
  247. "minimum_value": "0",
  248. "minimum_value_warning": "160",
  249. "maximum_value_warning": "250",
  250. "enabled": "i3_Change_extruderTwo"
  251. },
  252. "j1_Change_fanSpeed": {
  253. "label": "Change Fan Speed",
  254. "description": "Select if Fan Speed has to be changed",
  255. "type": "bool",
  256. "default_value": false
  257. },
  258. "j2_fanSpeed": {
  259. "label": "Fan Speed",
  260. "description": "New Fan Speed (0-100)",
  261. "unit": "%",
  262. "type": "int",
  263. "default_value": 100,
  264. "minimum_value": "0",
  265. "minimum_value_warning": "0",
  266. "maximum_value_warning": "100",
  267. "enabled": "j1_Change_fanSpeed"
  268. },
  269. "caz_change_retract": {
  270. "label": "Change Retraction",
  271. "description": "Indicates you would like to modify retraction properties.",
  272. "type": "bool",
  273. "default_value": false
  274. },
  275. "caz_retractstyle": {
  276. "label": "Retract Style",
  277. "description": "Specify if you're using firmware retraction or linear move based retractions. Check your printer settings to see which you're using.",
  278. "type": "enum",
  279. "options": {
  280. "linear": "Linear Move",
  281. "firmware": "Firmware"
  282. },
  283. "default_value": "linear",
  284. "enabled": "caz_change_retract"
  285. },
  286. "caz_change_retractfeedrate": {
  287. "label": "Change Retract Feed Rate",
  288. "description": "Changes the retraction feed rate during print",
  289. "type": "bool",
  290. "default_value": false,
  291. "enabled": "caz_change_retract"
  292. },
  293. "caz_retractfeedrate": {
  294. "label": "Retract Feed Rate",
  295. "description": "New Retract Feed Rate (mm/s)",
  296. "unit": "mm/s",
  297. "type": "float",
  298. "default_value": 40,
  299. "minimum_value": "0",
  300. "minimum_value_warning": "0",
  301. "maximum_value_warning": "100",
  302. "enabled": "caz_change_retractfeedrate"
  303. },
  304. "caz_change_retractlength": {
  305. "label": "Change Retract Length",
  306. "description": "Changes the retraction length during print",
  307. "type": "bool",
  308. "default_value": false,
  309. "enabled": "caz_change_retract"
  310. },
  311. "caz_retractlength": {
  312. "label": "Retract Length",
  313. "description": "New Retract Length (mm)",
  314. "unit": "mm",
  315. "type": "float",
  316. "default_value": 6,
  317. "minimum_value": "0",
  318. "minimum_value_warning": "0",
  319. "maximum_value_warning": "20",
  320. "enabled": "caz_change_retractlength"
  321. }
  322. }
  323. }"""
  324. def __init__(self):
  325. super().__init__()
  326. def execute(self, data):
  327. caz_instance = ChangeAtZProcessor()
  328. caz_instance.targetValues = {}
  329. # copy over our settings to our change z class
  330. self.setIntSettingIfEnabled(caz_instance, "e1_Change_speed", "speed", "e2_speed")
  331. self.setIntSettingIfEnabled(caz_instance, "f1_Change_printspeed", "printspeed", "f2_printspeed")
  332. self.setIntSettingIfEnabled(caz_instance, "g1_Change_flowrate", "flowrate", "g2_flowrate")
  333. self.setIntSettingIfEnabled(caz_instance, "g3_Change_flowrateOne", "flowrateOne", "g4_flowrateOne")
  334. self.setIntSettingIfEnabled(caz_instance, "g5_Change_flowrateTwo", "flowrateTwo", "g6_flowrateTwo")
  335. self.setFloatSettingIfEnabled(caz_instance, "h1_Change_bedTemp", "bedTemp", "h2_bedTemp")
  336. self.setFloatSettingIfEnabled(caz_instance, "i1_Change_extruderOne", "extruderOne", "i2_extruderOne")
  337. self.setFloatSettingIfEnabled(caz_instance, "i3_Change_extruderTwo", "extruderTwo", "i4_extruderTwo")
  338. self.setIntSettingIfEnabled(caz_instance, "j1_Change_fanSpeed", "fanSpeed", "j2_fanSpeed")
  339. self.setFloatSettingIfEnabled(caz_instance, "caz_change_retractfeedrate", "retractfeedrate", "caz_retractfeedrate")
  340. self.setFloatSettingIfEnabled(caz_instance, "caz_change_retractlength", "retractlength", "caz_retractlength")
  341. # is this mod enabled?
  342. caz_instance.enabled = self.getSettingValueByKey("caz_enabled")
  343. # are we emitting data to the LCD?
  344. caz_instance.displayChangesToLcd = self.getSettingValueByKey("caz_output_to_display")
  345. # are we doing linear move retractions?
  346. caz_instance.linearRetraction = self.getSettingValueByKey("caz_retractstyle") == "linear"
  347. # see if we're applying to a single layer or to all layers hence forth
  348. caz_instance.applyToSingleLayer = self.getSettingValueByKey("c_behavior") == "single_layer"
  349. # used for easy reference of layer or height targeting
  350. caz_instance.targetByLayer = self.getSettingValueByKey("a_trigger") == "layer_no"
  351. # change our target based on what we're targeting
  352. caz_instance.targetLayer = self.getIntSettingByKey("b_targetL", None)
  353. caz_instance.targetZ = self.getFloatSettingByKey("b_targetZ", None)
  354. # run our script
  355. return caz_instance.execute(data)
  356. # Sets the given TargetValue in the ChangeAtZ instance if the trigger is specified
  357. def setIntSettingIfEnabled(self, caz_instance, trigger, target, setting):
  358. # stop here if our trigger isn't enabled
  359. if not self.getSettingValueByKey(trigger):
  360. return
  361. # get our value from the settings
  362. value = self.getIntSettingByKey(setting, None)
  363. # skip if there's no value or we can't interpret it
  364. if value is None:
  365. return
  366. # set our value in the target settings
  367. caz_instance.targetValues[target] = value
  368. # Sets the given TargetValue in the ChangeAtZ instance if the trigger is specified
  369. def setFloatSettingIfEnabled(self, caz_instance, trigger, target, setting):
  370. # stop here if our trigger isn't enabled
  371. if not self.getSettingValueByKey(trigger):
  372. return
  373. # get our value from the settings
  374. value = self.getFloatSettingByKey(setting, None)
  375. # skip if there's no value or we can't interpret it
  376. if value is None:
  377. return
  378. # set our value in the target settings
  379. caz_instance.targetValues[target] = value
  380. # Returns the given settings value as an integer or the default if it cannot parse it
  381. def getIntSettingByKey(self, key, default):
  382. # change our target based on what we're targeting
  383. try:
  384. return int(self.getSettingValueByKey(key))
  385. except:
  386. return default
  387. # Returns the given settings value as an integer or the default if it cannot parse it
  388. def getFloatSettingByKey(self, key, default):
  389. # change our target based on what we're targeting
  390. try:
  391. return float(self.getSettingValueByKey(key))
  392. except:
  393. return default
  394. # This is a utility class for getting details of gcodes from a given line
  395. class GCodeCommand:
  396. # The GCode command itself (ex: G10)
  397. command = None,
  398. # Contains any arguments passed to the command. The key is the argument name, the value is the value of the argument.
  399. arguments = {}
  400. # Contains the components of the command broken into pieces
  401. components = []
  402. # Constructor. Sets up defaults
  403. def __init__(self):
  404. self.reset()
  405. # Gets a GCode Command from the given single line of GCode
  406. @staticmethod
  407. def getFromLine(line: str):
  408. # obviously if we don't have a command, we can't return anything
  409. if line is None or len(line) == 0:
  410. return None
  411. # we only support G or M commands
  412. if line[0] != "G" and line[0] != "M":
  413. return None
  414. # remove any comments
  415. line = re.sub(r";.*$", "", line)
  416. # break into the individual components
  417. command_pieces = line.strip().split(" ")
  418. # our return command details
  419. command = GCodeCommand()
  420. # stop here if we don't even have something to interpret
  421. if len(command_pieces) == 0:
  422. return None
  423. # stores all the components of the command within the class for later
  424. command.components = command_pieces
  425. # set the actual command
  426. command.command = command_pieces[0]
  427. # stop here if we don't have any parameters
  428. if len(command_pieces) == 1:
  429. return None
  430. # return our indexed command
  431. return command
  432. # Handy function for reading a linear move command
  433. @staticmethod
  434. def getLinearMoveCommand(line: str):
  435. # get our command from the line
  436. linear_command = GCodeCommand.getFromLine(line)
  437. # if it's not a linear move, we don't care
  438. if linear_command is None or (linear_command.command != "G0" and linear_command.command != "G1"):
  439. return None
  440. # convert our values to floats (or defaults)
  441. linear_command.arguments["F"] = linear_command.getArgumentAsFloat("F", None)
  442. linear_command.arguments["X"] = linear_command.getArgumentAsFloat("X", None)
  443. linear_command.arguments["Y"] = linear_command.getArgumentAsFloat("Y", None)
  444. linear_command.arguments["Z"] = linear_command.getArgumentAsFloat("Z", None)
  445. linear_command.arguments["E"] = linear_command.getArgumentAsFloat("E", None)
  446. # return our new command
  447. return linear_command
  448. # Gets the value of a parameter or returns the default if there is none
  449. def getArgument(self, name: str, default: str = None) -> str:
  450. # parse our arguments (only happens once)
  451. self.parseArguments()
  452. # if we don't have the parameter, return the default
  453. if name not in self.arguments:
  454. return default
  455. # otherwise return the value
  456. return self.arguments[name]
  457. # Gets the value of a parameter as a float or returns the default
  458. def getArgumentAsFloat(self, name: str, default: float = None) -> float:
  459. # try to parse as a float, otherwise return the default
  460. try:
  461. return float(self.getArgument(name, default))
  462. except:
  463. return default
  464. # Gets the value of a parameter as an integer or returns the default
  465. def getArgumentAsInt(self, name: str, default: int = None) -> int:
  466. # try to parse as a integer, otherwise return the default
  467. try:
  468. return int(self.getArgument(name, default))
  469. except:
  470. return default
  471. # Allows retrieving values from the given GCODE line
  472. @staticmethod
  473. def getDirectArgument(line: str, key: str, default: str = None) -> str:
  474. if key not in line or (";" in line and line.find(key) > line.find(";") and ";ChangeAtZ" not in key and ";LAYER:" not in key):
  475. return default
  476. # allows for string lengths larger than 1
  477. sub_part = line[line.find(key) + len(key):]
  478. if ";ChangeAtZ" in key:
  479. m = re.search("^[0-4]", sub_part)
  480. elif ";LAYER:" in key:
  481. m = re.search("^[+-]?[0-9]*", sub_part)
  482. else:
  483. # the minus at the beginning allows for negative values, e.g. for delta printers
  484. m = re.search(r"^[-]?[0-9]*\.?[0-9]*", sub_part)
  485. if m is None:
  486. return default
  487. try:
  488. return m.group(0)
  489. except:
  490. return default
  491. # Converts the command parameter to a int or returns the default
  492. @staticmethod
  493. def getDirectArgumentAsFloat(line: str, key: str, default: float = None) -> float:
  494. # get the value from the command
  495. value = GCodeCommand.getDirectArgument(line, key, default)
  496. # stop here if it's the default
  497. if value == default:
  498. return value
  499. try:
  500. return float(value)
  501. except:
  502. return default
  503. # Converts the command parameter to a int or returns the default
  504. @staticmethod
  505. def getDirectArgumentAsInt(line: str, key: str, default: int = None) -> int:
  506. # get the value from the command
  507. value = GCodeCommand.getDirectArgument(line, key, default)
  508. # stop here if it's the default
  509. if value == default:
  510. return value
  511. try:
  512. return int(value)
  513. except:
  514. return default
  515. # Parses the arguments of the command on demand, only once
  516. def parseArguments(self):
  517. # stop here if we don't have any remaining components
  518. if len(self.components) <= 1:
  519. return None
  520. # iterate and index all of our parameters, skip the first component as it's the command
  521. for i in range(1, len(self.components)):
  522. # get our component
  523. component = self.components[i]
  524. # get the first character of the parameter, which is the name
  525. component_name = component[0]
  526. # get the value of the parameter (the rest of the string
  527. component_value = None
  528. # get our value if we have one
  529. if len(component) > 1:
  530. component_value = component[1:]
  531. # index the argument
  532. self.arguments[component_name] = component_value
  533. # clear the components to we don't process again
  534. self.components = []
  535. # Easy function for replacing any GCODE parameter variable in a given GCODE command
  536. @staticmethod
  537. def replaceDirectArgument(line: str, key: str, value: str) -> str:
  538. return re.sub(r"(^|\s)" + key + r"[\d\.]+(\s|$)", r"\1" + key + str(value) + r"\2", line)
  539. # Resets the model back to defaults
  540. def reset(self):
  541. self.command = None
  542. self.arguments = {}
  543. # The primary ChangeAtZ class that does all the gcode editing. This was broken out into an
  544. # independent class so it could be debugged using a standard IDE
  545. class ChangeAtZProcessor:
  546. # Holds our current height
  547. currentZ = None
  548. # Holds our current layer number
  549. currentLayer = None
  550. # Indicates if we're only supposed to apply our settings to a single layer or multiple layers
  551. applyToSingleLayer = False
  552. # Indicates if this should emit the changes as they happen to the LCD
  553. displayChangesToLcd = False
  554. # Indicates that this mod is still enabled (or not)
  555. enabled = True
  556. # Indicates if we're processing inside the target layer or not
  557. insideTargetLayer = False
  558. # Indicates if we have restored the previous values from before we started our pass
  559. lastValuesRestored = False
  560. # Indicates if the user has opted for linear move retractions or firmware retractions
  561. linearRetraction = True
  562. # Indicates if we're targeting by layer or height value
  563. targetByLayer = True
  564. # Indicates if we have injected our changed values for the given layer yet
  565. targetValuesInjected = False
  566. # Holds the last extrusion value, used with detecting when a retraction is made
  567. lastE = None
  568. # An index of our gcodes which we're monitoring
  569. lastValues = {}
  570. # The detected layer height from the gcode
  571. layerHeight = None
  572. # The target layer
  573. targetLayer = None
  574. # Holds the values the user has requested to change
  575. targetValues = {}
  576. # The target height in mm
  577. targetZ = None
  578. # Used to track if we've been inside our target layer yet
  579. wasInsideTargetLayer = False
  580. # boots up the class with defaults
  581. def __init__(self):
  582. self.reset()
  583. # Modifies the given GCODE and injects the commands at the various targets
  584. def execute(self, data):
  585. # short cut the whole thing if we're not enabled
  586. if not self.enabled:
  587. return data
  588. # our layer cursor
  589. index = 0
  590. for active_layer in data:
  591. # will hold our updated gcode
  592. modified_gcode = ""
  593. # mark all the defaults for deletion
  594. active_layer = self.markChangesForDeletion(active_layer)
  595. # break apart the layer into commands
  596. lines = active_layer.split("\n")
  597. # evaluate each command individually
  598. for line in lines:
  599. # trim or command
  600. line = line.strip()
  601. # skip empty lines
  602. if len(line) == 0:
  603. continue
  604. # update our layer number if applicable
  605. self.processLayerNumber(line)
  606. # update our layer height if applicable
  607. self.processLayerHeight(line)
  608. # check if we're at the target layer or not
  609. self.processTargetLayer()
  610. # process any changes to the gcode
  611. modified_gcode += self.processLine(line)
  612. # remove any marked defaults
  613. modified_gcode = self.removeMarkedChanges(modified_gcode)
  614. # append our modified line
  615. data[index] = modified_gcode
  616. index += 1
  617. # return our modified gcode
  618. return data
  619. # Builds the restored layer settings based on the previous settings and returns the relevant GCODE lines
  620. def getChangedLastValues(self) -> Dict[str, any]:
  621. # capture the values that we've changed
  622. changed = {}
  623. # for each of our target values, get the value to restore
  624. # no point in restoring values we haven't changed
  625. for key in self.targetValues:
  626. # skip target values we can't restore
  627. if key not in self.lastValues:
  628. continue
  629. # save into our changed
  630. changed[key] = self.lastValues[key]
  631. # return our collection of changed values
  632. return changed
  633. # Builds the relevant display feedback for each of the values
  634. def getDisplayChangesFromValues(self, values: Dict[str, any]) -> str:
  635. # stop here if we're not outputting data
  636. if not self.displayChangesToLcd:
  637. return ""
  638. # will hold all the default settings for the target layer
  639. codes = []
  640. # looking for wait for bed temp
  641. if "bedTemp" in values:
  642. codes.append("BedTemp: " + str(round(values["bedTemp"])))
  643. # set our extruder one temp (if specified)
  644. if "extruderOne" in values:
  645. codes.append("Extruder 1 Temp: " + str(round(values["extruderOne"])))
  646. # set our extruder two temp (if specified)
  647. if "extruderTwo" in values:
  648. codes.append("Extruder 2 Temp: " + str(round(values["extruderTwo"])))
  649. # set global flow rate
  650. if "flowrate" in values:
  651. codes.append("Extruder A Flow Rate: " + str(values["flowrate"]))
  652. # set extruder 0 flow rate
  653. if "flowrateOne" in values:
  654. codes.append("Extruder 1 Flow Rate: " + str(values["flowrateOne"]))
  655. # set second extruder flow rate
  656. if "flowrateTwo" in values:
  657. codes.append("Extruder 2 Flow Rate: " + str(values["flowrateTwo"]))
  658. # set our fan speed
  659. if "fanSpeed" in values:
  660. codes.append("Fan Speed: " + str(values["fanSpeed"]))
  661. # set feedrate percentage
  662. if "speed" in values:
  663. codes.append("Print Speed: " + str(values["speed"]))
  664. # set print rate percentage
  665. if "printspeed" in values:
  666. codes.append("Linear Print Speed: " + str(values["printspeed"]))
  667. # set retract rate
  668. if "retractfeedrate" in values:
  669. codes.append("Retract Feed Rate: " + str(values["retractfeedrate"]))
  670. # set retract length
  671. if "retractlength" in values:
  672. codes.append("Retract Length: " + str(values["retractlength"]))
  673. # stop here if there's nothing to output
  674. if len(codes) == 0:
  675. return ""
  676. # output our command to display the data
  677. return "M117 " + ", ".join(codes) + "\n"
  678. # Converts the last values to something that can be output on the LCD
  679. def getLastDisplayValues(self) -> str:
  680. # convert our last values to something we can output
  681. return self.getDisplayChangesFromValues(self.getChangedLastValues())
  682. # Converts the target values to something that can be output on the LCD
  683. def getTargetDisplayValues(self) -> str:
  684. # convert our target values to something we can output
  685. return self.getDisplayChangesFromValues(self.targetValues)
  686. # Builds the the relevant GCODE lines from the given collection of values
  687. def getCodeFromValues(self, values: Dict[str, any]) -> str:
  688. # will hold all the desired settings for the target layer
  689. codes = self.getCodeLinesFromValues(values)
  690. # stop here if there are no values that require changing
  691. if len(codes) == 0:
  692. return ""
  693. # return our default block for this layer
  694. return ";[CAZD:\n" + "\n".join(codes) + "\n;:CAZD]"
  695. # Builds the relevant GCODE lines from the given collection of values
  696. def getCodeLinesFromValues(self, values: Dict[str, any]) -> List[str]:
  697. # will hold all the default settings for the target layer
  698. codes = []
  699. # looking for wait for bed temp
  700. if "bedTemp" in values:
  701. codes.append("M140 S" + str(values["bedTemp"]))
  702. # set our extruder one temp (if specified)
  703. if "extruderOne" in values:
  704. codes.append("M104 S" + str(values["extruderOne"]) + " T0")
  705. # set our extruder two temp (if specified)
  706. if "extruderTwo" in values:
  707. codes.append("M104 S" + str(values["extruderTwo"]) + " T1")
  708. # set our fan speed
  709. if "fanSpeed" in values:
  710. # convert our fan speed percentage to PWM
  711. fan_speed = int((float(values["fanSpeed"]) / 100.0) * 255)
  712. # add our fan speed to the defaults
  713. codes.append("M106 S" + str(fan_speed))
  714. # set global flow rate
  715. if "flowrate" in values:
  716. codes.append("M221 S" + str(values["flowrate"]))
  717. # set extruder 0 flow rate
  718. if "flowrateOne" in values:
  719. codes.append("M221 S" + str(values["flowrateOne"]) + " T0")
  720. # set second extruder flow rate
  721. if "flowrateTwo" in values:
  722. codes.append("M221 S" + str(values["flowrateTwo"]) + " T1")
  723. # set feedrate percentage
  724. if "speed" in values:
  725. codes.append("M220 S" + str(values["speed"]) + "")
  726. # set print rate percentage
  727. if "printspeed" in values:
  728. codes.append(";PRINTSPEED " + str(values["printspeed"]) + "")
  729. # set retract rate
  730. if "retractfeedrate" in values:
  731. if self.linearRetraction:
  732. codes.append(";RETRACTFEEDRATE " + str(values["retractfeedrate"] * 60) + "")
  733. else:
  734. codes.append("M207 F" + str(values["retractfeedrate"] * 60) + "")
  735. # set retract length
  736. if "retractlength" in values:
  737. if self.linearRetraction:
  738. codes.append(";RETRACTLENGTH " + str(values["retractlength"]) + "")
  739. else:
  740. codes.append("M207 S" + str(values["retractlength"]) + "")
  741. return codes
  742. # Builds the restored layer settings based on the previous settings and returns the relevant GCODE lines
  743. def getLastValues(self) -> str:
  744. # build the gcode to restore our last values
  745. return self.getCodeFromValues(self.getChangedLastValues())
  746. # Builds the gcode to inject either the changed values we want or restore the previous values
  747. def getInjectCode(self) -> str:
  748. # if we're now outside of our target layer and haven't restored our last values, do so now
  749. if not self.insideTargetLayer and self.wasInsideTargetLayer and not self.lastValuesRestored:
  750. # mark that we've injected the last values
  751. self.lastValuesRestored = True
  752. # inject the defaults
  753. return self.getLastValues() + "\n" + self.getLastDisplayValues()
  754. # if we're inside our target layer but haven't added our values yet, do so now
  755. if self.insideTargetLayer and not self.targetValuesInjected:
  756. # mark that we've injected the target values
  757. self.targetValuesInjected = True
  758. # inject the defaults
  759. return self.getTargetValues() + "\n" + self.getTargetDisplayValues()
  760. # nothing to do
  761. return ""
  762. # Returns the unmodified GCODE line from previous ChangeZ edits
  763. @staticmethod
  764. def getOriginalLine(line: str) -> str:
  765. # get the change at z original (cazo) details
  766. original_line = re.search(r"\[CAZO:(.*?):CAZO\]", line)
  767. # if we didn't get a hit, this is the original line
  768. if original_line is None:
  769. return line
  770. return original_line.group(1)
  771. # Builds the target layer settings based on the specified values and returns the relevant GCODE lines
  772. def getTargetValues(self) -> str:
  773. # build the gcode to change our current values
  774. return self.getCodeFromValues(self.targetValues)
  775. # Determines if the current line is at or below the target required to start modifying
  776. def isTargetLayerOrHeight(self) -> bool:
  777. # target selected by layer no.
  778. if self.targetByLayer:
  779. # if we don't have a current layer, we're not there yet
  780. if self.currentLayer is None:
  781. return False
  782. # if we're applying to a single layer, stop if our layer is not identical
  783. if self.applyToSingleLayer:
  784. return self.currentLayer == self.targetLayer
  785. else:
  786. return self.currentLayer >= self.targetLayer
  787. else:
  788. # if we don't have a current Z, we're not there yet
  789. if self.currentZ is None:
  790. return False
  791. # if we're applying to a single layer, stop if our Z is not identical
  792. if self.applyToSingleLayer:
  793. return self.currentZ == self.targetZ
  794. else:
  795. return self.currentZ >= self.targetZ
  796. # Marks any current ChangeZ layer defaults in the layer for deletion
  797. @staticmethod
  798. def markChangesForDeletion(layer: str):
  799. return re.sub(r";\[CAZD:", ";[CAZD:DELETE:", layer)
  800. # Grabs the current height
  801. def processLayerHeight(self, line: str):
  802. # stop here if we haven't entered a layer yet
  803. if self.currentLayer is None:
  804. return
  805. # get our gcode command
  806. command = GCodeCommand.getFromLine(line)
  807. # skip if it's not a command we're interested in
  808. if command is None:
  809. return
  810. # stop here if this isn't a linear move command
  811. if command.command != "G0" and command.command != "G1":
  812. return
  813. # get our value from the command
  814. current_z = command.getArgumentAsFloat("Z", None)
  815. # stop here if we don't have a Z value defined, we can't get the height from this command
  816. if current_z is None:
  817. return
  818. # stop if there's no change
  819. if current_z == self.currentZ:
  820. return
  821. # set our current Z value
  822. self.currentZ = current_z
  823. # if we don't have a layer height yet, set it based on the current Z value
  824. if self.layerHeight is None:
  825. self.layerHeight = self.currentZ
  826. # Grabs the current layer number
  827. def processLayerNumber(self, line: str):
  828. # if this isn't a layer comment, stop here, nothing to update
  829. if ";LAYER:" not in line:
  830. return
  831. # get our current layer number
  832. current_layer = GCodeCommand.getDirectArgumentAsInt(line, ";LAYER:", None)
  833. # this should never happen, but if our layer number hasn't changed, stop here
  834. if current_layer == self.currentLayer:
  835. return
  836. # update our current layer
  837. self.currentLayer = current_layer
  838. # Makes any linear move changes and also injects either target or restored values depending on the plugin state
  839. def processLine(self, line: str) -> str:
  840. # used to change the given line of code
  841. modified_gcode = ""
  842. # track any values that we may be interested in
  843. self.trackChangeableValues(line)
  844. # if we're not inside the target layer, simply read the any
  845. # settings we can and revert any ChangeAtZ deletions
  846. if not self.insideTargetLayer:
  847. # read any settings if we haven't hit our target layer yet
  848. if not self.wasInsideTargetLayer:
  849. self.processSetting(line)
  850. # if we haven't hit our target yet, leave the defaults as is (unmark them for deletion)
  851. if "[CAZD:DELETE:" in line:
  852. line = line.replace("[CAZD:DELETE:", "[CAZD:")
  853. # if we're targeting by Z, we want to add our values before the first linear move
  854. if "G1 " in line or "G0 " in line:
  855. modified_gcode += self.getInjectCode()
  856. # modify our command if we're still inside our target layer, otherwise pass unmodified
  857. if self.insideTargetLayer:
  858. modified_gcode += self.processLinearMove(line) + "\n"
  859. else:
  860. modified_gcode += line + "\n"
  861. # if we're targeting by layer we want to add our values just after the layer label
  862. if ";LAYER:" in line:
  863. modified_gcode += self.getInjectCode()
  864. # return our changed code
  865. return modified_gcode
  866. # Handles any linear moves in the current line
  867. def processLinearMove(self, line: str) -> str:
  868. # if it's not a linear motion command we're not interested
  869. if not ("G1 " in line or "G0 " in line):
  870. return line
  871. # always get our original line, otherwise the effect will be cumulative
  872. line = self.getOriginalLine(line)
  873. # get our command from the line
  874. linear_command = GCodeCommand.getLinearMoveCommand(line)
  875. # if it's not a linear move, we don't care
  876. if linear_command is None:
  877. return line
  878. # get our linear move parameters
  879. feed_rate = linear_command.arguments["F"]
  880. x_coord = linear_command.arguments["X"]
  881. y_coord = linear_command.arguments["Y"]
  882. z_coord = linear_command.arguments["Z"]
  883. extrude_length = linear_command.arguments["E"]
  884. # set our new line to our old line
  885. new_line = line
  886. # handle retract length
  887. new_line = self.processRetractLength(extrude_length, feed_rate, new_line, x_coord, y_coord, z_coord)
  888. # handle retract feed rate
  889. new_line = self.processRetractFeedRate(extrude_length, feed_rate, new_line, x_coord, y_coord, z_coord)
  890. # handle print speed adjustments
  891. if extrude_length is not None: # Only for extrusion moves.
  892. new_line = self.processPrintSpeed(feed_rate, new_line)
  893. # set our current extrude position
  894. self.lastE = extrude_length if extrude_length is not None else self.lastE
  895. # if no changes have been made, stop here
  896. if new_line == line:
  897. return line
  898. # return our updated command
  899. return self.setOriginalLine(new_line, line)
  900. # Handles any changes to print speed for the given linear motion command
  901. def processPrintSpeed(self, feed_rate: float, new_line: str) -> str:
  902. # if we're not setting print speed or we don't have a feed rate, stop here
  903. if "printspeed" not in self.targetValues or feed_rate is None:
  904. return new_line
  905. # get our requested print speed
  906. print_speed = int(self.targetValues["printspeed"])
  907. # if they requested no change to print speed (ie: 100%), stop here
  908. if print_speed == 100:
  909. return new_line
  910. # get our feed rate from the command
  911. feed_rate = GCodeCommand.getDirectArgumentAsFloat(new_line, "F") * (float(print_speed) / 100.0)
  912. # change our feed rate
  913. return GCodeCommand.replaceDirectArgument(new_line, "F", feed_rate)
  914. # Handles any changes to retraction length for the given linear motion command
  915. def processRetractLength(self, extrude_length: float, feed_rate: float, new_line: str, x_coord: float, y_coord: float, z_coord: float) -> str:
  916. # if we don't have a retract length in the file we can't add one
  917. if "retractlength" not in self.lastValues or self.lastValues["retractlength"] == 0:
  918. return new_line
  919. # if we're not changing retraction length, stop here
  920. if "retractlength" not in self.targetValues:
  921. return new_line
  922. # retractions are only F (feed rate) and E (extrude), at least in cura
  923. if x_coord is not None or y_coord is not None or z_coord is not None:
  924. return new_line
  925. # since retractions require both F and E, and we don't have either, we can't process
  926. if feed_rate is None or extrude_length is None:
  927. return new_line
  928. # stop here if we don't know our last extrude value
  929. if self.lastE is None:
  930. return new_line
  931. # if there's no change in extrude we have nothing to change
  932. if self.lastE == extrude_length:
  933. return new_line
  934. # if our last extrude was lower than our current, we're restoring, so skip
  935. if self.lastE < extrude_length:
  936. return new_line
  937. # get our desired retract length
  938. retract_length = float(self.targetValues["retractlength"])
  939. # subtract the difference between the default and the desired
  940. extrude_length -= (retract_length - self.lastValues["retractlength"])
  941. # replace our extrude amount
  942. return GCodeCommand.replaceDirectArgument(new_line, "E", extrude_length)
  943. # Used for picking out the retract length set by Cura
  944. def processRetractLengthSetting(self, line: str):
  945. # skip if we're not doing linear retractions
  946. if not self.linearRetraction:
  947. return
  948. # get our command from the line
  949. linear_command = GCodeCommand.getLinearMoveCommand(line)
  950. # if it's not a linear move, we don't care
  951. if linear_command is None:
  952. return
  953. # get our linear move parameters
  954. feed_rate = linear_command.arguments["F"]
  955. x_coord = linear_command.arguments["X"]
  956. y_coord = linear_command.arguments["Y"]
  957. z_coord = linear_command.arguments["Z"]
  958. extrude_length = linear_command.arguments["E"]
  959. # the command we're looking for only has extrude and feed rate
  960. if x_coord is not None or y_coord is not None or z_coord is not None:
  961. return
  962. # if either extrude or feed is missing we're likely looking at the wrong command
  963. if extrude_length is None or feed_rate is None:
  964. return
  965. # cura stores the retract length as a negative E just before it starts printing
  966. extrude_length = extrude_length * -1
  967. # if it's a negative extrude after being inverted, it's not our retract length
  968. if extrude_length < 0:
  969. return
  970. # what ever the last negative retract length is it wins
  971. self.lastValues["retractlength"] = extrude_length
  972. # Handles any changes to retraction feed rate for the given linear motion command
  973. def processRetractFeedRate(self, extrude_length: float, feed_rate: float, new_line: str, x_coord: float, y_coord: float, z_coord: float) -> str:
  974. # skip if we're not doing linear retractions
  975. if not self.linearRetraction:
  976. return new_line
  977. # if we're not changing retraction length, stop here
  978. if "retractfeedrate" not in self.targetValues:
  979. return new_line
  980. # retractions are only F (feed rate) and E (extrude), at least in cura
  981. if x_coord is not None or y_coord is not None or z_coord is not None:
  982. return new_line
  983. # since retractions require both F and E, and we don't have either, we can't process
  984. if feed_rate is None or extrude_length is None:
  985. return new_line
  986. # get our desired retract feed rate
  987. retract_feed_rate = float(self.targetValues["retractfeedrate"])
  988. # convert to units/min
  989. retract_feed_rate *= 60
  990. # replace our feed rate
  991. return GCodeCommand.replaceDirectArgument(new_line, "F", retract_feed_rate)
  992. # Used for finding settings in the print file before we process anything else
  993. def processSetting(self, line: str):
  994. # if we're in layers already we're out of settings
  995. if self.currentLayer is not None:
  996. return
  997. # check our retract length
  998. self.processRetractLengthSetting(line)
  999. # Sets the flags if we're at the target layer or not
  1000. def processTargetLayer(self):
  1001. # skip this line if we're not there yet
  1002. if not self.isTargetLayerOrHeight():
  1003. # flag that we're outside our target layer
  1004. self.insideTargetLayer = False
  1005. # skip to the next line
  1006. return
  1007. # flip if we hit our target layer
  1008. self.wasInsideTargetLayer = True
  1009. # flag that we're inside our target layer
  1010. self.insideTargetLayer = True
  1011. # Removes all the ChangeZ layer defaults from the given layer
  1012. @staticmethod
  1013. def removeMarkedChanges(layer: str) -> str:
  1014. return re.sub(r";\[CAZD:DELETE:[\s\S]+?:CAZD\](\n|$)", "", layer)
  1015. # Resets the class contents to defaults
  1016. def reset(self):
  1017. self.targetValues = {}
  1018. self.applyToSingleLayer = False
  1019. self.lastE = None
  1020. self.currentZ = None
  1021. self.currentLayer = None
  1022. self.targetByLayer = True
  1023. self.targetLayer = None
  1024. self.targetZ = None
  1025. self.layerHeight = None
  1026. self.lastValues = {"speed": 100}
  1027. self.linearRetraction = True
  1028. self.insideTargetLayer = False
  1029. self.targetValuesInjected = False
  1030. self.lastValuesRestored = False
  1031. self.wasInsideTargetLayer = False
  1032. self.enabled = True
  1033. # Sets the original GCODE line in a given GCODE command
  1034. @staticmethod
  1035. def setOriginalLine(line, original) -> str:
  1036. return line + ";[CAZO:" + original + ":CAZO]"
  1037. # Tracks the change in gcode values we're interested in
  1038. def trackChangeableValues(self, line: str):
  1039. # simulate a print speed command
  1040. if ";PRINTSPEED" in line:
  1041. line = line.replace(";PRINTSPEED ", "M220 S")
  1042. # simulate a retract feedrate command
  1043. if ";RETRACTFEEDRATE" in line:
  1044. line = line.replace(";RETRACTFEEDRATE ", "M207 F")
  1045. # simulate a retract length command
  1046. if ";RETRACTLENGTH" in line:
  1047. line = line.replace(";RETRACTLENGTH ", "M207 S")
  1048. # get our gcode command
  1049. command = GCodeCommand.getFromLine(line)
  1050. # stop here if it isn't a G or M command
  1051. if command is None:
  1052. return
  1053. # handle retract length changes
  1054. if command.command == "M207":
  1055. # get our retract length if provided
  1056. if "S" in command.arguments:
  1057. self.lastValues["retractlength"] = command.getArgumentAsFloat("S")
  1058. # get our retract feedrate if provided, convert from mm/m to mm/s
  1059. if "F" in command.arguments:
  1060. self.lastValues["retractfeedrate"] = command.getArgumentAsFloat("F") / 60.0
  1061. # move to the next command
  1062. return
  1063. # handle bed temp changes
  1064. if command.command == "M140" or command.command == "M190":
  1065. # get our bed temp if provided
  1066. if "S" in command.arguments:
  1067. self.lastValues["bedTemp"] = command.getArgumentAsFloat("S")
  1068. # move to the next command
  1069. return
  1070. # handle extruder temp changes
  1071. if command.command == "M104" or command.command == "M109":
  1072. # get our temperature
  1073. temperature = command.getArgumentAsFloat("S")
  1074. # don't bother if we don't have a temperature
  1075. if temperature is None:
  1076. return
  1077. # get our extruder, default to extruder one
  1078. extruder = command.getArgumentAsInt("T", None)
  1079. # set our extruder temp based on the extruder
  1080. if extruder is None or extruder == 0:
  1081. self.lastValues["extruderOne"] = temperature
  1082. if extruder is None or extruder == 1:
  1083. self.lastValues["extruderTwo"] = temperature
  1084. # move to the next command
  1085. return
  1086. # handle fan speed changes
  1087. if command.command == "M106":
  1088. # get our bed temp if provided
  1089. if "S" in command.arguments:
  1090. self.lastValues["fanSpeed"] = (command.getArgumentAsInt("S") / 255.0) * 100
  1091. # move to the next command
  1092. return
  1093. # handle flow rate changes
  1094. if command.command == "M221":
  1095. # get our flow rate
  1096. temperature = command.getArgumentAsFloat("S")
  1097. # don't bother if we don't have a flow rate (for some reason)
  1098. if temperature is None:
  1099. return
  1100. # get our extruder, default to global
  1101. extruder = command.getArgumentAsInt("T", None)
  1102. # set our extruder temp based on the extruder
  1103. if extruder is None:
  1104. self.lastValues["flowrate"] = temperature
  1105. elif extruder == 1:
  1106. self.lastValues["flowrateOne"] = temperature
  1107. elif extruder == 1:
  1108. self.lastValues["flowrateTwo"] = temperature
  1109. # move to the next command
  1110. return
  1111. # handle print speed changes
  1112. if command.command == "M220":
  1113. # get our speed if provided
  1114. if "S" in command.arguments:
  1115. self.lastValues["speed"] = command.getArgumentAsInt("S")
  1116. # move to the next command
  1117. return