Set parameters from a csv file and export to STEP

Description

Reads data from a .csv file and sets user parameters in the model and then exports the model to STEP. When setting parameters be aware that this sample is setting user parameters. It's also possible to set model parameters but that's not demonstrated here. Also when accessing parameters, it is case sensitive so the names you use in your program much exactly match the names in the model.

Code Samples

import adsk.core, adsk.fusion, traceback

def run(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface
        
        design = app.activeProduct
        # Read the csv file.
        cnt = 0
        file = open('C://Temp//values.csv')
        for line in file:
            # Get the values from the csv file.
            pieces = line.split(',')
            
            length = pieces[0]
            width = pieces[1]
            height = pieces[2]
            
            # Set the parameters.
            lengthParam = design.userParameters.itemByName('Length')
            lengthParam.expression = length
            
            widthParam = design.userParameters.itemByName('Width')
            widthParam.expression = width

            heightParam = design.userParameters.itemByName('Height')
            heightParam.expression = height
            
            #Export the STEP file.
            exportMgr = design.exportManager
            stepOptions = exportMgr.createSTEPExportOptions('C:\\Temp\\test_​box' + str(cnt) + '.stp')
            cnt += 1
            res = exportMgr.execute(stepOptions)
        
        ui.messageBox('Finished')
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
#include <Core/Application/Application.h>
#include <Core/UserInterface/UserInterface.h>
#include <Fusion/Fusion/UserParameters.h>
#include <Fusion/Fusion/UserParameter.h>
#include <Fusion/Fusion/STEPExportOptions.h>
#include <Fusion/Fusion/ExportManager.h>

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

using namespace adsk::core;
using namespace adsk::fusion;

Ptr<UserInterface> ui;

typedef std::vector<std::vector<std::string>> DataSet;

void loadCSVFile(const std::string& csvFilePath, DataSet& dataSet)
{
    std::ifstream infile(csvFilePath);

    while (infile)
    {
        std::string s;
        if (!getline(infile, s))
            break;

        std::istringstream ss(s);
        std::vector<std::string> record;

        while (ss)
        {
            std::string s;
            if (!getline(ss, s, ','))
                break;
            record.push_back(s);
        }

        dataSet.push_back(record);
    }
}

std::string getTempPath()
{
    std::string strTempPath;
#ifdef XI_WIN
    char chPath[MAX_PATH];
    if (::GetTempPathA(MAX_PATH, chPath))
        strTempPath = chPath;
#else  // Mac
    NSString* tempDir = NSTemporaryDirectory();
    if (tempDir == nil)
        tempDir = @"/tmp";
    strTempPath = [tempDir UTF8String];
#endif // XI_WIN
    return strTempPath;
}

extern "C" XI_EXPORT bool run(const char* context)
{
    Ptr<Application> app = Application::get();
    if (!app)
        return false;

    ui = app->userInterface();
    if (!ui)
        return false;


    // Read the csv file.
    int cnt = 0;

     DataSet dataSet;
     loadCSVFile("C:\\Temp\\values.csv", dataSet);

    for (auto data : dataSet)
    {
        // Get the values from the csv file.
        std::string length = data.at(0);
        std::string width = data.at(1);
        std::string height = data.at(2);

        // Set the parameters.
        Ptr<UserParameters> userParams = design->userParameters();
        if (!userParams)
            return false;
        Ptr<UserParameter> lengthParam = userParams->itemByName("Length");
        if (!lengthParam)
            return false;
        lengthParam->expression(length);

        Ptr<UserParameter> widthParam = userParams->itemByName("Width");
        if (!widthParam)
            return false;
        widthParam->expression(width);

        Ptr<UserParameter> heightParam = userParams->itemByName("Height");
        if (!heightParam)
            return false;
        heightParam->expression(height);

        // Export the STEP file.
        Ptr<ExportManager> exportMgr = design->exportManager();
        if (!exportMgr)
            return false;
         std::string filename = "C:\\Temp\\test_box" + std::to_string(cnt) + ".stp";
         Ptr<STEPExportOptions> stepOptions = exportMgr->createSTEPExportOptions(filename);
        if (!stepOptions)
            return false;

        ++cnt;
        exportMgr->execute(stepOptions);
    }


    return true;
}
/**
 * Set parameters from a csv file and export to STEP
 * Reads data from a .csv file and sets user parameters in the model and then exports the model to STEP. When setting parameters be aware that this sample is setting user parameters. It's also possible to set model param...
 */

import { adsk } from '@adsk/fusion';

function getDataFile(app: adsk.core.Application,
  hubId: string,
  fileURN: string): adsk.core.DataFile {
  if (hubId) {
    // Possible hubId formats: base64 encoded string, or business:<id>,
    // or personal:<id> (deprecated)
    const hub =
      app.data.dataHubs.itemById(hubId) ||
      app.data.dataHubs.itemById(`a.${adsk.btoa(`business:${hubId}`, true)}`) ||
      app.data.dataHubs.itemById(`a.${adsk.btoa(`personal:${hubId}`, true)}`);
    if (!hub) {
      adsk.log(`Hub with id ${hubId} not found.`)
      throw "Hub not found"
    }
    adsk.log(`Setting hub: ${hub.name}.`);
    app.data.activeHub = hub;
    adsk.log(`Hub has been set`)
  }
  const file = app.data.findFileById(fileURN);
  if (!file) {
    adsk.log(`File not found ${fileURN}.`)
    throw "File not found"
  }
  return file
}

function wait(ms: number) {
  const start = new Date().getTime();
  while (new Date().getTime() - start < ms) adsk.doEvents();
}

function download(hubId: string, fileURN: string, path: string) {
  const app = adsk.core.Application.get() as adsk.core.Application;
  const file = getDataFile(app, hubId, fileURN);
  adsk.log("downloading file")
  let future = file.dataObject
  adsk.log("download started")
  while (future.state == adsk.core.FutureStates.ProcessingFutureState) {
    adsk.log(".")
    wait(1000)
  }
  if (future.state != adsk.core.FutureStates.FinishedFutureState) {
    adsk.log("Download Failed")
    throw "Download Failed";
  }
  let dataObect = future.dataObject
  adsk.log("Saving file to \"" + path + "\"")
  dataObect.saveToFile(path)
  adsk.log("Download successfull")
}

function run() {

  // Get the parameters passed to the script
  const scriptParameters = JSON.parse(adsk.parameters);
  if (!scriptParameters) throw "Invalid parameters provided.";

  const app = adsk.core.Application.get() as adsk.core.Application;
  if (!app) throw Error("No adsk.core.Application.");

  const design = app.activeProduct as adsk.fusion.Design;
  if (!design) throw Error("No active Fusion design.");

  const fileName = scriptParameters.fileName;
  if (scriptParameters.csvURN) {
    download(scriptParameters.hubId, scriptParameters.csvURN, fileName)
  }

  // Read the CSV file
  const filePath = "values.csv";
  const fileContent = adsk.readFileSync(filePath);
  const lines = fileContent.split("\n");

  let cnt = 0;
  for (const line of lines) {
    if (!line.trim()) continue;
    const pieces = line.split(",");
    const length = pieces[0];
    const width = pieces[1];
    const height = pieces[2];

    // Set the parameters
    const lengthParam = design.userParameters.itemByName("Length") as adsk.fusion.UserParameter;
    if (lengthParam) lengthParam.expression = length;

    const widthParam = design.userParameters.itemByName("Width") as adsk.fusion.UserParameter;
    if (widthParam) widthParam.expression = width;

    const heightParam = design.userParameters.itemByName("Height") as adsk.fusion.UserParameter;
    if (heightParam) heightParam.expression = height;

    // Export the STEP file
    const exportMgr = design.exportManager as adsk.fusion.ExportManager;
    const stepOptions = exportMgr.createSTEPExportOptions(`test_box_${cnt}.stp`) as adsk.fusion.STEPExportOptions;
    cnt += 1;
    exportMgr.execute(stepOptions);
  }
}

run();