pythoninkscapeg-code

How to check if a number inside an IF statement has changed and only then execute a script?


I am creating a tool changer for a pen plotter that only makes a tool change every time the source file moves to read data from a new layer (inside inkscape). This script injects a certain piece of GCODE (code that a CNC-based machine needs to know what it should do) on each layer change.

I already have all the variables ready and only need to know how to see how long the layer number stays '1' until it changes to '2' so that the script knows when to inject the 'tool change gcode'.

After hours of searching through possible solutions, I haven't managed to get it working. I tried some while statements, but they all failed, I even made my software crash a few times. I've come so far as to now strip all layer data from it's characters with a 're.sub' and make the variable 'layer number' that contains the '1' or '2' or '3' (should be able to expand until like 9 or further).

        try :
            self.last_used_tool == None
        except :
            self.last_used_tool = None
        print_("working on curve")
        print_(curve)

        if tool != self.last_used_tool :
            layernumber = re.sub('[^0-9]','', layer.get(inkex.addNS('label','inkscape'))) 
            g += ("Layer %s" % layernumber + "\n;(Change tool to %s)\n" % re.sub("\"'\(\)\\\\"," ",tool["name"]) ) + tool["tool change gcode"] + "\n"

This script works, but in this script 'self.last_used_tool' doesn't exist anywhere else so it's a dummy code I believe.

Right now the if statement outputs the tool change gcode each time it starts to work on a new path, causing multiple tool changes of the same tool in one layer. I need the tool change to only happen the first time it moves to a new layer.

I am looking for a way to make the if statement see if the layer number has gone up or down and change the tool accordingly only in that case. Later on I might not check for the layer number but for the tool number, however, for now, in the way that I'm working it was more clear for me to use the layer number since that number corresponds with the tool number anyway and intuitively it felt more clear to me to do it this way.

Thanks for your time and effort, I hope someone is able to help me find the solution. When the script is finished I will publish it online so that others can also make use of it. The script I'm working on is an old open source project that was abandoned and apparently lacks some functionality. I've already fixed most of the extension (including language) but the tool change has never worked.


Solution

  • It seems you are missing to set

    self.last_used_tool = tool
    

    at the end of your if-block. Without that, self.last_used_tool will always be None and never compare equal to tool.