Updated 2017-04-19 22:37:29 by Molecool

p-Shell - A Tcl Interface to Creo Parametric edit

Scripting in Creo

p-Shell is a Creo Application which runs synchronous or a-synchronous with Creo 2.0 until 4.0 as a Binary Tcl Extensions, and enables you to access Creo Files and their Database via Tcl commands within a running Tcl/Tk environment.

  • For a synchronous application you will setup a menu once during Creo start, and specify a file to be sourced if the user picked this menu button.
  • In a-synchronous mode you start Creo, and after the connection is established you can call any p-Shell command or whatever may required for your application.

This pages shows some of many p-Shell built-In commands. This allows scripting in Creo for administrative or automation jobs and application development.

Parameter

This section shows how to work with parameter/attributes in Creo using the p-Shell command 'ps_param'

Sample: Create new parameter (or modify if exists) and change/set the value
#
# Create a parameter
#
set paramCmd [ps_param set MY_Param String {Hello World}  ]

#
# Configure the value
#

$paramCmd configure -value "Hello wiki.tcl.tk" -designate Yes -description "Don't change me manually"

#
#Create two string parameter at the first feature with the ID 1 
#

ps_modelitem miObj -model box.prt -type Feature -id 1

set paramObjs [ps_param set -at_item miObj -- [list MY_Param1 MY_Param2] String {Unknown} ]

Sample: Simple output of all parameter within the current Creo CAD model.
#
# write all parameter from the current model into a csv file with the name param.txt
#
proc GetParamToCSV {} {
#
# csv delimeter ',' or ';' ?
#
  set del ";"

# create the file

  set fp [open param.csv w]

#
# write the header
#
  puts $fp [join [list Name Type Value] $del]

#
# sorted param names output
#

  foreach paramObj [lsort -dictionary [ps_param  list] ] {

    set nam [$paramObj cget -name]
    set val [$paramObj cget -value]
    set typ [$paramObj cget -type]

    puts $fp [join [list $nam $typ $val] $del]

  }

# close and done

  close $fp

}

Creo Callback Menu

Provide a Callback menu in Creo.

Based on the installation, there is a 'program' folder, each folder may provide a Tcl Callback program if you place a 'pshell_init.tcl' file within this folder.

Sample 'pshell_init.tcl' file, argv0 is the path to the init file. The 'program' folder are parsed once, recursively on Creo Start. The command may supply additional arguments.
proc PShell_Init {dir} {
  ps_auto_menu add -root     {My Attributes}                 \
                   -text     {Model Attributes}              \
                   -command  [list $dir/MyAttributes.tcl]


}

PShell_Init [file dirname $argv0]

If the user select now the menu "Tools->My Attributes->Model Attributes" in Creo the file '$dir/MyAttributes.tcl' in the same dir of the 'pshell_init.tcl' file gets sourced an executed. All required files for Creo (menu files) will be created automatically on run time. To end the Tcl program call 'exit', which will only end the running Tcl program.

Another Parameter Sample

Show some commands and usage. Assume the parameter name is 'IDENT' and the final value should be "A-123-K-009", enable export to Windchill
#
# Set a parameter by name, type and value
# Make sure we have a parameter which is a STRING
#
# Check if exists
#

if ![ps_param  exists IDENT] {

#
# Okay create it
#    
   set paramCmd [ps_param  set IDENT String "This is a Identnumber, please change me." ]

  } else {


#
# Paramter exists. Is parameter a STRING type ?
#  If locked create an error
#

    set paramCmd [ps_param  list IDENT]

    if  [$paramCmd islocked]  {

      error "Error: Parameter IDENT is locked"

    }



    if ![string equal [$paramCmd cget -type]  STRING ] {
#
# Wrong type
#
# Get val and create a string type
#      
    set val [$paramCmd cget -value]

#
# Delete the param
#      
    $paramCmd delete

#
# Create as a STRING type with old value
#      

    set paramCmd [ps_param  set  IDENT String $val ]


  }

}

#
# Change to the final value and enable with designate the export to Windchill
#  

$paramCmd configure -value "A-123-K-009" -designate Yes -description "This Parameter will hold the Article Number"


Note: Working with dimensions is similar, a dimObj will contain more info (Tolerance, Tolerance Label, owning FeatId, the value,...) which can be extracted with the 'cget' option.

Asyn Sample

In Asynchronous mode you start Creo or connect to an existing session. After this you can drive Creo without having a callback in a Creo Menu.
#
# Simple asynchrounes Creo Session
# to load a Creo Drawing and export an DXF file
# Execute in Tcl as a callback or just in plain Tcl
#

#
# Setup to callback functions
#
# Invoked after connection is establish
#
proc pShell_Init {} {puts "Connected"}
#
# Invoked after connection is closed
#
proc pShell_Exit {} { puts "Session closed"}

#
# In Tcl get the DLL
#
package req pshell_asyn 


#
# Configure and Start the Creo Session
#
ps_session ::PS::SessionCmd                               \
        -exit                pShell_Exit                  \
        -init                pShell_Init                  \
        -timeout             20                           \
        -text                C:/p-Shell/programs/text     \
        -pro_comm_msg        [file native "C:/Creo 2/Common Files/M200/x86e_win64/ob/pro_comm_msg.exe"] 

#
# Start Creo 
# after connect 'pShell_Init' is called
#
::PS:SessionCmd start [file native "C:/Creo 2/Parametric/bin/creo2.bat"]

#
# Note: This script continues if Creo is running and connection is established 
#
#
# Make sure that all Datums are not displayed
# Load a config file wich will turn on/off what we want
#

ps_import config c:/Release/release.pro

#
# Open the Drawing in the current Working Dir
#
ps_file open box.drw

#
# Get the referenced model
# No error check here (None or more than one)
#
set refMdl [ps_draw list -drawing box.drw]

#
# Make sure not to display a certain layer, turn off a layer where we have only curves
# No error check here (Layer exists, current status)

ps_layer set -model $refMdl -- ALL_CURVES Blank

#
# Update the title block to display the current day (This is Based on the used Format)
# assume parameter DRW_RELASE_DATE is new or exists as a string 
#
ps_param  set DRW_RELEASE_DATE String [clock format [clock seconds] -format "%m/%d/%y"]


#
# Display the Drawing in a Window
#
ps_wind set box.drw

#
# Create the DXF file
#
ps_export dxf -model box.drw -- box.dxf


#
# Save the drawing with the updated parameter
#
ps_file save box.drw

#
# Stop the session
# This will eval 'pShell_Exit' and delete all p-Shell commands
#
::PS:SessionCmd stop

Asyn & Windchill (Sample)

Another example to export Creo Objects to a local folder from Windchill
#
# Setup to callback functions
#
# Invoked after connection is establish
#
proc pShell_Init {} {puts "Connected"}
#
# Invoked after connection is closed
#
proc pShell_Exit {} { puts "Session closed"}

#
# In Tcl get the DLL
#
package req pshell_asyn 


#
# Configure and Start the Creo Session
#
ps_session ::PS::SessionCmd                               \
        -exit                pShell_Exit                  \
        -init                pShell_Init                  \
        -timeout             20                           \
        -text                C:/p-Shell/programs/text     \
        -pro_comm_msg        [file native "C:/Creo 2/Common Files/M200/x86e_win64/ob/pro_comm_msg.exe"] 

#
# Start Creo 
# after connect 'pShell_Init' is called
#
::PS:SessionCmd start [file native "C:/Creo 2/Parametric/bin/creo2.bat"]

#
# Create the Server Command
#
ps_server serverObj

#
# Configure the Server Command
#
serverObj configure -serverurl http://MyWindchill/windchill -alias MyConnectionName

#
# Prepare Username and Password for http://MyWindchill/windchill
#
serverObj login MyUserName MyPassword

#
# Register an existing Workspace 'MyWorkspace'
#
serverObj register MyWorkspace


#
# Add both assemblies into the Workspace MyWorkspace
# After add to workspace the objects are not "Checked Out"
#

serverObj multiobjcheckout  [list assy1.asm assy2.asm] false

#
# Open both assemblies in Creo
#

ps_file open assy1.asm
ps_file open assy2.asm

#
# Save both assemblies in an existing folder named 'c:/temp/export/assyX'
#
ps_file backup assy1.asm c:/temp/export/assy1
ps_file backup assy2.asm c:/temp/export/assy2


#
# Stop the session
#
::PS:SessionCmd stop

Assemblies

Command options for ps_assy are:
     component_name       FeatID
     is_bulk_item         FeatID
     type                 FeatID
     matrix_get           comppathObj Matrix
     matrix_set           comppathObj Matrix
     explode              ?NewState?
     interchange          IDs ReplaceModel
     create               NAME.EXT Unplaced ?Template?
     dynamic_position     ?NewState?
     assemble             Component Matrix modelItemObjReturn
     setconstraints       ModelItem Constraints ?CompPath?
     getconstraints       ModelItem Constraints
     numofconstraints     ModelItem
     -help

Assemble a Component

Example: Assembly by CSYS

If you assemble by Coordinate system, you can use the name of the CSYS to identify the model item. Like in Creo you have to specify the assembly reference and the component reference.

For placing Components (single model or another assembly) in one assembly you need to specify the target assembly, the component/assembly to assembly and an initial matrix.

The return value on placing a component is a model item, which contains the component info, for feature id and type.

We assembly the component 'comp.prt' by using the coordinate system with the name 'CS0' into the assembly 'assy.asm' by using the coordinate system with the name 'ACS0'.

You must supply the same info, as if you would do this in Creo manually.

Basically a selection object contains a component path and a model item reference, this must be supplied by your calls. Component Path is not required in the following example.

You need to supply a component path if you would like to use a reference in the target assembly, which is for example a csys of an already assembled component.

Note: A component can be assembled multiple times, the component path will uniquely identify the model item in an assembly.
#
# Vars for the models to be used
# model handle
#
 
set ASSY assy.asm
set PART comp.prt

# Create two selection objects
#
# one for the assembly reference 
# one for the component reference

ps_sel AssySelObj
ps_sel CompSelObj

# create two modelitem Obj
#
# one for the assembly
# one for the component

ps_modelitem AssyMiObj
ps_modelitem CompMiObj
 
 
# A csys for sure has a name
# Note: The Feature ID of the CSYS is not the ID, which is used later
# The Geometric ID will be used
# set data, fill csys geometric id, type and owner.
#
# one for the assembly
# one for the component

# This too calls will setup the model items with valid values
# if the given name and type is valid

AssyMiObj byname $ASSY csys ACS0
CompMiObj byname $PART csys CS0

#
# Configure selection object's
# to use the model item information
#
# one for the assembly
# one for the component

AssySelObj                config -modelitem AssyMiObj
CompSelObj                config -modelitem CompMiObj

#
# create the constraint Object
#
ps_asmconstraint constraintObj
 
#
# setup the type by 'csys'
#
constraintObj         config -constrainttype   CSYS
#
# set the info, same as manually done in Creo after selecting the references
# Could be done in one statement as well
#
constraintObj         config -asmselection   AssySelObj -asmdatumside none
constraintObj         config -compselection  CompSelObj -compdatumside NONE

#
# Create a default matrix for initial position
#
ps_matrix matrixObj

#
# Assemble the component first without any constraints
# You only have to take care that 
# 'PlacedMiObj' does not exists as a command with another type.
# You can create it upfront as well, same for the Matrix Object
# 
ps_assy assemble -model $ASSY -- $PART matrixObj PlacedMiObj

# Final call to set the constraints
# We don't need to specify a component path in this sample 
# Only 2 (not 3) args given to the function
# 'PlacedMiObj' is the result from assembling without constraints
# 'list' is used to keep in mind that you may need to specify more the one constraint
# If you assembly by datum planes you need to supply normally 3 constraints 
#
# If this fail, you may want to delete the placed component with ps_feat delete ?ID? 
# The feature id you get with: 'PlacedMiObj cget -id'
#
# Configure the placed component to make if fully parametric
#
ps_assy setconstraints PlacedMiObj  [list asmconObj] 

#
# Component is now fully constraint and assembled 
#

Assume you have have an active assembly test.asm where feature ID 43 is the subassembly sub.asm and contains a component with the name bolt.prt at feature id 30.
#
# Assembly test.asm is active
# '0' the path is invalid or
# '1' the path is valid.
#
set member1 [ps_assy component_name    43 ] 
set member2 [ps_assy component_name  -model sub.asm  -- 30 ] 

member1 will be set to SUB.ASM

member2 will be set to BOLT.PRT

Component Path

Create a component path object. A component path object identifies a unique component in one assembly.
#
# Note: creation or configuration return 0 or 1. 
# '0' the path is invalid or
# '1' the path is valid.
#
ps_comppath    myPath  -model test.asm -path {43 30} -component bolt.prt

Export to file

Options for ps_export are:
     relation             Filename
     model_info           Filename
     program              Filename
     iges_2d              Filename
     dxf                  Filename
     render               Filename
     sla_binary           Filename
     sla_ascii            Filename
     catiafacets          Filename
     bom                  Filename
     dwg_setup            Filename
     feature_info         Filename
     mfg_oper_cl          Filename
     mfg_feat_cl          Filename
     material             Filename
     iges_3d              Filename
     step                 Filename
     vda                  Filename
     set                  Filename
     cgm                  Filename
     inventor             Filename
     fiat                 Filename
     connector_params     Filename
     catia                Filename
     cable_params         Filename
     optegra_vis          Filename
     dwg                  Filename
     -help

Geometric Data

Options for ps_data are:
     axis               Geom_ID lineObj
     edge               Geom_ID lineObj
     arc                Geom_ID arcObj
     csys               Geom_ID csysObj
     surface            Geom_ID csysObj
     point              Geom_ID pointObj
     outline            lineObj
     eval_surface       Geom_ID UVpointObj lineObj
     extremes           Geom_ID pointObj lineObj
     edge_eval_xyz      IDs Params
     curve_eval_xyz     IDs Params
     edge_dir           SurfID EdgeID
     curve              Geom_ID lineObj
     tessellation       Geom_ID Tolerance
     -help

Matrices

ps_matrix matrixObj

This command will create a 4x4 identity matrixObj
1.00.00.00.0
0.01.00.00.0
0.00.01.00.0
0.00.00.01.0

Options for matrixObj are:
     cget                   Option
     configure              Option ?Value?
     rot2d                  angle
     invert
     normalize              ?matrixOut?
     reset
     identity
     copy                   matrixOut
     product                matrixObj ?matrixOut?
     x_to_vector            pointObj
     y_to_vector            pointObj
     z_to_vector            pointObj
     origin_to_vector       pointObj
     x_from_vector          pointObj
     y_from_vector          pointObj
     z_from_vector          pointObj
     origin_from_vector     pointObj
     shift_to_vector        pointObj
     shift_from_vector      pointObj
     scale_xyz              ScaleValue

Sample command
# copy the matrix
matrixObj copy bckMatrix

Similar commands available for points, arcs, coordinate systems, and single line (2 Points)

Options for pointObj are:
     cget              Option
     configure         ?Option?
     transform         matrixObj pointObj
     rotate            matrixObj pointObj
     copy              pointObj
     product           pointObj
     angle             pointObj
     lenght
     normalize
     cross_product     point2Obj resultPointObj
     dircos
     add               point2Obj resultPointObj
     move              point2Obj resultPointObj
     diff              point2Obj resultPointObj
     2d_values         XY_List
     3d_values         XYZ_List
     multiply          matrixObj pointObj
     draw              ?Color?
     -help

Feature

Command options for ps_feat are:
     count
     name                     FeatIDs
     type                     FeatIDs
     list
     exists                   FeatIDs
     children                 FeatID
     parents                  FeatID
     status                   FeatIDs
     visible                  FeatIDs
     active                   FeatIDs
     number                   FeatIDs
     has_geom_checks          FeatIDs
     suppress                 FeatIDs
     delete                   FeatIDs
     resume                   FeatIDs
     protype                  FeatIDs
     subtype                  FeatIDs
     show_param               selObj ParamType
     set_name                 FeatID NewName
     is_read_only             FeatIDs
     unset_read_only
     set_read_only            FeatID
     ungroup                  GroupIDs
     groupstatus              FeatIDs
     isgroup                  FeatIDs
     num_section              FeatID
     section_copy             FeatID secNumber sectionObjName
     cancel_insert_mode       ?BoolResume?
     is_insert_mode
     insert_mode_activate     FeatID
     -help
#
# Children of a feature in the active model
#
ps_feat child 23

#
# Parents from FeatID 45 in model box.prt
#
ps_feat parents -model box.prt -- 45


# 
# get the status for all features in the active model
#
set stat  [ps_feat stat [ps_feat list]]

Files

Options for ps_file are:
     open        Filename
     erase       Filename
     exists      Filename
     save        Filename
     delete      Filename
     display     Filename
     copy        Source Target
     rename      Source Target
     backup      Filename NewDir
     create      Filename
     get         ?Filter? ?InitPath? ?Label? ?PreSelect?
     -help

Note: Get working directory with 'ps_pwd' and change with 'ps_cd TargetDir'
#
# open file from disc into memory
#
ps_file open c:/workdir/box.prt

Selection

Invoke a user selection
#
# create the selection object
#
ps_sel selObj

#
# The usr should select an edge
# Wirite something into the Creo message area
#

ps_mess "Please select an edge"

#
# Control goes to Creo
#
selObj select edge

# Back in p-Shell:
# Get the model item from the selection object
# Note: You can also get the status if a user abort.
#
selObj modelitem miObj

#
# It's an edge - get the edge data into an lineObj
# Note: the line object will contains more info, calculate length is only one option
#

ps_data edge -model [miObj get -model] --  [miObj get -id ]  lineObj

#
# get the vector length
#
set len  [lineObj len]

More info: Tcl4Creo (at) gmail (dot) com


CAD[Category 3D][Category Creo][Category Creo Scripting]