Message 1 of 2
Script error when running through multiple files for CAM data
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
I'm trying this script to get cycletimes from multiple files. I ran it on multiple projects succesfully, but run into 2 issues:
- My recent files gets fully populated by these file
- I get a script error without an idea whats the problem on some projects.
about 2. I seems to happen in the for loop "for files". How can I see what causes this error?
import adsk.core, adsk.fusion, adsk.cam, os, traceback, csv
from datetime import datetime, timedelta, timezone
# Initialize Fusion 360 application objects
app = adsk.core.Application.get()
ui = app.userInterface
def format_machining_time(minutes):
#"""Converts machining time from minutes to hours:minutes:seconds format."""
# Convert minutes to seconds for timedelta
seconds = int(minutes * 60)
# Use timedelta for easy conversion and formatting
td = timedelta(seconds=seconds)
# Format as hours:minutes:seconds
return str(td)
def export_project_data_to_csv(output_folder):
# Access the active project's root folder
project_root = app.data.activeProject.rootFolder
# Prepare the CSV file for output
csv_path = os.path.join(output_folder, 'Fusion360_Project_Data.csv')
# Open the CSV file
with open(csv_path, mode='w', newline='', encoding='utf-8') as csv_file:
csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
# Write the headers
headers = ['Document Name', 'Creation Date', 'Last Updated', 'Setup Name', 'Machining Time (Minutes)', 'Thumbnail Path',"Total Operations", "Valid Operations"]
csv_writer.writerow(headers)
# Iterate through each file in the root folder
for file in project_root.dataFiles:
if file.fileExtension.lower() == 'f3d' or file.fileExtension.lower() == 'f3z':
try:
document = app.documents.open(file, True) # Open the document in read-only mode
except:
ui.messageBox('Failed to open document:\n{}'.format(traceback.format_exc()))
continue
products = document.products
try:
product = products.itemByProductType('CAMProductType')
except:
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)
continue
# product = document.products.itemByProductType('CAMProductType')
cam = adsk.cam.CAM.cast(document.products.itemByProductType('CAMProductType'))
# Document details
creation_date = convert_epoch_to_dutch_datetime(file.dateCreated)
last_update = convert_epoch_to_dutch_datetime(file.dateModified)
# Generate thumbnail for the document
thumbnail_path = generate_thumbnail(document.name, output_folder)
# Iterate through CAM setups in the document
for setup in cam.setups:
setup_name = setup.name
# Calculate actual machining time using the CAM API
try:
machTimeResult = cam.getMachiningTime(setup, 1, 100, 15)
machining_time_minutes = machTimeResult.machiningTime # Time in minutes
machining_time_formatted = format_machining_time(machining_time_minutes)
except:
machining_time = "Error calculating time"
# Count total and valid operations based on Operation.isValid property
num_operations = setup.allOperations.count
num_valid_operations = sum(1 for op in setup.allOperations if op.isToolpathValid)
# Write details to the CSV file
csv_writer.writerow([
document.name, creation_date, last_update, setup_name, machining_time_formatted,
thumbnail_path, num_operations, num_valid_operations
])
# Close the document after processing
document.close(False)
# Notify the user
ui.messageBox('CAM project data and thumbnails exported to CSV successfully.')
def convert_epoch_to_dutch_datetime(epoch_time):
# Assuming CET as UTC+1 for simplicity
CET_OFFSET = timedelta(hours=1)
UTC_ZONE = timezone.utc
# Convert the epoch time to a datetime object in UTC
utc_time = datetime.fromtimestamp(epoch_time, tz=UTC_ZONE)
# Manually adjust for CET (without considering daylight saving time)
dutch_time = utc_time + CET_OFFSET
# Format the datetime object to a string in the desired format
return dutch_time.strftime('%d-%m-%Y %H:%M:%S')
def generate_thumbnail(document_name, folder_path):
try:
# Get the active viewport
viewport = app.activeViewport
# Create a camera for isometric view
camera = viewport.camera
# Set the camera to look at the model isometrically
camera.isSmoothTransition = False
camera.viewOrientation = adsk.core.ViewOrientations.IsoTopRightViewOrientation
# Apply the camera to the viewport
viewport.camera = camera
viewport.refresh()
# Define the file name for the saved image
file_name = f'thumbnail_{document_name}.png'
file_path = os.path.join(folder_path, file_name)
# Save the current viewport as an image
viewport.saveAsImageFile(file_path, 400, 300)
return file_path
except:
ui.messageBox('Failed to generate thumbnail:\n{}'.format(traceback.format_exc()))
return ''
# Specify the output folder path
output_folder_path = 'C:/temp'
# Ensure the output folder exists
os.makedirs(output_folder_path, exist_ok=True)
# Execute the export function
export_project_data_to_csv(output_folder_path)
Inventor HSM and Fusion 360 CAM trainer and postprocessor builder in the Netherlands and Belgium.