
h1(#tutorial_five-minutes_tutorial). Five-minutes tutorial

The five-minutes tutorial gives you a brief introduction into modeling state machines with YAKINDU Statechart Tools by a simple example. It models a light switch, which has the states _on_ and _off_. Operating the switch repeatedly turns the light on, off, back on again, and so forth. You can simulate this behavior in a dynamic statechart model (state machine model). Here's how this looks like:

!(standard-image full)images/tuto_light_switch_330_statechart_simulator_state_on.png(Interactive light switch statechart simulation)!

p=. Interactive light switch statechart simulation

In the simulation screenshot above, the light switch is currently in the _on_ state. To toggle the light switch, the user clicks on _operate_ on the right-hand side of the window.




h2(#tutorial_importing-light-switch-example). Importing light switch example

Now try this for yourself. We are assuming that you have already installed and started YAKINDU Statechart Tools. If you don't, please see the "Installation Guide":../user-guide/installation.html#inst_installing_yakindu_statechart_tools for details.

# If the "Welcome" page is still open, close it. <p>!(standard-image small)images/tuto_5min_010_close_welcome.png(Closing the "Welcome" page)!</p>
# In the main menu, select _File → New → Example…_.
# In the dialog, select _YAKINDU SCT Examples_, then click _Next >_.
# The example wizard opens. If needed, follow the instructions to download the examples repository.
# On the left-hand side of the example wizard, select _Light Switch Example_, then click _Finish_.
# The sample project named _light_switch_ is created.
# In the project explorer on the left-hand side of the window, open the _light_switch_ project by clicking on the small triangle left from the project name ("light_switch"). Also open the _model_ folder.<p>!(standard-image small)images/tuto_5min_020_expand_project.png(Expand project)!</p>
# The light switch statechart is defined in the file _light_switch.sct_. Double-click on this file to open the model.




h2(#tutorial_running-the-light-switch-simulation). Simulating the light switch

# Right-click on _light_switch.sct_ and select _Run As → Statechart Simulation_ in the context menu.
# The simulation starts and shows the light switch model in its _off_ state. The rectangle named *Off* is highlighted in red, meaning it is the active state. <p>!(standard-image)images/tuto_light_switch_320_statechart_simulator_state_events.png(Light switch simulation in "off" state)!</p>
# At the right-bottom side of the window, the simulation view is located. In this view, you can change variable values and raise events during a simulation run. Click on the small triangle left from _internal_ to unfold the _operate_ link. This link represents the _operate_ event to switch the light on or off.
# Click on the _operate_ link. The active state changes accordingly from *Off* to *On*. <p>!(standard-image)images/tuto_light_switch_330_statechart_simulator_state_on.png(Light switch simulation in "on" state)!</p>
# Click on _operate_ again to switch off the light.




h2(#tutorial_generating-statechart-code). Generating statechart code

You have developed and tested your statechart model, and now you need it as a C, C++, or Java implementation? YAKINDU Statechart Tools can create it for you.

As an example, we will take the light switch statechart and generate Java source code from it. Please proceed as follows:

# In the project explorer, right-click on _light_switch.sct_ and select _New → Code generator model_ in the context menu. <p>!(standard-image)images/tuto_5min_110_new_code_generator_model.png(Creating a new code generator model)!</p>
# In the dialog, replace @default.sgen@ by @light_switch.sgen@, then click _Next >_.
# In the next dialog, check the checkbox left from _light_switch.sct_, then click _Finish_.
# Java classes implementing the statechart model are generated. You can find the generated source code in the folders _src_ and _src-gen_ within the _light_switch_ project. <p>!(standard-image)images/tuto_5min_140_generated_java_source_code.png(Generated Java source code)!</p>

That's it. If you want to know more, take the time and work through the "Comprehensive Tutorial":../tutorials/tutorials.html#tutorial_comprehensive_tutorial.





h1(#tutorial_comprehensive_tutorial). 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&#43;&#43;, 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":https://en.wikipedia.org/wiki/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":#tutorial_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":../user-guide/installation.html.




h2(#tutorial_the-light-switch-example). 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.



h3(#tutorial_the-behavior-of-a-light-switch). 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.




h2(#tutorial_modeling-the-light-switch-as-a-statechart). 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:

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



h3(#tutorial_creating-an-eclipse-project). 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..._:

!(standard-image)images/tuto_light_switch_010_menu_file_new_project.png(Selecting "File → New → Project..." in the main menu)!

p=. Selecting _File → New → Project..._ in the main menu

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

!(standard-image)images/tuto_light_switch_020_wizard_new_project_general_project.png(The "New Project" wizard)!

p=. The _New Project_ wizard

Select _General → Project_ and click _Next &gt;_.

The wizard shows its next page:

!(standard-image)images/tuto_light_switch_040_wizard_new_project.png(Specifying project name and location)!

p=. 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:

!(standard-image)images/tuto_light_switch_060_project_created.png(Project "LightSwitch" created)!

p=. Project _LightSwitch_ created



h3(#tutorial_creating-a-folder-for-the-model). 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.

!(standard-image)images/tuto_light_switch_100_menu_new_folder.png(Selecting "New → Folder" in the context menu)!

p=. Selecting _New → Folder_ in the context menu

The _New Folder_ wizard opens:

!(standard-image)images/tuto_light_switch_110_wizard_new_folder.png(The "New Folder" wizard)!

p=. 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.



h3(#tutorial_starting-with-an-empty-statechart-model). Starting with an empty statechart model

h4(#tutorial_using-the-yakindu-statechart-wizard). 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:

!(standard-image)images/tuto_light_switch_120_menu_new_other.png(Selecting "New → Other" in the context menu)!

p=. Selecting _New → Other_ in the context menu

The _New_ wizard opens. Select _YAKINDU SCT → Statechart model_

!(standard-image)images/tuto_light_switch_130_wizard_new.png(Selecting "YAKINDU SCT → Statechart model")!

p=. Selecting _YAKINDU SCT → Statechart model_

Click _Next &gt;_. The wizard shows the _New YAKINDU Statechart_ dialog:

!(standard-image)images/tuto_light_switch_140_wizard_new_yakindu_statechart.png(The "New YAKINDU Statechart" dialog)!

p=. 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:

!(standard-image)images/tuto_light_switch_150_dialog_confirm_perspective_switch.png(Dialog "Confirm Perspective Switch")!

p=. 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.

bq. *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.


h4(#tutorial_the-initial-model). 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.

p(#tutorial_light_switch_220_statechart_editor). 
!(standard-image)images/tuto_light_switch_220_statechart_editor.png(The statechart editor)!

p=. 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.



h3(#tutorial_statechart-validation). Statechart validation

h4(#tutorial_error-markers-in-the-model-graph). 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.

###. FIXME: Bring documentation up to date!

bq. *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.


h4(#tutorial_error-markers-in-the-project-explorer). 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.


h4(#tutorial_validation-principles). 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 pop-up appears and displays the error description: "A state must have a name."

!(standard-image)images/tuto_light_switch_210_error_marker_and_pop-up.png(An error marker and a pop-up window explaining it)!

p=. An error marker and a pop-up window explaining it


h4(#tutorial_error-markers-in-the-problems-view). 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":#tutorial_light_switch_220_statechart_editor. 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!



h3(#tutorial_giving-a-state-a-name). 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*.

table(scedit).
|<. Double-click on the string @<name>@ in the state object. The string turns into a text input field with @<name>@ being highlighted:|<. !(standard-image)images/tuto_light_switch_230_statechart_editor_change_state_name_01.png(Double-clicking on the state name)!|
|<. Type the state's new name, i.e., @Off@:|<. !(standard-image)images/tuto_light_switch_230_statechart_editor_change_state_name_02.png(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:|<. !(standard-image)images/tuto_light_switch_230_statechart_editor_change_state_name_03.png(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:|<. !(standard-image)images/tuto_light_switch_230_statechart_editor_change_state_name_04.png(Dragging the state)!|
|<. Drop the state box at this very place, and everything looks much better now:|<. !(standard-image)images/tuto_light_switch_230_statechart_editor_change_state_name_05.png(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:|<. !(standard-image)images/tuto_light_switch_230_statechart_editor_change_state_name_06.png(Deselecting the state)!|



h3(#tutorial_creating-a-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.

table(scedit).
|<. 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.|<. !(standard-image)images/tuto_light_switch_240_statechart_editor_create_state_01.png(Dragging a new state from the palette to the editing area)!|
|<. Release the mouse button over a gray area, a region:|<. !(standard-image)images/tuto_light_switch_240_statechart_editor_create_state_02.png(Dropping a new state in a region)!|
|<. The new state appears in the model graph:|<. !(standard-image)images/tuto_light_switch_240_statechart_editor_create_state_03.png(A new state)!|
|<. Rename the new state to *On*. Vertically align it to the *Off* state, if you like:|<. !(standard-image)images/tuto_light_switch_240_statechart_editor_create_state_04.png(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 pop-up 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.|<. !(standard-image)images/tuto_light_switch_240_statechart_editor_create_state_05.png(Creating a state using the pop-up menu)!|



h3(#tutorial_creating-a-transition). 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.

table(scedit).
|<. In the _Palette_, click on the _Transition_ symbol. The symbol's background turns blue.|<. !(standard-image)images/tuto_light_switch_250_statechart_editor_create_transition_01.png(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.|<. !(standard-image)images/tuto_light_switch_250_statechart_editor_create_transition_02.png(Drawing a new transition)!|
|<. Once the mouse pointer reaches the target state, it changes its shape.|<. !(standard-image)images/tuto_light_switch_250_statechart_editor_create_transition_03.png(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.|<. !(standard-image)images/tuto_light_switch_250_statechart_editor_create_transition_04.png(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:|<. !(standard-image)images/tuto_light_switch_250_statechart_editor_create_transition_05.png(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:

!(standard-image)images/tuto_light_switch_260_statechart_editor_create_definitions_01.png(Creating definitions [1])!

p=. Creating definitions &#91;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:

bc. internal:
    event operate


The keyword @internal@ makes the following definition of the _operate_ event belong to the internal scope. The latter is explained in section "&quot;Internal scope&quot;":../user-guide/statechart_language.html#sclang_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:

!(standard-image)images/tuto_light_switch_260_statechart_editor_create_definitions_02.png(Creating definitions [2])!

p=. Creating definitions &#91;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*.

table(scedit).
|<. 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.|<. !(standard-image)images/tuto_light_switch_270_statechart_editor_create_transition_01.png(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.|<. !(standard-image)images/tuto_light_switch_270_statechart_editor_create_transition_02.png(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.|<. !(standard-image)images/tuto_light_switch_270_statechart_editor_create_transition_03.png(Completing the transition creation)!|




h2(#tutorial_simulating_the_light_switch_model). 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_:

!(standard-image)images/tuto_light_switch_300_statechart_simulator_run_as_statechart_simulation.png(Selecting "Run As → Statechart Simulation" in the context menu)!

p=. 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 pop-up window. Figure "&quot;Light switch simulation in &quot;off&quot; state&quot;":#tutorial_fig_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 pop-up 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:

p(#tutorial_fig_light_switch_simulation_in_off_state). 

!(standard-image)images/tuto_light_switch_310_statechart_simulator_state_off.png(Light switch simulation in "off" state)!

p=. 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.

!(standard-image)images/tuto_light_switch_320_statechart_simulator_state_events.png(Displaying event names in the statechart simulator's "Simulation" view)!

p=. 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.

!(standard-image)images/tuto_light_switch_330_statechart_simulator_state_on.png(Light switch simulation in "on" state)!

p=. 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.




h2(#tutorial_code-generation). Code generation

YAKINDU Statechart Tools include code generators for Java, C, and C&#43;&#43; 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.



h3(#tutorial_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:

!(standard-image)images/tuto_callhandling_model.png(The CallHandling statechart model)!

p=. 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.



h3(#tutorial_creating-the-statechart-model). Creating the statechart model

In the "previous section":#tutorial_starting-with-an-empty-statechart-model 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.


h4(#tutorial_creating-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&#95;call_.
* The _User_ interface comprises two incoming events: _accept&#95;call_ and _dismiss&#95;call_.

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

bc.. interface User:
    in event accept_call
    in event dismiss_call

interface Phone:
    var duration : integer
    in event incoming_call

p. 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:

!(standard-image)images/tuto_callhandling_example_final.png(The CallHandling statechart modeled in the statechart editor)!

p=. The CallHandling statechart modeled in the statechart editor



h3(#tutorial_creating-a-generator-model). 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.

!(standard-image)images/tuto_callhandling_200_generation_create_generator_model.png(Selecting "New → Code generator model" in the context menu)!

p=. 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 &gt;_.

!(standard-image)images/tuto_callhandling_210_generation_new_sgen_model_1.png(Selecting a filename for the generator model)!

p=. 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_.

!(standard-image)images/tuto_callhandling_220_generation_new_sgen_model_2.png(Selecting generator type and statechart model)!

p=. 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_.

!(standard-image)images/tuto_callhandling_230_generation_new_sgen_model_3.png(The generator model)!

p=. The generator model

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

bc.. 
GeneratorModel for yakindu::java {

    statechart CallHandling {

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

p. 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.

###. FIXME: Insert a reference here.



h3(#tutorial_enhancing-the-generator-model-by-timing-capabilities). 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:

bc. feature GeneralFeatures {
    TimerService = true
}



h3(#tutorial_generating-java-source-code). 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.

!(standard-image)images/tuto_callhandling_240_generation_timer_service.png(Adding the timer service feature)!

p=. 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.

!(standard-image)images/tuto_callhandling_250_generation_use_as_source_folder.png(Declaring "src-gen" as a source folder)!

p=. 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.



h3(#tutorial_integration-with-client-code). 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.


h4(#tutorial_creating-client-code). Creating client code

Let's establish a new Java class _CallHandlingClient_ and integrate the state machine with it:

# Right-click on the _src_ folder.
# Select _New → Class_ in the context menu.
# Name it _CallHandlingClient_.<br/>!(standard-image)images/tuto_callhandling_300_java_integration_create_new_class.png(Creating a class containing the client code)!
# Click _Finish_.

Next, copy the following code into the created class:

bc.. 
  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:
          sm.init();

          // Enter the state machine and implicitly activate its "Idle" state:
          sm.enter();

          // Raise an incoming call:
          sm.getSCIPhone().raiseIncoming_call();
          sm.runCycle();

          // Accept the call:
          sm.getSCIUser().raiseAccept_call();
          sm.runCycle();

          // Keep the phone conversation busy for a while:
          for (int i = 0; i < 50; i++) {
              Thread.sleep(200);
              sm.runCycle();
          }

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

          // Hang up the phone:
          sm.getSCIUser().raiseDismiss_call();
          sm.runCycle();
      }
  }

p. 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&#95;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.


h4(#tutorial_executing-the-client-code). Executing the client code

You can execute the client code via _Run As → Java Application_ from the class file's context menu.




h2(#tutorial_closing-remarks). 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.
