Browse Source

Add helper function to write g-code lines

Requested during the post-processing script workshop that I was giving.
Ghostkeeper 7 years ago
parent
commit
5160373580
1 changed files with 52 additions and 0 deletions
  1. 52 0
      plugins/PostProcessingPlugin/Script.py

+ 52 - 0
plugins/PostProcessingPlugin/Script.py

@@ -105,6 +105,58 @@ class Script:
         except:
             return default
 
+    ##  Convenience function to produce a line of g-code.
+    #
+    #   You can put in an original g-code line and it'll re-use all the values
+    #   in that line.
+    #   All other keyword parameters are put in the result in g-code's format.
+    #   For instance, if you put ``G=1`` in the parameters, it will output
+    #   ``G1``. If you put ``G=1, X=100`` in the parameters, it will output
+    #   ``G1 X100``. The parameters G and M will always be put first. The
+    #   parameters T and S will be put second (or first if there is no G or M).
+    #   The rest of the parameters will be put in arbitrary order.
+    #   \param line The original g-code line that must be modified. If not
+    #   provided, an entirely new g-code line will be produced.
+    #   \return A line of g-code with the desired parameters filled in.
+    def putValue(self, line = "", **kwargs):
+        #Strip the comment.
+        comment = ""
+        if ";" in line:
+            comment = line[line.find(";"):]
+            line = line[:line.find(";")] #Strip the comment.
+
+        #Parse the original g-code line.
+        for part in line.split(" "):
+            if part == "":
+                continue
+            parameter = part[0]
+            if parameter in kwargs:
+                continue #Skip this one. The user-provided parameter overwrites the one in the line.
+            value = part[1:]
+            kwargs[parameter] = value
+
+        #Write the new g-code line.
+        result = ""
+        priority_parameters = ["G", "M", "T", "S", "F", "X", "Y", "Z"] #First some parameters that get priority. In order of priority!
+        for priority_key in priority_parameters:
+            if priority_key in kwargs:
+                if result != "":
+                    result += " "
+                result += priority_key + str(kwargs[priority_key])
+                del kwargs[priority_key]
+        for key, value in kwargs.items():
+            if result != "":
+                result += " "
+            result += key + str(value)
+
+        #Put the comment back in.
+        if comment != "":
+            if result != "":
+                result += " "
+            result += ";" + comment
+
+        return result
+
     ##  This is called when the script is executed. 
     #   It gets a list of g-code strings and needs to return a (modified) list.
     def execute(self, data):