I could not able to run this add in

I could not able to run this add in

Boopathi_Sivakumar
Collaborator Collaborator
909 Views
4 Replies
Message 1 of 5

I could not able to run this add in

Boopathi_Sivakumar
Collaborator
Collaborator

I am trying to create some simple stuff

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

# Global list to keep all event handlers in scope.
# This is only needed with Python.
handlers = []

def run(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface

        # Get the CommandDefinitions collection.
        cmdDefs = ui.commandDefinitions
        
        # Create a button command definition.
        buttonSample = cmdDefs.addButtonDefinition('MyButtonDefIdPython', 
                                                   'Python Sample Button', 
                                                   'Sample button tooltip',
                                                   'Resources'
                                                   )
        
        # Connect to the command created event.
        sampleCommandCreated = SampleCommandCreatedEventHandler()
        buttonSample.commandCreated.add(sampleCommandCreated)
        handlers.append(sampleCommandCreated)
        
        # Get the ADD-INS panel in the model workspace. 
        addInsPanel = ui.allToolbarPanels.itemById('CAMActionPanel')
        
        # Add the button to the bottom of the panel.
        buttonControl = addInsPanel.controls.addCommand(buttonSample)

        buttonControl.isPromotedByDefault = True
        buttonControl.isPromoted = True
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


# Event handler for the commandCreated event.
class SampleCommandCreatedEventHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
        cmd = eventArgs.command

        # Connect to the execute event.
        onExecute = SampleCommandExecuteHandler()
        cmd.execute.add(onExecute)
        handlers.append(onExecute)


# Event handler for the execute event.
class SampleCommandExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        eventArgs = adsk.core.CommandEventArgs.cast(args)
    try:
        # Code to react to the event.
        app = adsk.core.Application.get()
        ui = app.userInterface
        doc = app.activeDocument
        products = doc.products
        product = products.itemByProductType('CAMProductType')

        # check if the document has a CAMProductType
        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

        cam = adsk.cam.CAM.cast(product)

        # specify the program name
        programName = doc.name
        outputFolder = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop') 

       # fileDlg = ui.createFileDialog()
       # fileDlg.isMultiSelectEnabled = False
       # fileDlg.title = 'Fusion Post File Dialog'
       # fileDlg.filter = '*.*'

        postConfig = os.path.join(cam.genericPostFolder, 'dump.cps') 

        # specify the NC file output units
        units = adsk.cam.PostOutputUnitOptions.DocumentUnitsOutput

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

        scenario = 1
        if scenario == 1:
           # ui.messageBox('All toolpaths will be posted')
            cam.postProcessAll(postInput)
        elif scenario == 2:
          setup = cam.setups.item(0) 
          cam.postProcess(setup, postInput)
           
        ui.messageBox('Post processing is complete. The results have been written to:\n"' + os.path.join(outputFolder, programName) + '.dmp"') 
    
     except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))	


def stop(context):
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface
        
        # Clean up the UI.
        cmdDef = ui.commandDefinitions.itemById('MyButtonDefIdPython')
        if cmdDef:
            cmdDef.deleteMe()
            
        addinsPanel = ui.allToolbarPanels.itemById('SolidScriptsAddinsPanel')
        cntrl = addinsPanel.controls.itemById('MyButtonDefIdPython')
        if cntrl:
            cntrl.deleteMe()
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))	

 I don't know where i am making mistake.

 

Boopathi Sivakumar
Sr Application Engineer
www.usamcadsoft.in
Facebook | Twitter | LinkedIn

0 Likes
910 Views
4 Replies
Replies (4)
Message 2 of 5

kandennti
Mentor
Mentor

Hi @Boopathi_Sivakumar .

 

I wasn't sure what the purpose was, but I tried to fix it with the goal of moving anyway.

There were a lot of corrections and I couldn't describe it in detail, but the biggest cause was the gap in the index.

import adsk.core, adsk.fusion, adsk.cam, traceback
import os
# Global list to keep all event handlers in scope.
# This is only needed with Python.
handlers = []

def run(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface

        # Get the CommandDefinitions collection.
        cmdDefs = ui.commandDefinitions
        
        # Create a button command definition.
        buttonSample = cmdDefs.addButtonDefinition('MyButtonDefIdPython', 
                                                   'Python Sample Button', 
                                                   'Sample button tooltip',
                                                   'Resources'
                                                   )
        
        # Connect to the command created event.
        sampleCommandCreated = SampleCommandCreatedEventHandler()
        buttonSample.commandCreated.add(sampleCommandCreated)
        handlers.append(sampleCommandCreated)
        
        # Get the ADD-INS panel in the model workspace. 
        addInsPanel = ui.allToolbarPanels.itemById('CAMActionPanel')
        
        buttonControl :adsk.core.ToolbarControl = addInsPanel.controls.itemById(buttonSample.id)
        if buttonControl:
            buttonControl.deleteMe()

        # Add the button to the bottom of the panel.
        buttonControl = addInsPanel.controls.addCommand(buttonSample)
        buttonControl.isVisible = True
        buttonControl.isPromotedByDefault = True
        buttonControl.isPromoted = True
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


# Event handler for the commandCreated event.
class SampleCommandCreatedEventHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
        cmd = eventArgs.command

        # Connect to the execute event.
        onExecute = SampleCommandExecuteHandler()
        cmd.execute.add(onExecute)
        handlers.append(onExecute)

# Event handler for the execute event.
class SampleCommandExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        ui = None
        eventArgs = adsk.core.CommandEventArgs.cast(args)
        try:
            # Code to react to the event.
            app = adsk.core.Application.get()
            ui = app.userInterface
            doc = app.activeDocument
            products = doc.products
            product = products.itemByProductType('CAMProductType')

            # check if the document has a CAMProductType
            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

            cam = adsk.cam.CAM.cast(product)

            # specify the program name
            programName = doc.name
            outputFolder = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop') 

            # fileDlg = ui.createFileDialog()
            # fileDlg.isMultiSelectEnabled = False
            # fileDlg.title = 'Fusion Post File Dialog'
            # fileDlg.filter = '*.*'

            postConfig = os.path.join(cam.genericPostFolder, 'dump.cps') 

            # specify the NC file output units
            units = adsk.cam.PostOutputUnitOptions.DocumentUnitsOutput

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

            scenario = 1
            if scenario == 1:
            # ui.messageBox('All toolpaths will be posted')
                cam.postProcessAll(postInput)
            elif scenario == 2:
                setup = cam.setups.item(0) 
                cam.postProcess(setup, postInput)
                
            ui.messageBox('Post processing is complete. The results have been written to:\n"' + os.path.join(outputFolder, programName) + '.dmp"') 

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

def stop(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface
        
        # Clean up the UI.
        cmdDef = ui.commandDefinitions.itemById('MyButtonDefIdPython')
        if cmdDef:
            cmdDef.deleteMe()
            
        addinsPanel = ui.allToolbarPanels.itemById('SolidScriptsAddinsPanel')
        cntrl = addinsPanel.controls.itemById('MyButtonDefIdPython')
        if cntrl:
            cntrl.deleteMe()
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
0 Likes
Message 3 of 5

kandennti
Mentor
Mentor
0 Likes
Message 4 of 5

Anonymous
Not applicable

I am having some similar issue but cannot spot a mistake... Can anyone help by any chance? Basically all i want is: user pressed tbhe button -> the script 'Holes Command Execute' is run..

 

#Author-
#Description-

import adsk.core, adsk.fusion, adsk.cam, traceback
# global var used to maintain reference to all event handlers 
handlers = []

def run(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface
        ### SETUP:
        # Create a command definition and add a button to the CREATE panel.
        createHolesCmdDef = ui.commandDefinitions.addButtonDefinition('CreateHolesAddInPYTHON', 'Add holes in model to reduce heat', 'Creates holes in the model that help reduce heat', 'resources')        
        # grabbing correct toolbar panel 
        addinsPanel = ui.allToolbarPanels.itemById('SolidScriptsAddinsPanel')
        # adding the button into the Solid Addins Panel 
        createHolesControl = addinsPanel.controls.addCommand(createHolesCmdDef, 'createHolesControl')
        
        # putting this button in the panel instead of dropdown menu 
        createHolesControl.isPromotedByDefault = True
        createHolesControl.isPromoted = True 

        ### TO EXECUTE MAIN FUNCTION WHEN THE BUTTON IS PRESSED: 
        
        holesButtonPressed = CreateHolesControlPressedEventHandler()
        createHolesCmdDef.commandCreated.add(holesButtonPressed)
        handlers.append(holesButtonPressed)
        createHolesCmdDef.execute()
        
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

def stop(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface
        ui.messageBox('You stopped "CREATE HOLES" addin.')
        
        # after addin is stopped, delete the button in UI and all the references to newly created command
        addinsPanel = ui.allToolbarPanels.itemById('SolidScriptsAddinsPanel')
        createHolesControl = addinsPanel.controls.itemById('CreateHolesAddInPYTHON')       

        if createHolesControl:
            ui.messageBox('hi')
            createHolesControl.deleteMe()
        
        cmdDef = ui.commandDefinitions.itemById('CreateHolesAddInPYTHON')
        if cmdDef:
            cmdDef.deleteMe()

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

class CreateHolesControlPressedEventHandler(adsk.core.CommandCreatedEventHandler): 
    def __init__(self): 
        super().__init__()
    def notify (self, args): 
        eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
        cmd = eventArgs.command

        # Connect to the execute event.
        onExecute = HolesCommandExecuteHandler()
        cmd.execute.add(onExecute)
        handlers.append(onExecute)

class HolesCommandExecuteHandler(adsk.core.CommandCreatedEventHandler): 
    def __init__(self): 
        super().__init__()
    def notify(self, args):
        ### -- SETTING UP: 
        try:
            app = adsk.core.Application.get()
            ui  = app.userInterface
            design = app.activeProduct
            # ensuring that there is model built & active:
            if not design:
                ui.messageBox('No active Fusion design', 'No Design')
                return
            # Get the root component of the active design:
            rootComp = design.rootComponent
            bodies = rootComp.bRepBodies
            ### --
            #cmd = args.command

            ### RUNNING SIMULATION ON THE CURRENT DESIGN
            ### --

            ### STORAGE FOR ALL THE FACES WHERE HOLES WILL BE PLACED--
            # [[face_ref, [which_side, length_x, width_y, height_z], [face.centroid x y z]], ...] 
            unsafe_faces = [] 
            flat_only = True # TODO: in future adjust for other shapes
            planeSurface = adsk.core.SurfaceTypes.PlaneSurfaceType
            ### -- 

            ### -- SELECTION OF THE FACES. TWO WAYS: (1) by user; (2) by our script
            user_answer = ui.messageBox('Do you want to specify faces where holes will be placed? \nIf not, then the program will use all the upper faces.', 
            "Selection",
            adsk.core.MessageBoxButtonTypes.YesNoCancelButtonType, 
            adsk.core.MessageBoxIconTypes.QuestionIconType)

            if user_answer == adsk.core.DialogResults.DialogYes: 
                selected_face = ui.selectEntity("Please, choose faces which need better heat dissipation.\
                \n If needed, choose all the faces under the upper case.", "Faces")
                unsafe_faces.append([selected_face.entity])

                while True:
                    user_answer = ui.messageBox('Great. \nDo you want to have holes on *another* face?', "AnotherFace", 
                    adsk.core.MessageBoxButtonTypes.YesNoButtonType, 
                    adsk.core.MessageBoxIconTypes.QuestionIconType)
                    if user_answer == adsk.core.DialogResults.DialogNo: 
                        break
                    else: 
                        selected_face = ui.selectEntity("Great. Then, please, choose face № {} \n upon which holes need to be added".format(len(unsafe_faces) + 1), 'Faces')
                        unsafe_faces.append([selected_face.entity])
                    
            elif user_answer == adsk.core.DialogResults.DialogNo: 
                ui.messageBox("You chose NO, hence the program will place holes on all the top faces of your model.")
                all_faces = []

                ## getting all the faces present in the design
                for body in bodies: 
                    if flat_only:             
                        for f in body.faces: 
                            if f.geometry.surfaceType == planeSurface:
                                all_faces.append(f) 
                    else: 
                        for f in body.faces: 
                            all_faces.append(f)
                # --
                vectors_only = []

                ## getting normal vecs out of all these possible faces
                for face in all_faces: 
                    vec = face.geometry.normal
                    vectors_only.append(vec)
                ## --
                
                ### SETUP FOR THE FOR**2 LOOP
                pp = rootComp.physicalProperties
                center_rootComp = pp.centerOfMass #  Get center of mass from physical properties
                seen = []
                unsafe_faces_coll =[]
                # --
                
                ### CHECKING IF VECTORS COMING FROM THOSE FACES ARE THE SAME 
                # IF THE ARE, THEN WE NEED TO FIND WHICH FACE FOR THIS SPECIFIC VECTOR
                # IS THE OUTHER ONE
                for vector_i in range(len(vectors_only)): 
                    for vector_j in range(len(vectors_only)):
                        if (not [vectors_only[vector_i], vectors_only[vector_j]] in seen) and (not [vectors_only[vector_j], vectors_only[vector_i]] in seen): 
                            if vectors_only[vector_i].isEqualTo(vectors_only[vector_j]):
                                found_faces_intersecting = rootComp.findBRepUsingRay(center_rootComp, vectors_only[vector_i], 1)
                                needed_face = found_faces_intersecting.item(found_faces_intersecting.count-1)
                                if needed_face not in unsafe_faces_coll: 
                                    unsafe_faces.append([needed_face])  
                                    unsafe_faces_coll.append(needed_face)  
                                    
                            seen.append([vectors_only[vector_i], vectors_only[vector_j]])
                ### --
            
            else: 
                ui.messageBox("You canceled the program. Please re-run the add-in if you wish to proceed.")
                return
            ### -- the end of user prompt & face selection
        except:
            if ui:
                ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

 

0 Likes
Message 5 of 5

kandennti
Mentor
Mentor

Hi @Boopathi_Sivakumar .

 

I haven't gone through the details, but it's the part that seems to need fixing at the very least.

 

If you want to run it by pressing the button on the menu.
In "def run"
I don't think createHolesCmdDef.execute() is necessary.

 

Class HolesCommandExecuteHandler inherits from "adsk.core.CommandEventHandler" instead of "adsk.core.CommandCreatedEventHandler".
should be.

 

・・・
def run(context):
    ・・・
        holesButtonPressed = CreateHolesControlPressedEventHandler()
        createHolesCmdDef.commandCreated.add(holesButtonPressed)
        handlers.append(holesButtonPressed)
        # createHolesCmdDef.execute()

・・・
# class HolesCommandExecuteHandler(adsk.core.CommandCreatedEventHandler): 
class HolesCommandExecuteHandler(adsk.core.CommandEventHandler): 
    def __init__(self): 
・・・
0 Likes