h1. SCT Reference
h2. Statechart elements
In the following the state chart elements of the YAKINDU SCT 2 editor are described. The meta model of the YAKINDU SCT 2 is the model of finite state machines. It is based on the view of a system that is defined by a finite number of states. The behavior of that system is based on the active states. These states are determined by the history of the state machine. Very important are the theoretical models for state machines by Mealy and Moore. Mealy state machines associate actions with transitions. Moore machines associate actions with states (entry, exit). In the YAKINDU SCT 2 both is possible.
The YAKINDU SCT 2 meta model is designed similar to the UML state chart meta model with the following differences
* they are self contained with interfaces defined by events and variables
* core execution semantics are cycle driven, not event driven
** this allows to process concurrent events
** event driven behavior can be defined on top
* time is an abstract concept for state charts
* time control is delegated to the environment
The model interpreter and different flavors of generated code follow these same core semantics.
Please refer to the description of the "UML Statecharts":http://en.wikipedia.org/wiki/UML_state_machine for more details.
h3. Regions
As already mentioned the YAKINDU state charts are self contained. They are organized in regions. Due to this it is possible to organize multiple state machines in different regions and to run them concurrently.
!images/parallelRegions.jpg!
h3. States
States are the central elements of a state machine. A state has to be placed inside a region and needs a unique name inside this region. During simulation each state can be active or passive. An active state has actions that are accomplished. Either an action is carried out on entering a state, during active state or on exit.
h3. Transitions
A transition is the transfer of one state to another. Transitions are diagrammed as arrows and can carry events and actions but must not.
The syntax of events and actions is defined by a textual description language (#Statechartdescriptionlanguage). Please refer to the documentation section "Events":#Events for more details. For more details on Actions refer to the chapter "Actions":#ReactionTriggers.
If a state has more than one outgoing transition without event that transition is carried out first that was modeled first.
h3. Initial state and final state
Initial and final states are pseudo states, because the state chart does not rest on them. Pseudo states express characteristics that are impossible to express by simple states.
The initial state is always the first state that is active during interpretation or simulation of the state machine. An initial state can only have one outgoing transition and no incoming. This transition has no events or actions.
Inside a region only one initial state is allowed, but every region can have an initial state.
h3. Choice
Choice is also a pseudo state. It can be used to model a conditional path. Choice nodes divide a transition into multiple parts.
Usually the first transition points towards the choice node. One of the choice outgoing transitions can carry a condition.
h3. Junction
A junction is a pseudo state do combine transitions. This is very comfortable if a state machine has many similar transitions. Junctions add clear arrangement to the state machine.
h3. Composite State
A composite state is a state that is composed of other state machines. These are also organized in regions. Besides the simple composite state YAKINDU knows two kinds of composite states: orthogonal state and submachine states.
Composite states contain other state machine branches.
h4. Orthogonal states
In the context of state machines orthogonal states are states that are independent from each other. The most famous example is the keyboard example:
!images/orthogonalState_example.jpg!
h4. Subdiagrams
When using Composite States, the statechart model often becomes too big to get a complete overview of the whole diagram. Although it is possible to collapse and expand a state's figure compartment, these actions spoil the diagram layout each time they are executed. Therefore, we introduced so-called Subdiagrams.
!images/extract_subdiagram.png!
If the 'Extract Subdiagram' refactoring is executed on a Composite State, all containing Regions are extracted into a separate diagram. A small decorator in the lower right corner of the State indicates the existence of such a subdiagram. If you hover with the mouse cursor over the decorator, you get a small preview image of the subdiagrams content. The refactoring also creates required Entry and Exit Points for you.
!images/extract_subdiagram2.png!
With a click on the decorator, the subdiagram opens in a separate editor tab. The breadcrumb on the top allows easy navigation throughout the different hierachy levels.
!images/extract_subdiagram3.png!
h3. Shallow History
The shallow history state is a pseudo state that is placed inside regions of composite states. It is used to 'remember' the last active state inside a composite state. So it is possible to jump to this state instead of starting at the inner entry state again. The following example of a questionaire answering will explain this:
!images/shallowHistory01.jpg!
The interesting parts in this state chart are the events _checkProgress_ and _goon_. CheckProgress jumps back to the init state while assigning the current progress count to the variable _temp_. _goon_ jumps to the shallow history state that was placed inside the composite state.
!images/shallowHistory02.jpg!
!images/shallowHistory03.jpg!
On triggering the _goon_ event the last active state is activated again.
h3. Deep History
Deep history is similar to shallow history but more complex. With a deep history the latest state of multiple nested states is remembered.
h2. Statechart description language
The textual description language is used to declare and describe behaviors in the state machine. It is case sensitive.
h3. Typesystem
The language has an integrated small typesystem with the following simple types:
* integer
* real
* boolean
* string
* void
So events and variables can be declared with types:
bc..
var intVar : integer
var realVar : real
var boolVar : boolean
var stringVar : string
event addInt : integer
event addReal : real
event checkValidity : boolean
event stringEvent : string
event voidEvent : void
h3. Expressions
Expressions can be defined similar to other programming languages. The language offers operators to define logical expressions, bitwise arithmetic, and arithmetic expressions and bit shifting.
Logical expressions are similar to other programming languages. The return type is *boolean*. In the following there are some examples of these:
h4. Logical AND
bc..
var1 && var2
h4. Logical OR
bc..
var1 || var2
h4. Logical NOT
bc..
!var1
h4. Conditional expression
bc..
var1 ? var2 : 23
h4. Bitwise XOR
bc..
var1 ^ var2
h4. Bitwise OR
bc..
var1 | var2
h4. Bitwise AND
bc..
var1 & var2
h4. Logical Relations and Shift Operators
|less than | < |
|equal or less than | <= |
|greater than | > |
|equal or greater than | >= |
|equal | == |
|not equal | != |
|shift left | << |
|shift right | >> |
h4. Binary arithmetic operators
|plus | + |
|minus | - |
|multiply | * |
|divide | / |
|modulo | % |
h4. Unary arithmetic operators
|positive | + |
|negative | - |
|complement | ~ |
h3. Statements
A statements can be either an assignment, raising an event or call an operation. The language has the following assignment operators:
* simple assignment: =
* multiply and assign: *=
* divide and assign: /=
* calculate modulo and assign: %=
* add and assign: +=
* subtract and assign: -=
* bitshift left and assign: <<=
* bitshift right and assign: >>=
* bitwise AND and assign: &=
* bitwise XOR and assign: ^=
* bitwise OR and assign: @|=@
An event is raised by the keyword _raise_ followed by the event name and if it is an interface event the name of the interface.
An operation is called similar to other programming languages with the operation name and passing concrete parameters. The parameters can be expressions.
h3. Scopes
====
h4. Namespace
The language allows to define unique namespaces, which can be used to qualify references to the statechart.
bc..
namespace trafficlights
p. ====
====
h4. interface scope
Declarations in the interface scope are externally visible. They can be shared within the environment.
bc..
interface NamedInterface:
in event event1
out event event3 : integer
var variable1 : integer
p. ====
====
h4. internal scope
Declarations made in an internal scope are only visible for contained states.
bc..
internal:
var localVariable1: integer
event localEvent: integer
local event localEvent2
operation localOperation (int1 : integer, int2 : integer): integer
localEvent2 / raise NamedInterface.event3 :
localOperation(valueof(localEvent) , NamedInterface.variable1)
p. ====
h3. Declarations
Within scopes there can be declarations of Events, Variables, Operations, LocalReactions.
====
h3. Events
Within interface scope events have an direction. They can either be ingoing or outgoing:
bc..
interface NamedInterface:
in event event1
out event event2
p. Within local scope events can carry variables:
bc..
internal:
event localEvent1 : integer
p. Local events can have a value assignment:
bc..
internal:
event localEvent1: integer = 25
p. ====
====
h3. Variables
Variables can have different visibilities. They can be visible for the environment:
bc..
var variable1: real
p. Variables can be *readonly* (constants):
bc..
var readonly pi: real = 3.1415
p. Variables can be referenced by the environment.
bc..
var external variable3: integer = 34
p. ====
h3. Reaction Triggers
Actions are key constructs in state machines to model behavior. The YAKINDU SCT 2 knows the following kinds of actions.
====
h4. after
The _after_ trigger specifies one-shot time events.
After the specified time the reaction is triggered. An _after_ trigger can be used in transitions of states as well in local reactions of states and statecharts. The specified time starts when the state or statechart is entered.
bc. after 20 s
Structure:
@after@ _@time@_ _@unit@_
The time value may be a constant or an expression that returns an integer value.
The time unit can be:
* ==== s - seconds ====
* ==== ms - milliseconds ====
* ==== us - microseconds ====
* ==== ns - nanoseconds ====
p. ====
====
h4. every
The _every_ trigger specifies periodic time events.
The reaction is triggered periodically after the specified time. An _every_ trigger can be used in transitions of states as well in local reactions of states and statecharts. The specified time starts when the state or statechart is entered and repeats periodically.
bc. every 200 ms
Structure:
@every@ _@time@_ _@unit@_
The time value may be a constant or an expression that returns an integer value.
The time unit can be:
* s - seconds
* ms - milliseconds
* us - microseconds
* ns - nanoseconds
====
====
h4. always
This trigger is always true and enables a reaction to be executed in every run to completion step (RTS). It is equivalent to _oncycle_.
====
====
====
h4. default, else
The _default_ trigger is equivalent to the _else_ trigger. It is intended for use for the outgoing transitions of _choice_ pseudo states, to make sure that always an outgoing transition can be taken. It can only be be used in transitions and implies the lowest evaluation priority for that transition.
====
====
====
h4. entry
An _entry_ trigger marks actions that are carried out on entering a state or state machine.
====
====
h4. exit
An _exit_ trigger marks actions that are carried out on exiting a state or state machine.
====
====
h4. oncycle
The _oncycle_ trigger is always true and enables a reaction to be executed in every run to completion step (RTS). It is equivalent to _always_.
====
====
h3. Operations
Operations can have none, one or multiple parameters. The parameters are declarated with a name and a type. An operation can have one return type similar to Java.
bc..
operation localOperation (xValue : integer, yValue : integer):integer
p.
====
h3. Build-In Functions
====
h4. valueof(event)
Returns the value of an valued event that it passed to the function as parameter.
bc..
myVar = valueof(myEvent)
p.
====
====
h4. active(state)
Returns "true" if a state is active or "false" otherwise.
bc..
myBool = active(StateA)
p.
====
h3. LocalReactions
Local reactions describe the internal behavior of a state. So they have internal scope. A local reaction is declared as follows:
bc..
LocalReaction: ReactionTrigger '/' ReactionEffect ('#' ReactionProperties)?
ReactionTrigger: (Event ("," Event )* (=> '[' Expression ']')?) | '[' Expression ']'
ReactionEffect: Statement (';' Statement )* (';')?
Statement: Assignment | EventRaising | OperationCall
ReactionProperties: (EntryPoint | ExitPoint)*
p. Within a local reaction an interface event can be raised:
bc..
internal:
localEvent1 / raise NamedInterface.event3 : localOperation (valueof(localEvent), NamedInterface.variable1);
p. Local reactions can have priority values. These are defined by a following # and the integer number of priority:
bc..
localEvent2 / NamedInterface.variable2 += 3; #1
localEvent3 / NamedInterface.variable4 += 2.0; #2
h2. SGen Generator Features
All generators can be customized with a generator model. This is a textual model file where generator features, like i.e. the outlet path, can be specified. The following screenshot shows an example configuration for the java code generator.
To get started with the generator model, we included a new Eclipse wizard that creates a basic configuration file with default values.
!images/sGenEditor.png!
The generator model is associated with the builder. If *Project* > *Build Automatically* is checked the files are generated. In the following the specific customizing features of the generator models are explained.
The following section describes the *Core Features* which are available for all code generators:
====
h4. Outlet
The *Outlet* feature specifies the target project and folder for the generated artifacts. It is a *required* feature and consists of the following parameters:
# __targetProject__ (String, required): The project to store the generated artifacts
# __targetFolder__ (String, required): The folder to store the generated artifacts
Example configuration:
bc..
feature Outlet {
targetProject = "ExampleProject"
targetFolder = "src-gen"
}
p. ====
====
h4. LicenseHeader
The *LicenseHeader* feature specifies the license text that should be added as a header to the generated artifacts. It is an *optional* feature and consists of the following parameters:
# __licenseText__ (String, required): The license text to add as a header
Example configuration:
bc..
feature LicenseHeader {
licenseText = "Copyright (c) 2012 committers of YAKINDU and others."
}
p. ====
====
h4. FunctionInlining
The *FunctionInlining* feature allows the inlining of expressions instead of generating separate functions or methods. This might reduce the readability of the generated code, but increases performance because less operation calls are necessary.
It is an *optinal* feature and consists of the following parameters:
# __inlineReactions__ (Boolean, optional): Inlines the expression for reactions
# __inlineEntryActions__ (Boolean, optional): Inlines the expression for entry actions
# __inlineExitActions__ (Boolean, optional): Inlines the expression for exit actions
# __inlineEnterSequences__ (Boolean, optional): Inlines the expression for enter sequences
# __inlineExitSequences__ (Boolean, optional): Inlines the expression for exit sequences
# __inlineChoices__ (Boolean, optional): Inlines the expression for choices
# __inlineEnterRegion__ (Boolean, optional): Inlines the expression for enter regions
# __inlineExitRegion__ (Boolean, optional): Inlines the expression for exit regions
# __inlineEntries__ (Boolean, optional): Inlines the expression for entries
Example configuration:
bc..
feature FunctionInlining {
inlineChoices = false
inlineEnterRegion = true
inlineEntries = true
}
p. ====
====
h4. Debug
The *Debug* feature dumps the Execution Model to the target folder as xmi model. It is an *optional* feature and consists of the following parameters:
# __dumpSexec__ (Boolean, required): The license text to add as a header
Example configuration:
bc..
feature Debug {
dumpSexec = true
}
p. ====
h2. Java Generator Features
====
h4. Naming
The *Naming* feature allows the configuration of package names as well as class name prefix / suffix.
It is an *optional* feature and consists of the following parameters:
# __basePackage__ (Boolean, required): The package to create for the generated java classes
# __implementationSuffix__ (Boolean, optional): The suffix for the implementing classes
Example configuration:
bc..
feature Naming {
basePackage = "org.yakindu.sct"
implementationSuffix = "Impl"
}
p. ====
====
h4. GeneralFeatures
The *GeneralFeatures* feature allows to configure additional services to generate with the statemachine. Per default, all parameters are configured to __false__ It is an *optional* feature and consists of the following parameters:
====
# __InterfaceObserverSupport__ (Boolean, optional): Enables/disables the generation of listener interfaces for the statemachine
# __RuntimeService__ (Boolean, optional): Enables/disables the generation of a runtime service that triggers the runcycle of a cycle based statemachine
# __TimerService__ (Boolean, optional): Enables/disables the generation of a timer service implementation using __java.util.Timer__
====
====
Example configuration:
bc..
feature GeneralFeatures {
InterfaceObserverSupport = true
RuntimeService = true
TimerService = true
}
p. ====
h2. Create Custom Code Generators
YAKINDU Statechart Tools provides a rich feature set to supports custom code generators out of the box. These code generators can be either written in Java, "Xtend":http://www.eclipse.org/xtend/ or in "Xpand":http://www.eclipse.org/modeling/m2t/?project=xpand
h3. Writing a custom code generator with Xtend2/Java
First, you have to create a new Xtend2 generator project. Click *File* > *New* > *Other...* > *YAKINDU* > *YAKINDU Xtend2/Java Generator Project* to create a new Xtend2 Generator Project.
!images/xtendGenerator.png!
The wizards asks for a *Project name* and the name of the *Generator class*, where you have to specify a full qualified class name. If you check the *Use Xtend* checkbox, the Generator class will be initially created as an "Xtend":http://www.eclipse.org/xtend/ class. Otherwise, Java will be used for the generator.
The check box *Configure for Plugin Export* adds all required extension point registrations to the new project for exporting as a plugin The Generator Model can refer to the new Generator Plugin via its unique *Generator ID*. If you want to contribute custom generator features for your code generator, check the *Create Feature Library* check box.
After click on *Finish* a new project is created in your workspace. All required plugin dependencies and extension points are registered and you can start to write your code generator based on the ExecutionFlow meta model [Link].
h3. Executing a custom Xtend2/Java code generator
YAKINDU Statechart Tools provide a convenient way to execute your generator while you are developing it.
Therefore, you have to create a new *Generator Model* with the generator id *yakindu::generic*, either by using the *New Statechart Generator Model* wizard or by simple creating a new text file with the file extension *.sgen*. the following feature allows to configure your code generator.
====
h4. Generator
The *Generator* feature allows the configuration of a custom code generator located in the workspace and written in Java or another JVM language. It is a *required* feature and consists of the following parameters:
# __generatorProject__ (String, required): The name of the generator project
# __generatorClass__ (String, required): The full qualified class name of the code generator class.
# __configurationModule__ (String, optional): The full qualified class name for a guice module to configure the code generator
Example configuration:
bc..
feature Generator {
generatorProject = "org.yakindu.sct.mygenerator"
generatorClass = "org.yakindu.sct.MyGenerator"
}
p. ====
h3. Executing a custom Xpand code generator
to execute an xpand based custom code generator, you have to create a new *Generator Model* with the generator id *yakindu::xpand*, either by using the *New Statechart Generator Model* wizard or by simple creating a new text file with the file extension *.sgen*. the following feature allows to configure your code generator.
====
h4. Template
The *Generator* feature allows the configuration of a custom code generator located in the workspace and written in Java or another JVM language. It is a *required* feature and consists of the following parameters:
# __templateProject__ (String, required): The name of the generator project
# __templatePath__ (String, required): The full qualified template path to the main template.
Example configuration:
bc..
feature Template {
templateProject = "ExampleProject"
templatePath = "org::yakindu::sct::generator::xpand::Main::main"
}
p. ====
h2. API specifications of the generated code
In the following comments the TrafficLight example statemachine is used to describe the API specifications of the code generated by the Yakindu C and Java code generators. The following image shows the statechart. It is a model of a simple pedestrian crossing with a traffic light for pedestrians and a traffic light for the cars.
!images/TrafficLight.png!
h3. Specifications of Java code
For Java you can checkout the project 'org.yakindusct.examples.trafficlight' from the Yakindu google code repository ( "Google code link":http://svn.codespot.com/a/eclipselabs.org/yakindu/SCT2/trunk/examples ). The Java example contains the statechart, sgen model, graphical widgets and some glue code to connect the generated code with the widgets. The graphical widgets are based on SWT. To execute the Java example you can run the file 'CrossingDemoCycleBased.java' as 'Java Application' from the eclipse 'Run As' context menu.
You find the generated code in the 'src-gen' folder of the traffic light example.
In the package 'org.yakindu.sct.examples.trafficlight.cyclebased' are the most basic statemachine interfaces and classes located. These are needed by each statemachine and are independend from the concrete statemachine design.
h4. Interface IStatemachine
The interface @IStatemachine@ is implemented by each generated statemachine:
bc..
package org.yakindu.sct.examples.trafficlight.cyclebased;
/**
* Basic interface for statemachines.
*
*
*/
public interface IStatemachine {
/**
* Initializes the statemachine. Use to init internal variables etc.
*/
public void init();
/**
* Enters the statemachine. Sets the statemachine in a defined state.
*/
public void enter();
/**
* Exits the statemachine. Leaves the statemachine with a defined state.
*/
public void exit();
/**
* Start a run-to-completion cycle.
*/
public void runCycle();
}
p. It contains the four methods @init()@, @enter()@, @exit()@ and @runCycle()@. The @init()@ method is used to initialize the internal objects of the statemachine after instantiation. Variables are initialized to a default value. If you have initialized variables in the statechart definition these initializations are done in the init method too. The @enter()@ method should be called if the statemachine is entered. It sets the statemachine into a defined state. The @exit()@ method is used to leave a statemachine statefully. If for example a history state is used in one of the top regions the last active state is stored and the statemachine is leaved via @exit()@ and reentered via @enter()@ it continues working with this state. The @runCycle()@ method is used to trigger a run to completion step in which the statemachine evaluates arising events and computes possible state changes. A run to completion step consists in a simplified view of the following steps:
* Clear list of outgoing events.
* Check whether events have occurred which lead to a state change
* If a state change has to be done:
** Execute exit actions of leaving state.
** Save history state if necessary.
** Set the new State active.
** Execute entry action of the new state.
* Clear list of incoming events.
h4. Timed statemachines
In the traffic light example timing is used (after clauses). To support this the interfaces 'ITimedStatemachine', 'ITimerService' and the class 'TimeEvent' are generated.
bc..
package org.yakindu.sct.examples.trafficlight.cyclebased;
/**
* Interface for state machines which use timed event triggers.
*/
public interface ITimedStatemachine {
/**
* Set the {@link ITimerService} for the state machine. It must be set
* externally on a timed state machine before a run cycle can be correct
* executed.
*
* @param timerService
*/
public void setTimerService(ITimerService timerService);
/**
* Returns the currently used timer service.
*
* @return {@link ITimerService}
*/
public ITimerService getTimerService();
/**
* Callback method if a {@link TimeEvent} occurred.
*
* @param timeEvent
*/
public void onTimeEventRaised(TimeEvent timeEvent);
}
p. @ITimedStatemachine@ extends the generated statemachine to set an @ITimerService@ and provides a callback method @onTimeEventRaised(TimeEvent timeEvent)@ to let the timer service raise @TimeEvents@.
Basically the correct handling of time has to be implemented by the developer because timer functions generally depend on the hardware target used. So for every hardware target a timer service class which implements the @ITimerService@ interface has to be developed. Let's have a look at the @ITimerService@ interface:
bc..
package org.yakindu.sct.examples.trafficlight.cyclebased;
/**
* Interface a timer service has to implement. Use to implement your own timer
* service. A timer service has to be added to a timed state machine.
*
*/
public interface ITimerService {
/**
* Starts the timing for a given {@link TimeEvent}.
*
* @param event
* : The TimeEvent the timer service should throw if timed out.
* @param time
* : Time in milliseconds after the given time event should be
* triggered
* @param cycleStartTime
* : The absolute start time in milliseconds at which the last
* run cycle was called. Can be used to produce a more accurate
* timing behavior.
*/
public void setTimer(TimeEvent event, long time, long cycleStartTime);
/**
* Unset the given {@link TimeEvent}. Use to unset cyclic repeated time
* events.
*
* @param event
*/
public void resetTimer(TimeEvent event);
/**
* Cancel timer service. Use this to end possible timing threads and free
* memory resources.
*/
public void cancel();
/**
* Returns the system time in milliseconds.
*
* @return the difference, measured in milliseconds, between the current
* time and a defined point of time in the past.
*/
public long getSystemTimeMillis();
}
p. The @ITimerService@ interface defines four methods. The @public void setTimer(TimeEvent event, long time, long cycleStartTime)@ method is called by a statemachine to tell the timer service that it has to start a timer for the given time event and raise it after the time given by the same named parameter is expired. It is important that within the 'setTimer' method only a timer thread or a hardware timer interrupt is started and no long time taking operations like Thread.sleep(...) or waiting are done. Otherwise the statemachine execution may hang within the timer service or it shows a not expected runtime behavior.
To raise a @TimeEvent@ after the time is expired the method @onTimeEventRaised(TimeEvent timeEvent)@ has to be called on the statemachine (should be a @ITimedStatemachine@). So the time event is recognized by the statemachine and will be processed by the next run cycle. You can conclude that the runtime environment has to call the statemachines 'runCycle' method as often as needed to process time events raised by the timing service as fast as possible. If you have in example a time event which should be raised by the timer service after 500 ms and the runtime environment only calls the statemachines @runCycle@ method with a time period of 1000 ms the event could not be processed in the correct time.
The parameter 'cycleStartTime' holds the absolute start time of the last run cycle. It can be used to reduce or remove the time offset used by the statemachines runtime operations to get a more precise timing behavior.
The method @resetTimer(TimeEvent event)@ is called by the statemachine to unset the timer.
The last class used by timed statemachine is @TimeEvent@:
bc..
package org.yakindu.sct.examples.trafficlight.cyclebased;
/**
* Event that reflects a time event. It's internally used by
* {@link ITimedStatemachine}.
*
* @author muehlbrandt
*
* @param