CAM scripting/it: Difference between revisions

From FreeCAD Documentation
(Created page with "Tuttavia, i Path Compounds possono usufruire del Placement (posizionamento) dei propri figli (vedi sotto).")
(Created page with "== Gli utensili e la tabella utensili ==")
Line 215: Line 215:
Tuttavia, i Path Compounds possono usufruire del Placement (posizionamento) dei propri figli (vedi sotto).
Tuttavia, i Path Compounds possono usufruire del Placement (posizionamento) dei propri figli (vedi sotto).


== Gli utensili e la tabella utensili ==
== The Tool and Tooltable objects ==


The Tool object contains the definitions of a CNC tool. The Tooltable object contains an ordered list of tools. Tooltables are attached as a property to Path Project features, and can also be edited via the GUI, by double-clicking a project in the tree view, and clicking the "Edit tooltable" button in the task views that opens.
The Tool object contains the definitions of a CNC tool. The Tooltable object contains an ordered list of tools. Tooltables are attached as a property to Path Project features, and can also be edited via the GUI, by double-clicking a project in the tree view, and clicking the "Edit tooltable" button in the task views that opens.

Revision as of 21:53, 12 December 2015

Introduzione

L'ambiente Path offre strumenti per importare, creare, manipolare e esportare percorsi delle macchine utensili in FreeCAD. Con esso, l'utente è in grado di importare, visualizzare e modificare i programmi GCode esistenti, generare percorsi di forme 3D, ed esportare questi percorsi utensile in Gcode.

Allo stato attuale, però, lo sviluppo dell'ambiente Path è appena iniziato, e non offre la funzionalità molto avanzate che si trovano in alcune alternative commerciali. Tuttavia, la sua ampia interfaccia di script Python rende facile modificare o sviluppare degli strumenti più potenti, e quindi per ora è rivolto più agli utenti con una certa conoscenza di script Python che agli utenti finali.

Nel seguito troverete una descrizione più approfondita delle API di script Python.

Avvio rapido

Gli oggetti Path (percorso) di FreeCAD sono fatti di una sequenza di comandi di movimento. Un utilizzo tipico è questo:

    >>> import Path
    >>> c1 = Path.Command("g1x1")
    >>> c2 = Path.Command("g1y4")
    >>> c3 = Path.Command("g1 x2 y2") # spaces end newlines are not considered
    >>> p = Path.Path([c1,c2,c3])
    >>> o = App.ActiveDocument.addObject("Path::Feature","mypath")
    >>> o.Path = p
    >>> print p.toGCode()

Formato del GCode all'interno di FreeCAD

A preliminary concept is important to grasp. Most of the implementation below relies heavily on motion commands that have the same names as GCode commands, but aren't meant to be close to a particular controller's implementation. We chose names such as 'G0' to represent 'rapid' move or 'G1' to represent 'feed' move for performance (efficient file saving) and to minimize the work needed to translate to/from other GCode formats. Since the CNC world speaks thousands of GCode dialects, we chose to stick with a very simplified subset of it. You could describe FreeCAD's GCode format as a "machine-agnostic" form of GCode.

All'interno dei file .FCStd, i dati Path vengono salvati direttamente in quella forma di GCode.

Tutte le traduzioni dai/nei dialetti del GCode di FreeCAD vengono effettuate tramite pre e post script. Ciò significa che, se si desidera lavorare con una macchina che utilizza uno specifico controller LinuxCNC, Fanuc, Mitusubishi o HAAS, ecc, si deve usare (o scrivere se è inesistente) un post processore per quel particolare controllo (vedere più avanti la sezione "Importare ed esportare GCode).

GCode reference

Le seguenti regole e linee guida definiscono il sottoinsieme di GCode utilizzato all'interno di FreeCAD:

  • I dati GCode, all'interno degli oggetti Path di FreeCAD, sono separati in "Commands" (comandi). Un comando è definito dal nome del comando, che deve iniziare con G o M, e da argomenti(opzionali), che sono nella forma Lettera = Float (flottante), ad esempio X 0.02 o Y 3.5 o F 300. Questi sono esempi di tipici comandi Gcode in FreeCAD:
   G0 X2.5 Y0 (Il nome del comando è G0, gli argomenti sono X=2.5 e Y=0)
   G1 X30 (Il nome del comando è G1, l'unico argomento è X=30)
   G90 (Il nome del comando è G90, non ci sono argomentis)
  • Per la parte numerica di un comando G o M, sono supportate sia la forma "G1" sia "G01" .
  • In questo momento sono supportati solo i comandi che iniziano per G o M.
  • Per ora, sono accettati solo i millimetri. G20/G21 non sono considerati.
  • Gli argomenti sono sempre in ordine alfabetico. Questo significa che se si crea un comando con "G1 X2 Y4 F300", viene memorizzato come "G1 F300 X2 Y4"
  • Gli argomenti non possono essere ripetuti all'interno di uno stesso comando. Ad esempio, "G1 X1 X2 Y2 Y3" non funziona. Deve essere diviso in due comandi, per esempio: "G1 X1 Y2, Y3 G1 X2"
  • Gli argomenti X, Y, Z, A, B, C sono assoluti o relativi, secondo la modalità attiva G90/G91. Predefinito (se non specificato) è assoluto.
  • I, J, K sono sempre relativi all'ultimo punto. K può essere omesso.
  • X, Y, o Z (e A, B, C) possono essere omessi. In questo caso, sono mantenuti le precedenti coordinate X, Y o Z.
  • I comandi GCode diversi da quelli elencati nella seguente tabella sono supportati, cioè, vengono salvati all'interno dei dati del percorso ( naturalmente, a patto che siano conformi alle regole di cui sopra), ma non producono alcun risultato visibile sullo schermo. Ad esempio, è possibile aggiungere un comando G81, esso viene memorizzato, ma non visualizzato.

Elenco dei comandi Gcode attualmente supportati

Comando Descrizione Argomenti supportati
G0 rapida X,Y,Z,A,B,C
G1 avanzamento normale X,Y,Z,A,B,C
G2 arco orario X,Y,Z,A,B,C,I,J,K
G3 arco antiorario X,Y,Z,A,B,C,I,J,K
G81, G82, G83 foratura X,Y,Z,R,Q
G90 coordinate assolute
G91 coordinate relative
(Message) commento

L'oggetto Command

L'oggetto Command rappresenta un comando Gcode. Ha tre attributi: Name, Parameters e Placement (Nome,Parametri e posizione), e due metodi: toGCode() e setFromGCode(). Internamente, contiene solo un nome e un dizionario di parametri. Il resto (posizionamento e gcode) viene calcolato da/a questi dati.

    >>> import Path
    >>> c=Path.Command()
    >>> c
    Command  ( )
    >>> c.Name = "G1"
    >>> c
    Command G1 ( )
    >>> c.Parameters= {"X":1,"Y":0}
    >>> c
    Command G1 ( X:1 Y:0 )
    >>> c.Parameters
    {'Y': 0.0, 'X': 1.0}
    >>> c.Parameters= {"X":1,"Y":0.5}
    >>> c
    Command G1 ( X:1 Y:0.5 )
    >>> c.toGCode()
    'G1X1Y0.5'
    >>> c2=Path.Command("G2")
    >>> c2
    Command G2 ( )
    >>> c3=Path.Command("G1",{"X":34,"Y":1.2})
    >>> c3
    Command G1 ( X:34 Y:1.2 )
    >>> c3.Placement
    Placement [Pos=(34,1.2,0), Yaw-Pitch-Roll=(0,0,0)]
    >>> c3.toGCode()
    'G1X34Y1.2'
    >>> c3.setFromGCode("G1X1Y0")
    >>> c3
    Command G1 [ X:1 Y:0 ]
    >>> c4 = Path.Command("G1X4Y5")
    >>> c4
    Command G1 [ X:4 Y:5 ]
    >>> p1 = App.Placement()
    >>> p1.Base = App.Vector(3,2,1)
    >>> p1
    Placement [Pos=(3,2,1), Yaw-Pitch-Roll=(0,0,0)]
    >>> c5=Path.Command("g1",p1)
    >>> c5
    Command G1 [ X:3 Y:2 Z:1 ]
    >>> p2=App.Placement()
    >>> p2.Base = App.Vector(5,0,0)
    >>> c5
    Command G1 [ X:3 Y:2 Z:1 ]
    >>> c5.Placement=p2
    >>> c5
    Command G1 [ X:5 ]
    >>> c5.x
    5.0
    >>> c5.x=10
    >>> c5
    Command G1 [ X:10 ]
    >>> c5.y=2
    >>> c5
    Command G1 [ X:10 Y:2 ]

L'oggetto Path

L'oggetto Path contiene un elenco di comandi

    >>> import Path
    >>> c1=Path.Command("g1",{"x":1,"y":0})
    >>> c2=Path.Command("g1",{"x":0,"y":2})
    >>> p=Path.Path([c1,c2])
    >>> p
    Path [ size:2 length:3 ]
    >>> p.Commands
    [Command G1 [ X:1 Y:0 ], Command G1 [ X:0 Y:2 ]]
    >>> p.Length
    3.0
    >>> p.addCommands(c1)
    Path [ size:3 length:4 ]
    >>> p.toGCode()
    'G1X1G1Y2G1X1'
    
    lines = """
    G0X-0.5905Y-0.3937S3000M03
    G0Z0.125
    G1Z-0.004F3
    G1X0.9842Y-0.3937F14.17
    G1X0.9842Y0.433
    G1X-0.5905Y0.433
    G1X-0.5905Y-0.3937
    G0Z0.5
    """
    
    slines = lines.split('\n')
    p = Path.Path()
    for line in slines:
        p.addCommands(Path.Command(line))
    
    o = App.ActiveDocument.addObject("Path::Feature","mypath")
    o.Path = p
    
    # but you can also create a path directly form a piece of gcode. The commands
    # will be created automatically:
    
    p = Path.Path()
    p.setFromGCode(lines)

Come scorciatoia, un oggetto Path può anche essere creato direttamente da una sequenza completa di GCode. Sarà diviso automaticamente in una sequenza di comandi.

    >>> p = Path.Path("G0 X2 Y2 G1 X0 Y2")
    >>> p
    Path [ size:2 length:2 ]

La funzione Path

La funzione Path è un oggetto documento di FreeCAD, che contiene un percorso, e lo rappresenta nella vista 3D.

    >>> pf = App.ActiveDocument.addObject("Path::Feature","mypath")
    >>> pf
    <Document object>
    >>> pf.Path = p
    >>> pf.Path
    Path [ size:2 length:2 ]

La funzione Path detiene inoltre una proprietà Placement. Cambiando il valore del posizionamento si cambia la posizione della funzionalità nella vista 3D, anche se le informazioni sul percorso sono invariate. La trasformazione è puramente visiva. Ciò consente, ad esempio, di creare un percorso attorno a una faccia che ha un particolare orientamento nel modello, e che non è lo stesso orientamento che il materiale da tagliare avrà sulla macchina CNC.

Tuttavia, i Path Compounds possono usufruire del Placement (posizionamento) dei propri figli (vedi sotto).

Gli utensili e la tabella utensili

The Tool object contains the definitions of a CNC tool. The Tooltable object contains an ordered list of tools. Tooltables are attached as a property to Path Project features, and can also be edited via the GUI, by double-clicking a project in the tree view, and clicking the "Edit tooltable" button in the task views that opens.

From that dialog, tooltables can be imported from FreeCAD's .xml and HeeksCad's .tooltable formats, and exported to FreeCAD's .xml format.

    >>> import Path
    >>> t1=Path.Tool()
    >>> t1
    Tool Default tool
    >>> t1.Name = "12.7mm Drill Bit"
    >>> t1
    Tool 12.7mm Drill Bit
    >>> t1.ToolType
    'Undefined'
    >>> t1.ToolType = "Drill"
    >>> t1.Diameter= 12.7
    >>> t1.LengthOffset = 127
    >>> t1.CuttingEdgeAngle = 59
    >>> t1.CuttingEdgeHeight = 50.8
    >>> t2 = Path.Tool("my other tool",tooltype="EndMill",diameter=10)
    >>> t2
    Tool my other tool
    >>> t2.Diameter
    10.0
    >>> table = Path.Tooltable()
    >>> table
    Tooltable containing 0 tools
    >>> table.addTools(t1)
    Tooltable containing 1 tools
    >>> table.addTools(t2)
    Tooltable containing 2 tools
    >>> table.Tools
    {1: Tool 12.7mm Drill Bit, 2: Tool my other tool}
    >>>

Features

The Path Compound feature

The aim of this feature is to gather one or more toolpaths and associate it (them) with a tooltable. The Compound feature also behaves like a standard FreeCAD group, so you can add or remove objects to/from it directly from the tree view. You can also reorder items by double-clicking the Compound object in the Tree view, and reorder its elements in the Task view that opens.

    >>> import Path
    >>> p1 = Path.Path("G1X1")
    >>> o1 = App.ActiveDocument.addObject("Path::Feature","path1")
    >>> o1.Path=p1
    >>> p2 = Path.Path("G1Y1")
    >>> o2 = App.ActiveDocument.addObject("Path::Feature","path2")
    >>> o2.Path=p2
    >>> o3 = App.ActiveDocument.addObject("Path::FeatureCompound","compound")
    >>> o3.Group=[o1,o2]

An important feature of Path Compounds is the possibility to take into account the Placement of their child paths or not, by setting their UsePlacements property to True or False. If not, the Path data of their children will simply be added sequentially. If True, each command of the child paths, if containing position information (G0, G1, etc..) will first be transformed by the Placement before being added.

Creating a compound with just one child path allows you therefore to turn the child path's Placement "real" (it affects the Path data).

The Path Project feature

The Path project is an extended kind of Compound, that has a couple of additional machine-related properties such as a tooltable. It is made mainly to be the main object type you'll want to export to gcode once your whole path setup is ready. The Project object is now coded in python, so its creation mechanism is a bit different:

    >>> from PathScripts import PathProject
    >>> o4 = App.ActiveDocument.addObject("Path::FeatureCompoundPython","project")
    >>> PathProject.ObjectPathProject(o4)
    >>> o4.Group = [o3]
    >>> o4.Tooltable
    Tooltable containing 0 tools

The Path module also features a GUI tooltable editor that can be called from python, giving it an object that has a ToolTable property:

    >>> from PathScripts import TooltableEditor
    >>> TooltableEditor.edit(o4)

The Path Shape feature

This feature is a normal Path object with an additional Shape property. By giving that property a Wire shape, its path will be automatically calculated from the shape. Note that in this case the placement is automatically set to the first point of the wire, and the object is therefore not movable anymore by changing its placement. To move it, the underlying shape itself must be moved.

    >>> import Part
    >>> v1 = FreeCAD.Vector(0,0,0)
    >>> v2 = FreeCAD.Vector(0,2,0)
    >>> v3 = FreeCAD.Vector(2,2,0)
    >>> v4 = FreeCAD.Vector(3,3,0)
    >>> wire = Part.makePolygon([v1,v2,v3,v4])
    >>> o = FreeCAD.ActiveDocument.addObject("Path::FeatureShape","myPath2")
    >>> o.Shape = wire
    >>> FreeCAD.ActiveDocument.recompute()

Python features

Both Path::Feature and Path::FeatureShape features have a python version, respectively named Path::FeaturePython and Path::FeatureShapePython, that can be used in python code to create more advanced parametric objects derived from them.

Importing and exporting GCode

Native format

GCode files can be directly imported and exported via the GUI, by using the "open", "insert" or "export" menu items. After the file name is acquired, a dialog pops up to ask which processing script must be used. It can also be done from python:

Path information is stored into Path objects using a subset of gcode described in the "FreeCAD's internal GCode format"section above. This subset can be imported or exported "as is", or converted to/from a particular version of GCode suited for your machine.

If you have a very simple and standard GCode program, that complies to the rules described in the "FreeCAD's internal GCode format" section above, for example the boomerang from http://www.cnccookbook.com/GWESampleFiles.html , it can be imported directly into a Path object, without translation (this is equivalent to using the "None" option of the GUI dialog):

    import Path
    f = open("/path/to/boomerangv4.ncc")
    s = f.read()
    p = Path.Path(s)
    o = App.ActiveDocument.addObject("Path::Feature","boomerang")
    o.Path = p

In the same manner, you can obtain the path information as "agnostic" gcode, and store it manually in a file:

    text = o.Path.toGCode()
    print text
    myfile = open("/path/to/newfile.ngc")
    myfile.write(text)
    myfile.close()

If you need a different output, though, you will need to convert this agnostic GCode into a format suited for your machine. That is the job of post-processing scripts.

Using pre- and post-processing scripts

If you have a gcode file written for a particular machine, which doesn't comply to the internal rules used by FreeCAD, described in the "FreeCAD's internal GCode format" section above, it might fail to import and/or render properly in the 3D view. To remedy to this, you must use a pre-processing script, which will convert from your machine-specific format to the FreeCAD format.

If you know the name of the pre-processing script to use, you can import your file using it, from the python console like this:

    import example_pre
    example_pre.insert("/path/to/myfile.ncc","DocumentName")

In the same manner, you can output a path object to GCode, using a post_processor script like this:

    import example_post
    example_post.export (myObjectName,"/path/to/outputFile.ncc")

Writing processing scripts

Pre- and post-processing scripts behave like other common FreeCAD imports/exporters. When choosing a pre/post processing script from the dialog, the import/export process will be redirected to the specified given script. Preprocessing scripts must contain at least the following methods open(filename) and insert(filename,docname). Postprocessing scripts need to implement export(objectslist,filename).

Scripts are placed into either the Mod/Path/PathScripts folder or the user's macro path directory. You can give them any name you like but by convention, and to be picked by the GUI dialog, pre-processing scripts names must end with "_pre", post-processing scripts with "_post" (make sure to use the underscore, not the hyphen, otherwise python cannot import it). This is an example of a very, very simple preprocessor. More complex examples are found in the Mod/Path/PathScripts folder:

    def open(filename):
        gfile = __builtins__.open(filename)
        inputstring = gfile.read()
        # the whole gcode program will come in as one string,
        # for example: "G0 X1 Y1\nG1 X2 Y2"
        output = ""
        # we add a comment
        output += "(This is my first parsed output!)\n"
        # we split the input string by lines
        lines = inputstring.split("\n")
        for line in lines:
            output += line
            # we must insert the "end of line" character again
            # because the split removed it
            output += "\n"
        # another comment
        output += "(End of program)"
        import Path
        p = Path.Path(output)
        myPath = FreeCAD.ActiveDocument.addObject("Path::Feature","ImportedPath")
        myPath.Path = p
        FreeCAD.ActiveDocument.recompute()

Pre- and post-processors work exactly the same way. They just do the contrary: The pre scripts convert from specific GCode to FreeCAD's "agnostic" GCode, while post scripts convert from FreeCAD's "agnostic" GCode to machine-specific GCode.