Five-minutes tutorial

The five-minutes tutorial gives you a brief introduction into modeling state machines with itemis CREATE 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 it looks like:

Interactive light switch statechart simulation

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.

Importing light switch example

Now try this for yourself. We are assuming that you have already installed and started itemis CREATE. If you don’t, please see the Installation Guide for details.

  1. If the “Welcome” page is still open, close it.

    Closing the "Welcome" page

  2. In the main menu, select File → New → Example….
  3. In the dialog, select itemis CREATE Statechart Examples, then click Next >.
  4. The example wizard opens. If needed, follow the instructions to download the examples repository.
  5. On the left-hand side of the example wizard, select Basic Tutorial, then click Finish.
  6. The sample project named org.yakindu.sct.examples.basic.tutorial is created.
  7. In the project explorer on the left-hand side of the window, open the org.yakindu.sct.examples.basic.tutorial project by clicking on the small triangle left on the left of the project name (“org.yakindu.sct.examples.basic.tutorial”). Open the model folder and the 01_basic folder.

    Expand project

  8. The light switch statechart is defined in the file 01_lightSwitch.ysc. Double-click on this file to open the model.

Simulating the light switch

  1. Right-click on 01_lightSwitch.ysc and select Run As → Statechart Simulation in the context menu.
  2. The simulation starts and shows the light switch model in its off state. The rectangle named Off is highlighted in yellow, meaning it is the active state.

    Light switch simulation in "off" state

  1. At the right 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 default to unfold the switch link. This link represents the switch event to switch the light on or off.

    Simulation View with the switch event

  2. Click on the switch link. The active state changes accordingly from Off to On.

    Light switch simulation in "on" state

  3. Click on switch again to switch off the light.

Generating statechart code

You have developed and tested your statechart model, and now you need it as a C, C++, or Java implementation? itemis CREATE 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:

  1. In the project explorer, right-click on 01_lightSwitch.ysc and select New → Code generator model in the context menu.

    Creating a new code generator model

  2. In the dialog, replace Statechart.sgen by light_switch.sgen, then click Next >.
  3. In the next dialog, check the checkbox left from 01_lightSwitch.ysc under the 01_basic folder, then click Finish.
  4. Java classes implementing the statechart model are generated. You can find the generated source code in the folders src and src-gen.

    Generated Java source code

That’s it. If you want to know more, take the time and work through the Comprehensive Tutorial.

Comprehensive tutorial

This tutorial introduces itemis CREATE 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 will teach you how to

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 itemis CREATE installed. For installation instructions, see the itemis CREATE 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:

Modeling the light switch as a statechart

Now let’s model the light switch as a statechart using itemis CREATE. 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 itemis CREATE 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 itemis CREATE 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 itemis CREATE → Statechart model

Selecting "itemis CREATE → Statechart model"

Selecting itemis CREATE → Statechart model

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

The "New itemis CREATE Statechart" dialog

The New itemis CREATE 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 is in the LightSwitch project. If you want, you can change the preset values.

The default file name in the File Name field is Statechart.ysc, 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 Next.

In the next dialog, in the dropdown menu you can select the domain you want to create a statechart for. A short description helps you to decide for the right domain for you, depending on your needs. In this example, the Default Domain is selected.

Selecting a statechart domain

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 itemis CREATE Modeling perspective by clicking on the Yes button. The itemis CREATE 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 itemis CREATE 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), two “normal” states, and three transitions.

Let’s start our editing with a simple operation, and delete the state called StateB. To do so, just right click on the state and select Delete from Model. Alternatively, you can just press the DEL key on your keyboard.

Delete state

As you can see not only the state, but the transitions connected to it had been deleted. This is the expected behavior, but let’s get back to transitions in a later part!

Giving a state a name

As we have seen, the created state has the default name StateA. You can rename any state depending on your requirements.

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

Double-click on the string <StateA> in the state object. The string turns into a text input field with <StateA> 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: 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 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. Creating a state using the pop-up menu

Statechart validation

Error markers in the model graph

In the previous section, after dragging the new state into the editing area and before you gave a name for it, the state had 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. Let’s create a new state, but don’t give a name for it, to guide you through the basics of the error display.

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 itemis CREATE' 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."

An error marker and a pop-up window explaining it

An error marker and a pop-up 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:

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

That’s all for now! This knowledge can help you in the future to speed up the fixing of errors in your projects. Let’s delete the incorrect state and move on to the next part to create our virtual light switch!

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. To change that:

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

Modify the existing text to the following:

interface:
    in event operate

The keyword interface makes the following definition of the operate event belong to the external scope, thus we can interact with it throughout the simulation. 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 [1]

Creating definitions [1]

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:

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 yellow 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 default 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 yellow 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

itemis CREATE 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:

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 itemis CREATE 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:

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

@EventDriven
@ChildFirstExecution

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, itemis CREATE 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 itemis CREATE 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 itemis CREATE 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 create::java {

    statechart CallHandling {

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

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

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 → Other.. → Java → 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:

package callhandling;

import callhandling.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());

		// 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();
	}
}

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

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 itemis CREATE features up to a certain degree. The itemis CREATE Statechart User Guide will explain statechart language, statechart editor, simulation, testing, programming language support, and code generation in detail.

Statechart concepts tutorial

This tutorial introduces main concepts which will be helpful for understanding and defining statecharts in itemis CREATE. While the previous tutorials explain how to use itemis CREATE, this tutorial does not require an installation of itemis CREATE as it makes use of embedded statechart players.

The different concepts are introduced step by step using a light control example. Starting from a simple On/Off switch, we will add further features like brightness adjustment and motion detection step-by-step while introducing new statechart elements with each iteration. In that way you will learn how to use:

While itemis CREATE supports even more concepts, this is a good starting point to dive into itemis CREATE headfirst. Within itemis CREATE these tutorial statecharts are also provided as an example project.

States, transitions and events

A statechart is a graphical model which describes the behavior of some thing or entity. It describes how such an entity reacts to changes and events in its environment. Due to it’s graphical nature, lucid concepts, and well defined semantics it provides a comprehensive and executable basis for system specification and implementation which can be shared between stakeholders without demanding too many technical skills.

The most basic element of a statechart are states, transitions, and events. To introduce these basic concepts we take a look at the simple light switch example below. States represent the modes of a system or entity and in the case of this very simple light switch two states Off and On exist. States have a name, are visualized as rounded rectangles. At any point of time states are either active or inactive. Active state are highlighted using a yellow background color while inactive states have a blue background color.

If something happens then the statechart may change its state. Each state can have outgoing transitions. These transitions connect two states and have a direction which is indicated by the arrow head. Our light switch states are mutually connected by transitions. These transitions are directed and define how state changes (state transitions) can occur under which conditions. Here, the light switch simply defines that Off and On are toggled whenever a switch event occurs. As the state machine only reacts in response to events, it is called event driven.

Events typically occur in the environment of the statechart’s entity. To simulate this environment and to play with the light switch you can interactively trigger events e.g. by clicking on interactive elements like switch.

The light switch declares the switch event as:

interface:
	in event switch 

State machines as a whole can be active or inactive. If a state machine is inactive then no state is active and it won’t react on any event. If a state machine is active then is has at least one active state and it is ready to react on events. Entering a state machine activates it exiting deactivates it. If you enter the light switch state machine then Off is the first active state. The first active state is called initial state and is defined by the entry node whose single outgoing transition points to Off.

Variables

While the classic theory of input/output automata is only aware of events, Harel statecharts and as such CREATE Statecharts have many more features, including variables. Variables allow to use quantitative values in statecharts and are very comparable to variables in programming languages.

To explain the use of variables we extend the light switch by adding dimming functionality. The light switch supports ten different dimming levels. It still defines the states Off and On with mutual transitions which are triggered by switch events.

To handle the dimming functionality the light switch statechart defines two additional elements:

To handle the brightness level correctly the statechart must maintain its value depending on the active state and the occurring events. As such it defines the following rules:

This example shows how variables can be used in conjunction with more complex conditions. Variables can be assigned and can also be used in conditions and calculation expressions. Actions can be specified as part of a transition as well as part of states.

The statechart interface is defined as:

interface:
	in event switch
	in event changeBrightness
	var brightness: integer


brightness:



Composite States

Normally, a statechart does not only consist of two states. The specification of even simple systems require tens and more complex systems hundreds of states and transitions. To cope with large number of states the base concept of composite states can be used.

Let’s enhance our light switch to explain this in more detail. The light switch now provides an additional motion sensing mode which automatically switches the light on and off depending on the input of a motion sensor. Initially, the light is off, but whenever the motion sensor senses a motion, it turns the light on. After 30 seconds without any motion the light is turned off again. As manually switching and dimming the light should still be supported the existing statechart must be extended.

First, an additional event toggleMode is defined. This is used to toggle between the already existing manual and the automated motion sensing mode. To model these modes two additional states are introduced.

  1. The composite state Manual contains the existing behavior. These are the On and Off states of previous statechart. Here only the dimming transitions were replaced by local state reactions.
  2. The composite state MotionSensing is completely new and contains the states MotionSensing.On and MotionSensing.Off. These handle the motionDetected event. The required timeout is specified using the time trigger after 30s. If the state does not change for 30 seconds then a time event is raised which will cause to switch the light off.

A composite state is a state that contains one or more other states (sub states). One of the advantages is the possibility to group states into logical compounds and thus make the statechart more comprehensible. Another advantage is the option to exit a composite state by transitions that have the composite state as their source states, not any substate. If such a transition is executed, the composite state is left regardless of which of its sub states are active at the moment. You could achieve the same without composite states, but it would be cumbersome since you would need a transition from each of the plain states in the group to the “outside”.

The transitions which toggles between MotionSensing and Manual state are defined for the composite states. This implies that the transitions will be taken independent of the concrete active sub state. So all sub states share the behavior of their parent states.

If you want to learn more about composite states, you can check out our Hierarchical tatecharts example or the chapter Composite states in our documentation.

The statechart interface is defined as:

interface:
	in event switch
	in event changeBrightness
	in event toggleMode
	in event motionDetected
	var brightness: integer



brightness:



History Entries and Named Interfaces

We already discussed the default entry behavior for regions and how sub states are activated. Histories provide an extension to this mechanism and this section clarifies how history entries work, what they do, and especially what they don’t do. To illustrate this, we introduce another mode to our light switch: light sensing. When operating in light sensing mode, the light control automatically turns on the light when it is dark and turns it off when it is bright. For this purpose a luminosity sensor is used. It permanently senses the ambient brightness and fires luminosity.bright or luminosity.dark events all the time. It is out of scope how “dark” and “bright” are defined and how they are configured in the luminosity sensor. Suffice to say that the sensor is always raising events – say, multiple times per second.

As before the light switch is either operated manually or operates automatically. When in automatic mode, the light switch functions either as a twilight switch as explained above or as the already introduced motion sense switch (see the previous iteration). The user interface gets another button to toggle between the two modes via the user.mode_button event. The light switch is starting to change into a full light control module.

The statechart interface is defined as:

interface:
	var brightness: integer
interface hmi:
	in event switch
	in event toggleMode
	in event changeBrightness
interface motion:
	const timeout: integer = 30
	in event detected
interface luminosity:
	const delay: integer = 10
 	in event bright
 	in event dark

As we added a couple of additional declarations we now use named interfaces to group the different events and variables. This grouping makes the design more clear and provides a better overview. The usage is not different except for the fact that the interface name must be used when referencing its declarations.

play stop

luminosity sensor:
bright dark

motion sensor:
motion



The automatic modes are grouped into the Automatic composite state. That state is subdivided into a composite state for the twilight functionality and another one for motion sensing. We have discussed motion sensing before, but the Light Sensing composite state deserves some explanation. When the ambient brightness is changing from day to night or from night to day, the luminosity sensor doesn’t deliver consistent values. Rather small fluctuations are causing a succession of quickly alternating luminosity.dark and luminosity.bright events. Having each of these events turn the light on or off, respectively, would result in a flickering lamp for some time during twilight. To avoid this, the state machine requires a certain permanence in the luminosity sensor’s results before actually toggling the light’s state.

This is done like this: During the day the Light Sensing composite state’s Bright sub state is active. In this state the state machine listens for luminosity.dark events. These events are starting to be raised when it is about to get dark. First they come in spuriously, later there are more luminosity.dark than luminosity.bright events within a given period of time, until only luminosity.dark events are raised. The first luminosity.dark changes the state from Bright to Getting Dark. In this state we are waiting until a certain time has passed, e. g. 10 seconds, to be configured as constant luminosity.wait_time. However, each luminosity.bright event brings the state machine back to the Off. Only if the waiting time has passed without any lum_sensor.bright interfering, the Dark state is reached and the light is turned on. The analogous happens in the morning when the first light of the day is close. The twilight switch is also robust against short disruptions like overshadowing the sensor during the day or illuminating it briefly by a car’s headlamps during the night.

An important requirement is that any of the automatic modes can be interrupted at any time by manually operating the light switch via . When the user later raises a event, the state machine should return to that particular sub state somewhere down in the Automatic composite state that was active before the manual intervention. Similarly, when toggling between Light Sensing and Motion Sensing the state machine should remember the respective active sub state and return there when control is turned back.

That’s what history entries are good for. The statechart contains a couple of shallow history entries. A shallow history state, contained in a composite state with a set of sub states, remembers which of these sub states was active when that composite state was left.

The shallow history state in Automatic remembers whether Light Sensing or Motion_Sensing was active when Automatic was left, but it doesn’t remember which state was active within the active one of these two. On re-entry, the history state would activate either Twilight or MotionSensing, but these would use their respective entries. This is why there is a history state in each of them as well.

If you have worked with history states before, you might be inclined now to say: "A deep history state would have been the correct thing here." However, you would only be partially right. A deep history state remembers the active state in its own region and everything that was active inside of this state, recursively down to the lowest level. We might spare the two shallow history states in Light Sensing and Motion Sensing. But it would not behave in the same way – a history state is activated only when its containing region is actually left. Using one deep history state would not allow to remember the active state in MotionSensing when switching to Light Sensing, and vice versa. The deep history state would be activated only if we left the whole Automatic composite state – and when switching between automatic modes this won’t happen.

More information on history states can also be found in the History States example or the corresponding chapter in our documentation.

Orthogonal States, Internal Events and Operations

The different versions of light switches which we discussed so far define a couple of states but are quite simple in that respect that at any time at most one single state is active. You may object that hierarchy made up of composite states features a set of active states. This is not really true. Composite states just group a set of states but are not independent of their sub states. Leaf states are the real active states and the activation of a leaf state implies that also all its parent states are active. The leaf states also inherit the parent states behavior. There are scenarios which require orthogonal states (sometimes also called parallel states or and states).

Additionally, there are also scenarios where calculation become so complex that you don’t want to maintain them within a statechart. In these cases operations can be applied.

To illustrate these concepts we define a variant of the light switch which includes a presence simulation. It behaves as if a person operated the light at sensible and irregular intervals although nobody is present. The presence simulation is active on certain hours of the day only, namely from 17:00 to midnight and from 07:00 to 10:00. Here the motion detection and the twilight detection are left out for clarity.

To define the presence simulation the orthogonal state Active is defined. It contains two sub regions which are independent of each other and are executed virtually in parallel (their order is relevant, though). Each region can contain one active state. Each region is caring about different aspects. The region schedule includes a single state which cares about scheduling the next changePresence event. This event in turn is consumed by the presence region which switches the light on and off.

The events changePresence, startSimulation, and stopSimulation are internal events (also called local events) which are raised by the statechart itself when a certain condition is fulfilled. They can’t be raised by the environment and are not visible externally. These internal events will be processed directly after the current event. So internal events can be used to chain multiple processing steps. The states Idle and Waiting raise these internal events.

The definition of Presence Simulation get quite complex. There are especially a couple of textual rules and expressions which include calculations. Additionally, a modeler may require functions which are not directly available within the statechart. However, itemis CREATE allows you to implement your own operations to overcome these limitations. An operation is called from the state machine itself, so you don’t have to care about when and how they will be called. Operations can receive arguments from the state machine and return a value, exactly like a normal function or method call. Operations are declared by the statechart but are not defined within the statechart and must be implemented externally. The presence simulation uses two operations:

  1. get_hour to ask for the current time of day to decide if the presence simulation must be activated.
  2. get_rand to ask for a random float to calculate a random waiting interval in minutes between WAIT_MIN and WAIT_MAX.
interface:
	var brightness: integer

interface hmi:
	in event switch
	in event toggleMode
	in event changeBrightness

interface simulation:
	var WAIT_MIN: integer = 5
	var WAIT_MAX: integer = 1200
	var UPDATE_PERIOD : integer = 2


internal:
	var wait_time: integer
	var hour: integer
	
	event changePresence
	event startSimulation
	event stopSimulation
	
	operation get_rand(): real
	operation get_hour(): integer

Use the simulation panel right to the model to simulate the model.

Video tutorials

You can find some video tutorials on the itemis website.