User Reference:Operator Module Scripting

From BCI2000 Wiki
Jump to navigation Jump to search

Operator scripts automate actions that the otherwise would be performed by the user, e.g. starting or suspending system operation. Scripts may be contained in script files, or given immediately in the operator module's preferences dialog. There is also an option to specify scripts from the command line when starting the operator module. When using the Operator Library from your own application, you may execute scripts at any time.

Also, the operator scripting language is used to control an operator module over a telnet connection.

Events

In the Operator GUI, script execution is bound to a number of events that occur during various stages of BCI2000 system operation:

OnConnect

This event is triggered at startup, as soon as all modules are connected to the operator module.

OnSetConfig

This event is triggered each time a set of parameters is applied to the system. This happens when the user clicks the SetConfig button. Execution of the SETCONFIG command also triggers this event.

OnStart, OnResume

These events correspond to the Start/Resume button. One of these events is also triggered when the Running state variable is set to 1 from a script. Whether OnStart or OnResume is triggered depends on whether the system has been running before with the current set of parameters.

OnSuspend

Triggered when the system goes from running into suspended mode. This happens whenever the Running state variable changes from 1 to 0. This may happen when the user clicks Suspend, when the application module switches the system into suspended mode, or when a script sets the Running state variable to 0.

OnShutdown

Triggered when the operator module shuts down connections, and switches into idle state.

OnExit

Triggered when the operator module exits. Execution of the QUIT command also triggers this event. This event is not available to the SET SCRIPT and CLEAR SCRIPT commands. Also, when both an OnShutdown and an OnExit script are defined, the OnExit script will be executed before the OnShutdown script.

Commands

Control commands

These commands allow conditional execution of parts of a script. When a condition is expected, any other scripting command may be given. Its result will be considered to represent a boolean value of "true" if it is empty, a nonzero number, or the string "true". It will be taken to represent a boolean value of "false" if it contains a numeric value of zero, or any string that does not evaluate to a nonzero number. Note that identification of an empty value with "true" differs from string handling in the EVALUATE CONDITION command. This is because most scripting commands return nothing on success, but an error message on failure.

The output of the SYSTEM and START EXECUTABLE commands is handled specially. There, the result code of the created child process is translated into a boolean value in the ordinary manner, treating a result code of zero as "true", and any other result code as "false". This allows to use external commands in the same way as in a native shell.

IF <condition>; <if commands>; [ ELSEIF <condition>; <elseif commands>;] ... [ ELSE; <else commands>;] END

Executes if commands if condition evaluates to "true". Otherwise, the elseif commands of the first matching elseif condition are executed. When none of the elseif conditions evaluates to "true", else commands are executed. ELSEIF and ELSE blocks may be omitted.

WHILE <condition>; <loop commands>; END

Executes loop commands while condition evaluates to true.

DO; <loop commands>; UNTIL <condition>

Executes loop commands until "condition" evaluates to true.

FOR <name> IN <item1> <item2> ... ; <loop commands>; END

Creates a local variable with the specified name. Then, sequentially assigns each item to that variable, and executes loop commands. If an item contains newline characters, it is split up into multiple items, corresponding to the lines contained in the item. E.g.,

FOR i IN top ${LIST FILES} bottom; LOG ${i}; END

will first write a log entry "top". Then, it will create a log entry for each file in the current directory, and finally, it will create a log entry "bottom".

Commands operating on Conditions

EVALUATE CONDITION <left> [<op> [<right>]]

Evaluates a comparison between the left and right operands. As a comparison operator, the following may be specified: ==, !=, ~=, <, >, <=, >=. There, the != operator behaves identically to the ~= operator. When a test for equality is performed, the two operands are treated as strings, and compared in a case-insensitive manner. When any of the inequality tests is performed, the two operands are converted into floating-point numbers before comparison.

The right operand may be omitted, in which case it is treated as if an empty string were specified. Also, the op operator may be omitted, in which case the following rules apply regarding the remaining operand: If it is an empty string, or equal to the string "false" in case-insensitive comparison, the result is "false". If entirely consists of the text representation of a floating-point number, the result is "false" if the number is 0, and "true" if the number is not 0.

Inspired by the GNU bash shell, there exists a short form of the EVALUATE CONDITION command, where the arguments of EVALUATE CONDITION may appear within square brackets. This allows constructs such as

IF [ ${MyVar} == MyValue ]; LOG Is equal; ELSE; LOG Is different; END

Note that the arguments to EVALUATE CONDITION must always be separated by white space, no matter whether its long or short form is used.

Commands operating on Variables

These scripting commands allow to read and modify environment variables. Changes to environment variables will be visible to child processes started with SYSTEM or START EXECUTABLE. Variable values are stored as strings. Variable names may not contain the equals sign.

SET VARIABLE <name> <value>

Sets the named variable to the specified value.

CLEAR VARIABLE <name>

Removes the named variable from memory.

GET VARIABLE <name>

Returns the variable's current value. When the variable does not exist, an empty value is returned rather than an error message.

Commands operating on Scripts

SET SCRIPT <events> <scripting commands>

Associates a sequence of scripting commands with the given events. Events are specified by names as given above. Multiple events may be specified by concatenating their names with a pipe character, e.g. "OnStart|OnResume".

Scripting commands must be included in double quotes, unless they consist of a single word. When specifying a sequence of scripting commands, they must be separated with a semicolon character: "SetConfig; Start". In order to use double quotes or semicolons within the commands themselves, encode these as you would in an URL, i.e. replace a double quote character with %22, and a semicolon with %3B: "Load Parameters %22my file%22".

To associate an event with a script file rather than a literal script, use the EXECUTE SCRIPT command:

SET SCRIPT OnConnect "EXECUTE SCRIPT myscript.txt"
GET SCRIPT <event>

Returns the script associated with the specified event.

CLEAR SCRIPT <events>

Clears scripts for the given events. Equivalent to calling SET SCRIPT with an empty script.

EXECUTE SCRIPT <file or event>

Executes a script contained in a file. To execute a script associated with an event, provide an event name rather than a file.

Commands operating on Parameters

LOAD PARAMETERFILE <file>, LOAD PARAMETERS <file>

Loads a parameter file specified by its path and name. Relative paths are interpreted relative to the operator module's working directory at startup. Usually, this matches the executable's location in the prog directory. As the parameter file name must not contain white space, please use HTML-type encoding for white space characters, such as Documents%20and%20Settings when referring to a user's "Documents and Settings" folder.

ADD PARAMETER <parameter definition>

Adds a parameter to the system. The parameter is specified as a parameter line. This command may not be used after system initialization has completed, i.e. its use is restricted to the "Idle" and "Publishing" phases of system operation. In terms of events, its use is restricted to the OnConnect event.

SET PARAMETER <name>[( idx1, idx2 )] <value>

Sets the named parameter to the specified value. Values that contain special characters, or whitespace must use the parameter value encoding. Use parentheses to specify indices or labels.

SET PARAMETER <parameter line>

Replace a parameter's value and definition with the information given in the parameter line. The parameter must exist in the system when this command is executed. 0

GET PARAMETER <name>[( idx1, idx2 )]

Prints the value of the named parameter. Use parentheses to specify indices or labels. Use parentheses to specify indices or labels.

LIST PARAMETER <wildcard expression>, LIST PARAMETERS

Prints all parameters with names matching the wildcard expression, in form of parameter lines.

CLEAR PARAMETERS

Clears the list of parameters in the system. May only be executed in Idle and Publishing system states.

Commands operating on States

ADD STATE <name> <bit width> <initial value>

Adds a state variable to the system. State variables are defined by name, bit width, and initial value (see Technical Reference:State Definition). This command may not be used after system initialization has completed, i.e. its use is restricted to the "Idle" and "Publishing" phases of system operation. In terms of events, its use is restricted to the OnConnect event.

SET STATE <name> <value>

Sets the named state variable to the specified integer value. Setting the Running state to 1 will start system operation, setting it to 0 will suspend the system.

GET STATE <name>

Gets the value of the named state. Note that state values are not updated from the application module when the OperatorBackLink parameter is 0. In that case, GET STATE will return the state's initial value.

LIST STATE <wildcard expression>, LIST STATES

Lists all states, or states with names matching the given wildcard expression, in form of state lines.

CLEAR STATES

Clears the list of states in the system. May only be executed in Idle and Publishing system states.

Commands operating on Events

Events are a special type of state, which are recorded asynchronously, at single-sample resolution. Events may only be added while the system is in "idle" state. This kind of events is not related to Operator Events as defined above.

ADD EVENT <name> <bit width> <initial value>

Adds an event to the system. Like state variables, events are defined by name, bit width, and initial value (see Technical Reference:State Definition). This command may not be used after the system has started up, so it is typically executed within a telnet session before STARTUP has been called.

SET EVENT <name> <value>

Asynchronously sets an event to the given value. Recording events requires the EventLink logger component to be present in the source module.

GET EVENT <name>

Gets the value of the named event. Note that evemt values are not updated from the application module when the OperatorBackLink parameter is 0.

LIST EVENT <wildcard expression>, LIST EVENTS

Lists all events, or events with names matching the given wildcard expression, in form of state lines.

CLEAR EVENTS

Clears the list of events in the system. May only be executed in Idle state.

Commands operating on VisProperties

SET VISPROPERTY <visID>.<name> <value>

Sets the named visualization property for the specified visualization ID to the given value. If the visualization ID contains a dot character, it must be encoded in parameter value encoding. E.g., setting the window width for the visualization ID "2.D1" would be written SET VISPROPERTY 2%2ED1.Width 200.

GET VISPROPERTY <visID>.<name>

Prints the value of the named visualization property for the specified visualization ID.

SET VISPROPERTIES <property set ID>

Applies a set of visualization property values as given in the VisPropertySets parameter. In that matrix-valued parameter, row labels specify visualization properties such as "SRCD.Left", and columns represent sets of property values. Column labels are IDs of the corresponding property sets.

Commands operating on the Control Signal

GET SIGNAL( <channel index>, <element index> )

Prints the value of the control signal at the given indices. Indices are 1-based.

Commands operating on Expressions

EVALUATE EXPRESSION <expression>

This command treats the remainder of the command as a literal mathematical expression (for a description, see User Reference:Expression Syntax. An expression may contain variable assignments; such variables may then be used in later expressions. Note that expression variables are different from the environment variables that may be accessed by GET/SET VARIABLE. Expression variables hold numerical values, while environment variables hold string values. Also, environment variables are accessible to child processes started with SYSTEM or START EXECUTABLE, while expression variables are accessible only to scripts. When a script is executed using the EXECUTE SCRIPT command, it will inherit a copy of all expression variables present. Changes to these variables from the executed script will not be visible in the parent script. However, the result of the last script command will be the result of the EXECUTE SCRIPT command.

CLEAR EXPRESSION VARIABLE <name>

Clears the named expression variable from storage.

Commands operating on Files, Directories, and Paths

EXTRACT DIRECTORY <path>, EXTRACT FILE <path>, EXTRACT FILE BASE <path>

Extracts the directory or file portion of a given path. When the path specifies a non-existing directory, the directory name must be followed with a separator ("/") in order to be recognized as a directory. The EXTRACT DIRECTORY command always returns its result with a trailing separator. The EXTRACT FILE BASE command returns the file portion without extension.

IS DIRECTORY <path>, IS FILE <path>, IS PATH <path>

Determines whether the specified path points to an existing directory, file, or any of the two. The result is returned as one of the strings "true" or "false".

PARENT DIRECTORY <path>

Returns the parent directory of the specified path, independently of whether the path points to a directory, or to a file.

CURRENT DIRECTORY

Returns the current working directory.

CHANGE DIRECTORY <path>

Changes the working directory.

MAKE DIRECTORY <path>

Creates a new directory with the given path. The directory's parent must exist for the command to succeed.

LIST DIRECTORY [<path> or <wildcard expression>]

Returns a listing of the specified directory, or the current working directory if no path is specified. The listing is in long form. You may use wildcard expressions in order to restrict the output.

LIST FILE <wildcard expression>, LIST FILES [<wildcard expression>]

Returns a list of file names relative to the current directory. From LIST FILES, the argument may be omitted, which results in a list of all files.

CANONICAL PATH <path>

Translates the given path into canonical form, i.e. into an absolute path without symlinks. All directories along the path must exist in order for the command to succeed.

Global commands

SET <name> <value>, GET <name>, <name>

Allows to set or retrieve the value of parameters, states, and environment variables. The name is matched against parameter, state, and environment variables in this order. When no variable with the given name is found, SET will create such an environment variable, while GET will result in an error. GET may be further abbreviated to only consist of a name.

GET further allows evaluation of mathematical expressions. When the expression is invalid, or contains an unknown variable, an error is triggered.

GET SYSTEM STATE

Prints the current system state. This will be one of Unavailable, Idle, Startup, Initialization, Resting, Suspended, ParamsModified, Running, Termination, Busy.

WAIT FOR <system state> <timeout seconds=5>

Waits until the system is in the specified state. This may be one of Unavailable, Idle, Startup, Initialization, Resting, Suspended, ParamsModified, Running, Termination, Busy, or a combination of these, separated with a pipe character: "Resting|Suspended". When timeout occurs, an error message is returned.

SLEEP

Waits (sleeps) for the given amount of time. Timing resolution is 50ms. Tends to sleep a little longer than specified, with the error growing with duration.

GET SYSTEM VERSION

Prints BCI2000 version information.

SETCONFIG, SET CONFIG

Applies current parameters to the system. Corresponds to the SetConfig button in the GUI version of the Operator module.

START

Starts or resumes system operation, corresponding to the Start/Resume button in the GUI version of the Operator module.

STOP

Stops system operation. Corresponds to the Stop button in the GUI version of the Operator.

STARTUP

When in idle state, starts up the system to wait for incoming connections from core modules.

SHUTDOWN

Shuts down core modules, and enters idle system state.

QUIT, EXIT

Quits the operator module after terminating all BCI2000 modules.

SYSTEM <command line>

Executes a shell command, redirecting any console output into the command's script result. E.g., to obtain a directory listing, under Windows, you would enter

SYSTEM DIR
START EXECUTABLE <command line>

Starts the specified executable with options. This command returns immediately after the started program has finished initialization.

ECHO <arg1> ...=

Prints its arguments.

LOG <message>

Append the specified message to the system log.

WARN <message>

Append the specified message to the system log, formatted as a warning.

ERROR <message>

Append the specified message to the system log, formatted as an error message.

CAPTURE MESSAGES <message types>

Captures system log messages into a background buffer. When no message type is given, all messages are captured. When "None" is given as a message type, message capturing is disabled. Otherwise, the message type must be one of "Errors", "Warnings", "Debug", "Log". Multiple message types may be specified in a single command. When "None" appears within a single command, all preceding message types are ignored. Multiple CAPTURE MESSAGES commands are cumulative, except when "None" is specified as a message type.

FLUSH MESSAGES

Clears the background message buffer, and returns its previous content. Use CAPTURE MESSAGES to capture messages into the background message buffer.

Syntax

Command separation. Scripts consist of sequences of the above commands, terminated with either a newline, or a semicolon (;). When the semicolon is used to terminate commands, a single line may contain multiple commands. Commands are case-insensitive, values are case-sensitive.

Comments. Lines starting with a '#' character are ignored. Such lines may be used to hold comments.

Escaping. In order to resolve ambiguity about command arguments that contain white space, they must be included in double quotes, or the white space must be encoded in URL-fashion, e.g. %20 instead of a space character. Similarly, when an argument contains a semicolon (;), it must be included in double quotes, or the semicolon must be encoded in URL-fashion, i.e. as %3B. Also, backtick characters indicate command substitution, so they must be encoded as %60 if substitution is not desired.

Substitution. When part of a command is enclosed with ${...}, this subexpression will be substituted with the result of its execution as a command. E.g.,

LOG "Current system state is: ${GET SYSTEM STATE}"
LOG "The path environment variable is: ${PATH}"

Note that the last example uses the short form of the GET command, which will return the value of a PATH parameter or a PATH state if such exists. To make sure that only environment variables are matched, use the long form of the GET command:

LOG MESSAGE "The path environment variable is: ${GET VARIABLE PATH}"

Substitutions may be nested, i.e. the following will work:

SET MyVar "LIST STATES"; LOG "States are: ${${MyVar}}"

Mathematical Expressions. A command may consist of a single mathematical expression. This expression is then evaluated, and its result is returned as the command's result. As a special case, this allows the use of expression variables in ${...} substitutions. Consider for example

x:=0; WHILE x<10; LOG ${x:=x+1}; END

There, the first command creates and initializes the expression variable x. In the WHILE condition, an expression is allowed as well as any command. In the LOG command, an expression appears in ${...}, which executes the expression in braces, and substitutes the result of the expression as an argument into the LOG command, which adds an entry to the Operator log. This results in a sequence of 10 log entries, containing the numbers from 1 to 10.

Predefined Variables

Variables marked with local are not environment variables, i.e. they are invisible to child processes that are launched using the SYSTEM or START EXECUTABLE commands. In script code, they may be used like ordinary variables however.

BCI2000LAUNCHDIR

The full absolute path to the working directory when the Operator module was launched. This is also prepended to the PATH environment variable.

BCI2000BINARY

The full absolute path to the Operator module.

Arg0, Arg1, ... Arg9 (local)

When a script file is being executed, these variables contain the arguments of the EXECUTE SCRIPT command. Arg0 contains the full absolute path to the current script file. Outside of scripts, these variables do not exist.

YYYYMMDD (local)

Localtime at execution of the current script, in YYYYMMDD format. In interactive sessions, reflects the time when the session was initiated.

HHMMSS (local)

Localtime at execution of the current script, in HHMMSS format. In interactive sessions, reflects the time when the session was initiated.

Abbreviated commands and synonyms

To minimize the need of consulting documentation, as well as for backward compatibility, a number of synonymous commands are provided. E.g., states may be added by INSERT STATE as well as ADD state, and the existence of a file may be queried by IS FILE as well as EXISTS FILE. For an overview over all allowed forms of commands, enter the HELP command.

To simplify operation in interactive sessions, abbreviated commands exist. Currently, these are:

cd for CHANGE DIRECTORY,
pwd and cd without argument for CURRENT DIRECTORY,
ls and dir for LIST DIRECTORY.

For better readability of scripts, it is suggested to use the long forms of these commands.

Associating Scripts with Events

In the operator module's preferences dialog, scripts may be entered for each of the events listed above. Scripts may be specified as paths to script files, or as immediate one-line scripts. Entries that start with a minus sign (-) are treated as one-line scripts, which may contain multiple commands separated with semicolons.

Scripts may also be specified from the command line used to start up the operator module. There, event names are followed with the content of the respective preference entry, enclosed in double quotes ("...").

Finally, scripts may be specified using the SET SCRIPT command of the scripting language itself.

Examples

1

To add a state variable called "Artifact", and to set it using the operator's function buttons, do this:

  • Enter the following line under "After All Modules Connected" in the operator's preferences dialog (note the minus sign):
-ADD STATE Artifact 1 0
  • Under "Function Buttons", enter "Set Artifact" as the name of button 1, and as its command, enter (note there is no minus sign):
SET STATE Artifact 1
  • Enter "Clear Artifact" as the name of button 2, and as its command, enter
SET STATE Artifact 0

2

The following example shows how to specify script commands from the command line. It fully automates BCI2000 operation by loading a parameter file, applying parameters, starting the system once the parameters are applied, and quitting the system once the run is over. For better readability, the example is broken across lines, using the ^ DOS line continuation character.

operator.exe --OnConnect "-LOAD PARAMETERFILE ..\parms\examples\CursorTask_SignalGenerator.prm; SETCONFIG" ^
             --OnSetConfig "-SET STATE Running 1"  ^
             --OnSuspend "-QUIT"

See also

User Reference:Module Command Line Options, User Reference:Operator Module, Technical Reference:States of Operation