Calling specific tool database in Script (Python)

Calling specific tool database in Script (Python)

MarcoNKE
Contributor Contributor
291 Views
3 Replies
Message 1 of 4

Calling specific tool database in Script (Python)

MarcoNKE
Contributor
Contributor

Hi everyone,

 

i can't find a solid method to call my specific tool library, located in local folder in fusion database, in script code

i tried to use some exemple in API Help in Fusion but it doesn't work
can you tell me a way to do it as simple as possible?

 

thanks

0 Likes
292 Views
3 Replies
Replies (3)
Message 2 of 4

kandennti
Mentor
Mentor

Hi @MarcoNKE -san.

Is this the tool library you were looking for?

# Fusion360API Python script

import traceback
from typing import Optional
import adsk.core as core
import adsk.cam as cam


def run(context: dict) -> None:
    """Entry point for the Fusion360 script.

    Retrieves the first tool found under the local tool library
    and prints its representative parameters to the debug console.
    """
    ui: Optional[core.UserInterface] = None
    try:
        app: core.Application = core.Application.get()
        ui = app.userInterface

        tool: Optional[cam.Tool] = get_first_tool_from_local_library()
        if tool:
            dump_tool_info(tool)
        else:
            print('No tool found in the local library.')

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


def get_first_tool_from_local_library() -> Optional[cam.Tool]:
    """Return the first tool found under the local tool library.

    Returns:
        The first tool, or None if no tool is found.
    """
    camMgr: cam.CAMManager = cam.CAMManager.get()
    toolLibs: cam.ToolLibraries = camMgr.libraryManager.toolLibraries

    rootUrl: core.URL = toolLibs.urlByLocation(
        cam.LibraryLocations.LocalLibraryLocation
    )
    return _find_first_tool(toolLibs, rootUrl)


def _find_first_tool(
    toolLibs: cam.ToolLibraries,
    url: core.URL,
) -> Optional[cam.Tool]:
    """Recursively search under the given URL and return the first tool.

    Args:
        toolLibs: The tool libraries manager.
        url: The folder URL to start searching from.

    Returns:
        The first tool, or None if no tool is found.
    """
    for assetUrl in toolLibs.childAssetURLs(url):
        toolLib: cam.ToolLibrary = toolLibs.toolLibraryAtURL(assetUrl)
        if toolLib and toolLib.count > 0:
            return toolLib.item(0)

    for folderUrl in toolLibs.childFolderURLs(url):
        found: Optional[cam.Tool] = _find_first_tool(toolLibs, folderUrl)
        if found:
            return found

    return None


def dump_tool_info(tool: cam.Tool) -> None:
    """Print representative parameters of a tool to the debug console.

    Args:
        tool: The tool whose information will be printed.
    """
    names: list[str] = [
        'tool_description',
        'tool_number',
        'tool_type',
        'tool_diameter',
        'tool_numberOfFlutes',
        'tool_material',
        'tool_vendor',
        'tool_productId',
    ]
    for name in names:
        prm: Optional[cam.CAMParameter] = tool.parameters.itemByName(name)
        if prm:
            print(f'{name}: {_format_param_value(prm)}')
        else:
            print(f'{name}: (not set)')


def _format_param_value(prm: cam.CAMParameter) -> str:
    """Return the value of a CAM parameter as a string.

    Numeric parameters are read via ``prm.value.value``, while
    string parameters are read via ``prm.expression``.

    Args:
        prm: The CAM parameter to read.

    Returns:
        The string representation of the value, or ``'(empty)'`` if
        it cannot be retrieved.
    """
    try:
        v = prm.value.value
        if v is not None and v != '':
            return str(v)
    except:
        pass

    try:
        expr: str = prm.expression
        if expr:
            return expr.strip("'\"")
    except:
        pass

    return '(empty)'
0 Likes
Message 3 of 4

MarcoNKE
Contributor
Contributor

Hi,

do i need to copy the whole code into mine?

i tried to do it but nothing happens

0 Likes
Message 4 of 4

kandennti
Mentor
Mentor

@MarcoNKE -san.

I was mistaken. Here is a sample that accesses the first tool in this tool library.
1.png

# Fusion360API Python script

import traceback
from typing import Optional
import adsk.core as core
import adsk.cam as cam


def run(context: dict) -> None:
    """Entry point for the Fusion360 script.

    Retrieves the first tool from the named library within the local tool library
    and prints its representative parameters to the debug console.
    """
    ui: Optional[core.UserInterface] = None
    try:
        app: core.Application = core.Application.get()
        ui = app.userInterface

        tool: Optional[cam.Tool] = get_first_tool_from_named_local_library("CustomTools")
        if tool:
            dump_tool_info(tool)
        else:
            print('No tool found in the local library.')

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


def get_first_tool_from_named_local_library(libraryName: str) -> Optional[cam.Tool]:
    """Return the first tool from the library matching libraryName within the local library.

    Args:
        libraryName: The name of the library to search for within the local library location.

    Returns:
        The first tool, or None if the library is not found or contains no tools.
    """
    camMgr: cam.CAMManager = cam.CAMManager.get()
    toolLibs: cam.ToolLibraries = camMgr.libraryManager.toolLibraries

    # Local
    rootUrl: core.URL = toolLibs.urlByLocation(
        cam.LibraryLocations.LocalLibraryLocation
    )

    # Custom Tools URL
    targetUrl: core.URL = None
    url: core.URL = None
    for url in toolLibs.childAssetURLs(rootUrl):
        if url.leafName == libraryName:
            targetUrl = url
            break

    if not targetUrl: return None
    
    # Custom Tools ToolLibrary
    targetToolLib: cam.ToolLibrary = toolLibs.toolLibraryAtURL(targetUrl)
    if targetToolLib.count < 1: return None

    # First Tool
    return targetToolLib.item(0)


def dump_tool_info(tool: cam.Tool) -> None:
    """Print representative parameters of a tool to the debug console.

    Args:
        tool: The tool whose information will be printed.
    """
    names: list[str] = [
        'tool_description',
        'tool_number',
        'tool_type',
        'tool_diameter',
        'tool_numberOfFlutes',
        'tool_material',
        'tool_vendor',
        'tool_productId',
    ]
    for name in names:
        prm: Optional[cam.CAMParameter] = tool.parameters.itemByName(name)
        if prm:
            print(f'{name}: {_format_param_value(prm)}')
        else:
            print(f'{name}: (not set)')


def _format_param_value(prm: cam.CAMParameter) -> str:
    """Return the value of a CAM parameter as a string.

    Numeric parameters are read via ``prm.value.value``, while
    string parameters are read via ``prm.expression``.

    Args:
        prm: The CAM parameter to read.

    Returns:
        The string representation of the value, or ``'(empty)'`` if
        it cannot be retrieved.
    """
    try:
        v = prm.value.value
        if v is not None and v != '':
            return str(v)
    except:
        pass

    try:
        expr: str = prm.expression
        if expr:
            return expr.strip("'\"")
    except:
        pass

    return '(empty)'
0 Likes