Controls State Notation Language (SNL) and Sequencer April 23, 2012 Kukhee Kim ICD Software SLAC National Accelerator Laboratory SNL and Sequencer 1 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Contents State Notation Language / Sequencer Definition of Terms State Transition Diagram Example 1: Simple Switch ON/OFF SNL General Syntax & Structures Declaration for Variable, Assigment, and Event Flags Event Action Example 2: Life Game SNL Variables and its Lifetime and Scopes Dynamic PV assignment Building SNL code Runtime Sequencer Executing SNL Program Debugging Additional Features Advantage of SNL Program SNL and Sequencer 2 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls SNL and Sequencer SNL is “C” like language for programming sequential operations The sequencer runs program which written in the SNL Fast execution using compiled code Common uses automated start-up and sequencing fault recovery or transition to safe state automatic calibration SNL and Sequencer 3 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Sequencer in an IOC LAN Channel Access IOC Sequencer Database Device Support I/O Hardware SNL and Sequencer 4 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Sequencer at CA Client side Tools Sequencer MEDM Client Client Client MEDM LAN Server IOC IOC IOC Meter Power Supply Camera SNL and Sequencer 5 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Definitions SNL: State Notation Language SNC: State Notation Compiler Sequencer: The tool that executes the compiled SNL code Program: A complete SNL application, consisting declarations and one or more state sets State Set: A set of states that make a complete finite state machine State: A particular mode of the state set in which it remains until one of its transition conditions evaluates to TRUE SNL and Sequencer 6 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls State Transition Diagram SNL- A tool to implement State Transition Diagram State A Event Transition A to B Action State B SNL and Sequencer 7 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Example 1 – On/Off switch State transition to ON Initialize signal No transition Threshold to ON State ON State transition to OFF Event: Threshold to OFF signal Toff Action: turn off the light time State OFF off on off on off Event: signal Ton Action: turn on the light SNL and Sequencer 8 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Example 1 – Sneak Look Initialize State ON Event: signal Toff Action: turn off the light State OFF Event: signal Ton Action: turn on the light SNL and Sequencer 9 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Example 1 – Sneak Look SNL and Sequencer 10 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC SNL: General Structure & Syntax Controls program program_name declarations ss state_set_name { state state_name { entry { entry action statements } when (event) { action statements } state next_state_name when (event) { ... } state next_state_name exit{ exit action statements } } state state_name { ... } } SNL and Sequencer 11 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC SNL: General Structure & Syntax Controls program name ss name { state name { option flag; when (event) { } state next entry {actions} exit {actions} A program may contain multiple state sets. The program name is used as a handle to the sequencer manager for state programs. Each state set becomes a separate task or thread. A state is somewhere the task waits for events. When an event occurs it checks to see which action it should execute. The first state defined in a state set is the initial state. A state-specific option. Define events for which this state waits. Specifies the state to go to when these actions are complete. Actions to do on entering this state. With option -e; it will do these actions even if it enters from the same state. Actions to do on exiting this state. With option -x; it will do these actions even if it exits to the same state. SNL and Sequencer 12 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Declaration: Variables Appear before a state set and have a scope of the entire program. Scalar variables int var_name; short var_name; long var_name; char var_name; float var_name; double var_name; string var_name; /* 40 characters */ Array variables: 1 or 2 dimensions, no strings int var_name[num_elements]; short var_name[num_elements]; long var_name[num_elements]; char var_name[num_elements]; float var_name[num_elements]; double var_name[num_elements]; SNL and Sequencer 13 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Declaration: Assignments Assignment connects a variable to a channel access PV name float pressure; assign pressure to "CouplerPressureRB1"; double pressures[3]; assign pressures to {"CouplerPressureRB1", "CouplerPressureRB2", " CouplerPressureRB3"}; To use these channels in when clauses, they must be monitored monitor pressure; monitor pressures; Use preprocessor macros to aid readability: #define varMon(t,n,c) t n; assign n to c; monitor n; varMon(float, pressure, "PressureRB1") SNL and Sequencer 14 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Declaration: Event Flags Event flags are used to communicate events between state sets, or to receive explicit event notifications from Channel Access Declare them like this: evflag event_flag_name; An event flag can be synchronized with a monitored variable sync var_name event_flag_name; The flag will then be set when a monitor notification arrives, e.g. evflag pressure_event; Sync pressure pressure_event; SNL and Sequencer 15 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Event Event: A specific condition on which associated actions are run and a state transition is made. Possible events: Change in value of a variable that is being monitored: when (achan < 10.0) A timer event (this is not a task delay!): when (delay(1.5)) The delay time is in seconds and is a double; literal constant arguments to the delay function must contain a decimal point. The timer starts when the state containing it was entered. Use the state specific option -t; to stop it from being reset when transitioning to the same state. SNL and Sequencer 16 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Event (continued) The state of an event flag: when (efTestAndClear(myflag)) when (efTest(myflag)) efTest() does not clear the flag. efClear() must be called sometime later to avoid an infinite loop. If the flag is synced to a monitored variable, it will be set when the channel sends a value update The event flag can also be set by any state set in the program using efSet(event_flag_name) Any change in the channel access connection status: when (pvConnectCount() < pvChannelCount()) when (pvConnected(mychan)) Any combination of the above event types SNL and Sequencer 17 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Action Built-in action function, e.g. : pvPut(var_name); pvGet(var_name); efSet(event_flag_name); efClear(event_flag_name); Almost any valid C statement switch() is not implemented and code using it must be escaped. %% escapes one line of C code %{ escape any number of lines of C code }% SNL and Sequencer 18 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Example 2: Life Game SNL and Sequencer 19 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Example 2: Life Game Basic Rule of Life Game Rule 1: Any live cell with fewer than two live neighbors died, as caused by under population. Rule 2: Any live cell with two or three live neighbors lives on to the next generation. Rule 3: Any live cell with more than three live neighbors died, as if the overcrowding. Rule 4: Any dead cell with exactly three live neighbors become a live cell, as if production SNL and Sequencer 20 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Example 2 - Continued Requirements 20x20 Bo records to represents cells Adjustable Initial population density (Ao record, operation range [0. to 1.] If the initial population density is changed, then starts new game Initialize cells with random number generator + constraint for the initial population density Evolution to next generation few times in a second Provides basic statistics: number of live cells and number of dead cells Additional Requirement Monitor the live cell counter in the statistics If the system reaches to thermal equilibrium (the counter values is not changed during 5 seconds) then, start new game. To start new game, apply a slight change on the initial population density (use, random walk, init_pop += small random number();) SNL and Sequencer 21 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Example 2 – State Diagram Init Entry: dynamic assignment for 20x20 PVs Event: if the initial population has been changed InitArray Event: if the initial population has been changed Entry: 1) Initialize work space with random + initial population density Exit: 1) Copy work space to the PV assigned variables 2) Make statistics for the current generation 3) Update PVs for display Event: always Run Entry: evolutes cells for next generation Exit: 1) Copy work space to the PV assigned variables 2) Update PV for display SNL and Sequencer 22 Event: if timer has been expired EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Example 2: C escapes SNL and Sequencer 23 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Example 2: C escapes SNL and Sequencer 24 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Example 2: Declarations SNL and Sequencer 25 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Example 2: Init State SNL and Sequencer 26 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Example 2: initArray State SNL and Sequencer 27 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Example 2: run State SNL and Sequencer 28 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Example 2: Additional State Set State Set: new_game INIT Event: changed live cell counter Action: update previous live cell counter to current loop Event: expired timer Action: random walk on the initial population State Set: main_loop Live cell counter PV Initial Population SNL and Sequencer 29 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Example 2: Additional State Set SNL and Sequencer 30 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls SNL Variable and Scope Global Variables lifetime/scope: entire program Memory allocation by sequencer with option +r; program mySNL option +r; double a; assign a to pvA; monitor a; Static variable in C with option –r; Local Variables State Set ss my_state_set { double b; state low { int i=0; Memory allocation by Sequencer State Memory allocation by Sequencer Entry/Exit/Action function when(a>0.5) { int j ; b = a; i++; for(j=-0;j<MAX;j++) { Stack variable SNL and Sequencer 31 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls SNL Variable’s Scope and Lifetime with Reentrance Variable Type Lifetime Scope Implementation Access in C escape Initialization Global static Program Instance malloc pVar->myVariable Yes, G_prog_init Local in a State Set static State Set malloc pVar->UserVar_myStateSet.myVariable Yes, G_prog_init Local in a State static State malloc pVar>UserVar_myStateSet.UserVar_myState.myVariable Yes, G_prop_init Local in a When() Function call Inside the when statement (action function) Stack variable myVariable NO Local in an entry/exit Function call Inside entry/exit (entry function/exit function) Stack variable myVariable NO SNL and Sequencer 32 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls SNL Variable’s Scope and Lifetime with Non-Reentrance Variable Type Lifetime Scope Implementation Access in C escape Initialization Global static Program Static variable myVariable Yes, Compiletime Local in a State Set static State Set Static structure UserVar_myStateSet.myVariable Yes, Compiletime Local in a State static State Static structure UserVar_myStateSet.UserVar_myState.myVariable Yes, Compiletime Local in a When() Function call Inside the when statement (action function) Stack variable myVariable NO Local in an entry/exit Function call Inside entry/exit (entry function/exit function) Stack variable myVariable NO SNL and Sequencer 33 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Dynamic PV assignments To allow PV assignment/re-assignment at runtime Requires an initial assigment (or NULL assignment) in the Declaration Section for single variables double myVar; assign myVar to “”; ...... pvAssign(myVar, “PV_MYVAR”); for array variables double myVar[MAX]; assign myVar to { “” }; ...... for(i=0;i<MAX;i++) pvAssign(myVar[i], str_pvName[i]); SNL and Sequencer 34 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Building an SNL Program Use editor to build the source file. File name must end with “.st” or “.stt”, e.g. “example.st” “make” automates these steps: Runs the C preprocessor on “.st” files, but not on “.stt” files. Compiles the state program with SNC to produce C code: snc example.st -> example.c Compiles the resulting C code with the C compiler: cc example.c -> example.o The object file example.o becomes part of the application library, ready to be linked into an IOC binary. The executable file “example” can be created instead. SNL and Sequencer 35 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls .st vs. .stt .stt .stt program ex1 option –r; #define MAX program ex1 Option –r; %{ #define MAX 20 Syntax error in SNL double myArray[MAX]; ss { myStateSet state myState { Define Macro in C escape 20 --- nip --for(i=0;i<MAX;++) { --}% double myArray[MAX]; when(index>= MAX) { ss { OK! to use macro in the C escape and the SNL code both SNL and Sequencer 36 Illegal to use the macro in the declaration myStateSet state myState { when(index>= MAX) { EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls .st vs. .stt - continued .st program ex1 option –r; #define MAX C preprocessing 20 %{ --- nip --for(i=0;i<MAX;++) { --}% Illegal, because the SNC doesn’t have compile time arithmetic double myArray[MAX]; double my2DArray[MAX*MAX] ss { myStateSet state myState { when(index>= MAX) { double a[MAX*MAX]; program ex1 option –r; /* #define MAX 20 */ %{ --- nip --for(i=0;i<20;++) { --}% double myArray[20]; double my2DArray[20*20] OK to use in the local variable in action/entry/exit function. C compiler does the compile time arithmetic SNL and Sequencer 37 ss { myStateSet state myState { when(index>= 20) { double a[20*20]; EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Runtime Sequencer The sequencer executes the state program It is implemented as an event-driven application; no polling is needed Each state set becomes an operating system thread The sequencer manages connections to database channels through Channel Access It provides support for channel access get, put, and monitor operations It supports asynchronous execution of delays, event flag, pv put and pv get functions Only one copy of the sequencer code is required to run multiple programs Commands are provided to display information about the state programs currently executing SNL and Sequencer 38 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Executing SNL Program From an IOC console On vxWorks: seq &vacuum_control On RTEMS seq(&vacuum_control) On other operating systems: seq vacuum_control To stop the program seqStop "vacuum_control" SNL and Sequencer 39 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Debugging Use the sequencer's query commands: seqShow displays information on all running state programs seqShow vacuum_control displays detailed information on program seqChanShow vacuum_control displays information on all channels seqChanShow vacuum_control,"-" displays information on all disconnected channels seqcar displays information on all channel access channels SNL and Sequencer 40 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Additional Features Connection management: when (pvConnectCount() != pvChannelCount()) when (pvConnected(Vin)) Macros: assign Vout to "{unit}:OutputV"; must use the +r compiler options for this if more than one copy of the sequence is running on the same ioc seq &example, "unit=HV01" Some common SNC program options: +r make program reentrant (default is -r) -c don't wait for all channel connections (default is +c) +a asynchronous pvGet() (default is -a) -w don't print compiler warnings (default is +w) SNL and Sequencer 41 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Additional Features – Cont’d Access to channel alarm status and severity: pvStatus(var_name) pvSeverity(var_name) Queued monitors save CA monitor events in a queue in the order they come in, rather than discarding older values when the program is busy syncQ var_name to event_flag_name [queue_length] pvGetQ(var_name) removes oldest value from variable's monitor queue. Remains true until queue is empty. pvFreeQ(var_name) SNL and Sequencer 42 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Advantage of SNL Program Can implement complicated algorithms Can stop, reload, restart a sequence program without rebooting Interact with the operator through string records and mbbo records C code can be embedded as part of the sequence All Channel Access details are taken care of for you File access can be implemented as part of the sequence SNL and Sequencer 43 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC Controls Acknowledgements Andrew Johnson, AES basic EPICS Training – January 2011 Benjamin Franksen, new Seq modules SNL and Sequencer 44 EPICS Training Class EPICS Collaboration Meeting 2012 @ SLAC