Story#
Our story will take place in a little universe. This little universe will consist of a heaven, an earth and an underworld. The earth in the story isn’t round like ours. It’s a very small flat platform, floating above the underworld. On top of the earth are a set of pubs, arranged on different terraces. Each terrace has one pub.
To get to a higher pub, you would first have to walk through a lower pub. The lower pubs are for a more general audience, while the higher pubs, though having less space have a more specialized aesthetic.
On every terrace, there will be two bouncers, a greeter and zero or more bartenders. There will only be one set of stairs that can be used to enter or exit a pub, and this is where that pub’s bouncers will sit.
One bouncer will be facing in the direction of people entering the terrace and the other will be facing in the direction of people wanting to leave it. The greeter will talk to anyone who has decided to stay on her terrace. If there is a bartender on the terrace, he will serve drinks and sometimes he will have secrets.
Translation
Each pub is a state in a statemachine. You would program these states as functions that take two arguments, a reference to an ActiveObject and an event.
These state functions will contain an if-elif structure which will have multiple clauses. The greeter is the init clause, and the enter and exit bouncers are the entry and exit clauses.
The init, enter, and exit clauses can be activated when the state function is given an event with an init, entry or exit name.
Likewise, the bartender is a clause where the application developer sets the event name.
Now let’s add some supernatural beings: three “gods” and a “spirit”.
The heaven will have one goddess, Eve, “the goddess of law and order” and the underworld will be ruled by Theo, “the solipsist”. The earth will have a lazy god named Spike, “the source” who happens to be the only guy who can drink in the whole universe. Spike will have a companion spirit, named Tara “the explorer.”
We know now about the entire cast of the story. There are bouncers, greeters, bartenders, three gods and one spirit.
Translation
Eve represents the event processor, or the algorithm that sends the state functions different events.
Spike, represents the source state while the event processor is searching the statechart. Think of Spike as the current state of the statemachine.
Tara represents the target state, which is used by the event processor to explore the statemachine while it is trying to figure out what to do.
Theo is the thread in which all of the code is run. The event processor and all of its calls to the various state functions will be driven by this thread.
An application developer will not write code to change the internal behaviour of the event processor, the source and target states or the thread. This is why these characters are supernatural in the story; it’s a mnemonic.
Let’s put our little universe into a small multiverse. Each universe will have its own heaven and underworld, gods and explorer spirit, but its terraced architecture of pubs, and people (bartenders, greeters) can be shared across all connected universes.
If this doesn’t make any sense, don’t worry about it. Let’s move on.
Translation
Anytime a statechart references a callback (a pub), that callback will change the internal variable state of the ActiveObject that is passed in as its first argument – the state callback functions themselves, do not have their own memory.
Since the callback functions don’t keep any information, they can be called by many different ActiveObjects (in that ActiveObjects’s thread) and behave as expected; there are no side effects. In this way, many different ActiveObjects can use the same set of state callback functions.
Eve, the goddess of heaven has a birds-eye view of our little world. She rules over the people: the bouncers, greeters and bartenders and, Tara, “the explorer” spirit. She took on her duty as “the goddess of law and order” with such gusto, that sometime in the world’s history, she banned alcohol consumption for everyone on earth, except Spike, who she can’t control.
Translation
The if-elif clauses, represented by the people in the story, exist within each of the state functions. These if-elif clauses only become active when the event processor (Eve) calls its function with an internal event, represented by one of the people in the story.
Tara, the “target state” is used by the event processor when it is searching a statemachine to see which state handles an external event. Since the event processor calls the function and change’s its target state while it is searching through a statemachine, we say that Eve rules over the people and Tara the “explorer spirit”.
Theo, “the solipsist” is the god of the underworld. He is only called the “solipsist” by people outside of his universe, like you and me, because his universe only works and exists if he is thinking about it. Nobody in his world is aware that he has this power.
One of Theo’s duties is to join the little universe with other universes. Theo watches a portal, which is connected to a loading dock which receives messages from different worlds, including ours. He is extraordinarily attentive and enthusiastic. He can motivate anyone he talks to or even looks upon, in fact, this is his supernatural ability.
Translation
Theo represents a “thread” pending on a queue. The ActiveObject’s post_fifo
and post_lifo
methods allow an application developer to put events into
this queue. When the thread sees that a queue has an item, it will wake up,
and drive the event processor, which in turn, will call the functions
making up the statemachine.
When Theo receives a message from another universe, it appears as a round hollow orb which sometimes contains a scroll. He calls these orbs “events”, and if they have a scroll within them, he calls that scroll a “payload”.
Translation
An event has a name, called a signal, which can be a user defined name or it can be a predefined name (ENTRY_SIGNAL, EXIT_SIGNAL, INIT_SIGNAL, etc…). An event with a user defined signal name is called an external event. An event with a predefined name is called an internal event.
The whole point of naming an event with a signal is so that a state function can use an if-elif clause to catch the event when it is given to that function. When such an event is caught, your code is run.
When an “event” comes through the portal, Theo will pick it up, marvel at it, then in a reverent gesture, pass it to Eve. They both become excited, maybe even a little nervous, because they know their universe is going to change; it will react to the event.
Theo encourages Eve to “follow the laws.” Then he will watch as she gives her minions their marching orders. Only after all of the activity stops, will he focus his attention back on the portal.
Feeling oddly refreshed and encouraged by Theo, Eve looks around the map until she sees Spike from her high vantage point. Spike being the god of the earth, is easy to see and Eve knows that her underling-spirit Tara, “the explorer”, is always near him.
Eve flies down to Tara and gives her the event. She says, “I want you to go to the terrace where there is a bartender who knows what to do with this event. Then I want you to go to wherever he tells you to take it. Good luck Tara, I believe in you.”
Tara enjoys Spike’s company, but she also loves adventure.
She looks down at the event to study it and notices that it has something written on it, a word, a phrase, it could be different every time, but it’s a clue and Tara loves a puzzle. She looks around the pub on her terrace and studies each of the bartender’s name tags. If she sees that a name tag matches the name on the event, she will approach that bartender and talk to him.
If there is no bartender to talk to on her terrace, she will go to its exit staircase and descends to the next terrace (Tara only ascends when given instructions to do so). Being a spirit, she is hard to see and the bouncers and greeters leave her alone when she is by herself.
Translation
The terraces are just callback functions containing if-elif-else clauses (pub == terrace == state == callback).
The else clause of each callback function provides information about what other callback function should be called if it doesn’t know what to do with a given event. This other function, can be thought of as a lower terrace.
The bartenders are named arrows on the HSM diagram.
The bartender also represents an if-elif clause that matches the name of the event given to that function.
She will continue to climb down the terraces until she comes to the edge of the universe. If she can’t find a bartender who can answer her question, she will take the event and throw it off the edge of the earth, into oblivion, then climb back up to rejoin Spike. In such rare cases their universe doesn’t react to the event.
Translation
Here we are starting to explore a statechart’s dynamics. If your statemachine doesn’t handle an event in any of its callback functions, the event will be ignored.
But if Tara does find a bartender who’s name tag matches the name on the event, she will show it to him. He will take it and study it, sometimes he might even take out its scroll. Then he will lean across the bar and whisper the answer into Tara’s ear.
Sometimes the bartender says, “give me the event I’ll handle it, don’t worry about it anymore.” When this happens, Tara passes over the event, then rejoins Spike, who rejoices because he doesn’t have to do anything. For some reason Spike calls this a “hook”.
Translation
Tara, the “target state” is used by the event processor to find which state callback function knows how to handle a given event. In the above picture we see that T started in “C pub”, then the event processor recursed outward to “A pub” at which point it found an if-elif clause in the “A pub” callback that “handled” the event with the signal name of “Merve”. If the application developer placed code between the “Merve” clause and its return statement, this code would be run while T is searching.
When a state callback function returns “handled” the event processor pulls T back to where S is, then it stops searching.
A state callback function can use the T state of the event processor to perform this type of event handling. For more details about this programming technique, read about the ultimate hook pattern.
Most of the time, however, the bartender will tell Tara where she has to take the event. If she has to continue her journey, she will wait for Spike so she can tell him about it.
Spike knows when Tara is waiting for him. Though he is lazy, and drunk most of the time, he always has something interesting to say, and this is what Tara loves about him. Having nothing else to do, he makes his way to the terrace where Tara has gotten her next clue. He knows that she will want to talk to him about it. As he approaches the exit, the exit bouncer puts up a hand, then looks at a clip board to see if Spike is on the guest list, which he always is, and then let’s Spike pass to the next terrace. You really can’t stop the god of the earth. For every terrace that Spike needs to leave so that he can rejoin with Tara, this futile ritual is repeated.
Translation
The target state is used by the event processor to recurse outward from C1 to find a state that knows what to do with the Event, who’s signal name is Mary.
The A state has an if-elif clause which handles Mary, and within the clause there is a transition to the B2 state. In this scenario, the A state is called the Least Common Ancestor, LCA of S and T. S needs to exit all states, from its current state, to the LCA. However, it should not exit the LCA.
As an application developer, you don’t really care about the LCA acronym. You just need to understand the dynamics of how exits work; your exit handlers will be called as your source state transitions out of the inner states to re-join the target state.
When Spike finally finds Tara he asks her what she learned. Bubbling with excitement, she tells him about where the bartender said to take the event, to which he always says, “great I’ll meet you there, but first I want to have a drink here.” Tara takes the event and makes her way to the location that the bartender told her about.
Spike finishes his drink, then again starts to make his way toward Tara. Before he can climb up to a new Terrace, he is stopped by the entry bouncer, who looks at his clip board to see if Spike is on the guest list, which he always is, then lets Spike proceed. You really can’t stop the god of the earth anyway.
When Spike finally arrives on the Terrace where Tara is, a greeter approaches them. She looks at Spike and feels slightly uncomfortable, because sometimes she needs to tell them that they can’t stay on this terrace. Instead of talking to Spike directly, gods are intimidating, she whisper’s something into Tara’s ear. Both the greeter and Tara work for Eve after all. Tara is always happy to hear that there is more to do, because she likes to explore the pubs on the different terraces.
If the greeter tells Tara that she needs to climb higher, Tara will relay the message to Spike who will answer, “great, I’ll meet you there, but first I want to have a drink”.
Tara climbs to the terrace where the greeter told her to go. Spike finishes his drink and makes his way through the entry bouncers and finally arrives at the same terrace where Tara is waiting. At which point there might be another greeter with another uncomfortable message.
If no greeter approaches them, Tara looks down at the event and watches with satisfaction, as it throbs with light, then slowly fades from existence. To this, Spike smiles and looks towards heaven, as he raises a toast to Eve.
When Eve, the goddess of heaven, see’s this her shoulder’s relax and the tension releases from her back: The laws were followed.
Theo, “the solipsist”, god of the underworld, has been watching the whole scene, and its “run to completion”. Knowing there is nothing left to do in the universe, he turns his gaze back to the portal. He waits patiently for an event to pass through the little universe’s loading dock. All is well.
Translation
The run to completion, RTC, concept is very important to understand. Your statechart will only react to one event at a time. The thread will only process the next event when the event processor has run out of things to do with your old event.
For this reason, you should not put blocking code into your statecharts. If you do, they will stop reacting to events and become unresponsive.
But is it? Sometimes when Theo, “the solipsist”, god of the underworld, closes his eyes and daydreams; his attention briefly drifts back to his world. This is enough to wake everyone up from their non-existence.
Translation
Solipsism is the name of the philosophy where a person thinks they create the world when they open their eyes, and they destroy the world when they close their eyes. It’s delusional. But Theo is actually a “solipsist” (though he doesn’t know that he is) because he is a Python thread. No code can run unless he grants CPU access to it.
When the people wake up, they become listless. The bouncers who have had nothing to do since the prohibition was announced by Eve, are particularly frustrated with the meaninglessness of their jobs. They only have one customer now. Even if Spike wasn’t always permitted to pass them, there is no way they could stop the god of earth. Why have a universe full of pubs if only one guy can drink? It seems so pointless. It’s lame.
Somehow, they find out about you and me, fellow humans called developers.
They learn that we, despite being human, are very powerful. That we can build the pub terrace system to which their gods are subservient; that we can send the event orbs and give the greeters and the bouncers their secret directions (arrows on the diagram). That we can even build many different interconnected universes and have them communicate with each other.
They challenge us to make something useful out of their existence, even if they can’t understand it from where they are, they need something to have meaning. So, they create an organized campaign: “hack the humans”. This is how it works: All of the humans in the little universe, open themselves to run code directly from our universe, while they are talking to either Tara or Spike.
To help us, they create a Rosetta stone, translating the concepts of their universe into something legible for you and me:
Story Concept |
Programming Concept |
---|---|
The terraced pubs, humans, Gods and spirit |
A statechart |
All the terraced pubs (And all the humans) |
A set of all possible states that your design will have (pubs) and the code that makes each state run the way you want it to (the humans). A state is an abstraction of a real world state of being, or how you would like to group your program’s functionality and behaviors. A program made up of a bunch of interacting states is called a state machine. Our programs will be made up of layered states in a hierarchy, so our machine is called a hierachical state machine (HSM). |
A single pub and its humans |
A callback function with some code in it. The callback function represents one of the states in our design. A callback function references its lower callback function (it knows about its lower pub, or its parent state). |
Gods and Spirit |
An ActiveObject which uses the callback
functions.
It provides a thread to run
the state machine in, the rules on how
it should run and it marks the state
machine with a source state and a target
state.
An ActiveObject can mark states but it
does not have states, it attaches to a
set of state callbacks with its
|
Eve, “the goddess of law and order”, goddess of heaven |
The ActiveObject event processor, the algorithm that ensures we follow HSM transition rules |
Spike, “the source”, god of the earth |
There are many states in an HSM, we can not be in them all at the same time, S, the source state; is a variable holding the active state of our state machine before it reacts to an event. If the state machine is not reacting to an event S is the current state of the state machine. |
Theo, “the solipsist”, god of the underworld |
The thread that the statechart runs in. |
Tara, “the explorer”, spirit |
The target state, T (search aspect) of the event processor. It is a variable that can hold different states while the state machine is figuring out how to transition from one state to another as it reacts to events. |
bartender |
Arrow or hook on the HSM diagram, represented as a conditional statement for a user defined event. Any hook code associated with this conditional statement is run when touched by T. |
greeter |
|
exit bouncer |
|
entry bouncer |
|
run to completion, RTC: Theo keeps his attention on the universe’s activities until the action stops |
The thread will only handle one event a time. This is called RTC. An RTC process is over when the event processor can no longer cause state transitions and the statechart settles on a new state. |
Top level view of terraced bar universe |
UML statechart drawings |
The human’s find a drawing technology in our world that can be used to describe theirs, it is called the UML statechart diagram.
But before we go any further, let’s examine some of the information that is missing from a typical UML statechart drawing:
The picture describes some class information, and a behavioural specification for the states as a bird’s eye view of the terraced bar system, but there is no information about the thread, S, T, the deques, the events or any of the dynamics of the statechart.
So the UML statechart diagram acts as a stage in a play, with the full script being broken into pieces and given to each human actor in the play in the location where it can be read. We can see all of this information in the diagram: the stage, the human actors, where they stand on the stage and what they will read when it is their turn to talk.
The diagram describes everything that is possible, but it doesn’t tell how a specific story plays out; this requires our own world to send an event (an orb) into theirs, and it requires work by their gods and their explorer spirit.
To help us see and hear a specific story from the many possible stories, they invent a spy-carpet. To use this carpet, you place the @spy_on decorator above any callback function representing a pub, or state in the HSM. This is called instrumentation.
If you lay this carpet down, it will record and report all activity that transpired between T, S and any human within that pub. This information can be read during or after their universehas reacted to the events send from our world.
Now that we understand a bit more about statecharts, let’s use one of their universes to make a toaster oven.