You are on page 1of 117

NX

Post Building Techniques


Student Guide
October 2011
MT11060 — Post Builder 8.0

© 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.

• Write simple Tcl programs.

© 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/

In Tcl syntax, the following grouping symbols are necessary:


() Parentheses
[] Brackets, or square brackets
{} Braces, or curly braces

© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 5 Siemens Industry Software – Março/2013
NX
Tcl command structure

Tcl is a command-based language. Commands instruct the Tcl interpreter to


perform some type of task.
Commands are made up of words that include the name of the command and may
also include options and arguments. The basic syntax of a Tcl command is:
command argument1 argument2 argument3 ...

© 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.

The second argument, X, is the text string to assign to the variable.

© 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]

The set command is going to assign a value to the variable ini_file_list.


The third word in the command consists of other words grouped inside square
brackets.
You can think of the content of the square brackets as an inner command. The
square brackets tell the interpreter to analyze their content before doing anything
else with the line, and substitute the resulting value before interpreting the outer
command, set.
The inner command glob -nocomplain *.ini is interprested first, and the result is
inserted into the set command string.
The result of the entire line is to assign the names of all files with the .ini extension
to the variable ini_file_list. The variable ini_file_list becomes a Tcl list, or, a
sequence of words, where words are:
• Sets of characters separated by spaces.

• Sets of words and spaces grouped in braces.


© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 11 Siemens Industry Software – Março/2013
NX
Tcl variables

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

In Tcl, the scope of variables can be either local or global.


A local variable is a variable that is recognized only in the procedure in which it
is declared. When the procedure ends, its local variables are removed. In Tcl,
a procedure is the equivalent of a subroutine or function in other programming
languages.
A global variable persists through the life of the program, outside of any
procedures. You can access the value of a global variable between calls to a
procedure, or share it among multiple procedures. The following shows the
method to set the scope of a variable to global:
global cycle_name

The variable cycle_name can be set, accessed, or modified in any procedure in


the post.
You must use the global command to specify global variables in procedures that
use them. You can specify more than one global variable on the same line. In the
following example from Post Builder, two global MOM variables are used:
proc PB_CMD_end_of_alignment_character {} {
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 15 Siemens Industry Software – Março/2013
NX
# This command restores sequnece number back to orignal setting.
# This command may be used with the
# command "PM_CMD_start_of_alignment_character"
#
global mom_sys_leader saved_seq_num
if { [info exists saved_seq_num] } {
set mom_sys_leader(N) $saved_seq_num
}
}

The indentation combined with the placement of braces in the preceding


example conforms to a common programming standard that makes the
code easier to read.

© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 16 Siemens Industry Software – Março/2013
NX
Arrays of variables

You can define variable arrays in Tcl.


Example:
• mom_pos(0) can have a value of 12.4567.

• mom_pos(1) can have a value of 33.9876.

• mom_pos(Xstr) can have a value of “X string is”.

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.

• The next string, one, is the second index.

• The value identified by index one is SomeValue.

To undefine an array, use the array unset command.


% array unset myarray

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 preceding example shows variables being referenced in a command. The $


character tells the Tcl interpreter to substitute the value of a variable.
The interpreter makes exactly one substitution pass before any interpretation
takes place. After the substitution, the example command is interpreted as:
set ang [expr atan2(0.5,0.866)]

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

• Curly braces prevent breaks and substitutions:


% set Y {{nested }{braces}}
{nested }{braces}
% set X 27.5
27.5
% set Y "X is $X"
X is 27.5
% set Y {X is $X}
X is $X

© 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

The closing square bracket does not need to be escaped:



% set XX \[\ escaped,\ ]\ not\ escaped
[ escaped, ] not escaped

If in doubt about a character, escape it — it does no harm.

• Substitutions do not change word structure:


% set abc "two words"
two words
% set b $abc
two words
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 25 Siemens Industry Software – Março/2013
NX
Tcl special characters

Some characters, such as $ (dollar sign), have special meaning. You must escape
special characters to output them as literal characters.

Character Example with special meaning


removed
$ \$
\ — the escape character or backslash \\ — outputs \ — useful in windows paths
; \;
[ \[
{ \{
} \}
" \"
# \#
] \]

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

Tcl mathematical expressions are performed by the expr command.


Basic operators Operation
+ addition
– subtraction
/ division
* multiplication
sin(x) sine of x, where x is in radians
cos(x) cosine of x, where x is in radians
tan(x) tangent of x, where x is in radians

More complex operators, such as inverse trigonometric and logarithmic functions


are also available.
Examples
Spaces around th eoperators are neither required nor meaningful, but they make
your code easier to read

© 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 following are some of the formatting rules:


• The charcter f sets a floating decimal point format.

• 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.

• A space character after the % inserts a blank space


© 2013. Siemens to theLifecycle
Product left Management
of the output.
Software Inc. All rights reserved
Page 30 Siemens Industry Software – Março/2013
NX
Activity: Tcl basics

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

A Tcl script consists of a sequence of commands separated by either a "new


line" or a semicolon.
Comments are preceded by the "#". The following example illustrates the use of a
comment and the concept of a script:

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

Procedures in Tcl are sets of commands that are analogous to subroutines in


other languages.
You can use common procedures throughout your programs. This makes it easier
to create and modify programs.
The following example illustrates the structure of a procedure:
proc procedureName {arg1 arg2 arg3 ...} {body}
If there is only one argument, you can omit the braces around the argument list:
proc procedureName argument {body}
When you define a procedure in Post Builder, proc is inserted , the standard
prefix PB_CMD_ is added to the name automatically , and the braces around the
body are placed for you . The brace placement is styled for legibility.

© 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

• No white space after second opening brace:


proc TEST { } (puts "testing 1 2 3" }
wrong # args: should be "proc name args body"

• No white space before second closing brace:


proc TEST { } ( puts "testing 1 2 3"}
extra characters after close-quote

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!"}

proc is the command to define a procedure.


HI is the name of the procedure.
There are no arguments.
Testing at the Tcl command prompt, you see the following:
% proc HI {} (puts "Hello World!"}
% HI
Hello World!
%

To call or execute the procedure, use the procedure name.


© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 37 Siemens Industry Software – Março/2013
NX
A procedure can have one or more arguments, and procedures return the value of
the last command they execute. For example:
% proc MULT {a b} {puts stdout "$a times $b equals [expr $a * $b]}
% MULT 3 4
3 times 4 equals 12
%

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

Arguments may contain local and global variables.

© 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

If you divide by zero, you get a terse error message:


% expr 1 / 0
divide by zero

The following example procedure is designed to return a string as a formatted


decimal value regardless of any valid input, and it gives a more explicit error
message.
% proc DIV {x y) {
if [expr $y == 0] {
return -errorcode —code error \
"Division by zero is an illegal operation"
} else {
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 41 Siemens Industry Software – Março/2013
NX
if [string is integer $x] {set x $x.0}
return [format "%1.4f" [expr $x / $y ]]
}
}

Examples using the DIV procedure after it is saved as div.tcl:


% source div.tcl
% DIV 1 2
0.5000
% DIV 1 0
Division by zero is an illegal operation

© 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

In the following command line examples, -code is an intermediate-level option for


the return command, and set errorInfo returns the most recent error text and
the name of the command or procedure that caused the error.
% proc OOPS {} {return —code 1 Mistake!}
% catch {OOPS} myInfo
1
% set myInfo
Mistake!
% set errorInfo
Mistake!
while executing
"OOPS"
%

© 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!

It is good programming practice to always supply stdout as the second argument


when you want the output to go to standard output. It avoids confusion for anyone
who has to interpret your code, and it assists with debugging.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 44 Siemens Industry Software – Março/2013
NX
gets
The gets command reads a string of text from the keyboard that the user
terminates by pressing the Enter key. The terminating Enter character is not kept
and not counted. The gets command assigns the input to the specified variable,
and returns the number of characters it reads, not counting the enter key.
% gets stdin title
King
4
% gets stdin name
Charles III
11
% puts stdout [concat $title $name]
King Charles III

© 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

In the format specification "%1.4f":

• % introduces the rest of the string as a format specification


© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 48 Siemens Industry Software – Março/2013
NX
The following example introduces a wider-than-necessary field width, and
specifies padding with zeros:
% puts [format "%010.5" $PI]
0003.14159

In the format specifier "%010.5f":


• % introduces the rest of the string as a format specification.

• 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.

• The f tells the interpreter to expect a floating-point number.

© 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 ...

The scan command uses the following format specifications:


• f — the input field must be a decimal number with an optional sign.

• d — the input field must be an integer in the decimal number system.

• 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.

• [^characters] — the input field consists of characters that do not match


any of the characters in the brackets.

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

Enclose multiple match patterns in braces so that the specification string is


recognized as a single word.
The following example matches uppercase letters, a string, lowercase letters, and
an integer, and sets four variables in an array:
% set claim "NX is number 1"
NX is number 1
% scan $claim {%[A-Z] %s %[a-z] %d} r(0) r(1) r(2) r(3)
4
% array get r
0 NX 1 is 2 number 3 1

Match anything but uppercase Z and set one variable:


% scan $claim {%[^Z]} great
1
% set great
NX is number 1

© 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

The scan command returns zero if there are no matches:


% scan $claim {%[AB_34]} nothing
0
% set nothing
can’t read "nothing": no such variable
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 53 Siemens Industry Software – Março/2013
NX
The following shows how the scan command is used in ugpost_base.tcl:
set a [scan $mom_tool_use($nn,0) %d tn]

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

File management is an essential component of postprocessing. In addition to the


basic function of writing NC output files, warnings files, and listing files, you can
do file-related tasks like the following:
• Write to or append to a log file

• Write a documentation file

• Read data files

• Delete files

To manage files, you can:


• Use Tcl built-in file commands.

• Call MOM procedures in Post Builder.

© 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.

Command line example:


% set fid [open "scratch.txt" w]
file633c10

In the previous example, the string file633c10 contains a random hexadecimal


number that is guaranteed to be unique.

© 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
}

In the example program:


• $fid can be used to identify the file in an argument to the read command.

• 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

In the two-argument syntax, gets returns the number of characters read, or 0


for a blank line. With two arguments, when the end of the file is reached, gets
returns –1.

© 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

MOM_output_literal is a procedure that writes a list of literal characters and


variables held in the variable $line, without a sequence number.
In the loop condition, the return from gets $sub line is compared to 0 or greater,
because the file could include blank lines for which gets returns 0. When the end
of file is reached, gets returns –1, the loop terminates, and the file is closed. The
net effect is to copy everything in $sub to the NC output file.

© 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.

read —nonewline file_id


The –nonewline option discards trailing newline characters in each line of text.
read file_id numchars
The numchars argument is an integer number. It modifies the read command
to read the specified number of number of characters, or to the end of the file
if there are not the specified number of characters remaining. For example,
read $fid 80 reads 80 characters from the file identified by $fid.

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
}

The foreach command is explained under program flow structures.


Working with file specifications
The following operations do not require that the file in filename exists, except
as specified.

© 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.

file Returns 1 if filename is a directory, or returns 0 otherwise.


isdirectory
% file isdirectory "C:/Windows"
filename 1
% file isdirectory "tclsh.exe"
0

© 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

Note that the size of tclsh.exe varies depending on platform and


version.

© 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.

Intermediate-level file commands


Intermediate-level and advanced-level programmers may refer to the Tcl
documentation for information about eof, seek, tell, and glob.

© 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

string Returns the number of characters in the string str. In UTF-8


length str encoding, characters may require two or three bytes. This explains
why string bytelength str is also available.
% string length "abcdef"
6
% set str abcdef
abcdef
% string length $str
6
% string length abcdef
6

© 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

The string tolower command has optional arguments. You can


specify the indices of the first and last characters to convert, or
you can specify one index, to convert only the specified character.
Remember that string indices start at 0.
% string tolower $str 0 1
abC123DEF
% string tolower $str 7
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

Although the intention was to remove any possible sequence number,


the value of the feed rate word is also removed! The string trimleft
command avoids this problem:
% string trimleft "N3670 G01 X100.35 Y50.10 F100" "N 0123456789"
G01 X100.35 Y50.10 F100

© 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

Although the intention was to remove any possible sequence number,


the value of the feed rate word is also removed! The string trimleft
command avoids this problem:
% string is double 10.0
1
% string is double 25
1
% string is double "fred"
0
% string is double ""
1
% string is double —strict ""
0
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 77 Siemens Industry Software – Março/2013
NX
Activity: Construct a simple procedure

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
}

Place comments only inside the body of statements to execute for a


matching value or pattern.
switch $mom_rotation_mode {
NONE {
# a comment in this position is acceptable
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.

• In the test, the current value of i is compared to a value stored in n. Notice


that for the comparison, the dollar sign prefix is required.

• In the update, incr i, the counter variable i is incremented by one.

• 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}

Command line example:


% foreach j {2 6 24} {puts "$j squared is [expr $j * $j]"}
2 squared is 4
6 squared is 36
24 squared is 576

Program example:
foreach address $address_list {
catch {MOM_set_address_format $address AbsCoord_mm}
}

The example repeatedly calls a procedure, MOM_set_address_format, which in turn


sets each address in a list of addresses to the format represented by the second
argument, 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

Regular expressions are a pattern matching syntax common to many languages


that have their origins in Unix.
Regular expressions use their own syntax to match patterns in character strings.
In your postprocessing, you might find uses for regular expressions in advanced
uses of the switch command, the regexp command, and the regsub command.
For complete information on regular expressions, see Practical Programming
in Tcl and Tk.

© 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.

| Designates alternate patterns. For example (a | b) matches either


a or b.
^ When first, the pattern must appear at the beginning of the string that
is being searched. Also used as a negation operator in character
groups. For example, {^G.*} matches strings that start with G.
$ When last, the pattern must appear at the end of the string that is
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 97 Siemens Industry Software – Março/2013
NX
regexp
Use regexp to determine whether a pattern can be matched in a string. The
command returns 1, or true, if the pattern is found, and 0, or false, if it is not found.
The syntax common in ugpost_base.tcl is as follows:
regexp {matchPattern} stringToSearch

Typical lines returned by a search for regexp in ugpost_base.tcl:


if {[regexp "MOM_msys" $mom_warning_info] == 1} {
return
}
if {[regexp "MOM_lintol" $mom_warning_info] == 1} {
return
}

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

In the following example code from ugpost_base.tcl, we assume that the


controller for which we are postprocessing requires different control-in and
control-out characters, or comment delimiters, than the parentheses used in
Fanuc-like controllers. The control-in and control-out characters for the controller
are specified by the strings $mom_sys_control_in and $mom_sys_control_out,
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 99 Siemens Industry Software – Março/2013
NX
Tcl and NX

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

• Tcl/Tk Programmer’s Reference by Christopher Nelson ISBN 0-07-212004-5

© 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

• Input and output statements

• Flow control structures

© 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

Sinumerik Sets default settings including tolerance, high speed machining


840D parameters, five axis orientation parameters, and whether the feed
rate is defined in a variable.
You can add the Sinumerik 840D start event for:
• A single milling operation

• The lowest level program group in the Program view of the


Operation Navigator.

The Compressor option works only with linear motion. If the


Compressor option is set to On, the post will disable circular output,
and output only linear motion.
If you choose Swiveling in the Transformation option of the
Sinumerik_840D user-defined event, CYCLE800 is output and
transformation is turned off (TRAFOFF), otherwise TRANS/AROT
is output for coordinate rotation.
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 105 Siemens Industry Software – Março/2013
NX
You can set the number of significant digits for the output format, and
the appropriate rounding resolutions, with the custom commands
PB_CMD_reset_output_digits and PB_CMD_set_resolution.

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

In the Postprocess with a Siemens controller section, do the following 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

Sets characters to follow macro


parameter words, for example, set to
List of macros in the current post. You none, you might see X1.234 as an output
can create a new macro, or cut, paste, parameter. With Link Character set to
or rename macros. Equal Sign, the output for the same
value is X=1.234.
Sets the format of the parameter list.
You can change the separator and the
Preview of the output macro call. start and end characters. The defaults
are a comma separator. The list starts
with ( and ends with ).
Right-click to set the word character
© 2013. Siemens Product Lifecycle Management Software Inc. All rights reserved
Page 114 Siemens Industry Software – Março/2013
NX
Notes
The additional output attributes are not applicable to the Siemens Sinumerik
840D. The options do not appear on the macro constructor for the Sinumerik
family of posts.
You can define as many parameters as your controller requires.
If a macro parameter is not to be output, its name is used only in Post Builder to
represent an available argument.
You can set the expression for each parameter using constants, global MOM
variables, or other Tcl variables. The variables you use should represent data of
the same type as specified by the Data Type option, the same number format, or
text.
Your macros for the current post appear in the list of available blocks on the
Program tab.
You can create new macros by choosing Custom Macro from the list of available
blocks. The tree list does not appear; otherwise, the interface is the same.
On the Program tab, when you attach your macro to an event, you can suppress
the sequence number.

© 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

You might also like