I have implemented a simple state machine for an embedded system using C's switch statement. I know it would be better if I used function pointers with a look up table but I'm saving that as a next step.
My state machine has the following states:
Startup (the initial state)
Startup Error.
Idle (the system only checks for input in this state. It does not update the display or anything else. It's just 'idle').
Check (this is the actual application)
Program
Copy to Internal Memory
When the system starts up, it enter the startup state which configures the ports, initializes the display and does a hand-shake with the ICs connected on the SPI bus to ensure everything is A-OK. If so, the system enters the Idle state. If not, it enters the Startup Error state, displays an error on the LCD, flags a variable and then enters the Idle state.
In the Idle state, the program polls 3 pins on the microcontroller to check if one of the 3 buttons (Check, Program, Copy to Mem.) is pressed. Depending on which button is pressed, it enters the appropriate state, executes some code, updates the LCD and then returns back to the Idle state. NOTE: The system does NOT care if a button is pressed if there was a hardware fault in the system. The Startup Error state flags a variable called hardware_fault which, if set, ensures that the Idle state does not bother polling any of the input buttons.
This is the first time I'm implementing a state machine and I was just unsure if this was a good design. I haven't really seen any examples of FSMs where they poll for input in an Idle state. Instead, it seems, most examples are rather sequential in nature (like a counter, for instance). So, my question is, is my design reasonable? It DOES work but as everyone here knows, there is bad design and then there is good design.
You should refactor your code away from a switch statement and use a transition table as you mention. Code around a switch doesn't scale, is messy and quickly becomes difficult to read and update.
To answer your question, I would say that most state machines are actually like yours: they react to events (in your case, the poll). If they are purely sequential, without events at all, they are for specialized usages, like implementing a regex...
As a note, the Idle state is equivalent to the runtime core of a state machine library: it intercepts events and posts them to the state machine. With a state machine library, it would be "hidden" from the client code, while a bare bones implementation like yours has to do event polling explicitly.
And now a design critique: one should avoid global variables in general, and especially so in a state machine. State Idle should not know about a hardware_fault global variable. With state machines, one should strive to "embed" global variables in the state machine itself, by adding states (when it makes sense!). A very good introduction to (hierarchical) state machines and explanation of the rationale is here.
Using the UML notation (see here for a tutorial), your state machine is:
An easy refactoring to remove the hardware_fault dependency all together is:
That is, we just stay forever in the StartupError state, without transitioning to Idle.
The ε (epsilon) represents an empty transition, that is, a transition that is taken as soon as the activity associated with the source node is over, without any event. This is what you mean by "sequential" state machines.
I am also including the sources to the first diagram (the second one is very similar), generated with the very easy and powerful PlantUML.
#startuml
skinparam shadowing false
title Embedded v1
state Startup
state StartupError
state Idle
state Program
state Check
state Copy
Startup : entry/ init HW
StartupError: entry/\n display error\n hw_fault = true
Idle : do/ if not hw_fault: poll
Program : do/ program
Check : do/ check
Copy : do/ copy
[*] -> Startup
Startup -> StartupError : ε [error]
Startup --> Idle : ε [not error]
StartupError --> Idle : ε
Idle --> Program : program_btn
Idle --> Check : check_btn
Idle --> Copy : copy_btn
Program --> Idle : ε
Check --> Idle : ε
Copy --> Idle : ε
#enduml
Related
I have a simple state machine like the above. As far as, I looked over the online resources (example - x-sate) the state machine could have three different things "State", "Action Or Event" and "Side effect".
So Basically the event comes from outside of the state machine like User clicks, Reboot triggered etc., and the state machine should change its state based on those events. Also, each state could perform some side effects, but the side effect should not affect the state machine (for example, perform a cleanup task before Reboot)
Questions:
Is it allowed for a state to perform some operations(side effects) which could change the state of the state machine(fetch A, B, C in the above diagram) without any external event or action?
I have a state machine diagram for an application that has a UI and a thread that runs parallel. I model this using a state with 2 parallel regions. Now I want when that thread gives some message, for example an error, that the state of the UI changes, for example to an error screen state.
I was wondering what the correct method to do this is, as I was not able to find any example of this situation online.
The options that I thought of were creating a transition from every state to this error state when the error state is called, which in a big diagram would mean a lot of transitions. Or by just creating a transition from the thread to the error state (As shown in the image), which could possible be unclear.
Example of second option
You don't need a transition from every state. Just use a transition from the State State to the Error window state. It will then fire no matter what states are currently active.
Such a transition will also leave the Some process state. Since you didn't define initial states in the orthogonal regions, the right region of the state machine will then be in an undefined state. Some people allow this to happen, but for me it is not good practice. So, I suggest to add initial states to both regions. Then it is clear, which sub state will become active, when the State state is entered for any reason. The fork would also not be necessary then.
How you have done it in your example would also be Ok. However, since the Some process state is left by this transition, this region is now in an undefined state. Again, the solution to this is to have an initial state here. I would only use such a transition between regions, when it contains more than one state and the On error event shall not trigger a transition in all of the states.
If the Some process state is only there to allow for concurrent execution, there is an easier way to achieve this: The State state can have a do behavior, that is running while the sub states are active. Orthogonal regions should be used wisely, since they add a lot complexity.
Following on the discussion at State machine program design in FreeRTOS - vTaskStartScheduler in a switch statement, I have a state machine with 4 states, each of them with different tasks reading sensor data.
When a sensor data reaches a threshold, its task has to cause a state change.
The idea is to have a superior task which controls the states (and suspends/resumes corresponding tasks) with a switch statement. My question is: how should the sensor tasks communicate the STATE with the superior task?
One proposed solution is to have a set_state function which is called by the event generating task, but I read that having global variables in FreeRTOS is discouraged. I thought to implement it through Queues:
1- Task1 detects sensor threshold, and sends STATE to a Queue.
2- Superior task is blocked waiting to receive data from Queue. When it receives STATE, the switch statement processes the state change.
If this approach is correct, my doubt relates on how and where should be STATE defined (global, or just existing in the stack of each task, or the superior task...)
STATE should exist only where it needs to, 'in' the superior task. I'm presuming you're using C, so declare STATE as a static variable in "superior_task.c" (or whatever it's called). This means it can then only be affected within that file - the C equivalent to a private member variable in C++.
Then, if your inferior tasks need to affect a state change, they post a state change event to a queue managed by the superior task. When the queue is processed, the superior state makes the change to the private STATE variable.
If other tasks need to know what the state is for their own processing, they can use an accessor for the private variable, e.g., State get_state() { return STATE; }. As Martin says though, the other tasks shouldn't need to know the state, as otherwise there's inter-dependencies between tasks that shouldn't exist.
As a newbie am trying to develop a state machine using Visio for a cd writer. below are the device operations/transactions and attached, is a diagram of what I've done so far, am unsure if its accurately represented.
Device operation
Load button- causes the drawer to open and to shut if open(load an empty cdr)
Burn button- starts recording document on the cdr, green light comes on in the burning process
and goes off when completed. Once cdr is burned writer stops.
Verify button- verifies the document previously recorded on the cdr, green light comes on in the
process and goes off when completed, then device stops
Cancel button- stops process anytime during recording or verifying
Cancel button- no effect if cd writer is empty or not busy verifying or recording When powered up- CD Writer will ensure the drawer is closed
Burn button – has no effect when cd writer is empty and during recording or verifying process.
Verifying can only be started when the CD Writer is not busy recording.
Visually your diagram looks like a state machine and states have good-sounding names - it's a good start. :)
The first issue I see there is the transition specification. It is definitelly not correct. State transitions in UML are specify in the folowing format:
event [guard] /action
where:
event (or trigger) is an external on internal "signal" that starts the transition. It can be a button activated by a user, an elapsed timer, a detected error, etc. It can even be omitted.
guard is a logical condition that should be fulfilled in order to start the transition. It is usually an expression returning a boolean value of tru or false. It can also be omitted.
action is a kind of side-effect, something that is executed when the transition is triggered. Ic can also be omitted.
Getting back to your diagram I would say that...
most of the labels on your transitions should not carrry "/" as it indicates an action. There are mostly manual triggers, like "load" (pressing the button to open the drawer), "Cancel", "butn", etc.
Consider some events that are triggered internally, like "burning done", or "CD loaded"
You can add some guard conditions in the situations where possible
I would remove all the triggers with no effect (like cancel with no CD in). It makes the diagram simplier with no loss of information
States LOADED and IDLE in your case are kind of strange, weak. It is not clear what makes them different (see the example below)
Here is a diagram that I find a bit more acurate (see notes for additional comments):
You need to specify explicit events as triggers of the transitions.
In the current state machine, each transition (except the one leaving the initial vertex) has an effect, but not a trigger. More accurately, they are triggered by the default completion event, and are therefore automatic.
Moreover, since all transitions react to the same event, your state machine is non-deterministic. For instance, in the state loaded, the transitions to Recording, empty, and loaded all react to the completion event. When the completion event is dispatched, these transitions are said to be conflicting, and one of them is selected non-deterministically. I am sure this is no what you want.
Read the UML Specification, and define triggers for your transitions.
You don't need to depict the transitions from "empty" to "empty" as transitions without any actions or state transitions would not need to be drawn in the Statemachine diagrams. (State Transition tables are often used for the checks of any missing transitions for such cases.)
"loaded" and "Idle" can be represented in one as a same state
To represent the "green light", I would write "turn on the green light" as entry action in Recording and "turn off the green light" as exit
Here's the diagram I drew. The status of tray (whether its opened or closed) should be considered in the actual model, but its not on my sample diagram below.
I have been using State machine based design tools for some time, and have seen UML modeling tools that allow you to execute your logic (call functions, do other stuff) inside a state. However, after spending a couple days with IAR VisualState, it appears that you cannot execute your logic inside a state without a trigger. I am confused as it does not make sense TO HAVE A TRIGGER for every single action inside a state !
Here is what I expect from a state chart tool:
If I enter StateA, upon entering the state I set my values in entry section, then I would like to call a function (I just want to call it, NO TRIGGER), and inside that function, I want to trigger an event based on some logic, and that event would trigget state transition from StateA to StateB or StateC.
Is there something wrong with this expectation? Is it possible in VisualSTATE?
Help is greatly appreciated.
VisualSTATE imposes the event-driven paradigm, just like any Graphical User Interface program. Anything and everything that happens in such systems is triggered by an event. The system then responds by performing actions (computation) and possibly by changing the state (state transition).
Probably the most difficult aspect of event-driven systems is the inversion of control, that is, your (state machine) code is called only when there is an event to process. Otherwise, your code is not even active. This means that you are not in control, the events are. Your job is to respond to events.
Perhaps before you play with visualSTATE, you could pick up any book on GUI programming for Windows (Visual Basic is a good starting point) and build a couple of event-driven applications. After you do this, the philosophy behind visualSTATE will become much clearer.
Create 3 states: A, B, C where state A is a default state.
By entering state A, call action function [that sets you
variables a and b following some algorithm], followed by ^Signal1.
Entry/ action()^Signal1
Make a transition driven by Signal1 [will serve you as an event] from state A with 2 guards:
a <= b, transition to state C
a > b, transition to state B