DOWNLOAD

CHANGES

SCREENSHOTS

DOCUMENTATION



Automatically generated state machines

Automatically generated state machine code

Although it may not seem obvious for a simple example, sometimes it gets very complicated to write the if-then-else state machine code by hand. Furthermore, it becomes difficult to optimize the source code (for speed and space) by minimizing the number of if-then-else statements performed. For these reasons, WhatOS includes tasks which can automatically generate the if-then-else statements from a given set of state transitions. Note that you do not need this functionality for the vast majority of simple tasks.

In this section we reimplement the SLIP receiver from the WhatOS Introduction using automatically generated state machine code. Let's draw the state transition diagram of a SLIP receiver. The nodes are the states and the edges are the conditions, as binary variable expressions which must evaluate to true for the transition to take place. Each binary variable can only be true or false and the allowable operators are the following: negation (~), or (|), and (&).

sliprx.png
variable meaning
esc received byte ESC
end received byte END
esc_esc received byte ESC_ESC
esc_end received byte ESC_END

How do you specify this state machine in WhatOS? The following file rewrites csliprx using whatos.core.cautotask:

slip2.py - pysliptx and automatically generated csliprx

Transitions are defined as methods named <from_state>_TO_<to_state>. Condition expressions are written as documentation strings of those methods. The action performed during the transition is returned by those methods. The resulting if-then-else statement containing the tests, transitions, and actions becomes a macro called transition_code(); you execute this macro in the task's process. Writing a python task using whatos.core.pyautotask is very similar.

Feature: Generate state machine code from state transition diagram.

Let's put these two tasks in a system:

system2.py - System made using slip2.py

The two csliprx tasks - the original created using ctask and the new one created using cautotask - behave identically. However, there is a little more debugging information available in the cautotask version; as the following interactive session shows, you can trace state transitions inside an autotask:

$ wospython
>>> from system1 import *
>>> system.dllbuild()
>>> system.dllload()
>>> system.inpacket.emit([1, 2, 3])
inpacket([1, 2, 3]) -> pysliptx
outbyte(192) -> csliprx
Transition(csliprx): idle -> idle
outbyte(1) -> csliprx
Transition(csliprx): idle -> receiving
outbyte(2) -> csliprx
Transition(csliprx): receiving -> receiving
outbyte(3) -> csliprx
Transition(csliprx): receiving -> receiving
outbyte(192) -> csliprx
Transition(csliprx): receiving -> idle
outpacket([1, 2, 3]) -> environment
© Mircea Hossu () WhatOS 2.0.3  (2006 Feb 26)