Comprehensive tutorial

This tutorial introduces YAKINDU Statechart Tools (SCT) which provides an integrated modeling environment for the specification and development of reactive, event-driven systems based on the concepts of Finite State Machines (FSM) and Harel Statecharts. It is an easy-to-use tool featuring sophisticated graphical statechart editing, validation and simulation of statecharts as well as code generation for C, C++, or Java.

This tutorial you will teach how to

  • create a new statechart model, and
  • execute it using the simulation engine.

Please note that this tutorial will not explain statecharts in general, so you should familiarize yourself with the basic concepts of state machines first, see UML state machine.

In order to get a fully-working state machine implementation that you can integrate with your project, you will have to familiarize yourself with code generation, which is covered by chapter Code generation in this documentation. You can generate your state machine implementation as source code in C, C++, and Java out of the box. Alternatively, you can write your own code generator for other programming languages or for other purposes.

Before we get started, make sure you have YAKINDU Statechart Tools installed. For installation instructions, see the YAKINDU Statechart Tools Installation Guide.

The light switch example

The most basic example of a state machine that actually does something is a light switch. In this scenario there is a light bulb and a switch to turn the bulb on and off. Of course there’s also a power source and some electrical cabling to put it all together, but for the purpose of our model we can omit them.

The behavior of a light switch

When modeling the light switch example as a statechart, we can disregard everything (even the bulb) except for the switch. The behavior of the switch is very simple:

  • Initially the light switch is off, i.e., it is in its Off state.
  • If the light switch is operated while being in its Off state, it changes to its On state.
  • If the light switch is operated while being in its On state, it changes to its Off state.

Modeling the light switch as a statechart

Now let’s model the light switch as a statechart using YAKINDU Statechart Tools. This involves the following steps:

  1. Creating an Eclipse project. It will serve as a container for the statechart model.
  2. Modeling the light switch using the YAKINDU Statechart Tools editor. The result will be a static statechart model.
  3. Simulating the model. We can play around with the model, operate the light switch and observe its behavior.

Creating an Eclipse project

The first step is to create a new Eclipse project that can serve as a container for our model. From the main menu, select File → New → Project...:

Selecting "File → New → Project..." in the main menu

Selecting File → New → Project... in the main menu

The New Project wizard opens, showing a couple of different project types structured in various folders.

The "New Project" wizard

The New Project wizard

Select General → Project and click Next >.

The wizard shows its next page:

Specifying project name and location

Specifying project name and location

Specify a meaningful Project name, e. g. LightSwitch, and optionally select a Location to create the project in.

Click Finish.

Eclipse creates the new project:

Project "LightSwitch" created

Project LightSwitch created

Creating a folder for the model

Now that we have created the Eclipse project, we can establish the statechart model of the light switch. It is good practice to use a separate directory for models, so let’s create a new folder called model.

Right-click on the project’s root, i.e., on LightSwitch, then select New → Folder from the context menu.

Selecting "New → Folder" in the context menu

Selecting New → Folder in the context menu

The New Folder wizard opens:

The "New Folder" wizard

The New Folder wizard

Give the model folder a reasonable name, e. g. model, and type it into the Folder Name text field. Then click Finish.

The new model folder is created and appears in the Project Explorer view at the left.

Starting with an empty statechart model

Using the YAKINDU Statechart wizard

Now we are going to create an empty statechart model in the model folder. Right-click on the model folder and select New → Other in the context menu:

Selecting "New → Other" in the context menu

Selecting New → Other in the context menu

The New wizard opens. Select YAKINDU SCT → Statechart model

Selecting "YAKINDU SCT → Statechart model"

Selecting YAKINDU SCT → Statechart model

Click Next >. The wizard shows the New YAKINDU Statechart dialog:

The "New YAKINDU Statechart" dialog

The New YAKINDU Statechart dialog

The dialog asks you for the project, the directory, and the name of the model file to be created. Eclipse project and directory should be preset correctly already. In our case the corresponding text field contains LightSwitch/model which means the directory named model in the LightSwitch project. You can change that if you wish, but most likely you won’t.

The default file name in the File Name field is default.sct, however. You should change that to something more meaningful. In our case we type LightSwitch.sct into the File name field, see the screenshot above.

Click Finish.

Since there’s a dedicated perspective for statechart models, Eclipse asks you whether you want to change to it now or not:

Dialog "Confirm Perspective Switch"

Dialog Confirm Perspective Switch

Please answer the question regarding switching to the YAKINDU Modeling perspective by clicking on the Yes button. The YAKINDU Modeling perspective has a graphical editor for statechart models, and you will need it to create and modify them. On the other hand your answer really doesn’t matter that much, because you can switch perspectives at any time. If you check Do not offer to switch perspective in the future before clicking Yes, Eclipse will never ask this question again, at least regarding the YAKINDU Modeling perspective.

Please note: If the Confirm Perspective Switch dialog does not appear as described above you probably have already confirmed Do not offer to switch perspective in the future once before.

The initial model

An empty statechart is created and displayed in the statechart editor in the middle of the Eclipse workbench. In the screenshot below the statechart editor is marked by a red rectangle. Subsequently, we will use the statechart editor to graphically develop the light switch statechart.

The statechart editor

The statechart editor

Actually the new statechart isn’t really empty. It already contains the initial state (a small filled black circle), a „normal” state, and a transition leading from the former to the latter.

Statechart validation

Error markers in the model graph

The „normal” state, however, has a small filled red circle containing a white ‘X' attached. This is an error marker and tells you that something is wrong with your model, particularly with the object it is attached to.

Please note: Since the current version of the statechart editor gives that state a proper name („StateA”), the error marker is no longer present in a new model. So the following description is somewhat out of date. This will be fixed in a future version of this documentation. Until then, please follow the subsequent text nevertheless, because you will learn something important about statechart validation.

Error markers in the project explorer

The error marker is also shown in the Project Explorer view at the left-hand side of the main window. In this way you can see immediately which of your projects contain errors. Click on the small show/hide symbol (triangle) left of a project’s or any other resource’s name to show or hide its respective contents. By doing so, you can quickly encircle the directories and files that are affected by errors. In the screenshot above we have clicked open the LightSwitch project and the model directory, showing the error is in the LightSwitch.sct file.

Validation principles

This error marker exemplifies YAKINDU Statechart Tools' model validation capabilities. Statechart validation includes syntactical and semantical checks of the whole statechart. For example, a statechart is checked for unreachable states, dead ends, or references to unknown events. These validation constraints are checked during editing. In case any constraints are violated, error or warning markers are attached to the faulty model elements. Thus the user receives direct and immediate feedback on the validation state of his statechart.

Hovering with the mouse over the error marker in the statechart editor reveals what the problem is. A small popup appears and displays the error description: "A state must have a name."

An error marker and a popup window explaining it

An error marker and a popup window explaining it

Error markers in the „problems” view

An alternative place to see error messages is the Problems view. This view has the particular advantage to comprise all notifications in a clearly arranged list form, see the screenshot above. It displays:

  • A summary comprising the total number of errors, warnings, and others. In our case we have one error and nothing else.
  • Zero or more lists containing errors, warnings, and other types of messages, if available. In our example there is a just a single list containing error messages. Click on the show/hide symbol to show the message list’s contents or the list’s header only.

Double-clicking on an error message in the Problems view brings you directly to the erroneous object.

Hang on, we will correct the error in a second!

Giving a state a name

As we have seen, the initial statechart is erroneous insofar as the state does not have a name. So let’s fix that.

Remember the requirements of our light switch example? The first requirement demands the switch to be off initially. The erroneous state is reached from the initial state immediately, so it is appropriate to name it Off.

Double-click on the string <name> in the state object. The string turns into a text input field with <name> being highlighted: Double-clicking on the state name
Type the state’s new name, i.e., Off: Typing the new state name
Hit the [Enter] key or click anywhere outside the text field. Bingo! The state now has a proper name and the error marker disappears: Completing the state name change
However, since the state box’s size is smaller than before now while the box’s left position remains unchanged, the graph looks crooked.
We can improve it by dragging the state box a little bit to the right. When it is centered below the initial state symbol, a vertical blue line appears giving the user a visual hint: Dragging the state
Drop the state box at this very place, and everything looks much better now: Dropping the state
Alternatively, we could have used the state box’s handles to resize it. However, we just deselect the box by clicking elsewhere: Deselecting the state

Creating a state

With the Off state only, the light switch statechart isn’t complete yet. We also need an On state, and we going to create it now.

In order to add another state, move the mouse pointer to the Palette compartment at the right-hand side of the statechart editor. Click on the State symbol in the palette without releasing the mouse button, and drag the symbol over to the editing area. Dragging a new state from the palette to the editing area
Release the mouse button over a gray area, a region: Dropping a new state in a region
The new state appears in the model graph: A new state
Rename the new state to On. Vertically align it to the Off state, if you like: Renaming the new state
You’ll notice that the new state is showing an error marker. The reason is that it is not yet possible to reach the On state.
Before we’ll go on and fix that problem, here’s another way to create a new state. When you are hovering with the mouse pointer over the main region, i.e., the large rectangle with a gray background, a popup menu shows up. If you click on the ‘S' symbol in that menu, a new state will be created. Other options in this menu are to create an initial state, a final state, or a choice. Creating a state using the popup menu

Creating a transition

As we have seen above, the On state is not reachable as of yet. So let’s model switching the light switch from „off” to „on” as a transition leading from the Off state to the On state.

In the Palette, click on the Transition symbol. The symbol’s background turns blue. Clicking on the _Transition_ symbol in the palette
Click on the Off state, but don’t release the mouse button. Drag the mouse pointer towards the On state. The arrow representing the transition to be established is drawn. Drawing a new transition
Once the mouse pointer reaches the target state, it changes its shape. The mouse pointer reaching a possible target state
Releasing the mouse button establishes the transition. A text input field to specify event trigger, guard condition and effect appears. We want the transition to be triggered when the light switch is operated, so let’s type operate into the text field. Editing a transition
If you suspect that something is not in order, because the input text is underlined in red, you are right. We will explain and deal with that in a minute.
Clicking anywhere outside the text field terminates the editing mode: Completing the transition editing mode

The event trigger operate is flagged as an error. The reason is that an event with that name is not known yet. The screenshot below shows how to change that:

Creating definitions [1]

Creating definitions [1]

Double-click into the definition section on the left-hand side of the statechart editor. The section becomes an editable text field.

Enter the following text:

    event operate

The keyword internal makes the following definition of the operate event belong to the internal scope. The latter is explained in section "Internal scope".

Click anywhere outside of the text field, which terminates editing the definition section. The statechart editor digests the definition, recognizes the definition of the operate event, and validates the model as being okay:

Creating definitions [2]

Creating definitions [2]

In its current state the model would not allow to turn the light switch off again, which is somewhat unsatisfactory. Operating the light switch while it is on should turn it off again. Let’s model this by adding another transition. It should lead from the source state On to the target state Off.

However, in order to not get two straight lines being close together in the graph, let’s first make some room and turn the present line into an arc. Move the mouse pointer over the transition line, but not over the text. The mouse pointer changes its shape to indicate that you can insert a control point. Click and hold to add the control point, then drag it to an appropriate position. Inserting a control point
Now let’s insert the second transition. This time we won’t use the palette, but instead use another method. Hover the mouse pointer over the source state, i.e., On. An incoming and an outgoing arrow appear, both with a handle. Click and hold the handle of the outgoing arrow and drag it to the Off target state. Creating a transition by using the source state's outgoing arrow handle
Upon releasing the mouse button the transition is established. Type operate as the transition’s event trigger into the text field. Reshape the transition arrow to make the graph look nice. Completing the transition creation

Simulating the light switch model

Simulating a statechart model means to execute it, raise events manually, have time-based and other events being triggered automatically, and observe the model’s behavior.

Start the simulation by right-clicking on the LightSwitch.sct file in the project explorer and selecting Run As → Statechart Simulation:

Selecting "Run As → Statechart Simulation" in the context menu

Selecting Run As → Statechart Simulation in the context menu

The perspective changes from SC Modeling to SC Simulation. This perspective defines two additional views:

  • The Debug view at the top shows all running state machine instances and allows to select one of them. YAKINDU Statechart Tools allow multiple executions of the same state machine as well as parallel executions of different state machines at the same time.
  • The Simulation view on the right-hand side is used to raise events and to inspect and modify variables. Depending on your screen resolution and font size settings, you might not be able to spot the Simulation view by its name, because the tab containing it is quite narrow and might not provide enough space for displaying the title. Hover over the tabs to reveal their respective titles in a popup window. Figure "Light switch simulation in "off" state" is demonstrating this: The user has hovered the mouse pointer over a tab that is just displaying the starting letter ‚S’ of its title. However, a popup window right besides the pointer is showing the tab’s full title „Simulation View”.

Not surprisingly, the simulation starts at the initial state and then transitions to the Off state immediately. The latter becomes the active state now. It is highlighted by a red background:

Light switch simulation in "off" state

Light switch simulation in „off” state

Now that the light switch is off, let’s turn the lights on by operating the switch. In the simulation, we will have to raise the operate event. How can we do this?

In the Simulation view at the right-hand side of the Eclipse workbench, click on the internal entry’s show/hide symbol to display its contents.

Displaying event names in the statechart simulator's "Simulation" view

Displaying event names in the statechart simulator’s Simulation view

The operate event is shown. Click on it to raise the event, i.e., to operate the light switch.

The transition arc leading from the Off state to the On state flashes briefly in red, and then the On state becomes active. Its background color changes to red while the Off state’s background color becomes normal again.

Light switch simulation in "on" state

Light switch simulation in „on” state

Click on operate again, and the active state changes back to Off. Click on operate several times and enjoy watching the state machine’s behavior.

Stop the simulator by clicking at the little red termination button in the toolbar at the top.

Code generation

YAKINDU Statechart Tools include code generators for Java, C, and C++ out of the box. The code generators are following a „code-only” approach: They are generating all the code that is needed and do not rely on any additional runtime libraries. The generated code provides a well-defined application programming interface and can be integrated easily with any client code. In this tutorial we will generate Java code for a sample statechart modeling the handling of a phone call, the CallHandling example.

The CallHandling example

The state machine handling a phone call works as follows:

  • After startup, the system is in an idle state and is waiting for incoming calls.
  • When a call comes in, the user can either accept the call or dismiss it.
  • If the users accepts the call and opens a connection, the system is tracking the duration of the call and is waiting for the user to hang up.
  • After hanging up, the system displays the total time of call and then returns to its idle state.

The complete statechart model is shown below:

The CallHandling statechart model

The CallHandling statechart model

In order to eventually obtain the CallHandling example in the form of executable code, we have to create the model in the statechart editor first, followed by creating a suitable generator model, followed by executing the code generator to create the source code we need.

Creating the statechart model

In the previous section we have seen how to work with the statechart editor. So let’s create a new project now and use the statechart editor to create the CallHandling statechart model as outlined above.

Since we are going to generate Java code, we should use a Java project to host the statechart model. Use File → New → Java Project and follow the New Java Project wizard to create one.

In addition to what we have learned above already, there is one new concept: interfaces.

Creating interfaces

Statecharts can describe very complex interactions between a multitude of actors and an even bigger multitude of events these actors can receive or trigger. It is therefore good practice to structure such events and associate them with their respective actors. For this purpose YAKINDU Statecharts Tools provides the concept of so-called interfaces.

In the CallHandling example, we have two actors: the user and the phone. Let’s model their communication as two interfaces:

  • The Phone interface provides a single incoming event named incoming_call.
  • The User interface comprises two incoming events: accept_call and dismiss_call.

We have to enter the respective definitions in textual form into the statechart editor. Here’s how the interface definitions look like:

interface User:
    in event accept_call
    in event dismiss_call

interface Phone:
    var duration : integer
    in event incoming_call

As you can see, the Phone interface also has an integer variable duration which will track the duration of the call. The interface definitions above have to go into the statechart editor’s definition block on the left-hand side of the statechart editor.

If everything went well, any error markers in the model are gone. Your model should look like the one in the screenshot below:

The CallHandling statechart modeled in the statechart editor

The CallHandling statechart modeled in the statechart editor

Creating a generator model

For code generation, YAKINDU Statechart Tools use a textual generator model called SGen. The generator model holds key parameters for the code generation process and allows for the latter’s customization.

The first step to code generation is to create a new SGen model. Right-click on the model folder in the project explorer and select New → Code generator model from the context menu.

Selecting "New → Code generator model" in the context menu

Selecting New → Code generator model in the context menu

The YAKINDU generator model wizard opens. Change the File name to CallHandling.sgen, then click Next >.

Selecting a filename for the generator model

Selecting a filename for the generator model

From the Generator drop-down menu at the top, select YAKINDU SCT Java Code Generator.

In the statechart tree beneath that menu, check the CallHandling.sct model, then click Finish.

Selecting generator type and statechart model

Selecting generator type and statechart model

Now the wizard creates the default SGen model for Java code generation and opens it in an SGen editor. The project explorer on the left-hand side shows the new model file CallHandling.sgen.

The generator model

The generator model

Here’s the generator model once again as plain text:

GeneratorModel for yakindu::java {

    statechart CallHandling {

        feature Outlet {
            targetProject = "CallHandling"
            targetFolder = "src-gen"
            libraryTargetFolder = "src"

Let’s have a closer look at the listing above:

  • yakindu::java is the unique ID of the Java code generator.
  • The statechart CallHandling { … } block references the statechart model we want to generate code for.
  • The feature Outlet { … } block specifies where the generated code artifacts are to be placed:
    • The parameters targetProject and targetFolder define the Eclipse project CallHandling as destination for generated code and within that project the src-gen folder.
    • However, certain source code modules are generated only once and won’t change with the underlying statechart. By default, these source code artifacts are generated into the folder specified by the libraryTargetFolder option which by default is src. You can change the folder name or even remove the libraryTargetFolder option at all. In the latter case the „library” components are generated into the targetFolder.

A statechart reference may contain various configuration features. You will learn more about them later.

Enhancing the generator model by timing capabilities

The default generator model is insufficient yet. The CallHandling statechart model uses after and every expressions. That is, it is dealing with time events, requiring a timer service to trigger them. We can instruct the code generator to provide us with a default timer service implementation by adding the following feature to the generator model:

feature GeneralFeatures {
    TimerService = true

Generating Java source code

What do we have to do to actually start the Java source code generation? Nothing!

The generator model is executed by a so-called Eclipse builder. That is, as long as the Project → Build Automatically menu item is checked (which it is by default), the artifacts are generated automatically with each modification of the statechart model or of the generator model.

As you can see in the project explorer, the folder src-gen has been created and populated with the generated Java source code artifacts.

Adding the timer service feature

Adding the timer service feature

Add the generated artifacts to the Java build path by right-clicking on the src-gen folder and selecting Build Path → Use as source folder in the context menu.

Declaring "src-gen" as a source folder

Declaring src-gen as a source folder

If you want to execute your generator model manually, select Generate Code Artifacts from the .sgen file’s context menu in the project explorer.

Integration with client code

Now that we have a generated Java implementation of the CallHandling state machine available, we want to actually use it from some client code. We’ll create that client code in a second.

Creating client code

Let’s establish a new Java class CallHandlingClient and integrate the state machine with it:

  1. Right-click on the src folder.
  2. Select New → Class in the context menu.
  3. Name it CallHandlingClient.
    Creating a class containing the client code
  4. Click Finish.

Next, copy the following code into the created class:

  import org.yakindu.scr.TimerService;
  import org.yakindu.scr.callhandling.CallHandlingStatemachine;

  public class CallHandlingClient {

      public static void main(String[] args) throws InterruptedException {

          // Create the state machine:
          CallHandlingStatemachine sm = new CallHandlingStatemachine();
          sm.setTimer(new TimerService());

          // Initialize the state machine:

          // Enter the state machine and implicitly activate its "Idle" state:

          // Raise an incoming call:

          // Accept the call:

          // Keep the phone conversation busy for a while:
          for (int i = 0; i < 50; i++) {

          // Before hang-up, output the duration of the call:
          System.out.println(String.format("The phone call took %d seconds.",

          // Hang up the phone:

Let’s have a detailed look at this client code:

  • First, this program creates a new instance of the state machine by calling the default CallHandlingStatemachine constructor:
    • CallHandlingStatemachine sm = new CallHandlingStatemachine();
  • Since we are using time events, the state machine implementation requires an implementation of the ITimer interface. And since we added the TimerService feature to the generator model, the code generator creates a default implementation org.yakindu.scr.TimerService that uses the java.util.Timer class. A new instance of the default TimerService is created and set to the state machine:
    • sm.setTimer(new TimerService());
  • The state machine and its internal data structures are initialized:
    • sm.init();
  • After that, sm.enter() enters the state machine and – via its initial state – activates its Idle state.
  • For each interface in the statechart definition block a getter method has been generated, here getSCIPhone() and getSCIUser(). You can access all incoming events and all variables via these interfaces.
    • sm.getSCIPhone().raiseIncoming_call(); raises the incoming_call event, activating the Incoming Call state after the next run cycle has been executed. The latter is triggered by sm.runCycle().
  • sm.getSCIUser().raiseAccept_call() accepts the call or, to be more precise, raises the accept_call event via the User interface. It activates the Active Call state after the next run cycle has been performed by sm.runCycle();.
  • In the for loop, the run cycle is executed periodically every 200 milliseconds. This simulates the duration of the phone call.
  • Before hanging up the phone, let’s find out how much time we spent in the call. sm.getSCIPhone().getDuration() retrieves the call’s duration, which is then formatted and printed to the console.
  • Finally, sm.getSCIUser().raiseDismiss_call() raises the dismiss_call event. It activates the Dismiss Call state after the next run cycle.

Executing the client code

You can execute the client code via Run As → Java Application from the class file’s context menu.

Closing remarks

At this point you have mastered the comprehensive tutorial and got to know the most important YAKINDU Statechart Tools features up to a certain degree. The subsequent sections will explain statechart language, statechart editor, simulation, and code generation in detail.