Sunteți pe pagina 1din 183

C A P L

R E F E R E N C E
M A N U A L
Table of Contents

TABLE OF CONTENTS

1 Overview of CAPL ................................................................


...................................................................
... 1
1.1 CAPL Applications ..................................................................................................... 2
1.2 CAPL Programming Environment .............................................................................. 3
1.3 CAPL Responds to Events......................................................................................... 4
1.4 Example CAPL Programs .......................................................................................... 6
1.4.1 Event Message Transmission ............................................................................ 6
1.4.2 Periodic Message Transmission......................................................................... 8
1.4.3 Conditionally Periodic Message Transmission .................................................. 10

2 The CAPL Language .............................................................


............................................................. 12
2.1 CAPL Fundamentals................................................................................................ 12
2.2 CAPL File Types...................................................................................................... 12
2.3 CAPL Program Organization.................................................................................... 12
2.4 Naming Conventions................................................................................................ 13
2.5 CAPL is based on C................................................................................................. 14
2.5.1 Procedures and functions................................................................................. 16
2.6 Important Differences from C ................................................................................... 16
2.6.1 Function overloading is allowed........................................................................ 16
2.6.2 The “this” keyword ........................................................................................... 17
2.6.3 Local variables are static.................................................................................. 18
2.6.4 Dynamic memory and the elCount() function .................................................... 19
2.6.5 Variables are assigned a default value implicitly ............................................... 20
2.6.6 Run-time error handling.................................................................................... 20
2.6.7 CAPL equivalents to C functions ...................................................................... 20
2.7 Using the CANdb database with CAPL..................................................................... 21
2.7.1 Using symbolic signal values............................................................................ 22
2.7.2 Using user-defined attributes............................................................................ 23
2.8 Variable and Object Types and Declarations ............................................................ 25
2.8.1 The Timer and msTimer Objects ...................................................................... 26
2.8.2 The Message Object ........................................................................................ 26
2.8.2.1 Declaring messages in CAPL..................................................................... 27
2.8.2.2 Accessing message signals ....................................................................... 27
2.8.2.3 Physical values and the phys attribute ....................................................... 29

CAPL Reference Manual i


Table of Contents

2.8.2.4 Round-off error in symbolic signal access .................................................. 29


2.8.2.5 Message selectors..................................................................................... 30
2.8.2.6 Accessing raw message data.................................................................... 31
2.8.2.7 Sending and receiving messages............................................................... 32
2.8.3 Environmental Variables .................................................................................. 32
2.8.4 Built-in Constants............................................................................................. 33
2.9 Events in CAPL ....................................................................................................... 34
2.9.1 The “on message” event .................................................................................. 36
2.9.2 The “on key” event ........................................................................................... 38
2.9.3 The preStart, start, and stopMeasurement events and CallAllOnEnvVar() ........ 39
2.9.4 The errorActive, errorPassive, warningLimit, and busOff events ....................... 39
2.9.5 The “on timer” event and the setTimer() and cancelTimer() functions................ 41
2.9.6 The “on errorFrame” event ............................................................................... 42
2.9.7 The “on envVar” event ..................................................................................... 42
2.10 P-Block placement and message pass-through....................................................... 43
2.11 Using a CAPL program to control logging................................................................ 44

3 Using the CAPL Browser .........................................................


......................................................... 46
3.1 Starting the Browser ................................................................................................ 46
3.2 Browser organization ............................................................................................... 47
3.2.1 The File menu.................................................................................................. 48
3.2.2 The Edit menu ................................................................................................. 50
3.2.3 The Procedure menu ....................................................................................... 51
3.2.4 The Compiler menu.......................................................................................... 51
3.2.5 The Options menu ........................................................................................... 52
3.2.6 The Window menu ........................................................................................... 52
3.2.7 The Help menu ................................................................................................ 52
3.2.8 The toolbar ...................................................................................................... 53
3.2.9 The Global Variables window ........................................................................... 54
3.2.10 The Event Types window ................................................................................. 55
3.2.11 The Event Procedures window ......................................................................... 56
3.2.12 The Procedure Editing window ......................................................................... 57
3.3 Compiling your code ................................................................................................ 58
3.4 Handling compilation errors...................................................................................... 58
3.5 Handling run-time errors .......................................................................................... 58
3.6 CAPL Source Development with Other Text Editors ................................................. 59
3.6.1 CAPL Source File Format ................................................................................ 59

CAPL Reference Manual ii


Table of Contents

4 CAPL Functions ................................................................


....................................................................
.... 61
4.1 Using file input and output functions......................................................................... 61
4.1.1 Set-up for file input and output functions........................................................... 62
4.1.2 Set-up for sequential file access functions ........................................................ 64
4.2 Function Compatibility.............................................................................................. 65
4.3 CAPL Function Groups ............................................................................................ 66
4.4 CAPL Function Compatibility.................................................................................... 70
abs ............................................................................................................ 74
atol ............................................................................................................ 75
beep .......................................................................................................... 76
callAllOnEnvVar......................................................................................... 77
cancelTimer............................................................................................... 78
canOffline .................................................................................................. 79
canOnline .................................................................................................. 80
cos ............................................................................................................ 81
elCount...................................................................................................... 82
exp ............................................................................................................ 83
fileName .................................................................................................... 84
fileReadArray............................................................................................. 85
fileReadFloat ............................................................................................. 87
fileReadInt ................................................................................................. 88
fileReadString ............................................................................................ 89
fileWriteFloat ............................................................................................. 90
fileWriteInt ................................................................................................. 91
fileWriteString ............................................................................................ 92
getCardType.............................................................................................. 93
getChipType .............................................................................................. 95
getLocalTime ............................................................................................. 96
getLocalTimeString.................................................................................... 98
getThisMessage ........................................................................................ 99
getValue .................................................................................................. 100
getValueSize ........................................................................................... 101
inport ....................................................................................................... 102
isExtId ..................................................................................................... 103
isStdId ..................................................................................................... 104
keypressed .............................................................................................. 105
ltoa .......................................................................................................... 106
mkExtId ................................................................................................... 107
outport ..................................................................................................... 108
output ...................................................................................................... 109
putValue .................................................................................................. 110

CAPL Reference Manual iii


Table of Contents

random .................................................................................................... 111


resetCan.................................................................................................. 112
runError ................................................................................................... 113
seqFileClose............................................................................................ 114
seqFileGetBlock ...................................................................................... 115
seqFileGetLine ....................................................................................... 116
seqFileGetLineSZ .................................................................................... 118
seqFileLoad ............................................................................................. 120
seqFileRewind ......................................................................................... 121
setBtr....................................................................................................... 122
setLogFileName....................................................................................... 123
setMsgTime............................................................................................. 124
setOcr ..................................................................................................... 125
setPostTrigger ......................................................................................... 126
setPreTrigger........................................................................................... 127
setTimer .................................................................................................. 128
sin ........................................................................................................... 129
snprintf .................................................................................................... 130
sqrt .......................................................................................................... 132
stop ......................................................................................................... 133
strlen ....................................................................................................... 134
strncat ..................................................................................................... 135
strncmp ................................................................................................... 136
strncpy..................................................................................................... 137
swapDWord............................................................................................. 138
swapInt.................................................................................................... 139
swapLong ................................................................................................ 140
swapWord ............................................................................................... 141
sysExit..................................................................................................... 142
sysMinimize............................................................................................. 143
timeDiff .................................................................................................... 144
timeNow .................................................................................................. 145
trigger ...................................................................................................... 146
valOfId..................................................................................................... 147
write ........................................................................................................ 148
writeToLog............................................................................................... 150

5 CAPL Programming
Programming Examples ................................................
................................................152
152
5.1 Sending an Event Message ................................................................................... 152
5.2 Sending a Periodic Message.................................................................................. 153
5.3 Sending a Conditionally Repetitive Message .......................................................... 155

CAPL Reference Manual iv


Table of Contents

5.4 Responding to a Received Message ...................................................................... 156


5.5 Reading the Data within a Received Message........................................................ 157
5.6 Responding to a message after a delay ................................................................. 158
5.7 Sending an Error Frame......................................................................................... 159
5.8 Responding to an Error Frame ............................................................................... 160
5.9 Responding to User Keyboard Inputs .................................................................... 160
5.10 Measuring the Time Between Periodic Messages ................................................. 161
5.11 Responding to the Bus Off Condition ..................................................................... 162
5.12 Responding to the Error Passive Condition ........................................................... 163
5.13 Responding to the Error Active Condition .............................................................. 163
5.14 Logging Single Module Conversation .................................................................... 163
5.15 Using Random Inputs to Exercise a System ......................................................... 164
5.16 Using CAPL to control logging................................................................................ 167
5.17 Responding to a change in an Environmental Variable .......................................... 168

6 J1939 Extensions for CAPL................................


CAPL.....................................................
.....................170
170
6.1 The pg (parameter group) object in CAPL .............................................................. 170
6.2 Parameter group selectors..................................................................................... 170
6.3 Using the predefined J1939 database .................................................................... 172
6.4 J1939 differences in CAPL..................................................................................... 172
6.5 CAPL functions used with J1939............................................................................ 173
6.5.1 The output() function ...................................................................................... 173
6.5.2 The getThisMessage() function ...................................................................... 173

Index ................................................................
.....................................................................................
.....................174
174

CAPL Reference Manual v


Overview of CAPL

1 OVERVIEW OF CAPL

For CAN-based networks, modules, and distributed embedded systems, Communication


Application Programming Language, CAPL, makes it possible to program the CANalyzer for
developer-specific applications that use the CAN protocol. For distributed product development,
CAPL may also be used in the CANoe tool.

Application Uses for CAPL


• Create and modify the behavior of the CANalyzer measurement environment
• Design a custom module tester.
• Create a black box to simulate the rest of the network.
• Create a module simulator.
• Create a custom module manufacturing tester
• Create a custom module diagnostic or service tool
• Create programs to perform customized analysis of network logging (playback) files.
• Create complex logging filters.
• Create a comprehensive message or data content generation tester for module/network
validation.
• Create a functional gateway between to different CAN networks.

Uses for Simulation with CAPL


• Simulate node or system behavior using readable English rather than hex
• Simulate event messages, periodic messages, or conditionally repetitive messages
• Simulate human events like button presses using the PC keyboard
• Simulate timed node or network events
• Simulate multiple time events each with its own programmable behavior
• Simulate normal operation, diagnostic operation, or manufacturing operation
• Simulate changes in physical parameters or symbolic values (“ON”, “OFF”)
• Generate CAN error frames to evaluate module network software strategy
• Simulate module and network and network faults to evaluate limited operation strategy
• Simulate simple or complex functions (sin,cos)

CAPL Reference Manual 1


Overview of CAPL

1.1 CAPL Applications

Node Emulation
Using the programmable version of CANalyzer, one can emulate functions a node including the
transmission of event, periodic, and conditionally periodic messages. Users can create
conversational responding messages to the reception of designated messages.

Network Emulation
Using CAPL, CANalyzer can emulate the system-level data traffic of all remaining nodes.

Node Testing
During a portion of CAN-based module development, CANalyzer can be used to test the
module’s communication behavior. Evaluation of message timing, handling of Bus Off, and other
functions is easy to accomplish.

Gateway
The programmable CANalyzer can be used as a temporary or permanent gateway (or bridge)
between different CAN buses to exchange data.

Bus Separator
Another target application is to insert CANalyzer Pro between a node to be tested and the actual
network. Such configurations can be used during system-level development to isolate behavior.
The ability to interconnect modules at different revision levels to the distributed product in order to
continue development is also another possible application.

CAPL Reference Manual 2


Overview of CAPL

1.2 CAPL Programming Environment

Even though CAPL can be thought of as a procedural programming language, CAPL can also be
considered as a programming environment.
Within this programming environment a user can create, modify, and maintain CAPL programs
which can interface with a wide variety of inputs, outputs and other functions. Start-stop events,
keyboard entry events, the ability to transmit and receive CAN messages, interaction with the
serial port and parallel port, the use of timers, and the ability to interconnect to customer specific
DLLs are some of the interface choices available inside the CAPL programming environment.
Most programs are developed using the CAPL Browser which provides an easy to use “edit-
thru-compilation” development process. Even though provided as an integrated component of
CANalyzer or CANoe, the CAPL Browser application program can also be used separately.

CAPL Reference Manual 3


Overview of CAPL

1.3 CAPL Responds to Events

In general, CAPL programs are simply designed to detect events and then execute the
associated event procedure.

For example, you could output the text “Start Test” to the Write window upon clicking on the start
button of CANalyzer by using the following program.

on start
{
write(“Start Test”);
}

The types of events that can be detected in CAPL include -


• the pressing of the start
• stop button
• user keyboard entry
• CAN message reception
• the timeout of a timer
• user input via a graphic panel (available only in CANoe).

CAPL Reference Manual 4


Overview of CAPL

Based on this “event causes procedural activity” technique, CAPL programs are constructed and
organized as a collection of event procedures.
The CAPL Browser is conveniently structured into different groupings of event procedures.
These so-called event procedural groups or event classes include system, CAN controller, CAN
message, timer, keyboard, and CAN error frame as shown in the CAPL event table.

CAPL EVENTS

EVENT CLASS EVENT NAME PROCEDURE EXECUTED


ProStart
System During initialization of CANalyzer or CANoe
Start
System On press of Start button for CANalyzer or CANoe
StopMeasureme
System nt On press of Stop button for CANalyzer or CANoe

CAN Controller BusOff On detection of Bus Off condition in tool hardware


CAN Controller ErrorActive On detection of Error Active condition in tool hardware
CAN Controller ErrorPassive On detection of Error Passive condition in tool hardware
CAN Controller WarningLimit On detection of Warning Limit condition in tool hardware

CAN-Message user defined On reception of designated message

Timer user defined On timeout of designated timer

Keyboard user defined key On keyboard press of designated key

ErrorFrame ErrorFrame On detection of each Error Frame in tool hardware

Function user defined On invocation of the user’s designated procedure

Environment user defined On change in designated environmental variable (Canoe only)

CAPL Reference Manual 5


Overview of CAPL

1.4 Example CAPL Programs


Let’s take a look at how much CAPL code is necessary to develop the three common information
transfer methods (or transfer dialogs) used by most CAN-based distributed embedded systems.
Our three examples will include the transmission of an event message, the transmission of a
periodic message, and the transmission of a conditionally periodic message.

1.4.1 Event Message Transmission


When information only needs to be transferred on an event basis, the event message is used.
This sample program uses the pressing of the ‘b’ key on the PC keyboard to initiate a single CAN
message transmission.

It is important to note that the use of each message must include a definition within the global
variables. In this example we have defined the message msg1 as having a CAN identifier of
555 hex and data length code (dlc) or data size of one byte.

Note: While this example shows defining a message completely within this APL program, it is
easy to use the CANdb program (another related application program in the vector CAN tool
suite) to link a user-defined or corporate specific messaging database.

CAPL Reference Manual 6


Overview of CAPL

In the “keyboard” event class we insert (via the right mouse button) a new procedure for the ‘b’
key press. Don’t forget to include the single quote marks. In this on key procedure, we fix the first
byte of the can message data equal to hexadecimal AA and then use the internal CAPL function
output to transmit the message. Notice that the message name used in the output function is
identical to the name defined in the global variables.
variables
{
message 0x555 msg1 = {dlc=1};
}

on key ‘b’
{
msg1.byte(0)=0xAA;
output(msg1);
}

CAPL Reference Manual 7


Overview of CAPL

1.4.2 Periodic Message Transmission

When information requires transferring on a repetitive basis, the periodic message is used.

To send the periodic message requires the use of a timer and this timer must be defined by name
in the global variables area. To get this timer running, we have chosen to initialize the timer in the
“on start” event procedure which is executed upon clicking on the tool start button. We need to
use one of the intrinsic CAPL functions called setTimer to initialize the time value to 100
milliseconds.
When this timer expires (or times out), the corresponding “on timer” event procedure will be
executed. Within this “on timer” event procedure the timer will be reset again to 100 milliseconds.
Additionally, we increment the first message data byte before sending the CAN message using
the CAPL output function.

CAPL Reference Manual 8


Overview of CAPL

This repetitive process will continue until one clicks on the tool’s stop button.
variables
{
message 0x555 msg1 = {dlc=1};
mstimer timer1; // define timer1
}

on start
{
setTimer(timer1,100); // initialize timer to
100 msec
}

on timer timer1
{
setTimer(timer1,100); // reset timer

msg1.byte(0)=msg1.byte(0)+1; // change the data


output(msg1); // output message
}

With respect to the CAPL program development, for this periodic message example, CAPL code
must be entered into three different locations and a total of 6 lines of code are used.

CAPL Reference Manual 9


Overview of CAPL

1.4.3 Conditionally Periodic Message Transmission


When information requires transferring on a repetitive basis only when a certain set of conditions
is true, the conditionally periodic message is used. This CAPL program uses the pressing of the
‘a’ key on the PC keyboard to toggle between no message transmission and a periodic message
transmission.

To send a conditionally periodic message also requires the use of a timer, but this timer does not
need to run continuously. We have chosen to activate or deactivate the timer based upon the
pressing of the ‘a’ key sequence. The first press of the “a” key will start the periodic message and
the second press of the ‘a’ key will stop the periodic message. Each subsequent press of the ‘a’
key will toggle back and forth between these two states.
Notice in the global variables, we have defined a different message and timer name than was
used for our periodic message example. This allows you the opportunity to experiment with both
message transfer methods inside the same CAPL program if desired.
To properly start the process in the inactive state, we have defined an integer variable called
conditionA in the global variables area and have initialize its value to 0 which represents the off
condition.
Once the user presses the ‘a’ key, the corresponding on key procedure will execute. This
procedure will toggle the condition variable and check to see if the condition is active or true. If
the condition is active, then the timer will be started.

CAPL Reference Manual 10


Overview of CAPL

When this timer expires, the corresponding “on timer” event procedure will be executed. The
timer is reset to continue running and after modifying the data the CAN message is transmitted.
Notice that when the condition has been toggled back to the off condition, it will be the next timer
event that actually stops the timer from running.
This conditionally repetitive process will continue until the tool is stopped.
With respect to the CAPL program development, source code must be entered into three different
locations and a total of 10 lines of CAPL code are used.

variables
{
message 0x400 msgA = {dlc=1};
mstimer timerA;
int conditionA = 0; // initialize conditionA
= off
}

on key ‘a’
{
conditionA =! conditionA; // toggle conditionA
if(conditionA == 1) // if condition is active
{
setTimer(timerA,200); // then start timer
}
}

on timer timerA
{
if(conditionA == 1) // if condition is still
true
{
setTimer(timerA,200); // then continue timer
}
msgA.byte(0)=msgA.byte(0)-1; // change the data
output(msgA); // output message
}

CAPL Reference Manual 11


The CAPL Language

2 THE CAPL LANGUAGE

2.1 CAPL Fundamentals


CAPL, the CAN Access Programming Language, allows you to quickly develop code that makes
CANalyzer or CANoe simulations more powerful. In order to write CAPL code, there are a few
concepts that you need to become familiar with first.
First of all, you should be familiar with the CAN protocol. It is beyond the scope of this manual to
teach the CAN protocol, but only a basic understanding of the protocol and message structure is
necessary to begin programming in CAPL. You should understand that each message can
contain up to 8 bytes of data, how message priorities work, and what causes an error frame to be
generated.
You should be comfortable using either CANalyzer or CANoe (whichever you intend to use with
CAPL) and CANdb, the CAN Database Editor. Throughout this manual, you will see references
to CANdb; using CANdb is intertwined with developing CAPL programs. If you are not familiar
with these programs, please see their respective manuals.
You should also be familiar with the C programming language. It is possible to learn to program
in CAPL without knowing C, but the basic program structure is the same.

Note for the CANoe Users: If you are using CAPL with CANoe, you need to understand the
concept of environmental variables. Environmental variables are used in CANoe to represent
external values on the network, such as the position of a switch. The environmental variables are
defined in an associated database with CANdb, and can be read and changed by your CAPL
programs.

2.2 CAPL File Types


CAPL utilizes two types of files. Source code files (*.CAN) contain CAPL programs as well as
special formatting codes used by the CAPL Browser. These files are in ASCII text format and
can be edited with any text editor, although that is recommended only for expert users. When
you compile a .CAN file in the CAPL Browser, CANalyzer, or CANoe a binary file with the
extension .CBF (CAPL Binary File) is created. These binary files can only be interpreted and
executed by a CANalyzer or CANoe simulation.

2.3 CAPL Program Organization


In contrast to a traditional C program, CAPL programs have three distinct parts:
1. Global Variable Declarations
In this section, you declare variables that can be read or changed by any part of your CAPL
program. It is a good idea to declare messages and timers in this section.

CAPL Reference Manual 12


The CAPL Language

2. Event Procedures
Event procedures are blocks of code that are executed when an event occurs. CAPL allows
you to define event procedures for several different kinds of events. Most of your program
code will be in event procedures, since most actions are performed after an event, such as a
message being received on the CAN bus. Event procedures cannot return a value.
3. User-Defined Functions
Your programs can contain procedures that can be used to complement CAPL’s built-in
functions. These procedures can contain any legal CAPL code and are globally accessible.
Putting frequently-used code in a procedure makes programs more efficient. User-defined
functions can return a value of any simple type.
In the chapter on using the CAPL Browser, you will see how the editor itself is designed to help
you write each of these three parts of your program.

2.4 Naming Conventions


CAPL uses a consistent and easy-to-read naming convention for its built-in functions. These
simple rules are followed:
• All standard C functions are in lower case.
For example: sin, cos, strlen, strncat
• Non-C one-word function names are in lower case.
For example: trigger, outport, inport
• Non-C function names with more than one word capitalize the first letter of all words
except the first.
For example: swapInt, timeDiff, valOfId
Although CAPL function names are not case sensitive, we recommend that you maintain this
convention in your own CAPL programs for ease in editing and readability.
It is important to understand the notation used in this manual in order to understand examples
throughout the manual.

CAPL Reference Manual 13


The CAPL Language

Notation Meaning
. . . When used in source code, an ellipse means that any code is
valid in this place. It is used to indicate that code unrelated to
the specific example would often exist, but has been removed
for readability purposes.
Source code appears in a fixed-width courier font.
the write() function Names of functions not in the context of source code are
followed by parentheses to indicate that they are functions.
Note that this does not mean that the function takes no
parameters.

message 101x msg; An “x” following a message ID number indicates an extended


identifier. This forces a 29-bit identifier instead of the standard
11-bit identifier.

msg.data = 0x35; A “0x” preceding a number indicates that the number is


hexadecimal (base 16). Hexadecimal numbers can be used in
place of decimal numbers anywhere in CAPL.
variables { To make examples easier to read, event procedures are shown
} only as they appear in the Procedure Editing window. The
procedures do not appear sequentially in the CAPL code; they
on message 101 { appear in their respective sections of the program. The CAPL
} Browser facilitates dividing the program based on event type.

2.5 CAPL is based on C


The CAPL programming language is based on C. Those familiar with C will need minimal
learning time to begin using CAPL effectively. The syntax, most standard functions, and some
mathematical functions of ANSI C have all been incorporated into CAPL. CAPL extends the C
foundation with extra network-specific functions and data types.
Standard C syntax supported:
Instruction blocks: { ... }
Type casting, i.e. (int) x
if { ... } and if {...} else { ... }
switch, case, default
for.., while.., do..while loops
continue and break
return
// Comments
/* Comments */

CAPL Reference Manual 14


The CAPL Language

Mathematical and Relational Operators

+, -, *, /, % add, subtract, multiply, divide, modulo

==, != Equal to, not equal to


Greater than, greater than or equal to, less
>, >=, <, <=
than, less than or equal to
Increment, decrement (can be used as a prefix
++, --
or postfix)
= Assignment
Compound assignment (addition, subtraction,
+=, -=, *=, /=, %=
multiplication, division, modulo)

Logical Operators
&&, || Logical AND, logical OR
?: Conditional operator
! Logical negation

Bitwise Operators
~ Bitwise negation

&, ^, | Bitwise AND, bitwise XOR, bitwise OR

<<, >> Left shift, right shift

<<=, >>= Compound assignment (left shift, right shift)


Compound assignment (bitwise AND, bitwise
&=, ^=, |=
XOR, bitwise OR)

Program organization and each of CAPL’s built-in functions is explored in detail later in
this manual.

CAPL Reference Manual 15


The CAPL Language

2.5.1 Procedures and functions


The classical definition of a function is a section of program code that can accept 0 or more
parameters and returns a value to the calling code upon completion. A procedure is the same,
except it does not return a value to the calling code. In this manual, however, built-in CAPL
subroutines are called functions (even if they do not return a value). User-defined subroutines
are called procedures (even if they return a value). The return type void is assumed when a
return type is not specified.

2.6 Important Differences from C


CAPL has several differences from standard C that are important to be aware of, especially for a
veteran C programmer. Most of the differences are improvements borrowed from C++ that make
CAPL easier to use. The most significant differences are outlined in this section.

2.6.1 Function overloading is allowed


CAPL has the ability to overload functions, similar to the way C++ does. This means that multiple
functions can have the same name but different parameter lists. The function that is called
depends on the parameters that are passed. For example, we could create two functions that
use write() to output different types of numbers:
void print (double num)
{
write(“Floating point %f”, num);
}

void print (int num, char units[])


{
write(“%d %s”, num, units);
}

After setting these functions up, we get these results:

print(5.7);
“Floating point 5.700000”
print(2.5, “angstroms”, 22);
“2 angstroms”

The last case is the most interesting. Since there are no overloaded functions with three
parameters, the function with two parameters is chosen. Since the first parameter to that function
is expected to be an integer, the floating point value 2.5 is first cast to an integer (2) before being
passed to the function. The third parameter (22) is discarded.

CAPL Reference Manual 16


The CAPL Language

2.6.2 The “this” keyword


Since CAPL provides event-driven program design, the “this” keyword is used to point to the
object that caused the event within the event procedure. You can use this to read data from the
object, such as a message, pg, or environmental variable.
Although the “this” pointer may be difficult to understand conceptually, its use is straightforward.
For example, if you set up an event to trigger upon receiving a CAN message with ID 555, you
can use the “this” pointer to access the message’s selectors or data bytes:
on message 555
{
byte val;
val = 0;

if (this.CAN == 1) // If the message was received


// on CAN channel 1
{

// Set “val” to the value of the first


// data byte in the CAN message
val = this.byte(0);
}
}

The “this” pointer can be used similarly for environmental variables. The event shown below is
triggered when the value of the environmental variable Switch changes. In order to read the new
value, you can use the “this” keyword with the getValue() function.
on envVar Switch { // Triggered when Switch changes
int val;
val = getValue(this); // Read value of Switch into val
}

Warning: Changes make to the “this” pointer remain local. The value of the “this” pointer may be
modified and passed as a function parameter, but the value will be lose upon the end of the “on
message” or “on envVar” procedures.

CAPL Reference Manual 17


The CAPL Language

2.6.3 Local variables are static


In a CAPL function, in contrast to C, all locally declared variables are static. This means that
once a variable is declared and assigned a value during one iteration of a function, the variable
retains that value the next time the function is called. This can cause confusion to programmers
accustomed to the C semantic.
For example:
void myFunc() {
byte value = 10;
write (“value = %d”, value);
. . .
value = 35;
}

The first time myFunc is called, it will print “value = 10” as expected. However, the second and all
subsequent times the function is called, it will print “value = 35”. Due to this semantic, the
preferred way to initialize non-static variables is to use a separate assignment after the variables
has been declared. In this example, the variables are reset to their initial values at the beginning
of every iteration of the function:
void myFunc() {
// Variable declarations
byte value;
int x, y;

// Variable initializations
value = 10;
x = 0;
y = 5;

// Main code of the function


. . .
}

CAPL Reference Manual 18


The CAPL Language

2.6.4 Dynamic memory and the elCount() function


CAPL does not allow traditional C pointers or memory allocation functions such as malloc().
Array dimensions must be specified in the array declaration. However, you can pass arrays of
arbitrary size as function parameters by using the elCount() function in your function. The
elCount() function returns the number of elements in a dimension of an array. For
multidimensional arrays, elCount() can be used on each dimension separately.
The example below shows how to implement a sum() function that returns the sum of every
element in a two-dimensional array of arbitrary size:
variables
{
int mat1[2][2] = { {1, 2}, {3, 4} };
int mat2[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
}

void sum (int matrix[][])


{
int i, j;
int answer;

answer = 0;

for (i = 0; i < elCount(matrix); i++)


{
for (j = 0; j < elCount(matrix[i]); j++)
{
answer += matrix[i][j];
}
}

write(“The sum is %d”, answer);


}

on start
{
sum(mat1); // prints 10
sum(mat2); // prints 45
}

In the above example, notice how elCount() is used in sum() twice, once in the inner “for” loop
and once in the outer “for” loop. In the outer loop, elCount(matrix) returns the size of the first
array dimension. In the inner loop, elCount(matrix[i]) returns the size of the second array
dimension. In combination, these loops are used to cycle through every index of the two-
dimensional arrays.

CAPL Reference Manual 19


The CAPL Language

2.6.5 Variables are assigned a default value implicitly


In contrast to standard C, all numeric variables are initialized to 0 and all strings are initialized to
null. Message objects are usually initialized with DIR = TXREQUEST. Timers are not initialized
automatically.

2.6.6 Run-time error handling


CAPL monitors a number of run-time errors:
• Division by zero
• Exceeding the upper or lower limits of an array
• Invalid direct accesses of a message’s data region
• Stack overflow when subroutines are called
If one of these errors is detected, the CAPL function runError() is called. This outputs an error
message to the Write window (in CANalyzer or CANoe) and halts the simulation. The error
message contains information that will help you find the location in your program that caused the
error.
You can also use the runError() function in your CAPL code to produce the same results. This
function requires two parameters: an error number (long integer) and an unused arbitrary
parameter (long integer). Error numbers under 1000 are reserved for internal use by CAPL.

2.6.7 CAPL equivalents to C functions


There are a few function equivalents that are helpful for a C programmer to know. This is a
concise list of the similar functions, but for more usage details of CAPL functions, please see the
function descriptions later in this manual.

C Function CAPL Function Notes


sizeof elCount sizeof has no exact equivalent
sprintf snprintf Similar string formatting parameters used
printf write Similar string formatting parameters used

CAPL Reference Manual 20


The CAPL Language

2.7 Using the CANdb database with CAPL


One powerful feature of CAPL is the ability to use databases created with CANdb. CAPL allows
you to work with symbolic names for environmental variables, messages, signals, and constants.
For this reason, we recommend that creating a database is the first step in the development
process.
To associate a database, pull down the File menu and choose “Assign Database.” Press the Add
button and select the file containing the database. Then press the OK button to return to the
CAPL Browser. The database must be selected every time that you open your CAPL program in
the CAPL Browser.
For example, instead of having to remember that the message with ID 0x64 contains information
about the engine, you can simply select the message called “Engine DATA” from a list of
messages in the database. Right-click in the Procedure Editing window and select “CANdb
Message” to see the list. Clearly, defining a database in CANdb and using it with CAPL makes
software development easier and CAPL code more readable.

CAPL Reference Manual 21


The CAPL Language

2.7.1 Using symbolic signal values


CAPL has the ability to use symbolic signal values (also called symbolic identifiers) that are
defined in an associated CANdb database. Using these symbolic names will make your code
easier to develop and read. To use the symbolic names for values, separate the message and
signal names from the value name with a double colon (::). For example, if you define a message
called LightStatus in CANdb, you could also define a 2-bit signal called State to indicate the four
light states. Each of these four states would have a value associated with it, and it would look like
this:

The sample code below uses the “Off” symbolic value name instead of the actual decimal value
of 3. Clearly, this provides many advantages, including being able to change the numeric value
corresponding to the “Off” state without changing any CAPL code.
on message LightStatus {
if (this.State == LightStatus.State::Off)
write (“The light is off.”);
else write (“The light is not off.”);

CAPL Reference Manual 22


The CAPL Language

2.7.2 Using user-defined attributes


The CANdb database editor allows you to define attributes in associated databases. An attribute
consists of a name for the attribute, a data type, a range of valid values, and a default value.
Attributes can be assigned to the entire database, network nodes, environmental variables,
messages, and signals.

-
From CAPL’s perspective, a user-defined database attribute is a constant value that you can read
in your CAPL programs. The values of the attributes can be changed in the database after each
successive measurement, allowing you to modify the behavior of your CAPL program without
altering the source code.
To access an attribute’s value in CAPL, append a period (.) and the name of the attribute to the
name of the database object. The object types are listed above, and examples of accessing
attributes for each object type are below.

CAPL Reference Manual 23


The CAPL Language

For this example, we will use CANdb to create a database named AUTO.DBC. Then we will
associate the database with a new CAPL program. Inside AUTO.DBC, we will create an
environmental variable called leftWindowButton with an attribute called style (type enum, with
values Button and Toggle). An database attribute called revision will be created as a string. We
will create a node called displayConsole and a message called windowControl. The message will
contain a signal called windowHeight. For clarity, here is how each attribute corresponds to each
database object:

Database Object Object Name User-defined attribute Attribute Type


AUTO (filename is
The database revision string
AUTO.DBC)
Environmental enum (Button or
leftWindowButton style
variable Toggle)
Node displayConsole nodeNumber hex

Message windowControl windowNumber integer

Signal windowHeight maximum float

Here is how we would access each of the attributes listed above:


// CAPL variable // User-defined attribute type
char rev[100]; // string
char butStyle[100]; // enumerated
int nodeNum; // hex
int winNum; // integer
float maxHeight; // float

strncpy(rev, AUTO.revision, elCount(rev) - 1);


strncpy(butStyle, leftWindowButton.style,
elCount(butStyle) - 1);
nodeNum = displayConsole.nodeNumber;
winNum = windowControl.windowNumber;
maxHeight = windowControl.windowHeight.maximum;

Note that in CAPL, enum data types are treated like strings. So when we read from the style
attribute, we are actually reading the string “Button” or “Toggle”. We use the strncpy() function for
this, just as we do for reading the revision string.

CAPL Reference Manual 24


The CAPL Language

2.8 Variable and Object Types and Declarations


CAPL supports many of the same data types as standard C and adds several types of its own.
These new types will be explored further in the sections below. CAPL also allows arrays to be
declared in the same manner as C.

CAPL Data Types


8-Bit byte, char
16-Bit int.word
32-Bit dword, long
64-Bit (Floating Point) float. double
object msTimer, Timer, message, pg

One important difference from C is that in CAPL, local variables are always created statically.
This means that an initialization is only executed at the program start, and when variables enter
the procedure they assume the value they had at the end of the previous execution of the
procedure.
Examples of variable declarations:
int j, k = 2; /* j = 0 implicitly */
double x = 33.7;
char p;

Examples of array declarations:


long data[10];
int vector[5] = { 0, 1, 2, 3, 4 };
int matrix[2][4] = { {2, 4, 6, 8}, {1, 3, 5, 7} };
char userName[10] = “Jack Beam”;

Note: You can initialize multi-dimensional arrays using the syntax shown. You can also initialize
character arrays with string constants.

CAPL Reference Manual 25


The CAPL Language

2.8.1 The Timer and msTimer Objects


Since CAPL is designed to provide an event-driven environment, timers provide an easy way to
cause periodic events. CAPL allows an infinite number of user-defined timers that can be set
using units of seconds (Timer) or milliseconds (msTimer).
Timers are set using the setTimer function. The most common way to set up a periodic timer is to
set the timer in the initialization (or “on Start”) function, set up an event based on this timer to
perform a given task, and then reset the timer at the end of this task.
The unit of the timer’s counter is set based on how the timer is declared.
Timer t1; /* Units of seconds */
setTimer(t1, 60); /* Set to one minute */

msTimer t2; /* Units of milliseconds */


setTimer(t2, 100); /* Set to one tenth of a second */

2.8.2 The Message Object


The message object is a major feature of CAPL. This object allows you to work with a CAN
message at an abstract level, without setting each of the bit fields in the message. The
message’s signals can be set up in an associated database using CANdb. Signals are the part of
the message that is used to store data.
Each CAN message can carry a whole number of data bytes from 0 to 8. Signals can be used to
partition these data bytes into to chunks from 1 to 32 bits each. A CAN message may carry
several signals, each with its own significance. For example, a CAN message could carry four 8-
bit signals and a 32-bit signal, sixteen 1-bit signals and three sixteen-bit signals, and so on.
The structure of a message’s data field can also be specified entirely in CAPL. Although you
cannot create signal names in CAPL, you can access raw data bytes and words in the message.
This is useful for messages with little data in them; otherwise, defining messages in CANdb will
save you a lot of work and make your code more readable.

CAPL Reference Manual 26


The CAPL Language

2.8.2.1 Declaring messages in CAPL


Since messages are objects, they must be declared (like variables) before they can be used. As
mentioned above, messages can be specified in two ways: either in an associated database or in
a CAPL program itself. Declaring a message specified in an associated database is easy — just
use the symbolic name of the message:
message EngineTemp eTemp;
message EngineStatus eStat1, eStat2;
These declarations automatically associate signal names and message ID numbers to the
message objects. If the message is not specified in a database, then you must provide the
message ID number yourself:
message 411 info; // Message ID 411 (decimal)
message 0xF2 windowStatus; // Message ID F2 (hex)
message 142x doorStatus; // Extended CAN message ID 142

Note that appending an “x” to the message ID tells CAPL that the identifier you specified is an
extended (29 bit) CAN ID. The default is the standard (11 bit) CAN ID.
You also need to specify the amount of data a message is going to contain. One way to do this
is to use the DLC (data length code) message selector as part of the message declaration. Other
message selectors will be covered later in this chapter. For example:
// Declare message ID FF (hex) with 4 data bytes
message 0xFF rearAxle = { DLC = 4 };

// Declare extended message ID 327 with 8 data bytes


message 327x frontAxle = { DLC = 8 };

CAPL Reference Manual 27


The CAPL Language

2.8.2.2 Accessing message signals


If you have defined a message in an associated database, it is easy to access individual signals
within the message. Signals are specified as a part of a message by putting a dot after the
message name and then the signal name. For example:
message EngData EDMsg; // Declare EDMsg as type EngData
EDMsg.EngSpeed = 100; // Access signal EngSpeed

The CAPL Browser makes signal selection easy by allowing you to insert a signal name from an
associated database using a pull-down menu system. Right-click on the location where you want
to insert the signal name, choose “CANdb Signal”, choose the message containing the signal,
and then choose the signal name.

CAPL Reference Manual 28


The CAPL Language

2.8.2.3 Physical values and the phys attribute


Occasionally, you will want to adjust the range of values a signal can contain. For example, if you
define an unsigned 16-bit signal, it would normally hold values between 0 and 65,535. However,
if the values in you are interested in lie between 0 and 100,000, then there is a problem. You
could use a more than 16 bits to specify a larger range, but that would waste bits and make
message sizes larger.
Instead, you could set up a conversion formula in CANdb that will allow you to use a 16-bit signal
to hold your data. The formula is specified by entering an Offset and Factor in CANdb’s
“Message and Signal Parameters” screen. The physical value is calculated as follows:

Physical Value = (Raw Value * Factor) + Offset

So for our example, entering a Factor of 2.0 and an Offset of 0 would allow us the desired range
of numbers. To access the physical value (and have CAPL automatically convert the number to
the appropriate raw value), simply add “.phys” to the signal name. Using the EngData example
from the above section, using the physical value would look like this:
message EngData EDMsg; // Declare EDMsg as type EngData
EDMsg.EngSpeed = 50000; // Set raw value
EDMsg.EndSpeed.phys = 50000; // Set physical value

Note that if a conversion formula is defined for EngSpeed, the two assignment statements do not
have the same effect. You should almost always use the .phys attribute whenever you have a
formula defined; not doing so can cause bugs that are difficult to track down.

2.8.2.4 Round-off error in symbolic signal access


It is important to remember that signal values are always saved as discrete numbers. A discrete
number is a whole number, with no significant digits after the decimal point. If a non-discrete
physical value is assigned to a signal, the closest discrete raw value is saved (after applying the
conversion formula). When the signal’s value is read, it may not agree with the value that you
previously set.
To demonstrate the round-off error, consider the example in the previous section. The
conversion formula had a Factor of 2.0 and an Offset of 0. If we make this assignment:
EDMsg.EngSpeed.phys = 4001;

Then the conversion formula is used to calculate a raw value of 2000.5. Since only discrete (or
whole number) values are legal, 2000 is saved in EDMsg.EngSpeed. The next time we read the
value of EDMsg.EngSpeed.phys, the conversion formula is used to produce the value 4000.

CAPL Reference Manual 29


The CAPL Language

2.8.2.5 Message selectors


In addition to the .phys attribute, CAPL also provides more built-in message controls called
selectors. Selectors offer complete control over the contents of a CAN message. For most
applications, they do not need to be set explicitly, but they can be helpful in some cases.

CAPL Message Selectors

Selector Description Valid values

ID Message identifier Any valid CAN message ID


CAN Chip number 1 or 2
DLC Data Length Code 0 to 8
RX (Receive)
DIR Direction of transmission TX (Transmit)
TXREQUEST (Transmit Request)
0 (not an RTR)
RTR Remote TransmissionRequest
1 (RTR)
TYPE Combination of DIR and RTR See below
Time stamp of the message in
TIME Long integer
units of 10ms (read only)

SIMULAT Sent by a simulated node 0 (real node)


ED (read only) 1 (simulated node)

Both the DIR and TYPE selectors provide predefined constants that you can use to make your
CAPL programs more readable. The TYPE selector is provided as an efficient way to evaluate
other selectors as one unit:

TYPE = (RTR << 8) | DIR

CAPL Reference Manual 30


The CAPL Language

The constants to compare to the TYPE selector are listed below.

Valid Values for the TYPE Message Selector

Constant Meaning Logical Derivation

RXREMOTE Remote message was received ((DIR == RX) && RTR

TXREMOTE Remote message was transmitted ((DIR == TX) && RTR)

Transmission request was set for


TXREQUESTREMOTE ((DIR == TXREQUEST) && RTR)
remote message

RXDATA Data message was received ((DIR == RX) && !RTR)

TXDATA Data message was transmitted ((DIR == TX) && !RTR)

Transmission request was set for data


TXREQUESTDATA ((DIR == TXREQUEST) && !RTR)
message

2.8.2.6 Accessing raw message data


If you have not defined signals for a message in an associated database, then you can access
the message’s data directly. CAPL provides three ways to do this: by the byte, word (2 bytes), or
long integer (4 bytes). To access the data, append a dot and “byte”, “word”, or “long” after the
name of the message. You can index into each as you would an array, with 0 as the first index.
Note that the index always uses bytes as the unit. For the word and long types, the index is the
position of the first byte. The index cannot exceed 7 for bytes, 6 for words, and 4 for longs to stay
within the limit of eight data bytes.
For example:
message 400 msg;
msg.DLC = 8; // 8 bytes of data

msg.long(0) = 333; // long integer starting at first byte


msg.byte(4) = 25; // Byte starting at fifth byte
msg.word(5) = 747; // Word starting at sixth byte
msg.byte(7) = 100; // Byte starting at eighth byte

CAPL Reference Manual 31


The CAPL Language

Example of Message Data Layout

Byte (7) word (5) Byte (4) long(0)

100 747 25 333

Eight Byte Seventh Byte Sixth Byte Fifth Byte Fourth Byte Third Byte Second Byte First Byte

2.8.2.7 Sending and receiving messages


Messages can be sent with the output() function. The output() function takes the message as a
parameter. All of the attributes of the message are set beforehand using the message selectors
mentioned above. The data is set using signal names or raw data access; both methods are
described above. Messages are received by message event procedures, which will be covered
in the events section. Here is an example of using the output() function:

message EngineData msg; // Declare msg as EngineData


m.Rpm.phys = 225; // Set physical value,actual value
// stored in message bits will be
// different.
m.CAN = 2; // Output on CAN channel 2
output(msg); // Send EngineData message out

2.8.3 Environmental Variables


Environmental variables are simple to use in CAPL. Once they are defined in an associated
database, you can insert the variable name into your code with the right mouse button menu.
CAPL provides two functions, getValue() and putValue(), that read and set the value of an
environmental variable, respectively. Since an environmental variable can be an integer, floating
point number, or a string, CAPL provides three ways to call each function:

getValue() and putValue() Declarations


Data Type getValue() functions putValue() functions

Integer int getValue(EnvVarName); putValue(EnvVarName, int val);

Floating Point float getValue(EnvVarName); putValue(EnvVarName, float val);

String getValue(EnvVarName, char buffer[]); putValue(EnvVarName, char val[]);

CAPL Reference Manual 32


The CAPL Language

When using the getValue() function with a string, notice that you must supply a buffer as the
second argument of the function call. This is different from using getValue() to read a number.
For example:
char[100] lightColor; // A 100-character buffer
// will suffice for the string
int lightState; // Light state is an integer

// First, read the value of the EV_LightState


// environmental variable into the lightState integer
lightState = getValue(EV_LightState);

// Next, read the value of the EV_LightColor


// environmental variable into the lightColor string
getValue(EV_LightColor, lightColor);

2.8.4 Built-in Constants


CAPL provides some built-in constant values for use in your programs. Some of them only are
used in specific cases, such as to evaluate message selectors. Those constants are covered in
their respective sections of the manual.
However, you might find the PI constant useful. It contains the value of pi to the maximum
precision useful to CAPL. Also, the constants LPT1, LPT2, and LPT3 can be used in the place of
port addresses for the inport() and outport() functions.

CAPL Reference Manual 33


The CAPL Language

2.9 Events in CAPL


CAPL is an event-driven language. This means that sections of a program are executed in
response to specific occurrences (events) rather than the whole program being executed all at
once. In CAPL, an event procedure is associated with every event that is important to the
application. For example, you can define event procedures for a user’s keystroke, the beginning
of a measurement, or the reception of a certain message.
Every event procedure consists of an event statement, which specifies the event to look for, and
a procedure block, which is executed shortly after the event occurs. Some event statements
require a parameter (such as a message event) and the rest do not allow parameters (such as an
error frame event). Message and key events also allow the wildcard parameter ‘*’ to cause an
event to occur on any message or keystroke, respectively. Here is an example of what event
blocks look like:
// Message event block with required parameter.
// Event occurs when message ID 101 is received.
on message 101
{
. . . // Your event code is executed here
}

// Error frame event block without a parameter.


// Event occurs when an error frame is received.
on errorFrame
{
. . . // Your event code is executed here
}

CAPL Reference Manual 34


The CAPL Language

The following is a complete list of all of the available events. Note that the last event, on envVar,
is only available if you are using CANoe. Event statements with an italicized parameter indicate
event statements that require a parameter. Since its use changes, the last column indicates how
you can use the “this” pointer inside each event procedure. For more detailed explanations, see
the section corresponding to each event type.

CAPL EVENT TYPES


Event description Event statement syntax Value of "this" inside event
procedure

Receipt of a CAN message on message message the message received

Press of a key on key key the key pressed

Initialization of measurement (before start) on preStart N/A

Program start on start N/A

End of measurement on stopMeasurement N/A

CAN controller goes into ErrorActive state on errorActive contains error counts

CAN controller goes into ErrorPassive state on errorPassive contains error counts

CAN controller goes into Warning Limit state on warningLimit contains error counts

CAN controller goes into Bus Off state on busOff contains error counts

Elapse of a user-defined timer on timer timer N/A

Occurrence of an error frame on errorFrame N/A

Environment variable change (CANoe only) on envVar env. variable the env. variable

CAPL Reference Manual 35


The CAPL Language

2.9.1 The “on message” event


The “on message” event occurs when a message is received. Inside the event procedure, the
“this” pointer can be used to access the contents of the message. The “on message” event must
have a parameter to specify which message or set of messages should trigger the event. For
example:

on message 123 Event occurs when message 123 (decimal) received

on message 0x123 Event occurs when message 123 (hex) received

Event occurs when message EngineTemp received


on message EngineTemp
(EngineTemp must be defined in database)

on message CAN1.123 Event occurs when message 123 received on CAN1

on message * Event occurs when any message is received

on message CAN2.* Event occurs when any message is received on CAN2

Event occurs when messages 0, 5, and 10 through 20 are


on message 0, 5, 10-20
received

Note: If more than one message parameter applies, then only the most specific event procedure
is executed. These two precedence rules apply:
• Specification of a chip number has precedence over the absence of a chip number.
• Specification of a message ID number has precedence over a wildcard.

CAPL Reference Manual 36


The CAPL Language

Here is an example of event procedure precedence given the following declarations:

on message CAN1.123 /* Message 123 on CAN1 calls this */


on message CAN2.* /* Any message on CAN2 calls this */
on message 123 /* This is never called. Message 123
would call one of the above two
events */
on message * /* Called by any message received on
CAN1 except message 123 */

It is important to remember that if you want to perform an action on all messages received, an “on
message *” event procedure will not be executed if another “on message” event procedure is
triggered.

2.9.2 The “on key” event


The “on key” event is executed when a key on the keyboard is pressed. Character constants are
used for normal keyboard keys, and symbolic identifiers are used for extended keyboard keys.
The wildcard “*” can also be used to signify any character. The constants are case-sensitive. For
example:

on key 'a' Event occurs when the (lower case) "a" key is pressed

on key 'A' Event occurs when the (capital) "A" key is pressed

Event occurs when the End key is pressed


on key End
(notice absence of quotes)

on key shiftF1 Event occurs when Shift-F1 is pressed

on key ctrlPageDown Event occurs when Control-Page Down is pressed

on key * Event occurs when any key is pressed (see below)

CAPL Reference Manual 37


The CAPL Language

The last event syntax, “on key *”, can be useful if you want to write all of your keystroke-handling
routines in one event procedure, or if you want to have several different keystrokes execute the
same instructions. The “this” keyword is used to determine the actual key that was pressed. For
example:
on key * {
switch(this) { // “this” holds the value of the key

write (“a or b was pressed.”);


break;
default:
write (“A key besides a or b was pressed.”);
break;
}
}

Note: If an “on key*” event procedure is declared as well as an “on key ‘a’” event procedure, only
the “on key ‘a’” event procedure is executed when the ‘a’ key is pressed. Only the most specific
event procedure is executed when more than one event statement matches the event.

CAPL Reference Manual 38


The CAPL Language

2.9.3 The preStart, start, stopMeasurement events, and CallAllOnEnvVar()


The preStart, start, and stopMeasurement events are used to perform actions before, at the start
of, and after CANalyzer or CANoe measurements. If they are defined, each is called once per
measurement. When the “Go” button is pressed in CANalyzer or CANoe, the preStart event
procedure is executed (if one exists). You use this procedure to read data from files, initialize
variables, or write to the Write window. Other actions, such as outputting a message onto the
bus, are not available in the preStart event. Generally, actions that are invalid in the preStart
event procedure can be moved to the start event procedure.
After the preStart event procedure has completed executing, the start event procedure is
executed (if one exists). The start event procedure can be used to initialize environmental
variables, set timers, and output messages onto the bus. The measurement is also started at this
time.

Note for the CANoe Users: It may be necessary to execute the same actions with environmental
variables at the beginning of the measurement as when the values of environmental variables
change during the measurement. These actions may include initializing variables, setting timers
related to environmental variables, and sending out messages onto the bus containing values of
environmental variables. To aid you in executing all of your environmental variable event
procedures, CAPL provides the CallAllOnEnvVar() function. This calls every environmental
variable event procedure that you have defined. CallAllOnEnvVar() is normally called from the
start event procedure.

When you press the Stop button in CANalyzer or CANoe, the stopMeasurement event procedure
is executed (if one exists). You can use this procedure to print statistics in the Write window,
output messages onto the bus, or write to a log file. After this event has finished executing, the
measurement is stopped.

2.9.4 The errorActive, errorPassive, warningLimit, and busOff events


A CAN controller can be in one of three states: error active, error passive, or bus off. The state is
determined by the number of errors detected by the CAN controller and the current state of the
controller. CAPL gives you the ability to have events occur when the CAN controller on CAN
Channel 1 changes state.

CAN Controller States


Error Active Transmit and receive error counts are less than or equal to 127
Error Passive Transmit or receive error count equals or exceeds 128
Bus Off Transmit error count is greater than or equal to 256

CAPL Reference Manual 39


The CAPL Language

The Warning Limit interrupt is not a state, but rather an interrupt that originates in the CAN
controller. The interrupt occurs when either the receive or transmit error counts exceed 96.
(Note: For some CAN controllers, the error count can be set, but defaults to 96. See the
documentation for your CAN controller for more information.)
Although interrupts and state changes are different, CAPL treats them both as events; therefore,
there is no difference in implementing the errorActive, errorPassive, warningLimit, or busOff
events. The event procedures can be used to print a warning message to the Write window or to
automatically stop the measurement. Inside these event routines, the “this” keyword allows you
read-only access to the CAN controller’s error counters.

this.errorCountRX Receive error count

this.errorCountTX Transmit error count

For example, if you want to output a warning when the Error Warning Level is reached and stop
the measurement if the controller goes into the Bus Off state, this is the implementation:
on warningLimit
{
write (“CAN controller is in the Warning Limit state.”);
write (“ Transmit errors = %d”, this.errorCountTX);
write (“ Receive errors = %d”, this.errorCountRX);
}

on busOff
{
write (“CAN controller is in the Bus Off state.”);
write (“Stopping measurement.”);
stop();
}

CAPL Reference Manual 40


The CAPL Language

2.9.5 The “on timer” event and the setTimer() and cancelTimer() functions
CAPL allows you to create timers for seconds (Timer) or milliseconds (msTimer). After these
timers have been set and expire, the corresponding “on timer” event procedure is executed. This
facility can be used to create a cyclic event if you reset the timer at the end of the timer event
procedure. Timers can also be used to respond to an event after a delay.
The setTimer() function takes two parameters, the name of the timer and the length of time to set
the timer. The length of time parameter has different units depending on what kind of timer you
are using. For a Timer, the units are seconds; for an msTimer, the units are milliseconds. The
maximum values are 1799 seconds and 65,535 milliseconds, respectively. The cancelTimer()
function can be called on a timer before it has expired to prevent the timer event from triggering.
Calling the cancelTimer() function has no effect if the timer is not set or has already expired.
An example of a cyclic timer with a 20 millisecond period:
variables {
msTimer t;
. . .
}

on start {
setTimer(t, 20);
. . .
}

on timer t {
. . . // Perform some action here
setTimer(t, 20);
}

CAPL Reference Manual 41


The CAPL Language

2.9.6 The “on errorFrame” event


The “on errorFrame” event is similar to the “on message” event, except it occurs whenever an
error frame is received on the bus. You can use this to keep statistics on the number and timing
of error frames. However, no further information on the cause of the error is available within the
event procedure.

2.9.7 The “on envVar” event


The “on envVar” event is caused by the value of an environmental variable changing. (Note:
Remember that environmental variables are only enabled in CANoe.) The “this” keyword is used
in conjunction with the getValue() function to access the value of the environmental variable. For
example:
on envVar Switch {
int val;
val = getValue(this); // Read value of Switch into val
}

CAPL Reference Manual 42


The CAPL Language

2.10 P-Block placement and message pass-through

In the Measurement Setup window in CANalyzer, the placement of your P-Blocks has important ramifications on
your CAPL programs. P-Blocks are inherently not transparent to bus events. This means that a message or error
frame in the evaluation branch (of CANalyzer or CANoe) will not pass through a P-Block unless the P-Block is
specifically told to pass it on. To make a P-Block allow messages and error frames to pass though, you would write
the following CAPL code:
on message * {
. . . // Insert your code here if desired
output(this);
};

on errorFrame {
. . . // Insert your code here if desired
output(errorFrame);
};

CAPL Reference Manual 43


The CAPL Language

Recall that if another message event procedure is executed instead of the “on message *” event
procedure, then the on “message *” event will not be executed. If you want to pass on those
messages, include the same “output(this)” line in the event procedures corresponding to those
messages.
However, you should not include this code in P-Blocks in CANalyzer’s transmission branch or in
CAPL programs in CANoe’s Simulation Setup window. This causes an infinite loop to occur,
which is rarely the desired effect. For each message received, the reaction is to immediately re-
send the same message, causing the message to be received again. This repeats until the
simulation is stopped.
It is also important to be aware that some built-in CAPL functions are not allowed in some areas. Mostly, this means
that file-related functions are not allowed in CANoe’s Simulation Setup window or CANalyzer’s transmission branch.
See the chapter on CAPL functions for more information.

2.11 Using a CAPL program to control logging


CAPL provides built-in functions to allow you full control over the logging system in CANalyzer or
CANoe. When “CAPL” is selected as the Trigger Type in the logging configuration window, your
CAPL program can be used to trigger and stop logging.

CAPL Reference Manual 44


The CAPL Language

It is beyond the scope of this manual to cover how to use logging in CANalyzer and CANoe, but
there are some concepts that you must understand to use CAPL to control logging. Since logging
an entire simulation can produce large log files containing mostly extraneous data, CAPL allows
you to selectively log portions of a simulation. When the conditions to begin logging are met, you
call the trigger() function in your CAPL code.
The pretrigger time is the period of time to record bus activity preceding the call to the trigger()
function. The posttrigger time is the period of time to record bus activity following the call to the
trigger() function. For example, assume that the start of a given measurement occurs at 0.0
seconds. We will set the pretrigger time to 1 second and the posttrigger time to 2 seconds. If a
call to trigger() occurs at 7.2 seconds into the simulation, then the bus activity between 6.2
seconds and 9.2 seconds is recorded in the log file.
To implement this example in CAPL code, the following functions are used: trigger(),
setLogFileName(), setPreTrigger(), and setPostTrigger(). Note that these functions can only be
used in P-Blocks in the analysis branch of CANalyzer’s simulation setup window or in CANoe’s
simulation setup window. Attempting to compile programs utilizing these functions in the CAPL
Browser will lead to an error message. Therefore, you need to compile these programs with
CANalyzer or CANoe’s compile command.

CAPL Reference Manual 45


Using the CAPL Browser

3 Using the CAPL Browser

The CAPL Browser is the program that comes with CANalyzer and CANoe which is designed to
help you develop CAPL code as quickly and easily as possible. It is versatile in that you can
choose to use all of its powerful features, or slowly progress up the curve, using only its basic
features at first.
Within the browser program itself, you can develop new programs, import and export source files, and compile your
code. The integrated compiler makes it easy to debug your CAPL programs.

Note for the right mouse button: The right mouse button provides context-sensitive
functionality in most CAPL Browser windows. Learning how and when to use the pull-down
menus that the right mouse button accesses will allow you to use the program effectively.
When in doubt, try clicking the right mouse button in a CAPL Browser window.

3.1 Starting the Browser


The CAPL Browser can be started several ways. First of all, you can execute it from a DOS
command prompt within Windows. You can also create a shortcut to CANBROW.EXE in
Windows. You can also start the CAPL Browser by double-clicking a CAPL node (or P-Block) in
CANalyzer or CANoe. For more information on creating CAPL nodes in CANalyzer or CANoe,
please see the respective reference manual.

CAPL Reference Manual 46


Using the CAPL Browser

3.2 Browser organization


The CAPL Browser is designed around the event-driven design philosophy. CAPL programs are
designed in pieces, so that when a certain event occurs, a corresponding piece of CAPL code is
executed. These pieces of code are called event procedures. The CAPL Browser’s window is
organized to support creating these event procedures.

CAPL Reference Manual 47


Using the CAPL Browser

3.2.1 The File menu


The File menu contains commands for creating, saving, importing, and exporting source files.
You can also associate a CAN database or quit the CAPL Browser. Most of the commands in the
File menu conform to the normal Windows conventions.

New (Control-N) Create a new CAPL source code file. CAPL Browser opens a new, blank Browser
window. When you save or close this window, you will be asked for a file name.

Open (Control-O) Display a file selection dialog box in which you can select a CAPL
source file to open. If you enter the name of a file that does not exist, a new file is created
with this name. If CAPL Browser cannot display the file that you want to open, it will ask you
if you want to open the file in a text editor.

Close Close the active Browser window. If you have made changes to the currently open
file, the CAPL Browser will ask if you would like to save the changes before you close the file.

Save (Control-S) Save the active window. If you have not assigned a file name yet, you
will be prompted to name the file before it is saved.

Save as... Assign a file name and save the active window. You can use this command to
create another copy of the current source code window. If you specify a file name that is
already in use, you are asked if you would like to overwrite the original file.

Import Read in a program which was not developed in the CAPL Browser. During the
process, the CAPL Browser attempts to determine the structure of the program. If this fails,
then the CAPL Browser displays the file in one text window instead of the normal four CAPL
Browser windows.

Export Save a CAPL program in ASCII format. The output file does not contain any
structure information that is used by the CAPL Browser, and therefore is human readable. If
you wish to open this file in the CAPL Browser at a later time, you must use the Import
command discussed above.

Associate database Associate a database created with CANdb with this CAPL
program. This allows you to use symbolic names for message and pg identifiers, signal
names, environmental variables, and attributes that are defined in the database. Selecting
this command opens a new window that allows you to add, delete, and modify database
associations. Using this window you can associate several databases with your program.

Preview Show a preview of what will be printed on screen. This opens a new preview
window with buttons that allow you to scroll through the pages of your source code and
toggle between a one-page or two-page display. The red “x” button allows you to close the
print preview window.

CAPL Reference Manual 48


Using the CAPL Browser

Print Print your CAPL source code. This opens a window that allows you to select a
printer and which pages you would like to print.

Print Setup Modify printer settings. This opens a window that allows you to change
printer-specific options like paper size and orientation. This should be used before you print.

Exit (ALT-F4) Exit the CAPL Browser. If you have source files open with unsaved
changes, you will be prompted to save each file before the CAPL Browser exits.

CAPL Reference Manual 49


Using the CAPL Browser

3.2.2 The Edit menu


The Edit menu contains commands for editing the selected text, find and replace commands, and
commands to insert symbolic names from an associated database. Most of the commands in the
Edit menu conform to normal Windows conventions.

Undo (Control-Z) Although it is not listed in the Edit menu, the Undo command is
available in the CAPL Browser. To undo the last editing change that you made, press
Control-Z.

Cut (Control-X) Delete the selected text and save it in the clipboard. To put the text
back into your source file, use the Paste command.

Copy (Control-C) Copy the selected text to the clipboard without changing your source
code. To insert this text elsewhere in your source code, use the Paste command.

Paste (Control-V) Insert the text on the clipboard at the cursor location.

Delete (Delete key) Delete the currently selected text without copying it to the clipboard.

CAPL Function Insert the name of a CAPL function at the cursor location. A window is
opened that allows you to choose which function to insert. This command is also available by
using the right mouse button in the appropriate editing window.

CANdb Message Insert a symbolic message name from an associated database at the
cursor position. This command opens a new window that allows you to select the name of the
message that you wish to insert. This command is not available if no databases are
associated with the current source file.

CANdb Signal Insert a symbolic name for a signal from an associated database at the
cursor position. This command opens a new window that first requires you to select the
message containing the signal, and then the name of the signal. This command is not
available if no databases are associated with the current source file.

CANdb Variable Insert the name of an environmental variable from an associated


database at the cursor position. This command open a window that allows you to select the
environmental variable to insert. This command is not available if no databases are
associated with the current source file.

Find Search through the text in the current editing window for the text that you specify.
(This command does not search through your entire program.) Selecting this command
opens a window that allows you to set search options and enter the text that you want to find.
After pressing the “Find Next” button, the first match is highlighted on the screen. You can
continue to press the “Find Next” button to find each successive match.

CAPL Reference Manual 50


Using the CAPL Browser

Replace Replace specified text with new text in the current editing window. Selecting this
command opens a window that allows you to specify the text to replace and the new text as
well as other options. The “Find Next” button highlights the next match, and the “Replace”
button makes the replacement and highlights the next match. You can use these buttons to
selectively make replacements, since the “Find Next” button does not alter your source code.

Next Repeat the previously executed search action, whether it was done with the Find
command or the Replace command. This command only affects the current editing window.

3.2.3 The Procedure menu


The Procedure menu contains commands for creating and deleting CAPL procedures in the
Event Procedures window. The commands in this menu can also be accessed by right-clicking in
the Event Procedures window.

New Insert a new procedure into the Event Procedures list for the current event type.
This may not be available if you have already inserted the maximum number of procedures in
one category. For example, the ErrorFrame category can only have one event procedure
defined. If a category has predefined event names, then a submenu is opened next to the
New command to choose a predefined name.

Delete Delete the selected procedure from the Event Procedures window. All of the code
associated with this procedure is also deleted.

3.2.4 The Compiler menu


The Compile menu allows you to compile one or more CAPL programs and locate run-time errors
in your programs.

Compile (F9) Compile the selected CAPL program. See the section on compiling for
more information.

Compile All Compile all open CAPL programs. See the section on compiling for more
information.

Find runtime error Find a runtime error in your CAPL code. This command opens a
window that allows you to enter an error code reported by CANalyzer or CANoe and find the
place in your CAPL program where the error occurred.

CAPL Reference Manual 51


Using the CAPL Browser

3.2.5 The Options menu


The Options menu allows you to configure editor and compiler options.

Editor Open a window to allow you to change editor settings such as font, tab stops, and
tool bar display.

Compiler Allow you to toggle between the real-time and analysis branches for the placement of your
CAPL node. Some CAPL functions are not available in the real-time branch.

3.2.6 The Window menu


The Window menu allows you to arrange the windows on the screen, view the compiler
messages, and switch between currently open source files. Most of the commands in the Window
menu conform to normal Windows conventions.

Cascade Arrange the open windows in a cascading format.

Tile Displays all open windows, giving each an equal amount of the screen.

Arrange Icons Arrange minimized window icons along the bottom of the screen.

Close All Close all open windows.

Messages Bring the Compiler Messages window to the foreground.

3.2.7 The Help menu


The help menu allows you to access the online help and program information. Standard
Windows help files are used; the hypertext help files conform to normal Windows conventions.

Contents Open the table of contents for the CAPL Browser help.

Search Allows you to search the CAPL Browser’s help file.

Using Help Open a tutorial on using the Windows help system.

About Display version and copyright information for the CAPL Browser program.

CAPL Reference Manual 52


Using the CAPL Browser

3.2.8 The toolbar

The toolbar allows quick access to commands that are also available in the pull-down menus.
For more information on the commands, see the documentation in the respective pull-down menu
section. At times, certain buttons will be “grayed out” when they are not available for use. Often,
clicking the mouse in the correct window or selecting text will allow you to use the buttons.

CAPL Reference Manual 53


Using the CAPL Browser

3.2.9 The Global Variables window

The Global Variables window, in the upper right corner of the CAPL Browser, allows you to enter
global variables for your CAPL program. The advantage of having them in a separate window is
that they are always visible when you are editing your event procedures, and you can easily edit,
add, or remove a variable without losing your place in the code you are editing.

In this area, you can declare variables of any type inside the variables { . . . } construct.
You can use the right mouse button to activate a pull-down menu with editing options and the
ability to insert CAPL functions.

CAPL Reference Manual 54


Using the CAPL Browser

3.2.10 The Event Types window


The Event Types window, in the upper left corner of the CAPL Browser, list the categories of all
the event procedures that you can define. Left-clicking on one of the categories selects the
category and enables category-specific options in the Event Procedures window below.

Event Categories in the Event Types Window

Event Category Event Procedures

System preStart, start, stopMeasurement

CAN Controller busOff, errorActive, errorPassive, warningLimit

CAN Message Message reception events (user-defined)

Timer Timer expiration events (user-defined)

Keyboard Keypress events (user-defined)

ErrorFrame Error frame reception event

Environment Environmental variable change events (CANoe only) (user-defined)

Function User-defined functions (not true event procedures)

CAPL Reference Manual 55


Using the CAPL Browser

3.2.11 The Event Procedures window

System Event Message Event

The Event Procedures window, in the lower left corner of the CAPL Browser, lists the event
procedures defined for the event category currently selected in the Event Types window. Some
event categories allow only a small number of CAPL-defined functions (like System), while others
(like Message) allow you to define as many event procedures as you want (in this case,
corresponding to messages IDs received).
In this window, the right mouse button activates a menu that allows you to create or delete an
event procedure. For event categories that only allow CAPL-defined procedures, the New menu
option extends to a submenu which allows you to pick one of the CAPL-defined procedures.

CAPL Reference Manual 56


Using the CAPL Browser

3.2.12 The Procedure Editing window

The Procedure Editing window, in the lower right corner of the CAPL Browser, is the place where
you enter the code for your event procedures. After you create a new event procedure in the
Event Procedures window, a skeletal procedure is set up for you. In most cases, you need to fill
in the details of the procedure declaration. For example, if you choose to create a new “on
errorFrame” event procedure, the Procedure Editing window will have this code in it:

on errorFrame
{
}

This event procedure declaration is complete as it is and does not need to be modified. You can
begin writing you code between the braces. On the other hand, if you create a new message
event procedure, you are presented with this:

on message <newMessage>
{
}

This is the generic skeletal code for an “on message” event procedure, and you need to fill in the
identifier, replacing the text . After the identifier has been specified, then you
can begin writing the event procedure code between the braces.

CAPL Reference Manual 57


Using the CAPL Browser

3.3 Compiling your code


When you are ready to compile your code, either to test it for syntax errors or to use it in your
simulation, there are many ways to accomplish this. You can press the F9 key, choose Compile
or Compile All from the Compiler menu, or press the lightning bolt button. Choosing Compile All
compiles all of the CAPL programs that you currently have open in the CAPL Browser.
When you compile your code, you must assign a file name if you have not yet saved the code. A
window will open and you will be asked for the name and location of the *.CAN source code file.
Compiling turns the text-format *.CAN source file into a compiled binary file. The process creates
a *.CBF (CAPL Binary Format) file in the same directory as the *.CAN file. Note that you should
not delete the *.CAN file at this point. The CAPL Browser cannot read compiled *.CBF files.

3.4 Handling compilation errors


When a compilation error occurs, the CAPL Browser creates a Messages window and brings it to
the foreground. The Messages window contains a description of the first compilation error
encountered. The error message is highlighted with a blue line. Double-clicking on this line
causes the CAPL Browser to bring the source editing window to the foreground and place the
cursor on the line where the error occurred. After you fix the error, compile your code again. If
there is another error, then this process repeats. This allows you to step through and fix all of
your errors one by one.

3.5 Handling run-time errors


When you use the runError() function in your CAPL programs or an internal run-time error is
generated, a message is displayed in the Write window with an error number. The output in the
Write window looks like this:

Start of measurement 04:02:33 pm


Bus with 500000 BPS.
PRG (CAPL): < MYPROG > generated an error at CAPL pos: 1.
Locate with CAPL browser option: Find runError - err number -> 1.
Unknown error
measurement stopped
End of measurement 04:03:56 pm

The line that begins with “Locate with CAPL browser...” reports the error number following
the “->” (in this example, this line has been wrapped onto the next line). Using the Compile
menu, select the “Find runtime error” command and input the error number (in this example, the
error number is 1). The CAPL Browser will then show you where this run-time error occurred.

CAPL Reference Manual 58


Using the CAPL Browser

3.6 CAPL Source Development with Other Text Editors


The development of CAPL source programs is possible outside the CAPL Browser environment,
however, the CAPL Browser still must be used to compile source programs for use in the
CANalyzer or CANoe tool environments.
The ability to concurrently modify a CAPL program, a CANdb file (message database), and a
CANalyzer configuration file is possible using text editing features such as global search and
replace (on multiple files).
Since the essential file format of CAPL source programs is in text, CAPL programs may be
modified using other text editing programs. This capability remains as long as programmers do
not change the inherent CAPL-dependent structure of the file.

3.6.1 CAPL Source File Format


Each CAPL program section requires both a beginning and ending CAPL-specific line which
appears as a C source code comment. These special lines always begin with the same character
sequence, include a CAPL-specific name, and end with the same character sequence.
Beginning character sequence: /*@@xxx: */
Ending character sequence: /*@@end */
Where xxx is equal to a CAPL-specific section, procedure name, or equal to the word “end”.
For example, in the following CAPL source file, three sections have been defined. The first code
group establishes a section for variables, the second code group is for a timer called T1, and the
third is for the procedure related to the “tool” start event.

CAPL Reference Manual 59


Using the CAPL Browser

/*@@var: */
variables {
msTimer T1;
}
/*@@end */

/*@@timer:T1: */
on timer T1 {
message 100 M100 = {dlc=4, word(0) = 0xaaaa, word(2) = 0x5555};

setTimer(T1,50);
M100.byte(0) = M100.byte(0) + 1;
output(M100);
}
/*@@end */

/*@@startStart: */
on start {
setTimer(T1,50);
}
/*@@end */

There’s no special requirement for the spacing between the difference CAPL-specific sections
and any number of blank lines may be used in between procedures. Programmers that develop
CAPL source programs outside of the normal CAPL browser may further use comment fields to
enhance readability and potentially improve the documentation quality of CAPL programs.

CAPL Reference Manual 60


CAPL Functions

4 CAPL Functions

4.1 Using files input and output functions


CAPL provides three methods for accessing files inside your programs. The first method is to
use the writeToLog() or writeToLogEx() functions to output a string to a log file. The next method
is to use the set of input/output functions prefixed with “file”, such as fileWriteInt() and
fileReadString(). The last method is for sequential, read-only access to text files. This is
accomplished by using the functions prefixed with “seq”, such as seqFileLoad() and
seqFileGetLine(). When using one of the latter two methods, special set-up may be required to
ensure proper operation of the CAPL functions. The special set-up requirements are detailed in
the next two sections.

METHOD EXAMPLE FUNCTIONS READ/WRITE LIMITATIONS

Write to log file writeToLog() Write only


File I/O functions fileWriteInt(), Read and write Special set-up may be
required. Uses INI file
fileReadString format
Sequential file seqFileLoad(), Read only Special set-up is ()required.
function seqFileGetLine Can only be used in
P-Blocks in some locations.

CAPL Reference Manual 61


CAPL Functions

4.1.1 Set-up for file input and output functions


File I/O functions such as fileWriteInt() or fileReadString() cannot read or write from files on disk
in real time when they are used in the transmission branch of CANalyzer’s Measurement Setup
window or in CANoe’s Simulation Setup window. In order to be able to access the files,
CANalyzer or CANoe can read in the files before the simulation has started, modify the data in
memory, and write the files to disk after the simulation has ended.
Therefore, you must tell CAPL which files to load before the simulation begins. This is done by
creating or editing a file called CAPL.INI in the CANalyzer or CANoe system directory (e. g.
c:\canwin\exec). There are several commands that you should include in the file, which are listed
in the table below.
File load and save activity is logged in text format in CAPL.RES. This file is created in the same
directory as CAPL.INI (e. g. the EXEC or EXEC32 directory of CANalyzer or CANoe).

Command Argument Description


// arbitrary Can be used for comments

[CAPL-INI] None Put this line at the start of CAPL.INI


Display File names that are loaded are displayed in the
0 or 1 Write window at the start of the measurement
MaskCount An integer The number of file mask entries in this file
(Mask1, Mask2, etc.)
MaskX File name or mask File name(s) that will be accessed by CAPL
where X = 1 .. MaskCount. Each name should
include a full path and may contain wild cards
such as *and?.

CAPL Reference Manual 62


CAPL Functions

Here is an example of a CAPL.INI configuration:

[CAPL-INI]

// Turn on Write Window display to verify setup


Display=1

// Two file masks (Mask1 and Mask2) are defined


MaskCount=2

// Load all .DAT files in the data directory


Mask1=C:\usr\max\capldata\*.dat

// Load the setup.txt file


Mask2=C:\temp\setup.txt

Warning: Do not open or modify the WIN.INI or SYSTEM.INI files using CAPL's file functions.

Warning: Due to the way that INI files are parsed, comments must start at the beginning of
a new line. Otherwise, unpredictable results will occur.

CAPL Reference Manual 63


CAPL Functions

4.1.2 Set-up for sequential file access functions


CAPL offers functions for sequential read-only file access such as seqFileGetLine() and
seqFileGetBlock(). These functions are only available for use in nodes located in CANalyzer’s
simulation branch and CANoe’s simulation setup window.
Before calling these functions in your CAPL code, you must edit the CAN.INI file to specify the
path where the data files are located. The CAN.INI file is located in the CANalyzer or CANoe
system directory (e. g. c:\canwin\exec). Open the file with a text editor, and find a section that
looks like this:

[CAPL]

SeqFilePath=”C:\usr\max\capldata”
; working folder for files that are to be read from
; CAPL with seqFileLoad

When seqFileLoad() is called to open a file, the path specified inside the quotation marks is
searched for the file. If the file cannot be found in that directory, the system (e. g. EXEC or
EXEC32) directory is searched for the file. If CANalyzer or CANoe is running while you edit
CAN.INI, you must restart the program for your change to take effect.

CAPL Reference Manual 64


CAPL Functions

4.2 Function Compatibility


Not all CAPL functions are available in all P-Blocks. Specifically, many functions which would be
too slow to use in the real-time branches of CANoe and CANalyzer are not allowed in these
branches. In CANalyzer, the real-time branch is the transmission branch of the Measurement
Setup window.Setup window. In CANoe, the Simulation Setup window is the real-time branch.

Since the CAPL Browser cannot tell where the P-Block is placed in the setup window of
CANalyzer or CANoe, sometimes it will not compile CAPL programs containing some functions
(for example: setLogFilleName()). In this case, compile the CAPL program using the compile
option in CANalyzer or CANoe. This provides the compiler with the location of the P-Block,
allowing normally restricted function calls.

CAPL Reference Manual 65


CAPL Functions

4.3 CAPL Function Groups

File I/O Functions


fileReadArray Read an array of data from a file
fileReadFloat Read a floating point number from a file
fileReadInt Read an integer from a file
fileReadString Read a string from a file
fileWriteFloat Write a floating point number to a file
fileWriteInt Write an integer to a file
fileWriteString Write a string to a file

Sequential File Access Functions


seqFileClose Close a file opened by seqFileLoad()
seqFileGetBlock Read a block of characters from a file
seqFileGetLine Read a line from a file
seqFileGetLineSZ Read a line from a file (null-terminated)
seqFileLoad Open a file for reading
seqFileRewind Reset a file to read from the beginning

Environmental Variable Functions (CANoe Only)


getValue Read the value of an environmental variable
putValue Assign a value to an environmental variable
getValueSize Get the size of an environmental variable in bytes
callAllOnEnvVar Call all environmental variable procedures

Byte Conversion Functions


swapDword Re-order bytes of double (64 bit data type)
swapInt Re-order bytes of integer (8 bit data type)
swapLong Re-order bytes of long integer (32 bit data type)
swapWord Re-order bytes of word (16 bit data type)

CAPL Reference Manual 66


CAPL Functions

String Handling Functions


atol Convert a string to a long integer
ltoa Convert a number to a string
snprintf Create a formatted string
strlen Get the length of a string
strncat Concatenate two strings
strncmp Compare two strings
strncpy Copy a string

Math Functions
abs Calculate an absolute value
cos Calculate a cosine
exp Calculate an exponent
random Calculate a random value
sin Calculate a sine
sqrt Calculate a square root

Message Handling Functions


isExtId Check for extended identifier
isStdId Check for standard identifier
mkExtId Create extended identifier
output Ouput message, pg, or error frame onto the bus
setMsgTime Assign time to message (obselete)
valOfId Get the value of a message identifier

Timer Functions
cancelTimer Stop an active timer
setTimer Set a timer

CAPL Reference Manual 67


CAPL Functions

User Interface Functions


beep Make the system beep
fileName Output the program name in the Write window
keypressed Query currently depressed key
write Output text to the Write window
sysExit Exit CANalyzer or CANoe
sysMinimize Minimize CANalyzer or CANoe window

Logging Functions
setLogFileName Set the file name of the log file
setPostTrigger Set the posttrigger time for logging
setPreTrigger Set the pretrigger time for logging
trigger Activate logging triggering
writeToLog Write a formatted string to the log file

Measurement Setup and Control Functions


getCardType Determine the type of CAN platform being used
getChipType Determine the type of CAN controller being used
resetCan Reset the CAN controller
runError Trigger a run-time error
setBtr Set baud rate
setOcr Set the Output Control Register
stop Stop the measurement

Time Functions
timeDiff Calculate time difference between two messages
timeNow Get current system time
getLocalTime Get array time information
getLocalTimeString Get human-readable time string

CAPL Reference Manual 68


CAPL Functions

Node Control Functions (CANoe Only)


canOnline Reconnects node to the bus
putValue Disconnects node from bus

Port I/O Functions


inport Read a byte from a port
outport Send a byte to a port

Miscellaneous Functions
elCount Count the number of elements in an array

J1939-Specific Functions
getThisMessage Read data from a parameter group

CAPL Reference Manual 69


CAPL Functions

4.4 CAPL Function Compatibility

Real-Time Branches Analysis Branches

CANalyzer CANalyzer
CANoe CANoe
CANalyzer (Windows) (Windows)
Function Simulation Measurement
(DOS) Transmission Analysis
Setup Window Setup Window
Branch Branch

abs b b b b b
atol b b b b b
beep b b b b b
callAllOnEnvVar b b
cancelTimer b b b b b
canOffline b
canOnline b
cos b b b b b
elCount b b b b b
exp b b b b b
fileName b b b b b
fileReadArray b * * b b
fileReadFloat b * * b b
fileReadInt b * * b b
fileReadString b * * b b
fileWriteFloat b * * b b
getCardType b b b b b
getChipType b b b b b
(Continued on next page)
b= can be used
* = can be used if CAPL.INI or CAN.INI is configured correctly.

CAPL Reference Manual 70


CAPL Functions

Real-Time Branches Analysis Branches

CANalyzer CANalyzer
CANoe CANoe
CANalyzer (Windows) (Windows)
Function Simulation Measurement
(DOS) Transmission Analysis
Setup Window Setup Window
Branch Branch

getLocalTime b b
getLocalTimeString b b
getValue b
getValueSize b b
input b b b b b
isStdld b b b b b
keypressed b b b b b
Itoa b b b b b
mkExtld b b b b b
output b b b b b
putValue b b
random b b b b b
resetCan b b b
runError b b b b b
seqFileClose * *

seqFileGetBlock * *
seqFileGetLine * *
seqFileGetLineSZ b b
seqFileLoad b b
seqFileRewind b b
(Continued on next page)

b= can be used
* = can be used if CAPL.INI or CAN.INI is configured correctly.

CAPL Reference Manual 71


CAPL Functions

Real-Time Branches Analysis Branches

CANalyzer CANalyzer
CANoe CANoe
CANalyzer (Windows) (Windows)
Function Simulation Measurement
(DOS) Transmission Analysis
Setup Window Setup Window
Branch Branch

setBtr b b b
setLogFileName b b
setMsgTime b b b b b
setOcr b b b b b
setPreTrigger b b
setPostTrigger b b
setTimer b b b b b
sin b b b b b
snPrintf b b
sqrt b b b b b
stop b b b b b
strlen b b b b b
strncat b b b b b
strncmp b b b b b
strncpy b b b b b
swapDWord b b b b b
swaplnt b b b b b
swapLong b b b b b
swapWord b b b b b
(Continued on next page)

b= can be used
* = can be used if CAPL.INI or CAN.INI is configured correctly.

CAPL Reference Manual 72


CAPL Functions

Real-Time Branches Analysis Branches

CANalyzer CANalyzer
CANoe CANoe
CANalyzer (Windows) (Windows)
Function Simulation Measurement
(DOS) Transmission Analysis
Setup Window Setup Window
Branch Branch

sysExit b b
sysMinimize b b
timeDiff b b b b b
timeNow b b b b b
trigger b b b b b
valOfld b b b b b
write b b b b b
writeToLog b b b

b= can be used
* = can be used if CAPL.INI or CAN.INI is configured correctly.

CAPL Reference Manual 73


CAPL Functions

abs abs

Syntax int abs(int num);


long abs(long num);
double abs(double num);

Function This function returns the absolute value of a signed number. Note that this
function is not necessary for the unsigned byte type.

Parameter Number to be converted.

Returns Integer, long integer, or double. Return type matches the parameter type.

Example
int one = -1;
long two = -2;
double three = -3.0;

write(“%d %d %lf”, abs(one), abs(two), abs(three));

This prints “1 2 3.000000” in the Write window.

CAPL Reference Manual 74


CAPL Functions

atol atol

Syntax long atol(string s);

Function This function converts the string s to a long number. The number base is
decimal. If the string starts with “0x”, base 16 is used. Leading blanks are
discarded.

Parameter String to be converted

Returns Long integer

Example
...
long z1;
long z2;
z1 = atol(“200”);
z2 = atol(“0xFF”);
...

Result: z1 = 200, z2 = 255

See also ltoa

CAPL Reference Manual 75


CAPL Functions

beep beep

Syntax beep(int freq, int duration);

Function Output a tone to the computer’s speaker.

Parameters freq = integer for tone pitch.


duration = integer for tone duration

In the Windows version, the parameters freq defines the tone output.
Different sounds are defined in the section [SOUND] in the file WIN.INI:

freq = 0x0000 (SystemDefault)


freq = 0x0010 (SystemHand)
freq = 0x0020 (SystemQuestion)
freq = 0x0030 (SystemExclamation)
freq = 0x0040 (SystemAsterisk)
freq = 0xFFFF Standard Beep

Note If you do not have a sound card installed in your computer, Windows will generate
a normal system beep. In this case, the freq parameter has no effect.

Returns none

Example
void sound() {
// with soundcard: 400 Hz beep
// without soundcard: standard system beep
beep (400,0);
}

See also write

CAPL Reference Manual 76


CAPL Functions

callAllOnEnvVar callAllOnEnvVar

Syntax callAllOnEnvVar();

Function Calls all event procedures for environment variables (onEnvVar). This can
be necessary at the start of measurement to initialize environment variables,
to start timers activated in response to changes of environment variables, or
to send messages on the bus with the start values of the environment
variables.

Parameters none

Returns none

Example on start
{
callAllOnEnvVar();
}

See also putValue


getValue

CAPL Reference Manual 77


CAPL Functions

cancelTimer cancelTimer

Syntax cancelTimer(msTimer t);


cancelTimer(timer t);

Function Stops an active timer that has been set with setTimer(). This prevents the
timer event procedure from being executed. If called on a timer that is not
set, this function has no effect.

Parameter timer or msTimer variable

Returns none

Example
variables {
msTimer msgTimer;
message dataMsg dMsg;
}

on timer msgTimer {
send(dMsg);
setTimer(msgTimer, 200);
}

on key F1 {
cancelTimer(msgTimer); // cancel timer
write(“msgTimer canceled”);
}

on key F2 {
setTimer(msgTimer, 200); // set timer to 200 ms
write(“msgTimer started”);
}

See also setTimer

CAPL Reference Manual 78


CAPL Functions

canOffline canOffline

Syntax canOffline();

Function Cuts the connection between the node and the bus. Messages sent from the
node are not passed through to the bus. The function canOnline() will
restore the connection to the bus.

Parameters none

Returns none

Example ...

canOffline();

...

See also canOnline

Compatiblity This function can only be used in nodes in CANoe’s Simulation Setup
window.

CAPL Reference Manual 79


CAPL Functions

canOnline canOnline

Syntax canOnline();

Function Restores the connection of the node to the bus. After a call to the function
canOffline() the node can be connected to the bus with the function
canOnline(). Messages sent from the node are passed through to the bus.

Parameters none

Returns none

Example ...

canOnline();

...

See also canOffline

Compatibility This function can only be used in nodes in CANoe’s Simulation Setup
window.

CAPL Reference Manual 80


CAPL Functions

cos cos

Syntax double cos(double x);

Function Calculate cosine of x

Parameter Value (in radians) whose cosine is to be calculated.

Note To convert degrees to radians, multiply degrees by PI/180.

Returns Cosine of x.

Example
double x;
x = cos(PI); // result -1, PI is a built-in
constant

double tangent(double x) {
return sin(x) / cos(x);
}

See also sin


sqrt
exp

CAPL Reference Manual 81


CAPL Functions

elCount elCount

Syntax long elCount(...);

Function Determines the number of elements in one dimension of an array. See ex


ample for usage with multi-dimensional arrays.

Parameter Array of any type

Returns Number of elements in the array

Example
// One-dimensional array
void bsp(int ar[]) {
int i;
for(i=0; i < elCount(ar); i ++)
...
}

// Two-dimensional array
void bsp2(byte ar[][]) {
int i, j;
for(j=0; j < elCount(ar); j ++ )
for(i=0; i<= elCount(ar[j]); i ++ )
...
}

Note: For the two-dimensonal array, elCount(ar) is used to get the number of elements in the
first dimension and elCount(ar[j]) is used to get the number of elements in the second
dimension.

See also runError


strlen

CAPL Reference Manual 82


CAPL Functions

exp exp

Syntax double exp(double x);

Function Calculate the value of the exponential function with a given degree

Parameter Exponent to base e

Example
double x;
x = exp(1.0); // Result: 2.7182...

See also cos


sin
sqrt

CAPL Reference Manual 83


CAPL Functions

fileName fileName

Syntax fileName();

Function Output the name of the CAPL program in the Write window. Helpful for
debugging purposes.

Parameters none

Returns none

Example
...
fileName();
...

Result: output of actual filename of CAPL program to write window

See also runError

CAPL Reference Manual 84


CAPL Functions

fileReadArray fileReadArray

Syntax long fileReadArray(string section, string entry,


string buffer, long bufferlen, string file);

Function Searches for the variable entry in the section section of the file file. Its
contents are interpreted as a list of byte values. The number format is
decimal or with the prefix 0x it is hexadecimal. Numbers are separated by
spaces, tabs, a comma, semi-colon or slash. The buffer is filled up to a
quantity of bufferlen bytes.

Parameters section = section of file


entry = name of variable
buffer = buffer for characters to be read
bufferlen = size of buffer in byte
file = name of data file
(backslashes should be doubled, i.e. “C:\\TEMP\\DATA.LOG”)

Returns Number of characters read.

Note This function is equivalent to the fileReadString() function. Since there is not
a corresponding fileWriteArray() function, you can use fileWriteString() to
write formatted strings to a data file that can later be read with
fileReadArray() or fileReadString().

Example
Data in TEST.INI:
[DATA]
FIELD=1,2,3,0x20,100

CAPL Code:
...
int len;
char buf[20];
len = fileReadArray(“DATA”, “FIELD”, buf, elCount(buf), “TEST.INI”);
...

Result: len = 5. The array buf is filled with the values 1,2,3,32,100.

CAPL Reference Manual 85


CAPL Functions

See also fileReadInt


fileReadFloat
fileReadString
fileWriteInt
fileWriteFloat
fileWriteString

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 86


CAPL Functions

fileReadFloat fileReadFloat

Syntax float fileReadFloat(string section, string entry,


float def, string file);

Function Searches for the variable entry in the section section of the file filename. If
its value is a number, this number is returned as the functional result. If the
file or entry is not found, or if entry does not contain a valid number, the
default value def is returned as the functional result.

Parameters section = section of file


entry = name of variable
buffer = buffer for characters to be read
bufferlen = size of buffer in byte
file = name of data file
(backslashes should be doubled, i.e.”C:\\TEMP\\DATA.LOG”)

Returns The floating point number read if it is found in the data file, otherwise the
value of the def parameter.

Example
Data in TEST.INI:
[DATA]
VOLUME=3.3000

CAPL Code:
...
float vol;
vol = fileReadFloat(“DATA”, “VOLUME”,0,“TEST.INI”);
...

Result: vol contains the value read or 0 if the data item was not found in the
datas file.

See also fileReadArray


fileReadIntfileReadString
fileWriteInt
fileWriteFloatfileWriteString

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 87


CAPL Functions

fileReadInt fileReadInt

Syntax long fileReadInt(string section, string entry, long


def, string file);

Function Searches for the variable entry in the section section of the file filename. If
its value is a number, this number is returned as the functional result. If the
file or entry is not found, or if entry does not contain a valid number, the
default value def is returned as the functional result.

Parameters section = section of file


entry = name of variable
def = value
file = name of data file
(backslashes should be doubled, i.e.”C:\\TEMP\\DATA.LOG”)

Returns The integer read if it is found in the data file, otherwise the value of the def
parameter.

Example
Data in TEST.INI:
[DATA]
ADDR=200

CAPL Code:
...
myAddress=fileReadInt(“DATA”,“ADDR”,0, “TEST.INI”);
...

Result: The value 2 is assigned to the variable myAddress. If the entry ADDR
does not exist in the file TEST.INI the default value 0 is assigned to
myAddress.

See also fileReadArray


fileReadFloat
fileReadString
fileWriteInt
fileWriteFloat
fileWriteString

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 88


CAPL Functions

fileReadString fileReadString

Syntax long fileReadString(string section, string entry,


string def, string buffer, long bufferlen,
string filename);

Function Searches for the variable entry in the section section of the file filename. Its
content (value) is written to the buffer buffer. Its length must be passed
correctly to bufferlen. If the file or entry is not found, the default value def is
copied to buffer.

Parameters section = section of file


entry = name of variable
def = value
buffer = buffer for characters to be read
bufferlen = size of buffer in byte
file = name of data file
(backslashes should be doubled, i.e.”C:\\TEMP\\DATA.LOG”)

Returns Number of bytes read

Example
Data in TEST.INI:
[DATA]
NAME=Marty

CAPL Code:
...
int len;
char buf[20];
fileReadString(“DATA”, “NAME”, buf, elCount(buf), “TEST.INI”);
...

Result: buf is filled with the characters “Marty”.

See also fileReadArray


fileReadInt
fileReadFloat
fileWriteInt
fileWriteFloat
fileWriteString

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 89


CAPL Functions

fileWriteFloat fileWriteFloat

Syntax long fileWriteFloat(string section, string entry,


float def, string file);

Function Opens the file filename, finds the section section and writes the variable
entry with the value value. If entry already exists, the old value is
overwritten. The functional result is 1 for success, or 0 for an error.

Parameters section = section of file


entry = name of variable
def = value
file = name of file (backslashes should be doubled, i.e. “C:\\TEMP\\DATA.LOG”)

Returns 0 if an error has occurred else 1

Example
...
if(!fileWriteFloat(“DeviceData”, “DeviceAddr”, 2.2, “TEST.INI”))
write(“Error writing DeviceAddr to TEST.INI”);
...

This call writes the following entry in the file TEST.INI:


[DeviceData]
DeviceAddr=2.2

See also fileReadArray


fileReadInt
fileReadFloat
fileReadString
fileWriteInt
fileWriteString

CAPL Reference Manual 90


CAPL Functions

fileWriteInt fileWriteInt

Syntax long fileWriteInt(string section, string entry,


long def, string file);

Function Opens the file filename, finds the section section and writes the variable
entry with the value value. If entry already exists, the old value is
overwritten. The functional result is 1 for success, or 0 for an error.

Parameters section = section of file


entry = name of variable
def = value
file = name of file (backslashes should be doubled, i.e. “C:\\TEMP\\DATA.LOG”)

Returns 0 if an error has occurred else 1

Example
...
if(!fileWriteInt(“DeviceData”, “DeviceAddr”, 2, “TEST.INI”))
write(“Error writing DeviceAddr to TEST.INI”);
...

This call writes the following entry in the file TEST.INI:


[DeviceData]
DeviceAddr=2

See also fileReadArray


fileReadInt
fileReadFloat
fileReadString
fileWriteFloat
fileWriteString

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 91


CAPL Functions

fileWriteString fileWriteString

Syntax long fileWriteString(string section, string entry,


string value, string filename);

Function Opens the file filename, finds the section section and writes the variable
entry with the value value. If entry already exists, the old value is
overwritten. The functional result is the number of characters written, or 0 for
an error.

Parameters section = section of file


entry = name of variable
value = string to write
filename = name of data file (backslashes should be doubled, i.e.
C:\\TEMP\\DATA.LOG”)

Returns Number of written characters of 0 if an error has occurred.

Example
if(!fileWriteString(“Device”, “DeviceName”, “LPT1”, “test.ini”))
write(“File error”);
...

This call writes the following entry in the file TEST.INI:


[Device]
DeviceName=LPT1

See also fileReadArray


fileReadInt
fileReadFloat
fileReadString
fileWriteInt
fileWriteFloat

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 92


CAPL Functions

getCardType getCardType

Syntax long getCardType();

Function Determines the type of CAN platform being used. Is needed e.g. to program
the BTR (Bit Timing Register) and OCR (Output Control Register) values.

Parameters None

Returns Type of board as one of the following values:

0 DBB196 - Daimler-Benz Board with FullCAN


1 DBB196B – Daimler-Benz Board with BasicCAN
2 CANIB - Bosch CANIB
3 DEMO - Demo driver
6 CANAC2 - Softing AC2/200/ANA
7 CANAC2X - Softing AC 2/527/ANA
8 CPC/PP - EMS wish module
9 INDIGO - Silicon Graphics Indigo2
10 CANCARD - PCMCIA 11 Bit
11 CANCARDX - PCMCIA 29 Bit
12 CANAC2B - Softing AC2/527 11 Bit
13 VAN462 - NSI VAN card
14 VANDEMO - VAN Demo driver

Additional types may be added in future versions of CAPL.

CAPL Reference Manual 93


CAPL Functions

Example
...
switch(getCardType()) {
case 6: setOcr(0,0x02); // CANAC2
break;
case ...
default:
write(“Unknown driver %d”, getCardType());
break;
}
...

See also getChipType

CAPL Reference Manual 94


CAPL Functions

getChipType getChipType

Syntax long getChipType(long channel);

Function Determines the type of CAN controller used.

Parameter channel:
0 = both controllers
1 = Channel 1
2 = Channel 2

Returns Type of controller with the following values:

5 NEC 72005
200 Philips PCA82C200
462 MHS29C462 VAN Controller
526 Intel 82526
527 Intel 82527

Other types may occur. Demo versions return the result 0 or simulate one of
the existing types. If an attempt is made to access a nonexistent channel
(e.g. Channel 2 for CPC/PP) or if the driver used does not support this
function, the functional result is 0.

Example
...
switch(getChipType( )) {
case 200: setOcr(0,0x02); // Philips PCA82C200
break;
case ...
default:
write(“Unknown CAN chip type: %d”,
getChipType());
break;
}
...

See also getCardType

CAPL Reference Manual 95


CAPL Functions

getLocalTime getLocalTime

Syntax getLocalTime(long timeArray[]);

Function Fills an array of type long with details of the date and time.

The entries of the array will be filled with the following information:

Array entry Meaning Range of values


timeArray[0] Seconds 0 – 59

timeArray[1] Minutes 0 – 59

timeArray[2] Hours 0 – 23

timeArray[3] Day of the month 1 – 31

timeArray[4] Month of year 0 – 11 (January is 0, etc.)

timeArray[5] Year (since 1900) 0...

timeArray[6] Day of week 0 – 6 (Sunday is 0, etc.)

timeArray[7] Day of year 0 – 365


timeArray[8] Daylight Savings Time 0 = Not Daylight Savings Time
1 = Daylight Savings Time

Parameters An array of type long with at least 9 entries.

Returns Nothing

CAPL Reference Manual 96


CAPL Functions

Example long timeArray[9]; // Array to hold time information

getLocalTime(timeArray);

write(“It is %d:%d:%d on %d/%d/%d.”,


timeArray[2], timeArray[1], timeArray[0],
timeArray[4] + 1, timeArray[3], timeArray[5]);

Above code prints:


It is 16:23:31 on 8/25/99.

See also getLocalTimeString

Compatiblity This function can only be used in P-Blocks located in the analysis branch of
CANalyzer’s Measurement Setup window or in P-Blocks in CANoe’s Mea
surement Setup window.

CAPL Reference Manual 97


CAPL Functions

getLocalTimeString getLocalTimeString

Syntax getLocalTimeString(char timeBuffer[]);

Function Copies a string representation of the current date and time into the supplied
character buffer. The format of the string is
ddd mmm dd hh:mm:ss yyyy (e.g., “Fri Aug 21 15:22:24 1998").
The string is null-terminated.

Parameters The buffer in which the string will be written. This buffer must be at least
26 characters long. Unpredictable results will occur if the buffer is not
at least 26 characters long.

Returns none

Example ...
char timeBuffer[64];

getLocalTimeString(timeBuffer);

// The timeBuffer will now contain, for


// example, Fri Aug 21 15:22:24 1998
...

See also getLocalTime

Compatiblity This function can only be used in P-Blocks located in the analysis branch of
CANalyzer’s Measurement Setup window or in P-Blocks in CANoe’s Mea
surement Setup window.

CAPL Reference Manual 98


CAPL Functions

getThisMessage getThisMessage

Syntax getThisMessage(pg pg_variable, int length);

Function Transfers the this parameter group to the indicated parameter group pg. The
number of bytes of the transmitted parameter group data is given by length.

This function must be used exclusively within the program block, and is only
used with J1939 buses.

Parameters Variable of the type “pg”,


Length entry of the type “int”

Return None

Example
pg TC1 pg_tc1; // Definition of a parameter group

on pg * { // Event procedure for all parameter


// groups
if (pg.pgn == TC1) {// If the received parameter group is
// TC1
// Transfer the received parameter group to the variable
GetThisMessage(pg_tc1, pg_tc1.dlc);
}

CAPL Reference Manual 99


CAPL Functions

getValue getValue

Syntax int getValue(EnvVarName);


float getValue(EnvVarName);
getValue(EnvVarName, char buffer[]);

Function Determines the value of the environment variable with identifier


EnvVarName. The type of the return value is based on the type of
environment variable (int for discrete (Form 1), float for continuous
environment variables (Form 2)). For character string environment variables
(Form 3) the active value is saved to a buffer which you identify in the
function call.

Parameters Environment Variable name for Forms 1 and 2. Environment variable name
and return buffer for Form 3.

Returns Active value of the environment variable for Forms 1 and 2. No return value
for Form 3.

Example
int val;
float fval;
char buff[25];

...

// Assign to val the value of the environment


// variable “Switch”
val = getValue(Switch);

// Assign to fval the value of


// the environment variable “Temperature”
val = getValue(Temperature);

// Read the value of environment variable


“NodeName”
val = getValue(NodeName, buff);

See also putValue

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 100


CAPL Functions

getValueSize getValueSize

Syntax int getValueSize(EnvVarName);

Function Returns the size of the environmental variable in bytes. For environmental
variables of type string, the string length plus the terminating null charac
ter will be returned.

Parameters Environment variable name

Returns Size of the data in bytes

Example // Size of an environment variable of


// data type integer:

int varSize;

...

varSize = getValueSize(switch);

See also getValue


putValue

CAPL Reference Manual 101


CAPL Functions

inport inport

Syntax byte inport(word addr);

Function Read in a byte from a port.

Parameter Port address.

Returns Byte that was read in.

Note The built-in constants LPT1, LPT2, and LPT3 can be used as a port address.

Example
...
val = inport(0x3f8); // Reads port 0x3f8
...

See also outport

CAPL Reference Manual 102


CAPL Functions

isExtId isExtId

Syntax long isExtId(dword id);


long isExtId(message m);

Function Checks parameter for extended identifier (29 bit)

Parameters Variable of type “message” or message ID number

Returns 1 if extended ID, else 0

Example
Passing the message ID as a parameter:
on message * {
if (isExtId(this.ID))
write(“Message with 29-bit identifier
received.”);
}

Passing the message variable as a parameter:


on message * {
if (isExtId(this))
write(“Message with 29-bit identifier
received.”);
}

See also isStdId

CAPL Reference Manual 103


CAPL Functions

isStdId isStdId

Syntax long isStdId(dword id);


long isStdId(message m);

Function Checks parameter for standard identifier (11 Bit).

Parameters Variable of type “message” or message ID number

Returns 1 if standard ID, else 0

Example
Passing the message ID as a parameter:
on message * {
if (isStdId(this.ID))
write(“Message with 11-bit identifier
received.”);
}

Passing the message variable as a parameter:


on message * {
if (isStdId(this))
write(“Message with 11-bit identifier
received.”);
}

See also isExtId

CAPL Reference Manual 104


CAPL Functions

keypressed keypressed

Syntax dword keypressed();

Function This function returns the key code of a currently pressed key. If no key is
being pressed it returns 0. Only one key can be pressed at a time.

Parameters None

Returns Key code of pressed key. If the 8 lower bits do not equal 0, keypressed
returns the ASCII code of the next key in the keyboard buffer. If the 8 lower
bits do not equal 0, the 8 upper bits represent the extended key code (see
IBM PC Technical Reference Manual).

Example
variables {
msTimer mytimer; // timer
message 100 msg; // CAN message
}

on key F1 {
setTimer(mytimer,100); // start 100 ms
timer
write(“F1 pressed”); // output to write
window
}

on timer mytimer {
if(keypressed()) { // True if any key is
pressed
setTimer(mytimer,100); // restart timer
output(msg); // send while
keypressed
}
else {
write(“F1 let go”);
}
}

CAPL Reference Manual 105


CAPL Functions

ltoa ltoa

Syntax ltoa(long val, string s, long base);

Function The number val is converted to a string s. In this case, base indicates a
number base between 2 and 36. s must be large enough to accept the
converted number!

Parameters val = number to be converted

s = string, which will contain the converted number

base = numeric base

Returns none

Example
...
long z = 255;
char s1[9];
char s2[9];
ltoa(z, s1, 2); // binary
ltoa(z, s1, 10); // decimal
...
Result: s1 = 11111111, s2 = 255

See also atol

CAPL Reference Manual 106


CAPL Functions

mkExtId mkExtId

Syntax dword mkExtId(dword id);

Function Generate an extended (29-bit) message identifier from a standard (11-bit)


message identifier.

Parameter Message identifier

Returns Extended message identifier

Example
...
msg.id = mkExtId(this.id);
...

See also isExtId


isStdId
valOfId

CAPL Reference Manual 107


CAPL Functions

outport outport

Syntax outport(word addr, byte value);

Function Output a byte to a port.

Parameters Port address or “LPT1”/”LPT2"/”LPT3" and value to be output..

Returns none

Note The built-in constants LPT1, LPT2, and LPT3 can be used as a port address.

Example
...
outport (0x3f8, 12); // Outputs 12 to port 0x3f8
outport (LPT2, ‘x’); // Outputs ‘x’ to LPT2
...

See also inport

CAPL Reference Manual 108


CAPL Functions

output output

Syntax output(message msg);


output(errorFrame);
output(pg pg_msg);

Function Outputs a message, an error frame, or a parameter group from the program
block onto the CAN bus.

Parameters Variable of type message, errorFrame, or pg.

Returns none

output(msg) Example
variables {
message can2.125 msg = { // declare CAN-Message
dlc = 1,
byte(0) = 1
};
}

on key F1 {
output (msg); // output Message to CAN 2
}

output(errorFrame) Example
on key F10 {
output(errorFrame); // output error frame to CAN1
}

output(pg) Example
variables {
pg DashDisplay dDisplay;
}

on key F9 {
dDisplay.FuelLevel.phys = 75;
output(dDisplay);
}

CAPL Reference Manual 109


CAPL Functions

putValue putValue

Syntax putValue(EnvVarName,int val);


putValue(EnvVarName,float val);
putValue(EnvVarName,char val[]);

Function Assigns the value val to the environment variable with identifier
EnvVarName. Integers are assigned to discrete environment variables,
floating point numbers are assigned to continuous environment variables, and
character strings are assigned to character string environment variables.

Parameters Environment variable name, new value of environment variable

Returns None

Example
// Assign the value 0 to environment variable
“Switch”
putValue(Switch,0);

// Assign the value 22.5 to environment


// variable “Temperature”
putValue(Temperature,22.5);

// Assign the value Master to environment


// variable “NodeName”
val = getValue(NodeName,”Master”);

See also getValue

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 110


CAPL Functions

random random

Syntax dword random(dword x);

Function Calculates a random value n such that 0 <= n < x.

Parameter Upper limit for the random value.

Returns The random value.

Example
...
dword randVal;
randVal = random(101); // Get a value 0..100
...

CAPL Reference Manual 111


CAPL Functions

resetCan resetCan

Syntax resetCan();

Function Resets the CAN controller. Can be used to reset the CAN controller after a
BUSOFF or to activate configuration changes. Since execution of the
function takes some time and the CAN controller is disconnected from the
bus briefly, messages can be lost when this is performed.

Parameters none

Returns none

Example
on key ‘r’ { // Controller is reset when ‘r’ key is
pressed
resetCan();
}

See also setOcr


setBtr

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 112


CAPL Functions

runError runError

Syntax runError(long err, long);

Function Triggers a run error. Outputs the error number to the Write window indicating
the error number and the passed number, and then terminates the
measurement.

Parameters Numbers that are represented in CANalyzer as a references for the user.
The values under 1000 are reserved for internal purposes. The second
parameter is reserved for future expansion. Currently, the second parameter
can be any number.

Returns none

Example
...
if(rpm < 0) runError(1001,1);
...

See also elCount

CAPL Reference Manual 113


CAPL Functions

seqFileClose seqFileClose

Syntax long seqFileClose(long fileHandle);

Function This function closes the file specified by the long integer fileHandle. The file
handle is assigned by the seqFileLoad() function. All buffers allocated by the
system are freed upon closing.

Parameters The file handle of the file to close.

Returns The function returns zero with success. If the operation fails, it returns
non-zero error code.

Example long fileHandle;


long errorCode;

fileHandle = seqFileLoad(“capl.dat”);
...
errorCode = seqFileClose(fileHandle);

if (errorCode == 0)
{
write(“File closed.”);
}
else
{
write(“Error number %d closing file.”, errorCode);
}

See also seqFileLoad


seqFileRewind
seqFileGetBlock
seqFileGetLine
seqFileGetLineSZ

Compatibility This function can only be used in P-Blocks in CANalyzer’s transmission


branch and CANoe’s simulation setup window.

CAPL Reference Manual 114


CAPL Functions

seqFileGetBlock seqFileGetBlock

Syntax long seqFileGetBlock(char buffer[],


dword bufferSize, long fileHandle);

Function The function reads at most bufferSize characters from the file specified
byhandle file into the array buffer. Newline characters are read into the
buffer.The file position indicator is advanced by the number of characters
successfully read.

Parameters buffer = a character array to put file data into


bufferSize = the size of the buffer in characters
fileHandle = the file handle long integer assigned by seqFileLoad()

Returns The return value is the number of characters successfully read, which may
be less than bufferSize if the end-of-file is encountered. The value is
negative when an error occurs.

Example char buffer[10];


long fileHandle;
long charsRead;

fileHandle = seqFileLoad(“capl.dat”);
charsRead = seqFileGetBlock(buffer, 10,fileHandle);

if (charsRead >= 0)
{
write(“Characters read: %d”, charsRead);
}
else
{
write(“Error %d reading from file.”, charsRead);
}

See also seqFileLoad


seqFileRewind
seqFileGetBlock
seqFileGetLine
seqFileGetLineSZ
seqFileClose

Compatibility This function can only be used in P-Blocks in CANalyzer’s transmission


branch and CANoe’s simulation setup window.

CAPL Reference Manual 115


CAPL Functions

seqFileGetLine seqFileGetLine

Syntax long seqFileGetLine(char buffer[],


dword bufferSize, long fileHandle);

Function The function reads at most bufferSize-1 characters from the file with the
handle file into the array buffer. No more characters are read after a newline
character or after end-of-file. The function retains the newline character, but
the line is not null-terminated. A null must be placed into the character array
after the data if the buffer is to be used as a string.

Parameters buffer = a character array to put file data into


bufferSize = the size of the buffer in characters
fileHandle = the file handle long integer
assigned by seqFileLoad()

Returns The number of characters successfully read, or a negative error code if the
operation fails.

Example char buffer[100];


long fileHandle;
long charsRead;

fileHandle = seqFileLoad(“capl.dat”);
charsRead = seqFileGetLine(buffer, 100,fileHandle);

if (charsRead >= 0)
{
write(“Characters read: %d”, charsRead);

// Add a null to end before printing


buffer[charsRead] = 0;
write(“The string read: %s”, buffer);

}
else
{
write(“Error %d reading from file.”, charsRead);
}

CAPL Reference Manual 116


CAPL Functions

See also seqFileLoad


seqFileRewind
seqFileGetBlock
seqFileGetLineSZ
seqFileClose

Compatibility This function can only be used in P-Blocks in CANalyzer’s transmission


branch and CANoe’s simulation setup window.

CAPL Reference Manual 117


CAPL Functions

seqFileGetLineSZ seqFileGetLineSZ

Syntax long seqFileGetLineSZ(char buffer[],


dword bufferSize, long fileHandle, unsigned
long nullTerm);

Function The function reads at most bufferSize-1 characters from the file with the
handle file into the array buffer. No more characters are read after a newline
character or after end-of-file. The function retains the newline character, and
the line is terminated by a null character.

Parameters buffer = a character array to put file data into


bufferSize = the size of the buffer in characters
fileHandle = the file handle long integer assigned by seqFileLoad()
nullTerm = A boolean value. Setting this value to 1 means to terminate the
line with a null. 0 means do not terminate the line with a null.

Returns The number of characters successfully read, or a negative error code if


the operation fails.

Example char buffer[100];


long fileHandle;
long charsRead;

fileHandle = seqFileLoad(“capl.dat”);
charsRead = seqFileGetLineSZ(buffer, 100,fileHandle, 1);

if (charsRead >= 0)
{
write(“Characters read: %d”, charsRead);
write(“The line read: %s”, buffer);
}
else
{

write(“Error %d reading from file.”, charsRead);


}

CAPL Reference Manual 118


CAPL Functions

See also seqFileLoad


seqFileRewind
seqFileGetBlock
seqFileGetLine
seqFileClose

Compatibility This function can only be used in P-Blocks in CANalyzer’s transmission


branch and CANoe’s simulation setup window.

CAPL Reference Manual 119


CAPL Functions

seqFileLoad seqFileLoad

Syntax long seqFileLoad(char fileName);

Function This function opens the file whose nameis the string pointed to by the
name.The file will be opened as read-only.

Parameters The name of the file, data type ‘char’

Returns The file handle. The return value is <= 0 if an error occurs.

Note The function searches the file in the path given by the SeqFilePath entry in
the [CAPL] section of the CAN.INI initialization file. If the entry does not
exist, the file is searched in the application directory (Exec/Exec32). Any
drive and path information provided in the parameter is ignored.

Example ...
long fileHandle;

fileHandle = seqFileLoad(“setup.txt”);

if (fileHandle <= 0)
{
write(“Error number %d opening setup.txt.”, fileHandle);
}
else
{
write(“setup.txt opened with file handle %d”, fileHandle);
}
...

See also seqFileRewind


seqFileGetBlock
seqFileGetLine
seqFileGetLineSZ
seqFileClose

Compatibility This function can only be used in P-Blocks in CANalyzer’s transmission


branch and CANoe’s simulation setup window. The CAN.INI file must be
properly set up before using this function.

CAPL Reference Manual 120


CAPL Functions

seqFileRewind seqFileRewind

Syntax long seqFileRewind(long fileHandle);

Function This function sets the file position indicator to the beginning of the file speci
fied by the handle file.

Parameters The file handle of the file to rewind. The handle is assigned by
seqFileLoad().

Returns The function returns zero if successful. If the operation fails, it returns anon-
zero error code.

Example long fileHandle;


long errCode;

fileHandle = seqFileLoad(“setup.txt”);

...

errCode = seqFileRewind(fileHandle);

if (errCode == 0)
{
write(“setup.txt rewind successful.”);
}
else
{
write(“Rewind failed.”);
}

See also seqFileLoad


seqFileRewind
seqFileGetBlock
seqFileGetLine
seqFileGetLineSZ
seqFileClose

Compatibility This function can only be used in P-Blocks in CANalyzer’s transmission


branch and CANoe’s simulation setup window.

CAPL Reference Manual 121


CAPL Functions

setBtr setBtr

Syntax setBtr(long channel, byte btr0, byte btr1);

Function Sets the baud rate. The values do not become active until the next call of the
function resetCan().The function can also be used to automatically determine
the baud rate. It should be noted that these values depend on the CAN
controller used.

Parameters CAN-Channel: 0 = both controllers


1 = Channel 1
2 = Channel 2

BTR0: Value of Bit Timing Register 0

BTR1: Value of Bit Timing Register 1

Returns none

Example
...
setBtr(0, 0x00, 0x3a); // 500 kBaud for 82C200
resetCan(); // activate
...

See also resetCan


setOcr

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 122


CAPL Functions

setLogFileName setLogFileName

Syntax setLogFileName(string fileName);

Function Set the name of the logfile.

Parameters New name of the logfile. The name may be an absolute path or a single
filename. If a path is supplied, the path must exist prior to the start of the
simulation. If the path does not exist, the call to setLogFileName() will be
gnored. The logfile will be placed in the directory of the current configuration,
if a single filename is supplied. The directories of the path must be separated
by a double backslash (‘\\’). The filename must not contain a file extension.
The extension will be set automatically based on the type of log file (.ASC for
ASCII or .LOG for binary).

Returns none

Example
...
setLogFileName(“newlog”);
...

Set the name of the logging file to “newlog” in the directory of the current
configuration.

...
setLogFileName(“c:\\canw\\demo\\automot\\newlog”);
...

Set the absolute path of the logging file. The path c:\canw\demo\automot
must be created before the simulation begins.

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 123


CAPL Functions

setMsgTime setMsgTime

Syntax setMsgTime(message m1, NOW);


setMsgTime(message m1, message m2);

Function Assigns to the message m1 the capture time of message m2 or the current
time. This function is obsolete and only serves to establish compatibility with
older versions.

Parameters Variable of type message and another variable of type message or “now”.

Returns none

Note This function has been made obsolete by the TIME message selector. See
the section on message selectors for more information.

CAPL Reference Manual 124


CAPL Functions

setOcr setOcr

Syntax setOcr(long channel, byte ocr);

Function Sets the CAN controller’s Output Control Register. The values do not become
active until the next call of the function resetCan().
It should be noted that these values depend on the CAN platform used.

Parameters CAN-Channel: 0 = both controllers


1 = Channel 1
2 = Channel 2

OCR: Value of the Output Control Registers

Returns none

Example
...
setOcr(0, 0x02); // set
resetCan(); // activate
...

See also resetCan


setBtr

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 125


CAPL Functions

setPostTrigger setPostTrigger

Syntax setPostTrigger(long preTriggerTime);

Function Set the posttrigger of the logging. The posttrigger set with this function is
valid until the end of the measurement or until the next call of this function.

Parameters New posttrigger value in milliseconds. If a value of -1 is supplied, the


prosttrigger will be set to infinity.

Returns 1, if the posttrigger is set to the given value, 0 else.

Example
// Set the posttrigger time of the logging to 2.5 seconds.
...
setPostTrigger(2500);
...

// Set the posttrigger of the logging to infinity.


...
setPostTrigger(-1);
...

See also setPreTrigger


trigger

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 126


CAPL Functions

setPreTrigger setPreTrigger

Syntax setPreTrigger(long preTriggerTime);

Function Set the pretrigger of the logging. The pretrigger set with this function is valid
until the end of the measurement or until the next call of this function.

Parameters New pretrigger value in milliseconds.

Returns 1, if the pretrigger is set to the given value, 0 else.

Example
...
setPreTrigger(25);
...
Set the pretrigger time of the logging to 25 milliseconds.

See also setPostTrigger


trigger

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 127


CAPL Functions

setTimer setTimer

Syntax setTimer(msTimer t, long duration);


setTimer(timer t, long duration);

Function Set a timer, which can be either Timer type or msTimer type.

Parameters Variable of type Timer or msTimer and the duration of the timer in units of
seconds or milliseconds, respectively.

Returns None

Example
variables {
Timer t1;
}

on start {
setTimer(t1, 5); // Initialize a 5-second cyclic timer
}

on timer t1 {
. . .
setTimer(t1, 5); // Reset timer for another 5 seconds
}

CAPL Reference Manual 128


CAPL Functions

sin sin

Syntax double sin(double x);

Function Calculate sine of x.

Parameters Value in radians whose sine is to be calculated.

Note To convert degrees to radians, multiply degrees by PI/180.

Returns Sine of x

Example
double x;
x = sin(PI); // x equals 0, PI is a built-in
constant

double tangent(double x) {
return sin(x) / cos(x);
}

See also cos


exp
sqrt

CAPL Reference Manual 129


CAPL Functions

snprintf snprintf

Syntax long snprintf(string dest, long len, string format, ...);

Function This function corresponds to the C function sprintf. In addition, the


parameter len indicates the maximum length of the array dest. The overall
length of the resulting string dest may not exceed 100.

Parameters Similar to the write() function, this function can take a variable number of
arguments. There should be an additional parameter after the format
parameter for each of the string formatting expressions used in the format
string. The string formatting expressions are the same used for the write()
function and are listed here:

Legal String Formatting Expressions


"%ld" or "%d" decimal display
"%lx" or "%x" hexadecimal display

"%lX" or "%X" hexadecimal display (with upper case letters)

"%lu" or "%u" unsigned display

"%lo" or "%o" octal display

"%s" display a string

"%g" or "%lf" floating point display

"%c" display a character

"%%" display %-character

Returns The length of the destination string.

CAPL Reference Manual 130


CAPL Functions

Example
char infoStr[100];
int vol = 55;
byte bal = 3;
long res;

res = snprintf(infoStr, 100, “Volume = %d, Balance = %u”, vol, bal);

Result: res = 24, infoStr = “Volume = 55, Balance = 3”

See also write

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 131


CAPL Functions

sqrt sqrt

Syntax double sqrt(double x);

Function Calculate the square root of the parameter

Parameter Value whose square root is to be calculated

Example
double x;
x = sqrt(4.0); // Result 2.0

See also cos


sin
exp

CAPL Reference Manual 132


CAPL Functions

stop stop

Syntax stop();

Function Programmed interrupt of the ongoing measurement

Parameters none

Returns none

Example
...
if( isExtId(this) )
stop(); // End measurement if we find an extended
ID
...

See also trigger

CAPL Reference Manual 133


CAPL Functions

strlen strlen

Syntax long strlen(string s);

Function Determine the length of string s.

Parameters String to find length of.

Returns Length of string.

Example
...
length = strlen(“CANalyzer”);
...
Result: length = 9

See also strncat


strncpy
strncmp

CAPL Reference Manual 134


CAPL Functions

strncat strncat

Syntax strncat(string dest, string src, long len);

Function This function appends src to dest. The function ensures that there is a
terminating ‘\0’ in the dest string. Thus, a maximum of len- 1 characters are
copied.

Parameters dest = Original string (that this function adds to).


src = String to append to dest.
len = the maximum length of the resulting string.

Returns None. The resulting string is contained in dest.

Example
...
string s1 = {“Vector”};
string s2 = {“CANalyzer”};
strncat(s1,s2,16);
...

Result: s1 = “VectorCANalyzer”

See also strlen


strncpy
strncmp

CAPL Reference Manual 135


CAPL Functions

strncmp strncmp

Syntax long strncmp(string s1, string s2, long len);

Function This function compares s1 with s2 for a maximum of len characters.

Parameters s1 and s2 - strings to compare


len - number of characters to compare. Can usually be set to the length of
the longest string.

Returns -1 if s1 < s2
0 if s1 = s2
1 if s2 > s1

Example
...
if(strncmp(s1, s2, strlen(s1))
write(“not equal”);
else
write(“equal”);
...

See also strlen


strncat
strncpy

CAPL Reference Manual 136


CAPL Functions

strncpy strncpy

Syntax strncpy(string dest, string src, long len);

Function This function copies src to dest. len indicates the maximum length of src and
dest. The function ensures that there is a terminating ‘\0’. Thus, a maximum
of len-1 cahracters are copied.

Parameters dest - String to copy src to.


src - Original string.
len - Number of characters to copy + 1 (usually the length of src plus 1).

Returns None. The string dest is updated.

Example
...
string s1 = {“Vector”};
string s2 = {“CANalyzer”};
strncpy(s1, s2, strlen(s2) + 1);
...

Result: s1 = “CANalyzer”

See also strlen


strncat
strncmp

CAPL Reference Manual 137


CAPL Functions

swapDWord swapDWord

Syntax dword swapDWord(dword x);

Function Swaps bytes of parameters. CAPL arithmetic follows the little-endian-format


(Intel). The swap-functions serve for swapping bytes for the transition to and
from the big-endian-format (Motorola).

Parameters Value whose bytes are to be swapped.

Returns Value with swapped bytes.

See also swapInt


swapLong
swapWord

CAPL Reference Manual 138


CAPL Functions

swapInt swapInt

Syntax int swapInt(int x);

Function Swaps bytes of parameters. CAPL arithmetic follows the little-endian-format


(Intel). The swap-functions serve for swapping bytes for the transition to and
from the big-endian-format(Motorola).

Parameters Value whose bytes are to be swapped.

Returns Value with swapped bytes.

See also swapDword


swapLong
swapWord

CAPL Reference Manual 139


CAPL Functions

swapLong swapLong

Syntax long swapLong(long x);

Function Swaps bytes of parameters. CAPL arithmetic follows the little-endian-format


(Intel). The swap-functions serve for swapping bytes for the transition to and
from the big-endian-format (Motorola).

Parameters Value whose bytes are to be swapped.

Returns Value with swapped bytes.

See also swapDword


swapInt
swapWord

CAPL Reference Manual 140


CAPL Functions

swapWord swapWord

Syntax word swapWord(word x);

Function Swaps bytes of parameters. CAPL arithmetic follows the little-endian-format


(Intel). The swap-functions serve for swapping bytes for the transition to and
from the big-endian-format (Motorola).

Parameters Value whose bytes are to be swapped.

Returns Value with swapped bytes.

See also swapDword


swapInt
swapLong

CAPL Reference Manual 141


CAPL Functions

sysExit sysExit

Syntax sysExit();

Function Exits the system (CANalyzer or CANoe) from within a CAPL program.

Parameters none

Returns none

Example ...

sysExit();

...

See also sysMinimize

Compatibility This function can only be used in P-Blocks in CANalyzer’s analysis branch or
in CANoe’s Measurement Setup window.

CAPL Reference Manual 142


CAPL Functions

sysMinimize sysMinimize

Syntax sysMinimize();

Function The application window of CANalyzer or CANoe will be minimized or re


stored. The first call of the function minimizes the window; afterwards the
window will be restored to normal size, then the next time minimized, etc.

Parameters none

Return none

Example ...

sysMinimize();

...

See also sysExit

Compatibility This function can only be used in P-Blocks in CANalyzer’s analysis branch or
in CANoe’s Measurement Setup window.

CAPL Reference Manual 143


CAPL Functions

timeDiff timeDiff

Syntax long timeDiff(message msg1, NOW);


long timeDiff(message msg1, message msg2);

Function Time difference between messages or between a message and the current
time in ms (msg2 - msg1 or now - msg1).

Note Starting with CANalyzer 2.0, this difference can be calculated directly using
the TIME message selector. See the section on message selectors for more
details.

Parameters A variable of type message as the first parameter, and then another
message variable or “NOW” as the second parameter.

Returns Time difference in ms

CAPL Reference Manual 144


CAPL Functions

timeNow timeNow

Syntax dword timeNow();

Function Returns the current system time

Parameters none

Returns Time since the start of the current measurement in units of 10 µsec. This
time is established with the help of the PC timer with a resolution of 1 msec.
Message times determined by the CAN PC-card have greater precision and
are therefore not directly comparable to timeNow().

Example
...
float x;
x = timeNow()/100000.0; //current time in seconds
...

See also timeDiff

CAPL Reference Manual 145


CAPL Functions

trigger trigger

Syntax trigger();

Function Activates logging.

This function is not allowed in all CAPL blocks. It can be used in program
blocks and as CAPL trigger.

Parameters none

Returns none

Example on message 100 {


write(“logging start”);
trigger(); // start logging
setTimer(logging,1000); // for 1000 ms
}

See also stop


setPreTrigger
setPostTrigger

CAPL Reference Manual 146


CAPL Functions

valOfId valOfId

Syntax long valOfId(dword id);


long valOfId(message m);

Function Returns the value of a message identifier independent of its type.


Identifier as long value

Parameters Variable of the type “message” or Id portion of a message

Returns Identifier as long value

Example
...
id = valOfId(this); // works with ext-id as well
...

See also isExtId


isStdId
mkExtId

CAPL Reference Manual 147


CAPL Functions

write write

Syntax write(string format, ...);

Function Outputs a text message to the Write window. Write is based on the C
function “printf”.

The compiler cannot check the format string. Illegal format entries will lead
to undefined results.

Parameters The write() function allows a variable number of parameters. The format for
the parameters is a format string containing string formatting expressions
followed by zero or more arguments, each of which corresponds to one of
The string formatting expressions are shown below:

Legal String Formatting Expressions


"%ld" or "%d" decimal display

"%lx" or "%x" hexadecimal display

"%lX" or "%X" hexadecimal display (with upper case letters)

"%lu" or "%u" unsigned display

"%lo" or "%o" octal display

"%s" display a string

"%g" or "%lf" floating point display

"%c" display a character

"%%" display %-character

Returns none

CAPL Reference Manual 148


CAPL Functions

Example
void display() {

int i = 10;
int j = 25;

write (“d = %ld, h = 0x%lx”,i,j);


}

Result: “d = 10, h = 0x19”


See also writeToLog
snprintf

CAPL Reference Manual 149


CAPL Functions

writeToLog writeToLog

Syntax writeToLog(string format, ...)

Function Writes on output string to an ASCII logging file. Write is based on the C
function “printf”. Data is only written to a log file when logging is enabled in
CANalyzer or CANoe. A call to this function is ignored when logging is
disabled. The compiler cannot check the format string. Illegal format entries
will lead to undefined results.

Parameters The writeToLog() function allows a variable number of parameters. The


format for the parameters is a format string containing string formatting
expressions followed by zero or more arguments, each of which corresponds
to one of the string formatting expressions. The string formatting expressions
are shown below:

Legal String Formatting Expressions


"%ld" or "%d" decimal display

"%lx" or "%x" hexadecimal display

"%lX" or "%X" hexadecimal display (with upper case letters)

"%lu" or "%u" unsigned display

"%lo" or "%o" octal display

"%s" display a string

"%g" or "%lf" floating point display

"%c" display a character

"%%" display %-character

Returns none

CAPL Reference Manual 150


CAPL Functions

Example
void MarkLogFile(int marker) {
// marks line of ASCII logging file with an
integer
writeToLog(“===> %d”, marker);
}

Result of MarkLogFile(3) as seen in an ASCII log file:


// 0.000 ===> 3

Note that the 0.000 indicates the time since the start of the simulation that
the log file entry was made in units of seconds.

See also write


snprintf
trigger
setLogFileName

Compatibility This function has restricted compatibility. Please see the function
compatibility chart for more details.

CAPL Reference Manual 151


CAPL Programming Examples

5 CAPL PROGRAMMING EXAMPLES

In this chapter, we will show examples of common programming tasks with CAPL. It is a good
idea to skim through the examples in this section to become familiar with what it contains so you
can refer to it later as a reference. Some examples build on examples and ideas from other
sections, so you might need to refer to more than one section to get a complete answer to your
question.

5.1 Sending an Event Message


You can send a message (or multiple messages) on any event, for example, a keypress, the
reception of another message, the reception of an error frame, or a timer expiring. Sending an
event message involves creating an event procedure, declaring a message to send, and sending
the message in the event procedure.
The message can be declared as a global variable so that it can be accessed in any event
procedure. As shown in the message object section, you can declare a message’s structure in
your program or you can use an associated database. In this example, we will declare one of
each in the Global Variables window (upper right corner).
variables {
message EngineData msg1; // Defined in database
message 0x101x msg2; // Extended message 101 (hex)
}

Now, to send a message, we only need to put one of these lines into an event procedure:
output(msg1);
output(msg2);

Of course, we can also add data to the message before we send it. The EngineData message
has signals defined in the database, but the other message does not. Therefore, we have to use
two different methods to add data to the messages.
msg1.EngSpeed.phys = 1000;
msg1.EngTemp.phys = 150;
msg1.IdleRunning = 1;
output(msg1);

msg2.DLC = 4; // Allocate 4 data bytes in msg2


msg2.word(0) = 0x165; // First word is 165 hex
msg2.word(1) = 747; // Second word is 747 decimal
output(msg2);

CAPL Reference Manual 152


CAPL Programming Examples

Notice that the phys modifier was used on msg1’s signals, because they had conversion formulae
defined in the associated database. The phys modifier was not used on the IdleRunning signal
because it is a one-bit signal with no conversion formula defined.
Statements like these (assigning data to messages and using output() to send them) can be
used in most event procedures, such as:
on key someKey { . . . }
on envVar someVar { . . . }
on message someMsg { . . . }
on errorFrame { . . . }
on Timer someTimer { . . . }
on start { . . . }

To define an event procedure, you must first select the corresponding category in the Event
Types window (upper left corner). Then, right-click in the Event Procedures window and select
New from the menu. Refer to the chart in the Events section of the manual for a list of event
types and corresponding event procedures.

5.2 Sending a Periodic Message


Sending a periodic message requires setting up a timer and using the timer event procedure to
send the message and reset the timer.
First, declare a timer in the Global Variables window (upper right corner). You can use a Timer
object for a seconds-based timer or an msTimer object for a milliseconds-based timer. You
should also define a global variable to contain the period for the timer. If you need to change the
timer’s period, it is much easier if you only need to change the value in one location in your code.
We will also declare a message as a global variable, but like the timer period variable, this is not
necessary to declare globally.
variables {
. . .
msTimer periodicTimer; // Set up an ms-based timer
long timerPeriod = 100; // Period will be 100ms

// We can declare any kind of message we want


// to send, but for simplicity’s sake, we will
// just make one up with 1 byte of data.
message 101 msg = { dlc = 1 };

. . .
}

CAPL Reference Manual 153


CAPL Programming Examples

Next, we need to initialize the timer in the start event procedure. If you do not yet have a start
event, select System from the Event Types window (upper left corner). Then right-click in the
Event Procedures window (lower left corner) and select Start from the New submenu. You will
see the on start event procedure created in the Event Procedure window (lower right corner).
After you are in the on start event procedure, you should add a setTimer command to
initialize the timer for the first time. If you do not do this, the timer event never occurs. Also,
make sure to use the global variable containing the period (timerPeriod in this case) with the
setTimer() function instead of the actual value (100 in this case).

on start {
. . .
setTimer(periodicTimer, timerPeriod);
. . .
}

As soon as the timer is set, it is activated and begins to count down. When the count reaches
zero, the corresponding on timer event procedure is executed. We need to create this event
procedure now. In the Event Types window (upper left corner), select Timer. Then, right-click in
the Event Procedures window (lower left corner) and choose New. In the Procedure Editing
window (lower right corner), you will see that a skeletal event procedure has been created.
To write your own event procedure, first replace the <newTimer> string with the name of the
timer you have declared (periodicTimer in this case). Then, write the code to send the message
in the body of the procedure. Finally, add a setTimer function call at the end of the body of code.

on timer periodicTimer
{
// We can send out whatever data we want here.
msg.byte(0) = 6;

output(msg);

// Again, use the global variable to set the


// timer instead of a variable
setTimer(periodicTimer, timerPeriod);
}

CAPL Reference Manual 154


CAPL Programming Examples

5.3 Sending a Conditionally Repetitive Message


Sending a conditionally repetitive message is a common task in distributed systems. A
conditionally repetitive message is a message that is sent periodically while a condition is true,
but is not sent when the condition is false. One example of this is sending out a message every
few milliseconds while a window button on a car door is held down to keep moving the window
up, but then not sending any messages while the button is not held down.
Obviously, we will need to use a periodic timer like the one used above, but there is an added
level of complexity. We could simply check the condition inside of the timer event procedure
above, but this is slow and could cause problems if we have several conditions we are trying to
monitor at the same time.
If you are using CANoe, the better way to implement this is to take advantage of CAPL’s ability to
execute an event procedure when an environmental variable changes. To implement this, we
need to declare an environmental variable event procedure and a timer event procedure.
The timer event procedure will look like the one in the section above. We also have to declare
the same environmental variables, of course. We will also have to create the environmental
variable procedure. To do this, select Environment in the Event Types window (upper left
corner). Then, right-click in the Event Procedures window (lower left corner) and select New.
Now, you should see a skeletal environmental variable procedure in the Procedure Editing
window (lower right corner). Replace the string <newEnvVar> with the name of the
environmental vari able (we will use buttonStatus in this case) by right-clicking in the Procedure
Editing Menu and choosing CANdb Variable. The environmental variable buttonStatus will have
two possible values: 0 when the button is not pressed and 1 when the button is pressed.

on buttonStatus
{
int val;
val = getValue(this); // Get the value of buttonStatus

if (val == 0)
{
// Going from “on” state to “off” state
cancelTimer(periodicTimer);
}
else
{
// Going from “off” state to “on” state
setTimer(periodicTimer, timerPeriod);
}
}

CAPL Reference Manual 155


CAPL Programming Examples

Since this event procedure is executed when the value of buttonStatus changes, we are either
changing from a “on” state to an “off” state or vice versa. Going to the “on” state means setting
the periodic timer so that the timer event procedure, which actually sends the periodic message,
is executed. While we remain in the “on” state, the timer event procedure resets the timer every
time it executes. Going to the “off” state means stopping the timer so that the timer event
procedure is not executed until we change states again.
As a final note, we also need to make sure that the system is initialized in the correct state. For
example, if the button is being held down while the system is started, we will not execute an
environmental variable event procedure until the button is released. Therefore, we could miss an
entire button press, no matter how long the button is held down. We also do not want to set the
timer in the on start event procedure like we did for a normal periodic message, because that
implies that the button is depressed when the system is started.
Using the CallAllOnEnvVar() function in the on start event procedure gives us the desired results.
CAPL provides this function for use in initialization routines to allow us to check the values of
environmental variables. CallAllOnEnvVar() executes the event procedures for every
environmental variable that has an event procedure defined. Using this, we will be able to
determine the state of the button at startup and act accordingly. Our on start event procedure
now looks like this:

on start {
. . .
// The setTimer() call is no longer used here.
CallAllOnEnvVar();
}

5.4 Responding to a Received Message


To respond to a received message, set up an on message event procedure. To do this, select
CAN-Message in the Event Types window (upper left corner). Then, right-click in the Event
Procedures window (lower left corner) and select New. You should see a skeletal on message
event procedure in the Procedure Editing window (lower right). Next, you must tell CAPL which
message or messages to respond to with this procedure by replacing the <newMessage> string.
The complete guide to defining message event procedures can be found in the Events section of
this manual. The important rules to remember are that you can use wildcards and ranges, and
only the most specific event procedure is executed for each message received. So if you have
an on message * event procedure defined and an on message 101 event procedure
defined, only the latter is executed when message 101 is received.
You can also use symbolic message names (instead of message ID numbers) as message
specifiers. To do this, remove the <newMessage> string and then right-click where it was.
Select CANdb Message from the pull-down menu and choose the symbolic name of the message
from the list. The message name will be inserted into your CAPL program.

CAPL Reference Manual 156


CAPL Programming Examples

Once you have created the on message event procedure, any code that you wish to execute in
response to this message should go in the body of the event procedure. You could send out
another message or print the a message to the screen:
on message ABSdata, EngineData
{
message WheelInfo wMsg; // Define a new message

// Print a message to the screen


write(“Message %lX received on CAN%ld”, this.ID,
this.CAN);

// Send out another message


output(cdMsg);

5.5 Reading the Data within a Received Message


Once you have set up your on message event procedure (as shown above), you can read the
data contained in the message received. In the Message Objects section of this manual, there is
an explanation of the two ways to access data. You can either use symbolic signal names
defined in an associated database or use raw byte, word, or long word access to the data. Here
is an example of reading the data out of a message, and analyzing it using symbolic names:
on message EngineData
{

long product;

// Read EngSpeed and EngTemp signals


product = this.EngSpeed.phys * this.EngTemp.phys;

write(“The product of the engine speed and”);


write(“engine temperature is %

Note the use of the “phys” modifier to ensure that conversion formula defined in the database are
used to get the true values of the speed and temperature.
Alternately, you can access the raw bytes of data in the message received. This is a quick way to
access messages with simple structures or to copy blocks of data from one message to another.
Suppose that the EngineTemp message was defined as having one byte of data and we did not
define any signal names for it in the database. We could then create this on message event
procedure:

CAPL Reference Manual 157


CAPL Programming Examples

on message EngineTemp
{
byte value;
float temp;

value = this.byte(0);

// Scale the number so we get 2 decimal places


temp = float / 100;

write(“The temperature is %lf degrees.”, temp);


}

Since we did not define a signal for this byte of data, there is no conversion formula and we
cannot use the “phys” modifier. This is important to remember — if the number needs to be
scaled or otherwise adjusted, you need to do it yourself when accessing raw data bytes.

5.6 Responding to a message after a delay


Sometimes, it is useful to respond to a message after a period of time has passed. For example,
after the door closes in a car, a message might be sent saying that the door is now closed. A few
seconds later, the dome light would react to this message by turning off. To respond after a
delay, you must use both a timer event procedure and a message event procedure.
First, we need a timer and delay variable declared in the global variables section:
variables {
. . .
Timer delayTimer; // Seconds-based timer
long delayTimerPeriod = 5; // Delay of 5 seconds
}

Next, we need to create the message event procedure which sets the timer if the doors are
closed. In the Event Types window (upper left corner), select CAN-Message. Then, in the Event
Procedures window (lower left corner), right-click and select New. You should see a skeletal
message event procedure in the Procedure Editing window (lower right corner). For this
example, we will change the string <newMessage> to doorState:
on message doorState {

if (this.Closed == 1)
setTimer(delayTimer, delayTimerPeriod);
else
{
. . . // Do this if doors are open
}
}

CAPL Reference Manual 158


CAPL Programming Examples

Finally, we will create the timer event procedure which will actually turn off the light five seconds
later. In the Event Types window (upper left corner), select Timer. Then, in the Event
Procedures window (lower left corner), right-click and select New. You should see a skeletal
timer event procedure in the Procedure Editing Window (lower right corner). For this example,
we will change the string <newTimer> to delayTimer:
on timer delayTimer
{
message DomeLight dlMsg;
dlMsg.Status = 0; // Turn off dome light
output(dlMsg);
}

5.7 Sending an Error Frame


To send an error frame, the same output() function is used as when sending a message or pg.
Simply place this line of code in the event procedure where you want an error frame sent onto the
bus on CAN1:
output(errorFrame);

For example, if we wanted to send an error frame every time the “e” key was pressed, we could
define an on key event procedure. To do this, select Keyboard in the Event Types window
(upper left corner). Then, right-click in the Event Procedures window (lower left) and choose
New. You should then see a skeletal event procedure in the Procedure Editing window (lower
right corner). Replace the string <newKey> with the character that we wish to make the event
occur (in this case, ‘e’). Then, simply add the line mentioned above to the body of the event
procedure.

{
output(errorFrame);
}

CAPL Reference Manual 159


CAPL Programming Examples

5.8 Responding to an Error Frame


To respond to an error frame, you need to create an on errorFrame event procedure. Within
this event procedure, you can include code to do anything that is an appropriate response to an
error frame. To create the event procedure, select ErrorFrame in the Event Types window (upper
left corner). Then, right-click in the Event Procedures window (lower left corner) and choose
New. (Note: You can only have one on errorFrame event procedure defined, so if you
already have one, you can modify or add to it.) At this point, you should see a skeletal on
errorFrame event procedure. In the body, you can add your code:
on errorFrame
{

// Print a message in the Write window


write(“Error frame detected.”);

// Turn on logging for 1000 milliseconds


trigger();
setTimer(logging, 1000);

// Make a noise.
beep();

// Send out a blip on the parallel port.


// (This is useful if you have a scope
// attached to the port.)
outPort(LPT1,1);
outPort(LPT1,0);

5.9 Responding to User Keyboard Inputs


To respond to a keyboard input, you must create a keyboard event procedure. To do so, select
Keyboard in the Event Types window (upper left corner). Then right-click in the Event
Procedures window (lower left corner) and select New. You should then see a skeletal on key
event procedure in the Procedure Editing window (lower right corner).
The string <newKey> can be replaced with the value of the key or keys that you want to cause
the event. This value can be a single character, a wildcard, a key’s ASCII numeric value, or a
symbolic value. The value is called a specifier. This is covered in more detail in the Events
section, but here are some examples:

on key * { . . . } // Any key


on key 71 { . . . } // Capital “G” only
on key altEnd { . . . } // Alt-End

CAPL Reference Manual 160


CAPL Programming Examples

Recall that if more than one specifier matches a keystroke, only the best matching event
procedure is executed. So if the above event procedures were all defined and the user pressed
the “j” key, the event procedure would be executed, but the on key * event
procedure would not.
Inside the event procedure itself, you can write any legal CAPL code. For example, you could
print a message to the Write window, send a message on the bus, or increment a variable’s
value.

5.10 Measuring the Time Between Periodic Messages


Sometimes, if is helpful to measure the time between periodic messages sent by another node on
the bus to verify that the node is functioning correctly. There are two ways to calculate the time
between messages.
The first method is to use the TIME message selector. We need to create an on message event
procedure that is executed when a specific periodic message is received. For this example, we
will be looking for message 101 hex. First, select CAN-Message in the Event Types window
(upper left corner). Then right-click in the Event Procedures window (lower left corner) and select
New. You should now see a skeletal on message event procedure in the Procedure Editing
window (lower right corner). We replace the string <newMessage> with 0x101 and enter this
code:
on message 0x101
{
long lastTime = 0;

write(“Message 0x101 recevied at %ld”, this.TIME);


write(“Time interval = %lf milliseconds”,
(this.TIME - lastTime) / 100.0);

lastTime = this.TIME;
}

The TIME message selector returns the time since the current simulation was started as a long
integer in units of 10 microseconds. Therefore, we divide the value by 100 to get the time in
milliseconds. Since all of CAPL’s procedure variables are static, the lastTime variable retains the
value of the time the last message was received from the last time this procedure was called.

CAPL Reference Manual 161


CAPL Programming Examples

The second method of calculating the time between periodic messages is to use CAPL’s
timeDiff() function. This function can either take two messages as parameters or one message
and the keyword NOW.
In order to use the function, we will need to save a copy of the last periodic message received. In
this example, the we are looking for message 202 hex, so we will declare one instance of the
message globally in the Global Variables window (upper right):
variables {
message 0x202 saveMsg;
. . .
}

Then, we will create the on message event procedure. First select CAN-Message in the Event
Types window (upper left corner). Then right-click in the Event Procedures window (lower left
corner) and choose New. You should then see a skeletal event procedure in the Procedure
Editing window (lower right). We replaced the string <newMessage> with 0x202 and entered this
code:
on message 0x202
{
write(“Message 0x202 received at % this.TIME);
write(“Time interval = %ld milliseconds”,
timeDiff(saveMsg, this));

saveMsg = this; // saveMsg declared globally


}

The major differences when using the timeDiff() function is that you work with whole message
objects (instead of just one variable) and that it automatically converts the units to milliseconds.
Pragmatically, the timeDiff() function has been made obsolete by the TIME message selector.

5.11 Responding to the Bus Off Condition


To respond to the Bus Off condition in one of the CAN controllers on your CAN hardware
interface, you must set up an event procedure. To do so, select CAN Controller in the Event
Types window (upper left corner). Then, right-click in the Event Procedures window (lower left
corner) and select BusOff in the New submenu. You should see a skeletal event procedure in the
Procedure Editing window (lower right corner):
on busOff
{
}

You can put any legal CAPL code into the body of this procedure. In this procedure, you might
want to activate logging, call the stop() function, or print a message to the Write window.

CAPL Reference Manual 162


CAPL Programming Examples

5.12 Responding to the Error Passive Condition


To respond to the Error Passive condition in one of the CAN controllers on your CAN hardware
interface, you must set up an event procedure. To do so, select CAN Controller in the Event
Types window (upper left corner). Then, right-click in the Event Procedures window (lower left
corner) and select ErrorPassive in the New submenu. You should see a skeletal event procedure
in the Procedure Editing window (lower right corner):
on errorPassive
{
}

You can put any legal CAPL code into the body of this procedure. In this procedure, you might
want to activate logging, call the stop() function, or print a message to the Write window.

5.13 Responding to the Error Active Condition


To respond to the Error Active condition in one of the CAN controllers on your CAN hardware
interface, you must set up an event procedure. To do so, select CAN Controller in the Event
Types window (upper left corner). Then, right-click in the Event Procedures window (lower left
corner) and select ErrorActive in the New submenu. You should see a skeletal event procedure
in the Procedure Editing window (lower right corner):
on errorActive
{
}

You can put any legal CAPL code into the body of this procedure. In this procedure, you might
want to activate logging, call the stop() function, or print a message to the Write window.

5.14 Logging Single Module Conversation


Sometimes, it is useful to separate one node from the bus and attach a CAN hardware interface
(with CANalyzer or CANoe) between that node and the rest of the bus. Since CAN messages do
not inherently contain information about the sender of the message, this allows you to see all of
the messages originating from the isolated node and all of the messages (from the rest of the
bus) that the isolated node sees.
In order to accomplish this, you have to use both CAN channels on your CAN hardware interface.
One channel is connected to the isolated node (we will say CAN1 in this example), and the other
channel (CAN2) is connected to the rest of the bus.
The on message event procedure can be used to intercept messages received on either CAN
channel. You can then do any processing that is necessary and send the message out the other
CAN channel:

CAPL Reference Manual 163


CAPL Programming Examples

on message CAN1.* // Called when a message recv’d on CAN1


{
if (isExtID(this.ID))
writeToLog(“Extended ID %lX recv’d from node.”,
this.ID);
else
writeToLog(“Message ID %lX recv’d from node.”, this.ID);

this.CAN = 2; // Output to the opposite CAN channel


output(this);
}

on message CAN2.* // Called when a message recv’d on CAN2


{
if (isExtId(this.ID))
writeToLog(“Extended ID %lX recv’d from bus.”, this.ID);
else
writeToLog(“Message ID %lX recv’d from bus.”, this.ID);

this.CAN = 1; // Output to the opposite CAN channel


output(this);
}

Of course, you could substitute any code for the writeToLog() calls. Also, you do not have to
output the messages to the opposite CAN channel — there are many possibilities for this
configuration.

5.15 Using Random Inputs to Exercise a System


It is often useful to use random inputs to test a system. This can be done to simulate human
interaction, i.e. button presses, sensors, switches, and the like. CAPL provides a random()
function which you can use as the basis for a random input generator. By combining timers with
random numbers, random inputs can be achieved by sending messages on the bus or by
changing the value of environmental variables.
We will show an example of a system that uses two rolls of the die to determine how long to wait
between inputs and which input to use. If you are using CANoe, your inputs will probably
correspond to environmental variables. However, if you are using CANalyzer, your inputs will
probably be in the form of messages.
For this example, we will use a set of three different inputs. The first will be an environmental
variable, the second a CAPL-declared message, and the third a database-defined message. The
environmental variable, as required, is defined in the associated database. We need to declare
a timer to keep track of when the next random input should occur. Finally, we declare
maxMsDelay and minMsDelay to represent the maximum and minimum number of milliseconds
between random inputs. The following code is from the Global Variables window (upper right
corner).

CAPL Reference Manual 164


CAPL Programming Examples

variables {
// Env. variable button1 declared in database

// Message to carry dial1 position


message 555 dial1 = { dlc = 1 };

// Message to carry dial 2 position


message DialMsg dial2;

// Timer to count between random inputs


msTimer randomTimer;

// Maximum and minimum ms between random inputs


int maxMsDelay = 600;
int minMsDelay = 50;
}

The DialMsg has been configured in the database to hold one 8-bit signal containing the position
of a dial. The dial1 message, which is not defined in the database, will also hold one byte of data.
Since the environmental variables are declared in the database, we do not declare them in CAPL.
Next, we need to set up the on start event procedure to start the timer for the first time. We use
the maxMsDelay and minMsDelay values in conjunction with the random() function to get a
number in our desired range. Note that random() returns a value between 0 and one less than
the argument. To create an on start event procedure, select System in the Event Types window
(upper left corner). Them right-click in the Event Procedures window (lower left corner) and
select New. You should then see a skeletal event procedure in the Procedure Editing window
(lower right corner).

on start {
int delay; // Delay until first input
. . .
delay = random(maxMsDelay - minMsDelay) + minMsDelay;
setTimer(randomTimer, delay);
}

The timer event procedure is where most of the work happens. The event procedure must first
decide which input to change, then change the input, and then reset the timer to a random value.
To create the event procedure, first click on Timer in the Event Types window (upper left corner).
Then, right-click in the Event Procedures window (lower left corner) and choose New. You
should then see a skeletal event procedure in the Procedure Editing window (lower right corner).
Make sure to change the string <newTimer> to randomTimer.

CAPL Reference Manual 165


CAPL Programming Examples

on timer randomTimer
{
int input; // Random value for picking input
int delay; // Delay until next input

input = random(3); // Returns 0..2

switch (input)
{
case 0:
// Toggle button1 (either 0 or 1)
write(“Toggling button1”);
putValue(button1, abs(getValue(button1) - 1));
break;

case 1:
// Change value of dial1 from 0..1000
write(“Changing value of dial1”);
dial1.byte(0) = random(1001);
output(dial1);
break;

case 2:
// Change value of dial2 from 0..1000
write(“Changing value of dial2”);
dial2.position.phys = random(1001);
output(dial2);
break;
}

// Reset the timer to a random value


delay = random(maxMsDelay - minMsDelay) + minMsDelay;
setTimer(randomTimer, delay);
}

If you experiment with the code shown above, you will see that its easy to control the nature and
randomness of the inputs. In case 0, the value of an environmental variables is changed. In
case 1, a message that is not defined in the database is used to transmit the new dial value. In
case 2, a database-defined message is used to transmit the new dial value.

CAPL Reference Manual 166


CAPL Programming Examples

5.16 Using CAPL to control logging


When CANalyzer or CANoe is properly configured, your CAPL code can be used to control
logging during a simulation. Before writing the code to control logging, two actions must be
taken. First, you must set up CANalyzer or CANoe’s logging to make sure that the Trigger Type
is set to CAPL in the Trigger Configuration menu. This menu is accessed by right-clicking on the
Logging box in the Measurement Setup window and choosing Configuration.
Secondly, you must place the CAPL node (or P-Block) in the simulation branch. For CANoe
users, this means that the P-Block must be placed in the measurement setup window. For
CANalyzer users, the P-Block must be placed on the right half of the measurement setup window.
After this has been done, we can use the CAPL Browser to edit the program. We will create an
on message event procedure that turns logging on when message ID 101 hex is received. To do
this, select CAN-Message from the Event Types window (upper left corner) and then right-click in
the Event Procedures window (lower left corner). Select New from the pop-up menu, and then
you should see a skeletal event procedure in the Procedure Editing window (lower right corner).
We will replace the string <newMessage> with 0x101 for this example and then enter the
following code:

on message 0x101
{
// Set the PreTrigger time to 1 second (1000 ms)
setPreTrigger(1000);

// Set the PostTrigger time to 5 seconds (5000 ms)


setPostTrigger(5000);

// Set the name and path of the log file


setLogFileName(“c:\\logs\\log101”);

// Trigger logging.
trigger();

When using the setLogFileName() function, three rules must be remembered:


• Do not specify the extension of the log file. This is automatically assigned based on the
type of log file you choose in CANalyzer or CANoe. The extension will be .ASC for ASCII log
files and .LOG for binary log files.
• Use double backslashes (\\) instead of single backslashes (\) in file paths.
• Make sure to specify a path that already exists. CAPL will not create directories for you. If
you specify a path that does not exist, CAPL will ignore the call to setLogFileName()
completely.

CAPL Reference Manual 167


CAPL Programming Examples

Also note that CAPL programs using the logging functions described above cannot be compiled
from the CAPL Browser, since the Browser does not know where the P-Block containing the code
will be placed. Therefore, you must first place and configure the P-Block containing the CAPL
program in CANalyzer or CANoe, then compile the CAPL program from the CANalyzer or
CANoe’s Configuration menu by selecting “Compile All Nodes”.

5.17 Responding to a change in an Environmental Variable


CANoe users can use CAPL programs to respond to the change of an environmental variable.
(Note for CANalyzer users: This feature is not available in CANalyzer.) Responding to the
change of an environmental variable is as simple as setting up an on envVar event procedure.
Before the event procedure is created, you must define the corresponding environmental variable
in the associated database with CANdb. Environmental variables are a special case in that they
cannot be defined in the CAPL code itself. Using the CANdb database editor to create a
database is beyond the scope of this manual, but once it is created, pull down the File Menu in
the CAPL Browser and choose Assign Database.
To set up the event procedure, select Environment in the Event Types window (upper left corner).
Then, right-click in the Event Procedures window (lower left corner) and select New. You should
then see a skeletal event procedure in the Procedure Editing window. We need to replace the
string <newEnvVar> with the name of our environmental variable. In this example, we will use
the environmental variable switchState, which we have defined in our database. We can insert
the name of this variable by right-clicking in the Procedure Editing window (lower right corner)
and choosing CANdb Variable. Our event procedure now looks like this:
on envVar switchState
{
}

You can put any legal CAPL code in the body of the procedure, so there are several choices for a
reaction to the change of the environmental variable. However, you will almost always want to
read the value of the environmental variable. This is accomplished using the getValue() function.
This function can return an integer, floating point number, or a string (refer to the section on
environmental variables for more details). In this case, we have declared switchState as an
integer in the database, so we will read an integer value from it and respond accordingly.

CAPL Reference Manual 168


CAPL Programming Examples

on envVar switchState
{
int switchValue;

switchValue = getValue(this);

switch (switchValue)
{
case 0:
write(“Switch is now off.”);
break;

case 1:
write(“Switch is now on.”);
break;

default:
write(“Switch returned an illegal value.”);
break;
}
}

Note that in this case, only the values 0 and 1 are legal. In your system, an environmental
variable could have thousands of states.
As a final note, CAPL provides a function called CallAllOnEnvVar() which should be used during
initialization. This function executes every environmental variable event procedure that you have
defined. This allows you to determine the states of all of the environmental variables at the start
of the measurement and react accordingly. Otherwise, you would have to wait until the value of
each environmental variable changes to respond to its state.
We can place this function call into the on start event procedure by selecting System in the Event
Types window (upper left corner). Then right-click in the Event Procedures window (lower left
corner) and select Start from the New submenu. You should then see the on start event
procedure in the Procedure Editing window (lower right corner). You can insert the
CallAllOnEnvVar() call anywhere in the body of the procedure.

on start
{
. . .
CallAllOnEnvVar();
}

CAPL Reference Manual 169


J1939 Extensions for CAPL

6 J1939 EXTENSIONS FOR CAPL

J1939 is a protocol that is built on top of the CAN protocol. The main differences are the manner
that the identifier field’s bits are partitioned and the predefined identifier names.
If you intend to program for a J1939 network with CAPL, you should be familiar with J1939
parameter groups (or “pgs”) and understand the differences between pgs and normal CAN
messages.

6.1 The pg (parameter group) object in CAPL


The key word pg is used to define parameter groups which are to be output from the CAPL
program. The parameter group number (PGN) is part of a complete definition, or when working
with symbolic databases, the name of the parameter group is used. For example, you would
write:
pg 0xFEF1 pg1;
pg RetarderConfig pg2;
...
output(pg1);
output(pg2);

to output onto the bus the parameter group with parameter group number 0xFEF1 (hex) as well
as the parameter group RetarderConfig as defined in an associated database.
Parameter group names can be selected using the right mouse button pull-down menu in the
CAPL Browser once a J1939 database is associated. The method is the same as selecting a
message name for a normal CAN database.

6.2 Parameter group selectors


Parameter groups have selectors which are analogous to the message selectors used for
standard CAN messages.
Thus, parameter groups are designated by their parameter group number (PGN), which is
entered as a number (integer) in decimal or hexadecimal representation.
The J1939 specific attributes of a parameter group can be accessed by indicating an attribute
selector. The following attribute selectors are available:

CAPL Reference Manual 170


J1939 Extensions for CAPL

Selector Usage
PGN Parameter group number
SA Sender of the parameter group
DA Receiver of the parameter group
PF PDU format
PS PDU specific
Characteristic Priority, data page and reserved bit of the
parameter group

When initializing a parameter group within the definition, the following supplemental attributes are
also available:

Selector Usage
PRIO Priority of the parameter group

DP Data page of the parameter group

You can use these selectors to define parameter groups in your CAPL code. For example, with
pg TC1 pg_tc1 = {
SA = 0x34, // Sender
DA = 0x24 // Receiver
};

output(pg_tc1);

you would define and send the parameter group TC1 (PGN = 0x100) from the station with
identification 0x34 to station 0x24.
Components of the objects are accessed by Component selectors. If you wish to define the object
for a certain chip (for CAN cards with more than one CAN chip), you would prefix the appropriate
selector (CAN1 or CAN2) followed by a dot (.).
No selector is provided for changing the length of a parameter group (DLC).

CAPL Reference Manual 171


J1939 Extensions for CAPL

6.3 Using the predefined J1939 database


When purchased with the J1939 package, CANalyzer or CANoe includes a predefined database
with all of the J1939 parameter groups already defined for you in the DMJ19_CN directory. The
file is called J1939.DBC.
When starting a new project, make a backup copy of J1939.DBC (never modify the original files).
Use the copy of the J1939 database as a basis for your project database, adding nodes and
environmental variables and changing parameter group specifications as necessary.
If you generate your own J1939 database or add on to the provided database, remember these
rules:
• All attribute names are case sensitive
• The database must have an integer attribute “J1939PGN” set to 1
• Signal indicators will only be supported if the signal has the string attribute “SigType”.

String Signal type

"RANGE" Transmitted signal range (8, 16, 32 bit)

"CONTROL" Transmitted value for control commands (2 bit status)


"DISCRETE" Transmitted value for discrete parameters (2 bit measured)

"SPECIFIC" All other signal types (e.g. 4 bit status)

Further signal types will be supported in later versions.

6.4 J1939 differences in CAPL


• It is not possible to change the Data Length Code (DLC) of a parameter group. Parameter
groups do not have any length limitations.
• It is not possible to define arrays with parameter groups.
• It is not possible to assign a parameter group to another parameter group or to the same
parameter group.
• Use of the “this” pointer in event procedures for parameter groups is not possible for pgs
with more than eight data bytes. The function getThisMessage() is provided for this purpose.

• A different set of selectors is used for parameter groups as opposed to messages.

CAPL Reference Manual 172


J1939 Extensions for CAPL

6.5 CAPL functions used with J1939

6.5.1 The output() function


The output() function can be used for parameter groups in exactly the same manner that it can be
used for CAN messages and error frames. The parameter group is passed as a parameter to the
function, i.e.:
pg TC1 pg_tc;
...
output(pg_tc);

6.5.2 The getThisMessage() function


Since you cannot directly copy the data from a parameter group, the getThisMessage() function
allows you to copy the parameter group pointed to by the this pointer. This is useful when you
want to keep a copy of a parameter group after an event procedure has completed. It can be
used as shown in this example:
variables {
pg TC1 pg_tc1; // Definition of a parameter group
...
}

on pg * { // Event procedure for all parameter


groups

if (pg.pgn == TC1) {
// If the received parameter group is TC1
// Transfer the received parameter group to the
variable
getThisMessage(pg_tc1, pg_tc1.dlc);
}

CAPL Reference Manual 173


Index

INDEX

enum 24
Symbols CANdb database 22
Environmental Variable 168
CAPL Browser 46
* 34, 37 Environmental variable 55
CAPL Programming
. 23, 27 environmental variable
Environment 3
.CAN file 58 17, 42, 50, 155
case 14
.CAN Files 12 Environmental Variables 32
char 25
.CBF File 12, 58 error active 39
Characteristic 170
:: 22 Error Frame 159, 160
Comments 14, 59
Error frame 55
Compile 51, 58
error frame 42
Component selectors 171
Error Passive 163
A Constants 23, 33
error passive 39
continue 14
errorCountRX 40
abs 74 CONTROL 172
errorCountTX 40
Analysis Branch 66 conversion formula 29, 157
Errors
Analysis Branches 66 cos 81 CAN bus 39
Arrays 19 Compilation 58
Multidimensional 19, 25 Round-off errors 29
arrays 172 Routine 51
atol 75 D Run-time 20, 58
DA 170 Evaluation Branch 43, 65
Data Length Code 30, 172 Event
Categories 55
B data length code 27 on errorActive 35
Data page 171 on key 35
beep 76 Database 59 on message 35
beep() 160 Associated on start 35
Binary File 58 26, 27, 48, 50, 168 on stopMeasurement 35
Binary Files 12 associated 22, 23 event procedure 34, 153, 155
break 14 J1939 172 Event Procedures 56
Browser 46 database 23 event procedures 32, 34
bus off 39 Database Assiociated 21 Event Prodcedures Window 47
byte 25, 31 default 14 Event table 5
DIR 30 Event Types Window 47
DISCRETE 172 Event Types window 55
DLC 27, 30, 172 Events 13, 34
C double 25 cyclic 41
C 13, 18, 20, 25 DP 171 envVar 35
CAPL equivalents 20 dword 25 Event procedures 13
Standard syntax 14 Dynamic memory 19 on busOff 35, 39
CallAllOnEnvVar() 39, 156, 169 on envVar and on envVar 42
CAN 30 on errorActive 39
CANBROW.EXE 46 on errorFrame 35
cancelTimer 78 E on errorPassive 35, 39
cancelTimer() 155 elCount 82 on key 37
CANdb 21, 23, 26 elCount() 19 on message 36
ellipse 14
else 14

CAPL Reference Manual 174


Index

INDEX
on pre Start 35
on start 39 H
on stopMeasurement 39 M
on time 41 Help menu 52
on timer 35, 41 hex 24 malloc() 19
on warningLimit 35, 39 hexadecimal 14 Menus
preStart 39 File 48
Procedures 56, 57 Message 26, 55
Sending an Event Message 152 Received 156, 157
Exit 49 I Responding 158
exp 83 message 17, 25, 152
extended CAN ID 27 ID 30 Message identifier 30
if 14 Message selectors 30
inport 102 message selectors 27
inport() 33 Messages 50
F int 25 Accessing raw data 31
integer 24 Periodic 153
Factor 29 isExtId 103 Repetitive 155
File menu 48 isStdId 104 messages 12, 32
fileName 84
pass-through 43
fileReadArray 85
mkExtId 107
fileReadFloat 87
msTimer 25, 26, 41
fileReadInt 88 J multidimensional arrays 19
fileReadString 89
fileWriteFloat 90 J1939 170
fileWriteInt 91 J1939.DBC 172
fileWriteString 92 N
Find 50
float 24, 25 naming convention 13
K notation 13
Function Compatibility 65
Functions 13, 50 Keyboard Inputs 160 NOW 162
built-in 13 Keypress 55
User-Defined Functions 13 keypressed 105
functions 16 keystrokes 37
Functions overloading 16 O
Funtions Object
User-defined 55 Message 26
L Parameter Groups 170
Objects
log files 45 messages 27
G logging 44, 167 msTimer 26
long 25, 31 Timer 26
getCardType 93 loops 14 Types 25
getChipType 95 LPT1 33 Offset 29
getLocalTime 96 LPT2 33 on BusOff 55
getThisMessage 99 LPT3 33 on busOff 162
getThisMessage() 172, 173 ltoa 106 on busOff events 39
getValue 100
on envVar 153, 168
getValue() 17, 33, 42, 155
on errorActive 39, 55, 163
Global
Variables 54 on errorFrame 153, 160
Global Variables Window 47 on errorPassive 39, 55, 163
Global Variables window 54 on key 153, 160
on key event 37

CAPL Reference Manual 175


Index

INDEX
on message
36, 153, 157, 158, 163, 167
on preStart 39, 55
R Source Code 59
on start 39, 153, 154, 156, 169 random 111 source file 58
on stopMeasurement 39 Random Inputs 164 SPECIFIC 172
on Timer 153 random() 164, 165, 166 sprintf 20
on timer 154, 159, 166 RANGE 172 sqrt 132
on warningLimit 39, 55 raw data access 32 static 18
onpreStart 55 raw value 29 stop 133
onstart 55 Real-Time Branches 66 string 24
onstopMeasurement 55 Receive 30 Strings
Options 52 constants 25
Remote Transmission Request
outport 108 strlen 134
30
outPort() 160 strncat 135
Replace 51
outport() 33 strncmp 136
resetCan 112
output 109 strncpy 137
return 14
output() swapDWord 138
RTR 30
32, 152, 157, 159, 170, 173 swapInt 139
Run-time errors 20
Ox 14 swapLong 140
run-time errors 58
swapWord 141
runError 113
switch 14
runError() 20, 58
symbolic identifiers 22
runtime error 51
P symbolic name 27
RX 30
symbolic names 21
P-Block 43, 46 RXDATA 31
symbolic signal access 29
P-Blocks 43, 65 RXREMOTE 31
symbolic signal values 22
pass-through 43
parameter group 170
parameter group number 170
parameter groups 170 S
T
parameters 16, 34 SA 170
pass-through 43 text editor 12
Saving files 48
Periodic Message 153 Text Editors 59
setBtr 122
PF 170 this 17, 35, 38, 40, 42
setLogFileName 123
pg 17, 25 TIME 30
setLogFileName() 45, 167
PGN 170 timeDiff 144
setLogFilleName() 65
pgs 170 timeNow 145
setMsgTime 124
phys attribute 29, 152, 157 Timer 25, 26, 41, 55, 158
setOcr 125
Physical values 29 timer 153
setPostTrigger 126
PI 33 timers 12
setPostTrigger() 45, 167
posttrigger time 45 Tool bar 47
setPreTrigger 127
precedence rules 36 toolbar 53
setPreTrigger() 45, 167
pretrigger time 45 Transmission Branch 65, 66
setTimer 26, 128
printf 20 Transmit 30
setTimer() 41, 154, 155, 165
Printing 49 Transmit Request 30
signal names 32
PRIO 171 trigger 146
signal values 29
priority 171 Trigger Type 44
Signals 26, 50
Procedure Editing 57 trigger() 45, 167
signals 27
Procedures 16 TX 30
SIMULATED 30
Prodedure Editing Window 47 TXDATA 31
Simulation Setup Window 66
PS 170 TXREMOTE 31
sin 129
putValue 110 TXREQUEST 30
sizeof 20
putValue() 32 TXREQUESTDATA 31
snprintf 130

CAPL Reference Manual 176


Index

INDEX

TXREQUESTREMOTE 31
TYPE 30, 31 X
Type casting 14
x 14, 27

U
Undo 50
User-Defined Attribute 24
user-defined attributes 23
User-defined function 55

V
valOfId 147
Variable 12
Global Variable Declarations
12–45
Types 25
Variables 50
Default values 20
Environmental 32
Variables Local 18
Variables Static 18

W
Window
Event Types 55
Events 55
Measurement Setup 65
Simulation Setup 65
Windows
Event Procedures 47, 56
Event Types 47
Global Variables 47, 54
Measurement Setup 66
Procedure Editing 57
Prodedure Editing 47
Simuation Setup 66
word 25, 31
write 148
Write window 20, 58
write() 157, 158
writeToLog 150

CAPL Reference Manual 177

S-ar putea să vă placă și