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: 

How to link an add-in application with web-server?

4 REPLIES 4
Reply
Message 1 of 5
state.of.grace.17
412 Views, 4 Replies

How to link an add-in application with web-server?

I try to make an add-in for Fusion 360 where I could get a parametric assembly from web-server.  I made a try but there was an error which I have no idea how to make it solved. 
User has to click on add-in and then parametric assembly and palette should appear at the same time (custom palette is for choosing user's parameters). 
Here are the code and an error: 

 

import adsk.core, adsk.fusion, adsk.cam, traceback
import urllib.request
import urllib.error
import urllib.parse
import pathlib

handlers = []
app = adsk.core.Application.get()
ui  = app.userInterface

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

        ui.messageBox('Добавлена надстройка для соединительных муфт')
        workSpace = ui.workspaces.itemById('FusionSolidEnvironment')
        tbPanels = workSpace.toolbarPanels
        tbPanel = tbPanels.itemById('NewPanel')
        if tbPanel:
            tbPanel.deleteMe()
        tbPanel = tbPanels.add('NewPanel''БИБЛИОТЕКА МУФТ''SelectPanel'False)

        cmdDef = ui.commandDefinitions.itemById('NewCommand')
        if cmdDef:
            cmdDef.deleteMe()
        cmdDef = ui.commandDefinitions.addButtonDefinition('NewCommand''Создать муфту''Ввод параметров для соединительных муфт','.//resource')
        tbPanel.controls.addCommand(cmdDef)


        sampleCommandCreated = SampleCommandCreatedEventHandler()
        cmdDef.commandCreated.add(sampleCommandCreated)
        handlers.append(sampleCommandCreated)


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


class SampleCommandCreatedEventHandler(adsk.core.CommandCreatedEventHandler😞
    def __init__(self😞
        super().__init__()
    def notify(selfargs😞
        eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
        cmd = eventArgs.command

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



class SampleCommandExecuteHandler(adsk.core.CommandEventHandler😞
    def __init__(self😞
        super().__init__()
    def notify(selfargs😞
        try:
            app = adsk.core.Application.get()
            ui  = app.userInterface
            # Create and display the palette.
            palette = ui.palettes.itemById('myExport')
            if palette:
                palette.deleteMe()
            if not palette:
                #make the [close] button invisible
                palette = ui.palettes.add('myExport''БИБЛИОТЕКА МУФТ''index.html'TrueTrueTrue400200)

                # Dock the palette to the right side of Fusion window.
                palette.dockingState = adsk.core.PaletteDockingStates.PaletteDockStateRight

                url = "http://195.133.144.86:4200//Half-coupling1.f3d"
                occ = importComponentFromURL(url)
    
            else
                palette.isVisible = True 
        except:
            ui.messageBox('Command executed failed: {}'.format(traceback.format_exc()))



def importComponentFromURL(url) -> adsk.fusion.Occurrence:

    app = adsk.core.Application.get()
    ui = app.userInterface

    # doc check
    doc = app.activeDocument
    if not doc.dataFile:
        ui.messageBox('Please save the document once.')
        return adsk.fusion.Occurrence.cast(None)

    folder = pathlib.Path(r'C:\Temp')
    if not folder.exists():
        folder.mkdir()

    parsed = urllib.parse.urlparse(url)
    filename = parsed.path.split('//')[-1]
    dlFile = folder / filename

    # suffix check
    if dlFile.suffix != '.f3d':
        ui.messageBox('F3D File Only')
        return adsk.fusion.Occurrence.cast(None)

    # delete download file
    if dlFile.is_file():
        dlFile.unlink()

    # file download
    try:
        data = urllib.request.urlopen(url).read()
        with open(str(dlFile), mode="wb"as f:
            f.write(data)
    except:
        ui.messageBox(f'File not found in URL\n{url}')
        return adsk.fusion.Occurrence.cast(None)

    # import f3d
    app.executeTextCommand(u'Fusion.ImportComponent {}'.format(dlFile))
    app.executeTextCommand(u'NuCommands.CommitCmd')

    # delete download file
    if dlFile.is_file():
        dlFile.unlink()

    des = adsk.fusion.Design.cast(app.activeProduct)
    comp = des.activeComponent
    return comp.occurrences[-1]
 
def stop(context😞
    ui = None
    try:
        ui.messageBox('Stop addin')

        workSpace = ui.workspaces.itemById('FusionSolidEnvironment')
        tbPanels = workSpace.toolbarPanels
                
        tbPanel = tbPanels.itemById('NewPanel')
        if tbPanel:
            tbPanel.deleteMe()

        cmdDef = ui.commandDefinitions.itemById('NewCommand')
        if cmdDef:
            cmdDef.deleteMe()
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

 

Labels (4)
4 REPLIES 4
Message 2 of 5

Hello,

 

I guess that the problem is in the next block of code:

 

 

 

            if palette:
                palette.deleteMe()

 

 

The deleteMe() method deletes the palette object but it doesn't clear the palette variable. So the condition "if not palette:" is false and the code goes to the line "palette.isVisible = True". But the palette object doesn't exist anymore. So the code crashes.

 

A solution could be to set the variable to None:

            if palette:
                palette.deleteMe()
                palette = None

 

But can you explain what you're trying to do?

 

Please use the "Insert/Edit code sample" tool ( </> icon in the toolbar) when you write your message.

 

Message 3 of 5

Hi! We are trying to create an add-in application to design parametric assemblies (couplings). We want to get a parametric coupling assembly from web-server and put it into Fusion 360 active design (user has to choose desired parameters and then click on Build button). 

Message 4 of 5

We tried to use your method but we still have the same error. 

Message 5 of 5

Hi @state.of.grace.17 .

 

I'm not sure what 'index.html' is doing, but I modified it like this and the error was avoided.

 

・・・
class SampleCommandExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            # app = adsk.core.Application.get()
            # ui  = app.userInterface
            # Create and display the palette.
            palette = ui.palettes.itemById('myExport')
            # if palette:
            #     palette.deleteMe()
            if not palette:
                #make the [close] button invisible
                palette = ui.palettes.add('myExport', 'БИБЛИОТЕКА МУФТ', 'index.html', True, True, True, 400, 200)

                # Dock the palette to the right side of Fusion window.
                palette.dockingState = adsk.core.PaletteDockingStates.PaletteDockStateRight

            palette.isVisible = True

            url = "http://195.133.144.86:4200//Half-coupling1.f3d"
            occ = importComponentFromURL(url)

        except:
            ui.messageBox('Command executed failed: {}'.format(traceback.format_exc()))
・・・

def importComponentFromURL(url) -> adsk.fusion.Occurrence:
・・・

    # import f3d
    app.executeTextCommand(u'Fusion.ImportComponent /NoMove {}'.format(dlFile))
    # app.executeTextCommand(u'NuCommands.CommitCmd')
・・・
def stop(context):
    # ui = None
    try:
        ui.messageBox('Stop addin')
・・・

 

We have also fixed the strange scope of 'ui'.

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