Edit on GitHub

Python Code Generation

This example demonstrates how to generate Python code from a statechart. We will use a simple light switch example and focus on the generator model.

Generator Model

In order to generate code we need to specify which code generator to use and into which folder to generate. For this, we need to create a so-called generator model. To do so,

  • Select the models folder in the Project Explorer
  • Right-click and choose New -> Code generator model
  • Follow the wizard to select the Python code generator and the state machine for which you want to generate Python code

The new generator model will look similar to this one:

GeneratorModel for yakindu::python {   statechart LightSwitch {     feature Outlet {       targetProject = "org.yakindu.sct.examples.codegen.python"       targetFolder = ""     }   } }

This is the simplest possible generator model. Line 1 defines which code generator to use. Line 3 refers to the statechart model. Lines 6 and 7 specify the target location for the generated artifacts.

Besides setting up the target location, the generator model allows you to adjust several aspects of the generated code like naming, license comments or function inlining. Press [Ctrl]+[Space] to get a list of available features. For more information, please refer to our documentation.

Invoking Code Generation

Code generation is usually invoked each time the statechart model is saved. This behavior can be disabled by unchecking the option Project -> Build Automatically. You can always manually invoke the code generation with Generate Code Artifacts in the context menu of the generator model.

The Example Application

As an example application we will use the light switch example with brightness adjustment from the Basic Tutorial.

Light switch model

Our application is a simple interactive console with which the user can switch the light on or off. The complete application code is implemented in main.py:

Application code

The interesting parts are the following:
  • Line 8 instantiates the state machine
  • Line 12 initiailizes the state machine, in particular all variables are set to a proper value
  • Line 13 enters the state machine; from this point on the state machine is ready to react on incoming events
  • Line 19 raises the On event in the state machine which causes the corresponding transition to be taken
  • Line 22 raises the Off event in the state machine

You can run the application with Run As -> Python Run on the main.py file. A console should open and ask you for input like in the screenshot below.

Light switch console application

Download examples

Drag to install

Drag to your running YAKINDU Statechart Tools (min. version 2.8.0) workspace.

Back to overview