CAPL Basics

CAPL:

    CAN Access Programming Language

CAPL Programming:

    The CAN Access Programming Language CAPL is a C-like programming language,

    which allows you to program CANoe for individual applications.

 Introduction to CAPL:

    CAPL, the CAN Access Programming Language, allows you to quickly develop code that makes CANalyzer or CANoe simulations more powerful.

    CAPL  is  a  procedural  language  whereby  the  execution  of  program  blocks  is  con-trolled by events. These program blocks are known as event procedures.

    The program code that you define in event procedures is executed when the event occurs.

    For example, you can send a message on the bus in response to a key press (on key), track the occurrence of messages on the bus (on message), or execute certain actions cyclically (on timer).

  Introduction to CAPL:

    A CAPL program consists of two parts:

            1. Declare and define global variables

            2. Declare and define user-defined functions and event procedures

 CAPL Program Organization:

    CAPL programs have three distinct parts:

            1. Global Variable Declarations

            2. Event Procedures

            3. User-Defined Functions

  CAPL Variables:

    Data types available for variables include integers (dwordlongwordintbytechar), floating point numbers (float and double),

    CAN messages (message) and timers (timer or msTimer). Except for the timers, all other variables can be initial-ized in their declarations.

      variables {

          int msgCount; // Is set to 0 at measurement start

              message 34 sendMsg = { // Declare message with Id 34

              dlc = 1, // Set Data Length Code = 1

              byte(0) = 1 // Set 1st data byte = 1

              }

      }

  CAPL Variables:

    Variables can be initialized when they are declared, whereby you can use either simple notation or brackets {}. With the exception of timers, the compiler initializes all variables with default values (unless otherwise defined: 0).

    CAPL permits the declaration of arrays (arrays, vectors, matrices), analogous to their declaration in the C programming language.

variables {

     int vector[5] = {1,2,3,4,5};

     int matrix[2][2] = {{11,12},{21,22}};

     char progname[10] = “CANoe“;

    }

  CAPL Variables:

    Variables  of  the  type  timer  (based  on  seconds)  or  msTimer (based on millisec-onds) serve to generate time events. Timer variables are not automatically initialized at  the  program  start,  rather  they  must  be  "set"  explicitly  with  the  function setTimer().

     variables {

     timer delayTimer; // Declaration of a second timer ...

     msTimer cycTimer; // ... and a millisecond timer

     }

     ...

     setTimer(delayTimer,3); // Set timer to 3 sec

     setTimer(cycTimer,100); // Set timer to 100 msec

     ...

  Declaration of Messages:

     Messages  to  be  output  from  the  CAPL  program  are  declared  with  the  key  word message. The complete declaration includes the message identifier or - when work-ing with symbolic databases - the message name. For example, you might write the following to output messages on the bus that have identifier A (hex) or 100 (dec) or the message EngineData defined in the database.

            message 0xA m1; // Message declaration (hex)

            message 100 m2; // Message declaration (dec)

            message EngineData m3; // Symbolic declaration

            message * wcrd; // Declaration without Id

            ...

            output(m1); // Transmit message m1

            output(m2); // Transmit message m2

            output(m3); // Transmit message m3

            wcrd.id = 0x1A0; // Define Id...

            output(wcrd);

  Declaration of Messages:

    It is possible to access control information for the CAN message objects using the following component selectors:

     ID                  Message identifier

     CAN              Chip number

     DLC               Data Length Code

     DIR                Direction of transmission, possible values: RXTX,     

     RTR              Remote Transmission Request; possible values: 0 (No RTR), 1 (RTR)                     

    TYPE               Combination of DIR and RTR for efficient evaluation.(TYPE = (RTR << 8) | DIR )

     TIME            Time point, units: 10 microseconds


  Event Procedures:

You can react to the following events in CAPL using event procedures

            

    Event

    Event Procedures

    Receipt of a CAN message

    on message{}

    Press of a key

    on key{}

    Initialization of measurement (before measurement start)

    on prestart{}

    Measurement start

    on start{}

    End of measurement

    on stopMeasurement{}

    CAN controller goes to ErrorActive

    on errorActive{}

    CAN controller goes to Error Passive 

    on errorPassive{}

    CAN controller reaches the warning limit

    on warningLimit{}

    CAN controller goes to Bus Off

    on busOff{}

    Elapse of a timer

    on timer{}

    Occurrence of an error frame

    on errorFrame{}

    Environment variable change

    on envVar{}


  React to Messages:

    The  event  procedure  type on message  is  provided  to  react  to  the  receipt  of CAN messages in the CAPL nodes.

            on message 123                      React to message 123 (dec),

                                                        Receiving chip is not considered

            on message 0x123      React to message 123 (hex);

                                                receive chip is not considered

            on message EngineData        React to message EngineData

            on message CAN1.123          React to message 123,

                                                if it is received by chip CAN1

            on message *              React to all messages

            on message CAN2.* React to all messages

                                                that are received by chip CAN2

           on message 100-200   React to all messages

                                                with identifiers between 100 and 200

  Example for React to Messages

            on message CAN1.34 {

                        message CAN2.34 sendMsg; // Local message variable with

                        // name sendMsg, identifier 34,

                        // target controller CAN 2

                        sendMsg = this; // Copy all data and attributes

                        // of received message (this)

                        // to message to be transmitted

                        sendMsg.byte(4) = 0; // Change byte 4,

                        // always enter 0

                        output(sendMsg); // Transmit message

            }

  React to Keyboard Events

    With on key procedures you can execute certain actions by key press. 

            on key 'a'                    React to press of .a. key

            on key ' ‘                     React to press of spacebar

            on key 0x20                React to press of spacebar

            on key F1                    React to press of F1 key

            on key ctrlF12             React to press of Ctrl-F12

            on key PageUp          React to press of Page Up

            on key Home              React to press of Home

            on key *                      React to any key press

    The code for a key press can either be input as a character, number or a predefined name for a function key.

  Example of React to Keyboard Events

variables {

int counter = 0;

}

on key 'a' {

write("A total of %d messages 0x1A1 counted",counter);

}

on message 0x1A1 {

counter++;

output(this); // Only in the evaluation branch

}

on message * {

output(this); // Only in the evaluation branch !!!

}

  React to Changes in Values of Environment Variables

    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

            }

  React to Time Events

    CAPL allows you to create timers for seconds (Timer) or milliseconds (msTimer). After thesetimers have been set and expire, the corresponding “on timer” event procedure is executed. 

    Thisfacility 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 setthe timer. The length of time parameter has different units depending on what kind of timer youare using. For a Timer, the units are seconds; for an msTimer, the units are milliseconds.

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

  Example for Time Events

    msTimer myTimer; // Define millisecond timer

    message 100 msg; // Define message to be transmitted

...........................................

on key 'a' { // React to key press of 'a'...

    setTimer(myTimer,20); // ... Set timer to 20 ms

}

..........................

on timer myTimer { // Send message after timer...

output(msg); // ... has elapsed

}

  React to System Events

    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 permeasurement. 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, initializevariables, or write to the Write window. Other actions, such as outputting a message onto thebus, 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.

  React to System Events

    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.

  React to CAN Controller Events

    The  event  procedures  on errorActive,  on errrorPassive,  on warningLimit and on busOff are called during a state transition or in response  to a change in the CAN controller's error counter. Use these procedures to monitor  the error counter (e.g. output a warning), to terminate the measurement if necessary,  or to execute a reset after a transition to the Bus-Off state.

    The  CAN  controller's  error  counters  can  be  accessed  within  the  CAN  controller's  event procedures using the key word this:

  React to CAN Controller Events

on errorPassive {

...

write("CAN Controller ist in errorPassive")

write(" errorCountTX = %d", this.errorCountTX);

write(" errorCountRX = %d", this.errorCountRX);

}

  Expressions in CAPL

    CAPL syntax  is based on the C programming language. The following expressions  are permitted as they are in C:

· Instruction blocks: { ... }

· if { ... } and if {...} else { ... }

· switchcasedefault

· for..while..do..while loops

· continue and break

· return

· ?: expression

  The Key Word this

    The key word this is used to refer to the the data structure of an object within an event procedure for receiving a CAN object or environment variable. For example, the following accesses the first data byte of message 100 which is just  being received: 

            on message 100 {

            byte byte_0;

            byte_0 = this.byte(0);

            ...

            }

  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.

            variables

            {

                        message 0x555 msg1 = {dlc=1};

            }

            on key ‘b

            {

                        msg1.byte(0)=0xAA;

                        output(msg1);

            }

  Periodic Message Transmission

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

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

}

  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.

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

}

  Handling of Run-Time Errors

A number of run-time errors are monitored in CAPL:

· Division by zero

· Exceeding upper or lower array limits

· Exceeding upper or lower offsets in the data fields of messages

· Stack overflow when CAPL subroutines are called

If a run-time error is detected, the instrinsic function runError() is called. This out-

puts a message to the Write window containing the name of the CAPL program, the

error type and an error index. The location of the particular CAPL source text which

caused the error is found with the help of the error index. The measurement is termi-

nated after output of the message.

The function runError() can also be called directly by the user to generate asser-

tions.

 

  Browser for Creating and Compiling CAPL Programs

Application Uses for CAPL

Create a black box to simulate the rest of the network.

Create a module simulator.

Simulate event messages, periodic messages, or conditionally repetitive messages

Application Uses for CAPL

Simulate human events like button presses using the PC keyboard

Simulate timed node or network events

Create a functional gateway between to different CAN networks.

CAPL Programming.

 

 

29 comments:

  1. How to send extended frame on CAN bus?

    ReplyDelete
    Replies
    1. Hi...priyanka thankyou for your comment

      IDE (Identifier Extension Bit) Is 0 (dominant) for standard format and 1(recessive) for extended format.
      If you want send the extended frame the IDE bit in the orbitration field should be recessive(1).

      Delete
    2. You are right Sreekanth,
      @ Pol,
      Please follow BOSCH 2.0 B CAN protocol spec for more details.

      Delete
    3. 1. First declare a message without ID
      message *ExtMsg; // Declaration without Id
      2. Use CAPl Function mkExtId() to return an extended ID
      3. assign that id to the message.


      variables
      {
      timer T1;
      message 0x100 stdMsg;
      dword ext_id ;
      message *ExtMsg; // Declaration without Id
      }

      on start
      {
      setTimer(T1,1);
      ext_id = mkExtId(0x34444);
      ExtMsg.id = ext_id;
      ExtMsg.dlc = 2;
      }

      on Timer T1
      {
      ExtMsg.byte(0) = 99;
      stdMsg.stdSignal =2;
      output(stdMsg);
      output(ExtMsg);
      setTimer(T1,1);
      }

      Delete
    4. HI, for can extended messages put x after identifier.
      variables
      {

      message 0x0000000x msg_one_one;

      }


      void send_function(int sample_value)
      {
      msg_one_one.id = 0x1EF712x;

      msg_one_one.dlc = 8;
      msg_one_one.byte(0) = sample_value;
      output(msg_one_one);

      }

      Delete
  2. Hi can any help how to extract data from text file and send it on message in capl. If that text file consist message bytes which are supposed to send on bus like 00 00 00 00 80

    ReplyDelete
  3. any open source tool for CAPL or open source CAN simulation tool??

    ReplyDelete
  4. Hi,

    You have mentioned here that we can create cyclic events with timers, but didn't make an example of that. If I reset the timer in my "on timer" by using the setTimer() then how will the program go back to the beginning of my "on timer" to run the code there again? This is not working for me, it always only run once.
    Also how can I put timer in a for loop? How can I

    Thanks, this is the most helpful example I found online for CAPL!

    ReplyDelete
    Replies
    1. Initiate the same timer again after the code execution within the block

      Delete
  5. hi,

    how to send a message 0x100 to the can bus using CAPL?

    ReplyDelete
    Replies
    1. on message 0x100
      {
      output(this) // sending to the can
      write(this) // printing on write window
      }

      Delete
  6. Hi Bijani,

    To send message cyclic, Set the timer within the timer function,

    for example,

    mstimer t1;
    message m1 msg;
    on timer t1
    {
    output(msg);
    setTimer(500);
    }

    Dont forget to trigger this timer for the first time at on start by using the same SetTimer function

    ReplyDelete
    Replies
    1. @Sanakaran:But if we use test modulea then this On start() will not work.So how do we call cyclic timer in case of test modules or test units?

      Delete
  7. Can someone write me a script for this in CAPL, kindly help. I really need it, kinda priority now. IT will be a big help if anyone can do it.
    Capl script
    1) Write the CAPL script for simulation of the ECU. The functionality of ECU is following:

    RQ 1) ECU shall generate on the CAN output pulses.(signal is jumping 0<>1 )
    RQ 2) ID of the output message is 0x100, start byte =1, start bit = 1, length=1
    RQ 3) Cycle time of the output is 10 ms
    RQ 4) Output is enabled/disabled by signal. Parameters of the signal are ID=0x300, start byte =5, start bit = 6, length =1, Cycle time of this input is 500 ms
    RQ 5) Frequency of the output signal is defined by signal in message 0x200, start byte =4, start bit = 0, length =8, 0=error, 1-200 is frequency, scale 1:1, Cycle time of this input is 200 ms.
    RQ 6) Default value of output frequency is 10 Hz
    RQ 7) If the input signal with the frequency is in error (0), output is disabled
    RQ 8) If the input signal frequency is in range 201 -255, output frequency is in default


    2) Make the test specification for the RQ1-RQ8

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. what is mean by dword and qword

    ReplyDelete
  10. Hello! I have found this post helpful. I have a question tho. How can you send a cyclic message between two signals. Example, I want to send the message 0xID and it contains signals A and B. How can I program this so that I can send the message with both signals alternating for a specific number of times? Thanks.

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Is it possible to convert a string in to bytes in CAPL , if yes please let me know how ,
    example : my string is "10 01" ... i want 10 to be my 1st byte and 01 2nd byte .

    ReplyDelete
  13. How do I compare my received message to something to verify what I've received is correct or not?

    ReplyDelete
  14. what is system variable in CAPL. what is environment variable in CAPL ... what is difference between them

    ReplyDelete
    Replies
    1. for example we have switch board, how do the switch board knows if u press down its on if u press up its off thats is system variable what we assign is environment variable.

      Delete
  15. Hello,

    I want to change message ID using capl scripting (In run time).
    I know this is not a proper scenario but right now i am working with this kind of requirement.

    Please let me know if you have some idea on it.

    Thank you,
    Akash Shah

    ReplyDelete
  16. can you explain capl Testing

    ReplyDelete
  17. any good source to learn capl?

    ReplyDelete
  18. In CAPL is it possible to use for loop for sending multiple message?

    ReplyDelete