Professional Documents
Culture Documents
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 1 Siemens Industry Software – Março/2013
NX
Lesson 8
Tcl basics for Post Builder
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 2 Siemens Industry Software – Março/2013
NX
Tcl basics for Post Builder
Purpose
This lesson describes the basics of the Tcl scripting language that is used by
existing NX Post and Post Builder programs, within postprocessors that you
create, and for customizing that you perform.
Objectives
After you complete this lesson, you will be able to:
• Interpret the syntax and basic structures of Tcl.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 3 Siemens Industry Software – Março/2013
NX
Tcl
Tcl is public domain software. The Tcl source and a link to a provider of the
compiled executable is available at tcl.sourceforge.net. Tcl stands for tool
command language. Tcl is an interpreted language, that is, a Tcl script is
interpreted at run time by a Tcl interpreter. The difference between Tcl and a
compiled language such as C or GRIP is that you can make changes to the scripts
and test them without having compile your code.
In NX CAM, you use Tcl for procedures in NX Post, Process Assistants, Shop
Documentation, the internal CLSF, and Post Builder. You also use Tcl to create
the following:
• User-defined event handlers
• User-supplied rules
Tcl has an extension called Tk, which stands for tool kit. Tk provides user graphic
interface elements such as buttons, check boxes, and scroll bars.
You can open a Tk window by running the program ugwish.exe in the
\mach\auxiliary directory.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 4 Siemens Industry Software – Março/2013
NX
Although Post Builder 8.0.0.4 uses Tcl 8.4.19 internally, NX Post uses an
older version. Siemens PLM Software recommends that you follow the 8.0.5
syntax to maintain compatibility with NX Post.
You can find Tcl 8.0.5 command documentation at:
http://www.tcl.tk/man/tcl8.0/
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 5 Siemens Industry Software – Março/2013
NX
Tcl command structure
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 6 Siemens Industry Software – Março/2013
NX
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 7 Siemens Industry Software – Março/2013
NX
Command arguments
Arguments can be any type of information that a command can process, change,
or use.
In the command set principal_axis X, the command is set, which instructs
to interpreter to assign a value to a variable. The two arguments convey the
following information:
The first argument, principal_axis, is the name of a variable to be assigned a
value. The variable is created if it does not already exist.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 8 Siemens Industry Software – Março/2013
NX
Command options
Options are used with some commands to give the interpreter detailed instructions
of the task that the command must perform. Options begin with the ‘–’ character.
For example, glob -nocomplain *.ini consists of:
The command glob, which instructs the interpreter to match patterns using the
standard file name wild card format.
The option -noclomplain which instructs the interpreter to return an empty list
if nothing matches. Without this option, an error would occur if there are
no matches.
The argument *.ini, which matches any text string that ends with .ini.
The effect of the command, when used in the correct context, is to identify all
file names that have the extension .ini.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 9 Siemens Industry Software – Março/2013
NX
Words
Tcl command strings are divided into words. By default, white space characters
divide strings of text characters into words.
In your programs, you often group words and white space with brackets or braces
to create words that consist of two or more other words. Brackets and braces
have different meanings to the interpreter. Braces prevent variable substation
from taking place on their content.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 10 Siemens Industry Software – Março/2013
NX
Specifying the order in which words are interpreted
Tcl is structured so that you can specify which words to interpret first. This allows
you to combine commands to achieve a more complex result. For example:
set ini_file_list [glob -nocomplain *.ini]
Variables
A variable can be thought of as a named place holder for information. In many
languages other than Tcl, variables must have a declared type, such as numbers
or strings of text characters. In these languages, in order to set aside the right
amount of memory to hold a value of the corresponding type, you must declare
variables before you use them.
Tcl variables always hold text. You need not declare a Tcl variable before you
use it.
The only declaration statement in Tcl is used to set the scope of a variable, or
whether the variable is known throughout the entire program, or only within the
procedure that contains it.
Variable names
A Tcl variable name must start with an alphabetic character and can consist of
alphanumeric characters and the underscore. Variable names are case sensitive.
For example, the following are all different variables.:
X
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
x 12
Page Siemens Industry Software – Março/2013
NX
Value of variables
When you execute the set command at the Tcl command prompt % to create or
modify a variable, the interpreter responds with the value that is stored in the
program memomry. For example:
% set X 10.5
10.5
% set mom_sys_debug_mode OFF
OFF
At the command prompt, you can use the set command with only one argument, a
variable name, to see the current value. In the following command line example,
we use set to define a variable X, and then use set to find the current value of X:
% set x 10.5
10.5
% set x
10.5
The unset command removes a variable from your program. The command
prompt returns nothing if the command is successful, but there is an error
message if there is no such variable.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 13 Siemens Industry Software – Março/2013
NX
% set pi 3.1415926535897932384626433832795
3.1415926535897932384626433832795
% unset pi
% set pi
can’t read "pi": no such variable
% unset fred
can’t unset "fred": no such variable
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 14 Siemens Industry Software – Março/2013
NX
Scope of variables
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 16 Siemens Industry Software – Março/2013
NX
Arrays of variables
In Tcl arrays, the values and the indices are character strings. In the last example,
mom_pos(Xstr), the character string Xstr is the index.
By convention, in Post Builder, array members use the numbers 0, 1, 2, and so on
as index strings . For example, mom_pos(0) stores an X-coordinate, mom_pos(1)
stores a Y-coordinate, and mom_pos(2) stores a Z-coordinate.
To define an array, you must place an index in parentheses after the variable
name:
% set myarray(0) 3.14
3.14
% set myarray(one) SomeValue
SomeValue
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 17 Siemens Industry Software – Março/2013
NX
To obtain all indices and corresponding values in an array, you must use the
array get command:
% array get myarray
0 3.14 one SomeValue
The output of the array get command is a series of text strings separated by
spaces. Each array index is followed by the value of the corresponding array
element. You can interpret the example output as follows:
• The first character string, 0, is the first index.
• The value of the array member identified by index 0 is the second character
string, 3.14.
After you undefine an array, the array get command used on the undefined array
does not return a list, and it does not cause an error.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 18 Siemens Industry Software – Março/2013
NX
Working with variables
The Tcl interpreter does not directly work with numbers. To do math with values
that represent numbers, you must use commands that work with numbers. For
example, the expr command is used to evaluate math expressions:
% set x 0.866
0.866
% set y 0.5
0.5
% set ang [expr atan2($y,$x)]
0.52361147777
The value of the variable named x is substituted for $x, and the value of the
variable named y is substituted for $y.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 19 Siemens Industry Software – Março/2013
NX
The example also shows one of many built-in math functions that are arguments
to expr, atan2(y,x). Because Tcl does not work with math and numbers directly,
if you try to use arguments to the expr command without expr, you get an error
like the following:
% atan2($y,$x)
invalid command name "atan2(0.5,0.86602540378)"
The atan2 function and many other functions that work with angles accept and
return values in radian measure.
You can define variables to hold radian conversion factors. Post Builder handles
conversion between degrees and radians with the following code:
% set RAD2DEG [expr 90.0 / asin(1.0)]
57.2957795131
% set DEG2RAD [expr asin(1.0) / 90.0]
0.0174532925199
Thus, to obtain the value of the previous example in degrees, you could write:
set ang [expr atan2($y,$x) * $RAD2DEG]
30.0007277808
You can be more precise:
% set x 0.86602540378
0.86602540378
% set y 0.5
0.5
set ang [expr atan2($y,$x) * $RAD2DEG]
30.0000000001
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 20 Siemens Industry Software – Março/2013
NX
Additional variable substitution examples
In the following examples, lines that begin with % (percent sign) show input at the
Tcl command prompt. The following lines show the returned values.
% set a N
N
% set b X
X
% set c $a$b
NX
% set b 32
32
% set a b
b
% set a $b
32
% set c $b+$a+$b
32+32+32
% set c [expr $b+$a+$b]
96
% set a $b.3
32.3
% set a $b9
can’t read "b9": no such variable
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 21 Siemens Industry Software – Março/2013
NX
Determining set variables
You sometimes need to know whether a variable name is safe to use in your
procedure. For example, there are many mom variables, but they may not always
be defined. At the Tcl command prompt, if x is undefined, you can type set x
for the following result:
% set x
can’t read "x": no such variable
Note that when a command expects a variable name, you do not use a dollar sign.
It would be a mistake to use $x in the preceding example.
If you attempt to use an undefined variable in an executing program, you get
a run-time error.
In Tcl you can use the info command to check many things by giving it different
arguments. To check whether a variable exists, use the command info exists
follwed by the name of a variable. You must not use a dollar sign in front of the
variable name. % info exists pi
% set pi 3.14 1
3.14 unset pi
% info exists pi
0
Tcl follows a common convention. The command info exists returns 1, or true,
when the variable is defined, and 0, or false, when the variable is not defined.
To use the info exists command effectively, you must use the if command.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 22 Siemens Industry Software – Março/2013
NX
if
The if command executes the block of code that is its second argument, if
its first argument, a logical comparison, evaluates to 1, the value for true in
logic commands.
if {[info exists variablename]==1} {
# some code that uses the variable
}
The first argument to if is the pair of commands in the first braces. The result
of the command in the brackets is compared to 1. If the command evaluates
to anything but 1, the comparison returns 0, a logical false, and the second
argument, a block of code in braces, is ignored. If the command evaluates to
1, then the comparison returns 1, a logical true, the next argument, a block of
code in braces, is executed.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 23 Siemens Industry Software – Março/2013
NX
Tcl control of word structure
Tcl words break at whitespace characters: space, tabs, and newlines. Semicolons
end a command.
The following are exceptions:
• Double quotes prevent breaks and must be used to specify strings that have
spaces:
% set X "this is a word which has spaces"
this is a word which has spaces
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 24 Siemens Industry Software – Março/2013
NX
• The backslash is the escape character. A backslash removes the special
meaning of characters, including spaces:
% set Z word\ with\ \[\ $\ and\ spaces
word with [ $ and spaces
You can use the backslash before the dollar sign to avoid getting an error
•
message when you want to output a dollar sign.
% puts "The cost is $100"
can’t read "100": no such variable
% puts "The cost is \$100"
The cost is $100
Some characters, such as $ (dollar sign), have special meaning. You must escape
special characters to output them as literal characters.
There are other special characters that require the escape character to give them
their special meaning. In many languages, these character strings are called
escape sequences.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 26 Siemens Industry Software – Março/2013
NX
Character Meaning in output
\n newline
\t tab
Examples:
% puts stdout "\tFred"
Fred
% puts stdout "Tab\tSeparated"
Tab Separated
% puts stdout "High\nLow"
High
Low
% puts stdout "\"Quoted\""
"Quoted"
% puts stdout "\$100"
$100
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 27 Siemens Industry Software – Março/2013
NX
Tcl mathematical expressions
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 28 Siemens Industry Software – Março/2013
NX
% expr 1+2
3
% expr 1 + 2
3
As with other languages, there is a hierarchy of operator precedence. For
example, multiplication and division are performed before addition and subtraction:
% expr 1 + 2 * 5
11
% expr 2 * 3 + 1
7
As with other languages, you can group operands with parentheses to control
the order of arithmetic operations, and to make you intention clear to anyone
who reads your code:
% expr (1 + 2) * 5
15
% expr 2 * (3 + 1)
8
You must do radian to degree conversion before doing trigonometric functions.
For example, to obtain the sine and cosine for 30 degrees, you must change
30 degrees to radians
% expr sin(30 * $DEG2RAD)
0.499999999999
% expr cos(30 * $DEG2RAD)
0.866025403785
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 29 Siemens Industry Software – Março/2013
NX
In Post Builder, numbers like those in the preceding example are automatically
output to your controller according to the word format you defined for the relevant
address. If you are outputting numbers to a print report, you can format numbers
to round them to a reasonable number of decimal places.
Tcl implements a formatting statement that uses the same modifying symbols as
many other languages:
% format %1.3f [expr sin(30 * $DEG2RAD)]
0.500
% format %1.6f [expr cos(30 * $DEG2RAD)]
0.866025
% format %1.2f [expr cos(30 * $DEG2RAD)]
0.87
• The number to the left of the decimal sets the minimum field width of the
output, including the decimal point.
• The number to the right of the decimal sets the number of decimal places to
show. The field is padded with zeros as necessary.
In the Tcl basics for Post Builder section, do the following activity:
• Tcl basics
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 31 Siemens Industry Software – Março/2013
NX
Tcl scripts
Lines in scripts
set mom_pos(0) 12.4
set mom_pos(1) 28.3
set mom_pos(2) 0
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 32 Siemens Industry Software – Março/2013
NX
is the same as
set mom_pos(0) 12.4; set mom_pos(1) 28.3; set mom_pos(2) 0
Comments in scripts
In the example, the lines beginning with # are comments. The Tcl interpreter
ignores comments except when they contain curly braces. Curly braces in
comments are counted for matching pairs of braces. This makes it awkward to
comment out sections of code for testing and debugging. You can work around
this issue with the if command. To do this, construct code similar to the following:
# example showing how to comment out lines in a script
if {0} {
# code between the braces is never executed!
}
You can use the ; (semicolon) and the # (pound or number sign) characters
together to add a comment on the same line as a command.
set mom_pos(0) 12.4; # set the X coordinate
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 33 Siemens Industry Software – Março/2013
NX
Tcl procedures
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 34 Siemens Industry Software – Março/2013
NX
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 35 Siemens Industry Software – Março/2013
NX
The white spaces adjacent to braces are critical. If you omit a space, your
program crashes and you might get one of the following messages:
• No white space between first pair of braces:
proc TEST {} ( puts "testing 1 2 3" }
wrong # args: should be "proc name args body"
• No white space between first closing brace and second opening brace:
proc TEST { }( puts "testing 1 2 3" }
extra characters after close-brace
or
proc TEST { } (puts testing}
wrong # args: should be "proc name args body"
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 36 Siemens Industry Software – Março/2013
NX
Use capital letters when you name procedures. Capitals, whether used
for the entire name or for the first word, make procedure names easier to
locate in scripts.
Use lowercase for variable names, so that you can easily distinguish
variables from procedures.
For example, in Post Builder, MOM_set_csys is a procedure, and
mom_csys_matrix is a variable.
In the command:
proc HI {} (puts "Hello World!"}
You can provide default values for variables by grouping the variable and the
default value in braces. For example:
% proc ECHO {{word "nothing to echo"}} {puts $word}
% ECHO fred
fred
% ECHO
nothing to echo
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 38 Siemens Industry Software – Março/2013
NX
Example of a procedure:
#==================================
proc PB_CMD_ptp_size { } {
#==================================
# Output the current size of the ptp output file.
# Add this to the end of the End of Program event.
global ptp_file_name
global mom_sys_control_out
global mom_sys_control_in
set ci $mom_sys_control_in
set co $mom_sys_control_out
# Check the file size
MOM_close_output_file $ptp_file_name
set ptp_size [file size $ptp_file_name]
MOM_open_output_file $ptp_file_name
# Put a message for the file size in the ptp file
set ptp_feet [expr $ptp_size/120.]
MOM_output_literal "$co PTP file size = $ptp_size bytes\
[format "%5.1f" $ptp_feet] feet $ci"
}
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 39 Siemens Industry Software – Março/2013
NX
Explicitly returning a value from a procedure
Procedures return the value of the last command they execute. You can use
program logic to return different values by determining which command is
executed last.
Use the return command with no arguments to return the value of a command.
return [expr $x / $y ]
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 40 Siemens Industry Software – Março/2013
NX
Intermediate-level use of the return command
In Tcl, division with the expr command when either operand is a decimal number
returns a decimal number. If both operands are integers, you get an integer result:
% expr 1.0 /2
0.5
% expr 1 / 2
0
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 42 Siemens Industry Software – Março/2013
NX
Basic error handling
When Tcl reports an error at run time, your program crashes. To prevent this, you
can use the catch command, which works at run time. Returned values are 1, or
true, if an error occurs, and 0, or false, if no error occurs. The catch command
places error text in the variable that you specify. The general format is:
catch {command | procedure} optional variablename
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 43 Siemens Industry Software – Março/2013
NX
Tcl input and output
Tcl maintains three standard input and output (I/O) channels: stdin for standard
input, stdout for standard output, and stderr for standard error. By default, stdin
accepts input from the keyboard and stdout and stderr output text to the Tcl
window.
puts
The puts command places its argument as a string of text to stdout, which is
usually the command window. The puts command has the following general
format:
puts [channel] string
The name of the output channel is optional. If only a single argument is supplied,
the argument is output to stdout.
% puts stdout "Hello, world!"
Hello, world!
% puts "Hello, world!"
Hello, world!
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 45 Siemens Industry Software – Março/2013
NX
Combining puts and gets
The puts command has an option that is useful when you are prompting for input:
puts —nonewline stdout "Please enter your name: "
flush stdout
You can follow the puts command with a gets command to prompt the user to
enter text on the same line as your prompt.
Example script:
# myio.tcl
proc MyIO {} {
global name; # make $name known outside this procedure
puts -nonewline stdout \
"Please enter your name: "; # issues the prompt
flush stdout; # required to output the incomplete line
gets stdin name; # accepts user typing until they press Enter
puts "Hello, $name"; # issues a personal greeting
}
You can use \ (backslash) before the newline character in procedures to
continue a long command over multiple lines.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 46 Siemens Industry Software – Março/2013
NX
source
The source command is another form of I/O. It reads a file into the current Tcl
session or program. It is used frequently in Post Builder. For example, near the
beginning of your posts, you see the source command used to retrieve a library of
standard procedures:
source ${cam_post_dir}ugpost_base.tcl
The following example shows a command prompt session to read and use the
procedure that is defined in the example for combining puts and gets in a script:
% source myio.tcl; # reads procedure into session
% unset name; # make certain that name does not exist
% MyIO; # executes the procedure
Please enter your name: Shengmin
Hello, Shengmin
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 47 Siemens Industry Software – Março/2013
NX
format
The format command lets you control the format in which output is written. For
example, you can control the number of decimal places, field width, scientific
notation, and so on. The general format for the command is:
format specification value1 value2 ...
The specification can contain literal output and formatting instructions. Because
the format string can contain white space, substitutions, and special characters,
it is common to place format specifications in double quotes. The command
operates by scanning the format string from left to right. Each character from
the format string is appended to the result string unless it is a percent sign. If
the character is % then the characters following the % character are treated as
a conversion specifier.
Here are some command line examples of using the format command for floating
point numbers.
% set PI [expr 2.0 * asin(1.0)]
3.14159265359
% puts [format "%1.4f" $PI]
3.1416
• The first 0 instructs the command to pad the output field to the left with zeros,
if necessary.
• The 10 sets the minimum field width for the output at ten characters, including
the decimal point and the decimal digits.
• The .5 specifies a 5 decimal precision. The decimal point and decimal digits
take up six characters of the ten-character width, leaving 4 characters for
the digit 3 and padding characters.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 49 Siemens Industry Software – Março/2013
NX
The interpreter does its one round of variable substitution before it analyzes
the format string. You can place format specifications in variables and use the
variables in the format specification.
% set myFormat %10.5f
%10.5f
# The % in the previous line is not the prompt;
# it is part of the value returned by the format statement.
% format $myFormat $PI
3.14159
# Notice the leading spaces.
# The field is 10 characters wide.
Please refer to the Tcl documentation for the complete list of formatting capabilities
and the corresponding specifications.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 50 Siemens Industry Software – Março/2013
NX
scan
The scan command lets you format text input to your specifications. When
you read a line of text from stdin, or from a file, you often want to set one or
more variables. The general format of the scan command is:
scan text_string format_specifcation var 1 var2 ...
• s — the input field consists of all the characters up to the next white-space
character.
• [characters] — the input field consists of the characters within the brackets
in any order. You can use the dash to represent a range of characters.
Please refer to the Tcl documentation for the complete list of formatting capabilities
and the corresponding specifications.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 51 Siemens Industry Software – Março/2013
NX
The scan command returns the number of matches it makes from an input string:
% scan "abc" %s result
1
% set result
abc
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 52 Siemens Industry Software – Março/2013
NX
Match anything but a space character and set one variable:
% scan $claim {%[^ ]} product
1
%set product
NX
The following example matches a string, anything but a space character, the
letters "r e n b u m" in any order, and an integer, and sets four variables:
% scan $claim {%s %[^ ] %[renbum] %d} a b c d
4
% set a
NX
% set b
is
% set c
number
% set d
1
Inside the square brackets, the variable tn is created or modified if a value taken
from an array called $mom_tool_use is recognized as a decimal integer. The
element from the array is determined by the row index specified by the value of
variable $nn, and by the column index "0".
Outside the square brackets, a is set to the number of matches returned by the
scan statement. If a is 1, then tn contains a tool number from the array location
$nn, 0. If a is 0, then either tn is not set, or the value in tn is from a previous
assignment.
The total effect is to attempt to assign a tool number out of the array $mom_tool_use,
and set a flag a to signal success or failure.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 54 Siemens Industry Software – Março/2013
NX
Working with files in Tcl
• Delete files
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 55 Siemens Industry Software – Março/2013
NX
I/O channels
In file management, you use I/O channels that you create to communicate with
files. The channel is called a file identifier, and you store it in a variable. You can
use the variable in the same context as you would use stdout, stdin, or stderr.
Refer to Tcl documentation for a more advanced type of channel that is beyond
the scope of this class.
file exists
Use the file exists command to check whether a file exists before you attempt
to work with it.
Command line example:
% file exists tclsh.exe
1
% file exists "nonexistent_file"
0
Program example:
if { [file exists "$result_file"]==1 } {
# work with the file named by $result_file
}
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 56 Siemens Industry Software – Março/2013
NX
open
The open command opens a file and returns an identifier. The general format for
the command is:
open filename access permissions
filename
Identifies an existing file. Include the full operating system path if the file is
not in the current directory.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 57 Siemens Industry Software – Março/2013
NX
access
Describes the type of access of which the channel is capable. Unless
otherwise specified, the file must exist. The following are the standard flags
for access. Advanced users may use the POSIX access flags, not described
here.
r Opens the file for reading.
r+ Opens the file for reading and writing.
w Opens the file for writing. Truncate the file if it exists. Create it
if it does not exist.
w+ Opens the file for reading and writing. Truncate the file if it exists.
Create it if it does not exist.
a Opens the file to append data. Data written is appended to the
end of the file.
a+ Opens the file for reading and to append data. Data written is
appended to the end of the file.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 58 Siemens Industry Software – Março/2013
NX
permissions
This argument applies only to Linux systems. Use the format described in the
man pages for the chmod command.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 59 Siemens Industry Software – Março/2013
NX
The following example from a Post Builder post shows a results file being opened
for reading:
if { [file exists "$result_file"] } {
set fid [open "$result_file" r]
# work with the file
}
• The double quotes are inserted automatically by Post Builder in case the
value being retrieved, a file name, has a space in it. If you are programming
the file name directly and you know that the name does not contain a space,
you do not need the double quotes.
close
Use the close command with a file identifier to close an I/O stream.
close $fid
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 60 Siemens Industry Software – Março/2013
NX
puts
Use the puts command without options to write a line of output and a newline
character to a file that is open for writing.
puts $fid $myString
You can force output without a newline character using the -nonewline option
before the first argument.
puts —nonewline $fid $myString
% set fid [open testfile.txt w]
file 1c7d770
% puts $fid "My name is Fred."
% puts -nonewline $fid "I write "
% puts $fid "postprocessors."
% close $fid
% set fid [open "testfile.txt" r]
file1c7d7e8
% read $fid
My name is Fred.
I write postprocessors.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 61 Siemens Industry Software – Março/2013
NX
gets
Use the gets command to read a line of input from a file that is open for reading
and discard the trailing newline character. Successive use of the gets command
reads the file line by line. There are subtleties to distinguishing between blank
lines and the end of file when gets is used with only one argument. In this
introduction the examples have two arguments:
gets $channel line
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 62 Siemens Industry Software – Março/2013
NX
The following example is used in a procedure.
while { [gets $sub line] >=0 } {
MOM_output_literal $line
}
close $sub
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 63 Siemens Industry Software – Março/2013
NX
read
The read command can be more efficient that gets because it returns a block of
data, which is often all of the remaining data in the specified file.
If you do not use any options, read returns all of the data remaining in the file,
formatted in the same way as it is in the file.
You can use one of the following options, but you cannot combine them.
split
The split command splits a text string into a Tcl list. The basic syntax is:
split string split_characters
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 64 Siemens Industry Software – Março/2013
NX
The string specified by the first argument is divided into a list element at every
character in the specified splitting characters. A single splitting character is not
enclosed in double quotes; however, several characters must be enclosed in
double quotes. The splitting characters are discarded, and braces are inserted as
needed.
% split "my.long.file.name" .
my long file name
% split "Aqlittlebpuzzlecfordyou" "qbcd"
A little puzzle for you
You can specify a null splitting character set to divide a string into characters:
% split "Hello, world!" {}
H e l l o , { } w o r l d !
Note that the space character is grouped inside braces in the output. The split
command groups any word that contains spaces within braces.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 65 Siemens Industry Software – Março/2013
NX
When the string being split is the contents of a file, for example, a big string
returned by the basic read command, the special character \n, the newline
character, is used to split the lines into list words:
foreach line [split [read $fid] \n] (
# do something with $line
}
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 66 Siemens Industry Software – Março/2013
NX
file Returns the path to the file identified by filename. If the path is the
dirname current directory, on Windows and Linux the single character ‘.’ is
filename returned, and on Mac the character ‘:’ is returned.
On Windows, you must escape any backslash characters in the path,
or simply convert them to forward slashes.
% file dirname "tclsh.exe"
.
% file dirname "C:\\Windows\\system.ini"
C:/Windows
% file dirname "C:/Windows/system.ini"
C:/Windows
Note that the path returned uses the forward slash, as in the Unix
or Linux style.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 67 Siemens Industry Software – Março/2013
NX
file Returns all of the characters in the text string filename after and
extension including the last dot in the last element of filename. Elements are
filename strings separated by the / (slash) character. If there is no dot in the
last element of filename then an empty string is returned.
% file extension "tclsh.exe"
.exe
% set fid [open "fred" w]
file1bc7bd8
% file exists fred
1
% set myext [file extension fred]
% info exists myext
1
% string length $myext
0
You can determine if a variable contains an empty string by
checking that the variable name is defined, and that the string
length of the variable value is zero characters.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 68 Siemens Industry Software – Março/2013
NX
file Removes all relative path characters the text string filename and
normalize returns the full operating system path to the file identified by filename.
filename On Windows, the backslash in the path is replaced by the forward
slash.
% file normalize "./tclsh.exe"
C:/Tcl/bin/tclsh.exe
file size Returns a decimal string giving the size of the file identified by
filename filename in bytes. If the identified file does not exist or if the size of
the identified file cannot be queried, an error occurs.
% file size "tclsh.exe"
20480
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 69 Siemens Industry Software – Março/2013
NX
file tail Returns all of the characters in the text string filename after the last
filename directory separator. If filename contains no separators, the command
returns filename.
% file tail "C:/Windows/system.ini"
system.ini
% file tail "tclsh.exe"
tclsh.exe
% file tail "C:/Nosuchfolder/nosuchfile.txt"
nosuchfile.txt
See the Tcl documentation for a list of the many other arguments that you can
use with the file command.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 70 Siemens Industry Software – Março/2013
NX
Tests for permissions
The file exists command may not give you enough information. For example,
you may need to know if the file is readable and writable for the current user, or if
the current user is the operating system owner of the file.
file Returns 1 if the current user has read permission to the file identified
readable by filename, or returns 0 otherwise.
filename
file Returns 1 if the current user has write permission to the file identified
writable by filename, or returns 0 otherwise.
filename
file owned Returns 1 if the current user owns the file identified by filename, or
filename returns 0 otherwise.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 71 Siemens Industry Software – Março/2013
NX
Tcl string commands
Strings, or sequences of text characters, are the only data type that Tcl stores. As
you might expect, the Tcl string command has several arguments that are useful
to investigate and manipulate text strings.
Several arguments specify an index or position in the string. Tcl follows the
common convention of numbering characters in the string beginning with zero;
thus, the character with index 1 is actually the second character in the string, and
the last character has an index that is one less than the number of characters
in the string.
There are other commands that work with strings, for example the concat
command splices its arguments together to form one string.
It is not necessary to quote a string argument if it consists of a single word.
To view a list of valid arguments for the string command, use an invalid argument
for the command at the Tcl command prompt.
% string bad
bad option "bad": must be bytelength, compare, equal, first,
index, is, last, length, map, match, range, repeat, replace,
tolower, toupper, totitle, trim, trimleft, trimright,
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 72 Siemens Industry Software – Março/2013
NX
wordend, or wordstart
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 73 Siemens Industry Software – Março/2013
NX
string Returns the lowercase conversion of str.
tolower
% set str ABC123DEF
str ABC123DEF
% string tolower $str
abc123def
string Returns the uppercase conversion of str. The syntax is the same
toupper as string tolower.
str
% set myUpper [string toupper "g17 g20 g40"]
G17 G20 G40
% set myUpper
G15 G20 G40
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 74 Siemens Industry Software – Março/2013
NX
string Returns the range of characters in the string between the first and last
range str integer indices. This is the Tcl equivalent of the substring command
first last in other languages. No error occurs if last is greater than the last
valid index.
% set home "G28 G91 X0 Y0 Z0"
G28 G91 X0 Y0 Z0
% string range $home 0 6
G28 G91
% set newHome [concat [string range $home 0 6] \
[string range $home 13 15]]
G28 G91 Z0
string Removes all whitespace characters from the beginning and end of
trim str str. The trim argument is useful to get rid of unwanted spaces, tabs,
and so on from user input.
% set bulky "\t abc \t"
abc
% string length $bulky
11
% set slim [string trim $bulky]
abc
% string length $slim
3
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 75 Siemens Industry Software – Março/2013
NX
string Removes any or all of the specified characters if they appear in any
trim str order at the beginning or end of str.
characters
% string trim ababcdebaba ab
cde
string Work like string trim except that they remove whitespace or optional
trimleft characters only from the left or right of the string.
str and
These commands are useful when string trim removes characters
string
that you want to keep:
trimright
str % string trim "N3670 G01 X100.35 Y50.10 F100" "N 0123456789"
G01 X100.35 Y50.10 F
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 76 Siemens Industry Software – Março/2013
NX
string There are several similar commands to see what kind of value is
is double represented by a string. Arguments include alpha, boolean, false,
and string true, and several more.
is double These commands return 1 if the string is a valid member of the
—strict
specified class, otherwise it returns 0. If the parameter -strict is
specified, an empty string returns 0, otherwise, an empty string
always returns 1.
% string trim "N3670 G01 X100.35 Y50.10 F100" "N 0123456789"
G01 X100.35 Y50.10 F
In the Tcl basics for Post Builder section, do the following activity:
• Construct a simple procedure
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 78 Siemens Industry Software – Março/2013
NX
Program flow control
Tcl has flow control commands for conditional execution or branching, and for
looping. In branching, you define logic to control which statements are executed.
In looping, you set a test to determine how many times a loop of commands
is repeated.
if then else
The branching structure uses the following general command formats.
if example:
if {test} {
# commands to execute if the test result is true
}
if else example:
if {test} {
# commands to execute if the test result is true
} else {
# commands to execute if the test result is false
}
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 79 Siemens Industry Software – Março/2013
NX
if elseif else example:
if {test_1} {
# commands to execute if the test_1 result is true
} elseif {test_2}
# commands to execute if the test_2 result is true
} else {
# commands to execute if both test results are false
}
The then command is optional in Tcl. If the test is a long string of code, use then to
make your code easier to read.
if {long test statement, perhaps more than 1 line}
then {
# commands to execute if the test returns true
}
The white space around the braces in if commands is critical, but not as critical is
it is with procedure syntax. You must place white space after a closing brace. The
error message is extra characters after close-brace. The constructions } else
{ and } elseif { must be on the same line of code, and spaced. Error messages
include invalid command name else{ and invalid command name elseif{.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 80 Siemens Industry Software – Março/2013
NX
The test can be a command that returns an integer, or a logical comparison.
Remember that Tcl is a string-based language, so you need to be mindful of
formatting and tolerances when you compare numbers.
Operator Comparison
== equal
!= not equal
> greater than
>= greater than or equal
< less than
<= less than or equal
You can combine logical statements with the following logical operators:
Tcl Operator Logical meaning
&& and
|| or
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 81 Siemens Industry Software – Março/2013
NX
Programming example of branching with multiple tests:
if {$mom_sys_cir_vector == "Vector - Arc Center to Start"} {
set mom_prev_pos($cir_index) 0.0
set mom_pos_arc_center($cir_index) $pitch
} elseif {$mom_sys_cir_vector == "Vector - Arc Start to Center"}{
set mom_prev_pos($cir_index) $pitch
set mom_pos_arc_center($cir_index) 0.0
} elseif {$mom_sys_cir_vector == "Unsigned Vector - Arc Center / to Start"} {
set mom_prev_pos($cir_index) 0.0
set mom_pos_arc_center($cir_index) $pitch
} elseif {$mom_sys_cir_vector == "Absolute Arc Center"} {
set mom_pos_arc_center($cir_index) $pitch
}
}
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 82 Siemens Industry Software – Março/2013
NX
switch
Use the switch command when you have a series of branching tests against
the same variable. The switch code is easier to read than a long series of if,
elseif, elseif, else commands.
The switch command has the following general syntax:
switch —options variablename value1 body1 value2 body2 ...
Programming example:
switch $mom_rotation_mode {
NONE {
set angle $mom_rotation_angle
set mode 0
}
ATANGLE {
set angle $mom_rotation_angle
set mode 0
}
ABSOLUTE {
set angle $mom_rotation_angle
set mode 1
}
INCREMENTAL {
set angle [expr $mom_pos($axis) + $mom_rotation_angle]
set mode 0
} © 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
} 83
Page Siemens Industry Software – Março/2013
NX
Do not place comments at the same level as the matching values or
patterns, as the interpreter will try to interpret the comment as a value to
test for a match.
switch $mom_rotation_mode {
# a comment in this position will confuse the Tcl interpreter
NONE {
set angle $mom_rotation_angle
set mode 0
}
There are no examples of the switch options here because the options are part of
advanced applications based on pattern matching.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 84 Siemens Industry Software – Março/2013
NX
while
The Tcl while command has the following general format:
while test commandBody
Program example:
while {[expr $a4-$mom_kin_4th_axis_min_limit] > 360.0} {
set a4 [expr $a4-360.0]
}
If the variable a4 is larger than 360, this loop executes, subtracting 360 from a4 on
each iteration, until a4 is less than 360. Note that if a4 is ever exactly 360, the loop
is going to execute one last time, because the test comparison operator is < (less
than), and not <= (less than or equal to).
The loop executes until the test is no longer true. You must do something in the
loop to update the test criteria, or the loop will never end.
while {1 == 1} {
# loop never exits, unless you use a break command.
}
You must make sure the test can be true, or the command body is never executed.
while {1 == 0} {
# never executed because the test is always false.
}
If the loop condition is a counter, it is common to use the incr command to update
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 85 Siemens Industry Software – Março/2013
NX
incr
Use the incr command to update a loop counter variable by adding 1 to the
value of the variable.
Command line example:
% set i 0
0
% incr i
1
% incr i
2
Note that the incr command expects the name of a variable as an argument. You
do not use the $ prefix.
for
The for command combines setting an initial loop test variable, specifying the test,
and updating the test variable in one compact statement. The general format is:
for {start} {test} {next} { commandBody }
The steps are executed in the following order: start, test, commandBody, next,
test, commandBody, next, test, commandBody, and so on.
Program example:
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 86 Siemens Industry Software – Março/2013
NX
for {set i 0} {$i < $n} {incr i} {
set v2($i) $v1($i)
}
}
In the example:
• The start condition sets a loop counter variable, i, to zero.
• Within the body of the loop, the value of i is used as an index into arrays v1
and v2.
The net result of the example loop is that the first n elements, specified by $n, of
array v1 are copied to array v2. The values of i range from 0 to n–1. This is typical
coding for arrays that start with index 0. When i is equal to n, the test fails and the
program moves on the next line after the loop body.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 87 Siemens Industry Software – Março/2013
NX
foreach
Use the foreach command to set one or more variables to values specified in a
list of values, using each value in turn as the loop body executes. This might be
considered as an intermediate-level programming method; however, you will
encounter it frequently in postprocessors. The basic syntax for only one variable is:
foreach variable {list} {commandbody}
Program example:
foreach address $address_list {
catch {MOM_set_address_format $address AbsCoord_mm}
}
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 88 Siemens Industry Software – Março/2013
NX
In this context, catch returns 1 if an error occurs. There is no code to save the
error message or act upon the returned value from catch; so, in effect, errors
in the loop are ignored.
For intermediate-level programmers, the foreach command lets you specify
multiple variables to assign values from the supplied list:
foreach {list of variables} {list of values} {commandBody}
Command line example to work with pairs of array indices and values:
% #preparation
% set inp(x) 1.234
1.234
% set inp(y) 2.345
2.345
% set inp(z) 3.456
3.456
% result demonstration
% array get inp
x 1.234 y 2.345 z 3.456
% example of foreach (on two lines):
% foreach {index value} [array get inp] \
{ puts "Element index $index is $value" }
Element index x is 1.234
Element index y is 2.345
Element index z is 3.456
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 89 Siemens Industry Software – Março/2013
NX
More explanations:
A search of Tcl programs in the NX 8 Post Builder folders did not reveal any
examples of intermediate-level or advanced-level uses of foreach.
At the most advanced level, the foreach command can interpret multiple pairs of
variable and value lists. The command iterates until all variables are used from
all variable lists.
break
You can gain additional control over your while, for, and foreach program loops
with the break and continue commands.
Use the break command to exit immediately from the loop that contains it.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 90 Siemens Industry Software – Março/2013
NX
In the following program example from ugpost_base.tcl, the for loop iterates
through pairs of vector components from vector u, the vector being tested, to
the corresponding components of vector v, a zero vector defined early in the
procedure. Inside the loop, if any element of u is within an optional tolerance of
vector v, the return value is_equal is set to 0, or false, and the break statement is
executed, stopping any further testing.
# VEC3_is_zero(u,tol) (|| u || < tol) Is vector zero?
proc VEC3_is_zero {u} {
upvar $u u1
set v1(0) 0.0 ; set v1(1) 0.0 ; set v1(2) 0.0
set is_equal 1
for {set ii 0} {$ii < 3} {incr ii} {
if {![EQ_is_equal $u1($ii) $v1($ii)]} {
set is_equal 0
break
}
}
return $is_equal
}
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 91 Siemens Industry Software – Março/2013
NX
The value of is_equal is set to one, or true, before the loop, so that true is
returned if nothing happens to change it. This ensures that the procedure returns
a defined value.
The upvar command, in the basic form shown here, lets you associate a variable
name in the calling procedure with a local variable. The variable named $u,
an array of vector components in the calling procedure, is associated with the
variable u1 in the VEC3_is_zero procedure.
The procedure EQ_is_equal is one of a family of procedures in Post Builder that
compare numeric values within a tolerance. For example, the Tcl operator = =
would do a string comparison of 1.99999999999 and 2.0 and report that they are
not equal. EQ_is_equal compares within a default or specified tolerance, and
reports that as far as the postprocessor is concerned, the numbers are close
enough to be considered equal.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 92 Siemens Industry Software – Março/2013
NX
continue
Use the continue command to skip the rest of the current loop iteration, and jump
to the next iteration of the loop that contains the continue command. The syntax,
in context of a dummy loop, is shown in the following:
for {start} {test} {next} {
# do some processing for current loop variable
...# test something
if [test] {
# skip further processing, jump to next
continue
}
# further processing for current loop variable value
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 93 Siemens Industry Software – Março/2013
NX
exit
Use the exit command to stop the execution of your program. Advanced users
may include an optional error code.
# test something
if [test] {
# stop the program
exit
if [another test] {
# end the program with an error code
exit 2
}
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 94 Siemens Industry Software – Março/2013
NX
Activity: Program flow control
In the Tcl basics for Post Builder section, do the following activity:
• Tcl flow constructs
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 95 Siemens Industry Software – Março/2013
NX
Regular expressions
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 96 Siemens Industry Software – Março/2013
NX
Common syntax elements
The following is a summary of some common patterns in regular expression
syntax.
. Matches any single character.
* Matches zero or more instances of the preceding match pattern item.
For example, .* matches zero or more instances of any characters.
+ Matches one or more instances of the preceding match pattern item.
For example, 0+ matches one or more zeros.
? Matches zero or one instances of the preceding match pattern item.
For example, 0? matches no zeros or exactly one zero.
( ) Groups a sub-pattern, which is treated as a single match pattern item
for the match characters described. For example, (abc)+ matches
one or more repetitions of abc.
The match patterns are simple literal strings so the programmer was not forced to
use curly braces around MOM_lintol; however, it is a good idea to use the braces
in your code at all times, to help you to develop safe programming habits.
The return value of regexp is compared to 1. If the pattern is present in the string
represented by $mom_warning_info, regexp returns 1, the test returns true, and the
body of the if command is executed. The body of the if command is the return
command, which ends the procedure that contains the example code and returns
the program flow to the next line of the calling procedure.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 98 Siemens Industry Software – Março/2013
NX
regsub
Use the regsub command to substitute a specified set of characters for a match
pattern found in a string. For example, in a very simple application, you could use
it to exchange the slash and backslash characters in a file path specification.
The general format is:
regsub —options {matchPattern} stringToSearch stringToSubstitute variableName
The most common option is -all, which causes every match for matchPattern to
be replaced by stringToSubstitute. Without -all, only the first instance of the
match would be replaced.
Command line example:
% regsub {[\\]} "C:\\tcl\\bin\\tclsh.exe" "/" myOutput
1
% set myOutput
C:/tcl\bin\tclsh.exe
% regsub -all {[\\]} "C:\\tcl\\bin\\tclsh.exe" "/" myOutput
2
% set myOutput
C:/tcl/bin/tclsh.exe
Extensions of Tcl were developed for specific applications such as NX Post, Shop
Documentation, Process Assistants, Libraries and User Defined Features.
Tcl can call NX Open routines, formerly called user function or UFUNC, and NX
Open routines can call GRIP routines. Tcl is easy to use and is extensible using
the C language.
You can access Tcl code through CAM modules such as NX Post or Shop
Documentation.
The custom command capability in Post Builder allows you to insert custom Tcl
procedures into a postprocessor. There is a library of procedures in various
folders under ...\Siemens\NX 8.0\MACH\resource.
Common procedures are provided, and new procedures are added to each
release.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 100 Siemens Industry Software – Março/2013
NX
Tcl reference manuals
For more programming examples, tips on error trapping and debugging, deeper
explanations of commands and syntax, and advanced usage, refer to one or
more of the following:
• Practical Programming in Tcl and Tk by Brent B. Welch ISBN 0-13-616830-3
• SAMS Teach Yourself Tcl/Tk by Venkat V.S.S. Sastry & Lakshmi Sastry
IBSN 0-672-31749-4
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 101 Siemens Industry Software – Março/2013
NX
Summary: Tcl basics for Post Builder
Summary: Tcl is a scripting language that is extensively used in Post and Post
Builder. The Custom Command feature of the Post Builder allows the insertion of
custom Tcl procedures that can be created for applications such as custom output
formats or specific custom machine tool/controller functionality. The following Tcl
functionality is used in the creation of Custom Commands:
• Variables
• Mathematical expressions
• Procedures
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 102 Siemens Industry Software – Março/2013
NX
Lesson 12
Postprocessing with a Siemens
controller
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 103 Siemens Industry Software – Março/2013
NX
Postprocessing with a Siemens controller
Purpose
This lesson describes the procedures required to build postprocessors through
the use of Siemens controller.
Objective
Upon completion of this lesson, you will be able to:
• See the additional information you can get from a Siemens controller post.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 104 Siemens Industry Software – Março/2013
NX
Events and cycles for Sinumerik controllers in NX
DNC Makes the NC output file accessible to the Siemens Motion Control
Header Information System (MCIS) by appending the following comments
and values to the file before the % (start of tape) symbol:
;HEADER-START
;NODENAME=$mom_dnc_machine_name
;NCDATANAME=$mom_dnc_program_name
;NCDATATYPE=$mom_dnc_data_type
;VERSION=$mom_dnc_version_number
;RELEASEID=$mom_dnc_release_number
;DEVELNAME=$mom_dnc_user_name
;HEADER-END
;NC-START
%
Add the user-defined event to the top working program group under
NC_PROGRAM in your milling program.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 106 Siemens Industry Software – Março/2013
NX
Sinumerik Lets you call external subroutines. Used by MOM_program_control,
Program PB_CMD_MOM_program_control, PB_CMD_start_of_extcall_operation,
Control PB_CMD_end_of_extcall_operation, PB_CMD_end_of_extcall_program,
and other procedures.
Add the event to a program group for the Sinumerik_840D and
Sinumerik_828D template posts. Do not add it to operations.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 107 Siemens Industry Software – Março/2013
NX
Procedures and settings
PB_CMD_set_Sinumerik_default_setting
Set the post default settings (mills only) according to the Sinumerik version.
If the sinumerik_version is not set, the procedure returns without making
any settings.
Interprets the On and Off parameters from the event dialog box and the
controller version to sets the appropriate values for variables.
PB_CMD_set_Sinumerik_V7_default_setting
Set the post default settings (802D_3axis) for Sinumerik version 7.
PB_CMD_set_Sinumerik_Version
Sets the Sinumerik version. The default is value is V7.
Sinumerik version 6 and later support CYCLE832 high speed machining G
code output.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 108 Siemens Industry Software – Março/2013
NX
Activity: Postprocess with a Siemens controller
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 109 Siemens Industry Software – Março/2013
NX
Summary Siemens controller support
The Siemens controller templates give you the necessary control and flexibility
to program your Siemens controllers.
In this lesson you:
• Built and examined a standard post for a Siemens 840D controller.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 110 Siemens Industry Software – Março/2013
NX
Lesson 13
Create a macro with Post Builder
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 111 Siemens Industry Software – Março/2013
NX
Create a macro with Post Builder
Purpose
This lesson describes the procedures required to build a macro with Post Builder.
Objective
After you complete this lesson, you will be able to:
• Build a macro with Post Builder.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 112 Siemens Industry Software – Março/2013
NX
Macro tab
Use this tab to create, edit, or remove block templates for making calls to macro,
cycle, or functions in the NC program.
The output codes are in the form of cycle or macro calls, such as CYCLE81(...)
for the Sinumerik 840D controller or CYCLE DEF 204 A200=... for the Heidenhain
iTNC530 controller, or other similar high level function calls.
Adding macros
Post Builder provides constructs for well-known hole-making cycles attached
to appropriate events.
Add you own macros when you wish to extend the post to output macro calls for
other calls that your controller accepts.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 113 Siemens Industry Software – Março/2013
NX
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 115 Siemens Industry Software – Março/2013
NX
Activity: Create a macro with Post Builder
In the Create a macro with Post Builder section, do the following activity:
• Create a Macro with Post Builder
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 116 Siemens Industry Software – Março/2013
NX
Summary: Create a macro with Post Builder
Creating a macro in Post Builder gives you the ability to machine a part to special
needs.
In this lesson you:
• Created a macro and used that macro to machine a portion of a part.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 117 Siemens Industry Software – Março/2013