User ManualCANape CASLCalculation and Scripting LanguageVersion 1.2English

ImprintVector Informatik GmbHIngersheimer Straße 24D-70499 StuttgartVector reserves the right to modify any information and/or data in this user documentation without notice. This documentation nor any ofits parts may be reproduced in any form or by any means without the prior written consent of Vector. To the maximum extent permittedunder law, all technical data, texts, graphics, images and their design are protected by copyright law, various international treaties andother applicable law. Any unauthorized use may violate copyright and other applicable laws or regulations. Copyright 2015, Vector Informatik GmbH. Printed in Germany.All rights reserved.

User Manual CANape Vector Product Reference41.3CASL Scripting Language in CANape41.4Prior Knowledge41.5General Process51.6About This User .6.4Trademarks566662Basic Information72.1Applications for Functions and Scripts82.2What Are Functions82.3What Are Scripts102.4Differences Between Functions and Scripts112.5Functions Editor122.6Additional Definitions2.6.1Variable Types2.6.2Arguments and In/Out Parameters (of Functions)2.6.3Comments2.6.4Taking Upper and Lower Case Into Account2.6.5Predefined Function Groups and Code Blocks of CANape1313151616162.7General System Limits183Syntax193.1Differences Between C Programming and CASL203.2Numbers and Characters3.2.1Data Types and Value Ranges3.2.2Parameter Types for Predefined l Structures (Statements)264Functions, Scripts, and Variables in CANape294.1Functions4.1.1Writing the Functions4.1.2Saving and Forwarding Functions (Exporting/Importing)4.1.3Commissioning or Instantiating Functions4.1.4Example Functions4.1.5Global Function Library4.1.6Integrating External Function Libraries30303132434546 Vector Informatik GmbHVersion 1.2-I-

User Manual CANape CASL4.2Contents4.1.7Debugging of 2.7Writing the ScriptsSaving and Forwarding Scripts (Exporting/Importing)Task ManagerCall-up of ScriptsScript Behavior When CANape is RunningDebugging of ScriptsExample Scripts50505152535858594.3Variables4.3.1Creating a Global Variable4.3.2Setting a Global Variable to a Defined Value4.3.3Setting a Local Variable to a Defined Value4.3.4Inserting a Device Variable61616163665General Tips675.1Proper Terminating of Functions and Scripts685.2Access to System Information686Addresses707Glossary718Index72 Vector Informatik GmbHVersion 1.2- II -

User Manual CANape CASLIntroduction1 IntroductionIn this chapter you will find the following information:1.1Objectivepage 41.2Vector Product Referencepage 41.3CASL Scripting Language in CANapepage 41.4Prior Knowledgepage 41.5General Processpage 51.6About This User ManualCertificationWarrantySupportTrademarkspage 5 Vector Informatik GmbHVersion 1.2-3-

User Manual CANape CASL1.1IntroductionObjectiveBasic informationThis manual starts with an introduction to the CANape scripting language where allassociated concepts are explained in detail and distinguished from one another.SyntaxThe following chapter covers the syntax of the CANape scripting language. Thischapter also serves as a reference guide.Integrating offunctions and scriptsAnother chapter describes how to integrate and check functions and scripts inCANape.General tipsTips on handling general issues are also provided.1.2Vector Product ReferenceCANape1.3The range of available functions differs depending on the respective Vector product(CANape or vSignalyzer) as well as the type (function or script). This manual refersexclusively to CANape. To determine whether the respective functions are alsoavailable in vSignalyzer, please refer to the Help.CASL Scripting Language in CANapeProprietary scriptinglanguageCANape uses its own scripting language, hereinafter referred to as CASL (Calculationand Scripting Language).SyntaxThe syntax of CASL is very similar to the C programming language. It permitsdevelopers to integrate their own C code or Simulink models.Note: Do not confuse CASL with the programming language CAPL, which is used inthe CANoe and CANalyzer environments.CAPL is an event-oriented programming language. So-called CAPL program nodesare used to specify when an event will be executed and the nature of the reaction.CASL, on the other hand, is a signal-oriented language.1.4Prior KnowledgePrior programmingknowledgeThis manual assumes that you have general programming knowledge in the Cprogramming language. Vector Informatik GmbHVersion 1.2-4-

User Manual CANape CASL1.5IntroductionGeneral ProcessProgrammingprocessFive steps are needed to develop a program.1. Think about which task is to be the primary task of the program.2. Decide how and when the program is to be executed.3. Develop suitable code.4. Compile the program.5. Test the program in CANape.1.6About This User ManualTo Find informationquicklyThis user manual provides you with the following access help: At the beginning of each chapter you will find a summary of the contents. The header shows in which chapter of the manual you are. The footer shows the version of the manual. At the end of the user manual you will find a glossary to look-up used technicalterms. At the end of the user manual an index will help you to find information quickly.ConventionsIn the two tables below you will find the notation and icon conventions usedthroughout the manual.StyleUtilizationboldFields/blocks, user/surface interface elements, window- and dialognames of the software, special emphasis of terms.[OK]Push buttons in square bracketsFile SaveNotation for menus and menu entriesCANapeLegally protected proper names and marginal notes.Source CodeFile and directory names, source code, class and object names,object attributes and valuesHyperlinkHyperlinks and references. Ctrl S Notation for shortcuts.SymbolUtilizationThis icon indicates notes and tips that facilitate your work.This icon warns of dangers that could lead to damage.This icon indicates more detailed information. Vector Informatik GmbHVersion 1.2-5-

User Manual CANape CASLSymbolIntroductionUtilizationThis icon indicates examples.This icon indicates step-by-step instructions.1.6.1 CertificationQualityVector Informatik GmbH has ISO 9001:2008 certification. The ISO standard is aManagement System globally recognized standard.1.6.2 WarrantyRestriction ofwarrantyWe reserve the right to modify the contents of the documentation or the softwarewithout notice. Vector disclaims all liabilities for the completeness or correctness ofthe contents and for damages which may result from the use of this documentation.1.6.3 SupportNeed help?You can reach our hotline by telephone at 49 (0)711 80670-200or by e-mail at [email protected] TrademarksProtectedtrademarksAll brand names in this documentation are either registered or non-registeredtrademarks of their respective owners. Vector Informatik GmbHVersion 1.2-6-

User Manual CANape CASLBasic Information2 Basic InformationIn this chapter you will find the following information:2.1Applications for Functions and Scriptspage 82.2What Are Functionspage 82.3What Are Scriptspage 102.4Differences Between Functions and Scriptspage 112.5Functions Editorpage 122.6Additional DefinitionsVariable TypesArguments and In/Out Parameters (of Functions)CommentsTaking Upper and Lower Case Into AccountPredefined Function Groups and Code Blocks of CANapepage 132.7General System Limitspage 18 Vector Informatik GmbHVersion 1.2-7-

User Manual CANape CASL2.1Basic InformationApplications for Functions and ScriptsIntroductionCANape contains a function editor for writing cross-device functions and scripts.The CASL scripting language used for this is similar to the C programming language.For easier use, CANape provides an IntelliSense input, code blocks, and variousbuilt-in function groups.General applicationsFunctions and scripts can be used to solve a variety of different tasks from simplecalculations, e.g., adding signals, to automation of CANape.Functions are processed synchronously during a measurement. Functions are usedmainly for various calculations and applications on an existing measurement file or anactive measurement.Scripts run independently of a measurement and are used for reproducibleautomation of sequences.2.2What Are FunctionsIntroductionFunctions are parts of a program code that is compiled under its own name. They canbe defined across devices in CANape.SyntaxThe code of the function follows the rules of the CASL language (Calculation andScripting Language).TasksA function can be a mathematical formula or program code, for example, in whichvariables stand as placeholders for signals or parameters.They facilitate analysis of measurement signals and enable the setting of calibrationobjects as well as other interventions at the device level.Online applicationsIn the case of online application, functions are executed during a measurementwhen triggered by an event. This occurs according to the measuring mode set in themeasurement configuration.Thus, it is possible to calculate virtual measurement signals and enable write accesses to device memory or external measuring hardware.Offline applicationsIn the case of offline application, functions access existing measurement files.Thus, it is possible to calculate virtual measurement file channels and perform Data Mining analyses.Function structureThe syntactical structure of a function is as follows:KeywordNameArguments, in/out parametersFunction headerfunction My function(input, output)Function body{double a 1;long b 2; Vector Informatik GmbHVersion 1.2-8-

User Manual CANape CASLBasic Informationoutput a b*input;writef("The result is: %d", output);return output;}Parameter passingWhen a function is called, parameters can be passed to the function. The parametersare passed to the function generally as reference and can thus be used for the inputas well as for the output.For more details on the passing of parameters, see section Arguments and In/OutParameters (of Functions) on page 15.Control structurereturnIn addition to issuing results from functions by parameter passing, the path via thereturn control structure (also keyword) can also be used. By default a value of typedouble will be returned. The optional return value thus always contains a scalar.It can be useful to return another type. For this purpose the return type must bedeclared in the function header. Fields or vectors (arrays) are not allowed as returnvalues. An overview of all available control structures can be found in section ControlStructures (Statements) on page 26.Example: Function header for alternative return value bytefunction byte TestFunction (signal){return 1;}UseThe return value of functions can be reused flexibly in CANape. For example, thesecan be displayed as a virtual measurement file channel in a Graphic window. For thisreason, it is recommended that an individual scalar return value be returned viareturn and not via the parameter list.If a function is not to return a value, this can be done in one of the following threeways: return cancel Neither return nor cancel are in the function code.Note: Measurement values that are write-protected (e.g., provided with a red pointerin the measurement list) cannot be used as an output parameter of a function.Function callFunctions can be inserted in the measurement signal list or used as a functiondefinition for the virtual measurement file channel (e.g., for Data Mining). They canalso be called directly from another user-defined function or a user-defined script. Fordetails, see section Commissioning or Instantiating Functions on page 32.Process priorityFunctions – such as the measurement itself – run under CANape with very highpriority. They should therefore be kept as efficient as possible since, otherwise, thefunction can influence the entire measurement (measured values may be lost, forexample). Infinite loops tie up the entire measurement and can only be interrupted by Vector Informatik GmbHVersion 1.2-9-

User Manual CANape CASLBasic Informationactuating the Esc key for 3 seconds.LimitationsBecause CANape processes are stopped during the measurement for functions, afew CASL functions are not available. They would trigger a runtime error. TheseCASL functions are therefore not even offered when user-defined functions arewritten, e.g., this applies to the built-in script function Sleep().Memory locationFunctions are saved as project-related functions in the canape.ini configuration filein your working directory.Function typesA distinction is made in CANape between user-defined functions and CASL functionspredefined by CANape.User-definedfunctionsUser-defined functions include project functions written by the user as well aseditable library functions. Both are displayed in the Symbol Explorer of CANape.Global functionlibraryYou obtain the library functions if you choose to have the global function librarycreated during the setup process (default setting). For details, see section GlobalFunction Library on page 45).Project functionYou see the user-written functions or edited functions under Project functions in thetree view of the Functions Editor.Function groupsBy contrast, the user cannot change the CASL functions of various function groupspredefined by CANape, such as diagnostic or Flash functions. These merely executecertain commands that you, in turn, can use within your user-defined functions andscripts. For details, see section Predefined Function Groups and Code Blocks ofCANape on page 16.MeasurementfunctionA measurement function is understood to be the combination of the function and themeasurement parameters (see section Using a Function During a Measurement onpage 35). Measurement functions are displayed under MeasurementSignal Functions in the tree view of the measurement configuration in CANape.2.3What Are ScriptsIntroductionScripts are parts of the program code and can be defined across devices in CANape.SyntaxThe code of a script follows the rules of the CASL language (Calculation and ScriptingLanguage).It can be written directly in the Editor window of the Functions Editor and is processedsequentially when called.TasksScripts are used in order to automate or control joint activities in CANape, such as thestarting and stopping of measurements and other system-related sequences.Scripts run independently of the measurement.They can also be used to call external models that are generated in Microsoft VisualStudio or MATLAB/Simulink.Script call-upScripts can be called in different ways. For call-up from the CANape user interface,see section Call-up of Scripts on page 53.In addition, the script behavior can be controlled using command line options whenCANape is running (see section Script Behavior When CANape is Running on page58). Vector Informatik GmbHVersion 1.2- 10 -

User Manual CANape CASLBasic InformationProcess priority ofscriptsScripts are subject to a relatively low process priority. Their execution is guaranteedonly every 100 ms.DebuggingDebugging of scripts using breakpoints is available for diagnosing and locating logicerrors in user-defined scripts. For details, see section Debugging of Scripts on page58.File format andmemory locationScripts are separate files in the *.scr or *.cns script format that can be copied toanother project directory at any time. Scripts are saved in your working directory bydefault.Example scriptsCANape includes examples scripts in its various sample configurations. These aredisplayed under Scripts in the tree view of the Functions Editor after the respectivesample configuration is opened. The user-defined scripts are also listed here.2.4Differences Between Functions and ScriptsProcess priorityDue to their relatively low process priority, scripts run asynchronously relative to themeasurement. Functions, on the other hand, are executed with high process priorityand synchronously with the measurement.As a result, limitations arise for functions such as the Sleep() script function. Incomparison to functions, scripts have a more extensive selection of predefinedfunction groups such as additional file and script functions, Flash functions, anddiagnostic and Data Mining functions.Return valuesThe RETURN keyword can return a value of data type DOUBLE (a scalar, no datafield/array, etc.) to the calling routine.Note: Return values of scripts cannot be evaluated at present.DebuggingUnlike scripts, functions cannot be debugged using breakpoints due to their highpriority. Instead, you can output debug information in the Write window usingWrite(), Writef(), Print(), or Printf() (see section Debugging of Functionson page 47).SubfunctionsIn CANape subfunctions of scripts are referred to as subfunctions. Thus,subfunctions are not available for functions.The definition of the subfunction must be written before the main part of the script.Arguments for the subfunction can be specified optionally.If during a measurement a Function2 is called from a different Function1, theterm subfunction would also be used for Function2 in common usage.In CANape, however, the term subfunction is not used in this context.Program codeScripts do not require a function header and body. The program code can simply bewritten directly to the editor and is then processed sequentially.FormatFunctions must be in the Functions Editor export format (*.cne) or in the ASCII text Vector Informatik GmbHVersion 1.2- 11 -

User Manual CANape CASLBasic Informationformat (*.txt). Scripts must be in the script format (*.scr or *.cns).Memory locationA function is saved to the canape.ini configuration file in your working directory.Script files instead are saved as a separate file in the working directory.FormatScripts are files in the *.scr or *.cns script format. Functions, however, areembedded in the canape.ini.2.5Functions EditorTasksGlobal variables, functions, scripts, and Seed & Key algorithms can be created,edited and compiled in the Functions Editor of CANape.Opening the Functions Editor1. Click theicon in the toolbar.orClick Functions and scripts in the Tools menu.The Functions Editor opens.List viewEditor windowTree viewMessage windowFigure 2-1: The Functions Editor in CANape Vector Informatik GmbHVersion 1.2- 12 -

User Manual CANape CASLAreas of theFunctions EditorBasic InformationThe Functions Editor is divided into the following areas: Tree view List view Editor window Message windowTree viewThe tree view lists all of the elements present. Global variables Project functions Scripts Seed & Key algorithmsList viewVarious tabs are located at the lower edge of the list view. Depending on the selectedtab, different information about the elements are displayed.The information columns can be sorted by a click on the respective column header.Message windowThe Output tab of the Message window displays error and progress messages.These messages can be processed via the popup menu.If debugging is activated, the variables, breakpoints, and debug tasks active in eachcase are also displayed here.Note: The Functions Editor in CANape offers two types of help that enable functionsand scripts to be created with little programming knowledge. Context-sensitive help: Place the cursor on a function definition in the popupmenu of the Editor window and click F1 . The help page for the correspondingfunction opens. Automatic syntax completion: When typing in the Editor window, a suggestionlist of all available functions, objects, and global variables whose names begin withthe typed-in letters is displayed. The suggestion is applied with [Enter] or the Tab key.2.6Additional Definitions2.6.1 Variable TypesAgreementVariables are placeholders for values of a certain type. Variables can be declared anddefined in scripts and functions.Definition(Type Value)In the case of definition, a value is assigned to the compiler. Undefined localvariables always have the start value 0. The definition of variables thus serves tocreate the type of variables and to create data objects in the memory.Declaration(Name Type)In the case of declaration, the respective variable is made known to the compiler.The declaration always consists of the name of an object and its type. As a result,the compiler knows which type it must connect a name to.Global variablesGlobal variables are declared in the list or tree view of the Functions Editor and canbe used in any function or script, for example.Local variablesLocal variables can be declared in the function or script header and can also besimultaneously defined. In/out parameters are declared in the parameter list of thefunction.LifespanWhile global variables live as long as the program, local variables are only valid Vector Informatik GmbHVersion 1.2- 13 -

User Manual CANape CASLBasic Informationduring the block call.Device variables2.6.1.1A device variable can be used to access a device-internal value.Global VariablesUsesGlobal variables are special data objects that can be used by all functions and scriptsin the CANape configuration.You can use global variables to pass information to other functions or scripts withoutthe help of in/out parameters.DefinitionGlobal variables are defined in the Functions Editor. One-dimensional ormultidimensional arrays as well as variables can be defined as global variables.Memory locationGlobal variables are saved as project-related global variables in the canape.iniconfiguration file in your working directory.PropertiesA global variable consists of a name, comment, data type, and conversion rule,among other things.ValidityGlobal variables are valid CANape-wide. They can be inserted into a Calibrationwindow so that the values of the variables can be changed by the user during themeasurement.OverwritingThey are overwritten by local variables and function arguments having the samename.Static behaviorGlobal variables are static. They retain their value between two measurements aswell as after loading of the project. Their current value is saved in a parameter filewhen the configuration or project is saved and reloaded when loading the project.Note: Note that values that were saved in a global variable during a priormeasurement are still present at the start of a new measurement.Integrating inCANapeFor information on how to create a global variable, read section Creating a GlobalVariable on page 61.In addition, for a description of how you can influence when the global variable is tobe set to a defined value, see section Setting a Global Variable to a Defined Value onpage VariablesValidityLocal variables are only valid within the respective function or script.OverwritingThey overwrite global variables of the same name and are, in turn, overwritten byfunction arguments of the same name.DeclarationIn contrast to C up to and including CANape 11.0, local variables can be declaredonly at the start of a function or script and retain their validity throughout the function.With CANape 12.0, a declaration within a function and within a block statement (e.g.,If statement or for loop) is also possible.DefinitionUndefined local variables always have the start value 0.Example: In the following example function, c is a local variable and A is an in/outparameter. Vector Informatik GmbHVersion 1.2- 14 -

User Manual CANape CASLBasic Informationfunction Function1 (Var A){double Result;Result A;if (A 0){int c 2; // no syntax error CANape 12.0 or higherResult c;}return Result;}Static or non-staticbehaviorLocal variables can exhibit static or non-static behavior in CANape. Static behaviormeans that the variables retain their value between the respective function calls.Below is an overview of the behavior of local variables within CANape:Location of variableBehaviorStaticNon-staticScriptDifferent start valuesXFunction in the scriptXUser-defined functionXUser-defined function when called by a scriptXUser-defined function when called by a user-definedfunctionXUser-defined function when called by a script functionXIf a function is used, for example, in the Data Mining environment or as a virtualmeasurement file channel, CANape provides the option of assigning a different startvalue of a local variable to each instance of a function.For information on how to set a local variable to a defined value, see section Setting aLocal Variable to a Defined Value on page VariablesAccess to deviceinternal valueA device variable can be used to access a device-internal value and to change it,when possible (database-dependent). The communication with the device takes placein the background without the user having to explicitly take care of this.ChangesChanges to device variables act immediately on the corresponding device.InsertingThe available device variables can be viewed in the Functions Editor via the popupmenu and inserted into functions and scripts. For information on how to insert adevice variable, see section Inserting a Device Variable on page Arguments and In/Out Parameters (of Functions)Passing as reference Arguments or in/out parameters are always passed to functions as reference (byreference) and can thus also be used for return of values (see also section WhatAre Functions on page 8).They overwrite local and global variables having the same name and can only take on Vector Informatik GmbHVersion 1.2- 15 -

User Manual CANape CASLBasic Informationthe equivalent var and double values as the data type.Function AAs a result, the following two functions are identical:function Add (var A, var B){return A B;}Function Bfunction Add (double A, double B){return A B;}Parameter typesTwo types of parameters are possible: Scalar and array parameters.Scalar parametersAny scalar variable, an individual array element, or a constant may be used as anargument for scalar parameters.Array parametersTo define array parameters, [ ] must be placed directly after the parameter name. Anyarray variable, constant strings, or global/database variables of type String may beused as an argument for array parameters.Optionally, the keyword var or double may be used as the data type prefix. There isno difference in the case of words. Other prefix types are not supported.2.6.3 CommentsDocumentationComments are used to document a section of code within a program. They aremarked by // for a single-line comment or are placed between /* . */ for multiline comments.2.6.4 Taking Upper and Lower Case Into AccountVariable namesVariable names in functions and scripts, global variables, and variables referencedfrom a database in the CANape Functions Editor are case sensitive.Device and functionnamesDevice names and internal function names are not case sensitive.2.6.5 Predefined Function Groups and Code Blocks of CANapeSupportCANape provides you with code blocks and various function groups to support youwhen drafting your functions.Code blocksRight click in the Editor window to open the popup menu. Select the desired codeblock, e.g., a control structure. Become familiar step-by-step with the C-like syntax ofCANape's own programming language.Function groupsSelect between the various CASL functions predefined by CANape. These areorganized into the following function groups:PrecompilerdirectivesPrecompiler directives for conditional compilation. On the basis of the precompilerdirectives, the precompiler can decide based on expressions and symbols which partof the source code can be inserted and compiled and which can be removed, Vector Informatik GmbHVersion 1.2- 16 -

User Manual CANape CASLBasic nometric functions can be used to calculate relationships between angle andheight-width ratio.Exponential functions Exponential functions can be used to calculate logarithms and powers and s functions include all functions not assigned to one of the othergroups.Access attributesBy means of the function group of the access attributes, you have access to featuresof various data objects, such as measurement values, axes, and maps/characteristiccurves. Features of data objects can be color, quantity, status, address, etc.Program functionsGeneral accesses to CANape are possible using program functions.The following subgroups provide more specific accesses: User input: Shows various dialogs Output: Formats outputs of a string, describes the progress display Control: Controls the various CANape windows Panel: Sets stop watches and accesses control and display elements. Configuration: Involves configurations and partial configurationsDevice functionsYou can use device functions to access devices directly as well as to access theirdatabases, drivers, status, etc.MeasurementThe functions of the Measurement function group enable access to a wide range ofactions that concern measuring. In the Recorder and Trigger subgroups, you will findfunctions that access the recorders and their triggering.CalibrationThe functions of the Calibration function group can be used to access parametersets and to change the calibration mode of devices. In addition, you receive read- andwrite-access to the device memory and access to the various values (physical, raw,or string values) of objects. The block-wise modification of a device can also becontrolled.In the Datasets subgroup, you will find the functions for handling datasets.EvaluationThe functions of the Evaluation function group enable access to the globalmeasurement and differential cursor and the time offset as well as to comments andinformation on trigger events. In addition, portions of an integer signal can beextracted or measurement values of a signal can be determined as a string.DatabaseThe functions of the

Note: Do not confuse CASL with the programming language CAPL, which is used in the CANoe and CANalyzer environments. CAPL is an event-oriented programming language. So-called CAPL program nodes are used to specify when an event will be executed and the nature of the reaction. CASL, on the other hand, is a signal-oriented language. 1.4 Prior .