Community
Fusion API and Scripts
Got a new add-in to share? Need something specialized to be scripted? Ask questions or share what you’ve discovered with the community.
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

script with cam.generateToolpath and cam.postProcess not working

2 REPLIES 2
Reply
Message 1 of 3
den.uz.89
454 Views, 2 Replies

script with cam.generateToolpath and cam.postProcess not working

     Hi, I've been messing around with this script for some time - trying to learn how to automate toolpath creation for different parameters of a model. If I enter the commands one by one into the console - everything's fine - a file is created. If I try to run it as a script - It doesn't work. Any ideas?

   Some time ago I made it work on an other file, but can't repeat my success 😞

 

2 REPLIES 2
Message 2 of 3
den.uz.89
in reply to: den.uz.89

 

Here is the script, so you don't have to download it.

# For this sample script to run, the active Fusion document must contain at least one CAM operation.

import adsk.core, adsk.fusion, adsk.cam, traceback, os, time
def run(context):
    ui = None
    try:
	app = adsk.core.Application.get()
	ui = app.userInterface
	doc = app.activeDocument
	design = app.activeProduct
	products = doc.products
	product = products.itemByProductType('CAMProductType')
	cam = adsk.cam.CAM.cast(product)
        
        file = open('D:/parameters/rings.csv')
        for line in file:
            # Get the values from the csv file.            
            diameter = line       
            # Set the parameters.
            diameterParam = design.userParameters.itemByName('diameter')
            diameterParam.expression = diameter
            setup = cam.setups.item(0)
            future = cam.generateToolpath(setup)
            numOps = future.numberOfOperations
    
            #  create and show the progress dialog while the toolpaths are being generated.
            progress = ui.createProgressDialog()
            progress.isCancelButtonShown = False
            progress.show('Toolpath Generation Progress', 'Generating Toolpaths', 0, 10)
            while not future.isGenerationCompleted:
                # since toolpaths are calculated in parallel, loop the progress bar while the toolpaths 
                # are being generated but none are yet complete.
                n = 0
                start = time.time()
                while future.numberOfCompleted == 0:
                    if time.time() - start > .125: # increment the progess value every .125 seconds.
                        start = time.time()
                        n +=1
                        progress.progressValue = n
                        adsk.doEvents()
                    if n > 10:
                        n = 0
                # The first toolpath has finished computing so now display better
                # information in the progress dialog.
    
                # set the progress bar value to the number of completed toolpaths
                progress.progressValue = future.numberOfCompleted
    
                # set the progress bar max to the number of operations to be completed.
                progress.maximumValue = numOps
    
                # set the message for the progress dialog to track the progress value and the total number of operations to be completed.
                progress.message = 'Generating %v of %m' + ' Toolpaths'
                adsk.doEvents()
            progress.hide()
            
            #The post-processing past which doesn't seem to work
            programName = 'ring_blank_'+str(diameter)
            outputFolder = 'D:/NGC/ring_blanks_test'
            postConfig = 'D:/FusionPostProcessors/linuxcnc.cps'
            units = adsk.cam.PostOutputUnitOptions.DocumentUnitsOutput
            postInput = adsk.cam.PostProcessInput.create(programName, postConfig, outputFolder, units)
            r = cam.postProcess(setup, postInput)
        if r==True:
            ui.messageBox('Post processing is complete. The results have been written to:\n"' + os.path.join(outputFolder, programName) + '.nc"') 
        else:
            ui.messageBox('Posting failed') 
        os.startfile(outputFolder)

        return
    
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

 

 

Message 3 of 3
den.uz.89
in reply to: den.uz.89

Somehow made it work (found the old script, and kept changes to a minimum). Maybe someone knows the right way to do it?

# For this sample script to run, the active Fusion document must contain at least one CAM operation.

import adsk.core, adsk.fusion, adsk.cam, traceback, os, time

def run(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui = app.userInterface
        doc = app.activeDocument
        design = app.activeProduct
        products = doc.products
        product = products.itemByProductType('CAMProductType')
        cam = adsk.cam.CAM.cast(product)
                
        file = open('D://Parameters//rings.csv')
        for line in file:
            # Get the values from the csv file.
            pieces = line.split(',')
            
            diameter = pieces[0]
            DUMMY = pieces[1]
            #outer_width = pieces[2]
            #inner_width = pieces[3]
            
            # Set the parameters.
            diameterParam = design.userParameters.itemByName('diameter')
            diameterParam.expression = diameter
            
            #rotationParam = design.userParameters.itemByName('rotation')
            #rotationParam.expression = rotation

            #outer_widthParam = design.userParameters.itemByName('outer_width')
            #outer_widthParam.expression = outer_width
            
            #inner_widthParam = design.userParameters.itemByName('inner_width')
            #inner_widthParam.expression = inner_width
            
            
            
            # check if the document has a CAMProductType.  I will not if there are no CAM operations in it.
            if product == None:
                ui.messageBox('There are no CAM operations in the active document.  This script requires the active document to contain at least one CAM operation.',
                            'No CAM Operations Exist',
                            adsk.core.MessageBoxButtonTypes.OKButtonType,
                            adsk.core.MessageBoxIconTypes.CriticalIconType)
                return
        
             #set the value of scenario to 1, 2 or 3 to generate all, the first setup, or the first operation of the first setup.
            scenario = 2
            if scenario == 1:
                future = cam.generateAllToolpaths(False)
                message = 'The toolpaths for all operations in the document have been generated.'
            elif scenario == 2:
                setup = cam.setups.item(0)
                future = cam.generateToolpath(setup)
                message = 'The toolpaths for the operations of the first setup in the document have been generated.'
            elif scenario == 3:
                setup = cam.setups.item(0)
                operations = setup.operations
                operation = operations.item(0)
                future = cam.generateToolpath(operation)
                message = 'The toolpath for the first operation of the first setup in the document have been generated.'
    
            numOps = future.numberOfOperations
    
            #  create and show the progress dialog while the toolpaths are being generated.
            progress = ui.createProgressDialog()
            progress.isCancelButtonShown = False
            progress.show('Toolpath Generation Progress', 'Generating Toolpaths', 0, 10)
    
            # Enter a loop to wait while the toolpaths are being generated and update
            # the progress dialog.
            while not future.isGenerationCompleted:
                # since toolpaths are calculated in parallel, loop the progress bar while the toolpaths 
                # are being generated but none are yet complete.
                n = 0
                start = time.time()
                while future.numberOfCompleted == 0:
                    if time.time() - start > .125: # increment the progess value every .125 seconds.
                        start = time.time()
                        n +=1
                        progress.progressValue = n
                        adsk.doEvents()
                    if n > 10:
                        n = 0
    
                # The first toolpath has finished computing so now display better
                # information in the progress dialog.
    
                # set the progress bar value to the number of completed toolpaths
                progress.progressValue = future.numberOfCompleted
    
                # set the progress bar max to the number of operations to be completed.
                progress.maximumValue = numOps
    
                # set the message for the progress dialog to track the progress value and the total number of operations to be completed.
                progress.message = 'Generating %v of %m' + ' Toolpaths'
                adsk.doEvents()
    
            progress.hide()
            #ui.messageBox(message)

            # specify the program name, post configuration to use and a folder destination for the nc file
            programName = 'ring_blank_d'+str(diameter)
            outputFolder = 'D://NGC//ring_test'

            # set the post configuration to use based on Operation Type of the first Setup
            firstSetupOperationType = cam.setups.item(0).operationType
            if firstSetupOperationType == adsk.cam.OperationTypes.MillingOperation:
                postConfig = os.path.join(cam.genericPostFolder, 'linuxcnc.cps') 
            elif firstSetupOperationType == adsk.cam.OperationTypes.TurningOperation:
                postConfig = os.path.join(cam.genericPostFolder, 'fanuc turning.cps') 
            elif firstSetupOperationType == adsk.cam.OperationTypes.JetOperation:
                postConfig = cam.genericPostFolder + '/' + 'omax.cps' 

            # prompt the user with an option to view the resulting NC file.
            viewResult = False
     
            # specify the NC file output units
            units = adsk.cam.PostOutputUnitOptions.DocumentUnitsOutput
#            units = adsk.cam.PostOutputUnitOptions.InchesOutput
#           units = adsk.cam.PostOutputUnitOptions.MillimetersOutput

            # create the postInput object
            postInput = adsk.cam.PostProcessInput.create(programName, postConfig, outputFolder, units)
            postInput.isOpenInEditor = viewResult

            # set the value of scenario to 1, 2 or 3 to post all, post the first setup, or post only the first operation of the first setup.
            scenario = 2
            if scenario == 1:
                ui.messageBox('All toolpaths will be posted')
                cam.postProcessAll(postInput)
            elif scenario == 2:
                #ui.messageBox('Toolpaths in the first Setup will be posted')
                setups = cam.setups
                setup = setups.item(0)
                cam.postProcess(setup, postInput)
            elif scenario == 3:
                ui.messageBox('The first Toolpath in the first Setup will be posted')
                setups = cam.setups
                setup = setups.item(0)
                operations = setup.allOperations
                operation = operations.item(0)
                if operation.hasToolpath == True:
                    cam.postProcess(operation, postInput)
                else:
                    ui.messageBox('Operation has no toolpath to post')
                    return
        
        ui.messageBox('Post processing is complete. The results have been written to:\n"' + os.path.join(outputFolder, programName) + '.nc"') 
        os.startfile(outputFolder)        
        return
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk DevCon in Munich May 28-29th


Autodesk Design & Make Report