Statecharts · Problem 3
P3 · The Elevator Controller
Two genuine regions, a queue that must not be states, and the run-to-completion ordering that will catch you exactly once. Eleven tests.
The system
An elevator. The doors go closed → opening → open → closing → closed, with an obstruction sensor that sends a closing door back to opening. The car goes idle → up or down → idle. People press buttons for floors, and those requests queue up.
Three rules do the teaching. The car never moves unless the doors are closed. A request made while the doors are open is remembered, not dropped, and served the moment they shut. And nobody sends a “go” event — the car departs because there is somewhere to be and it is safe to go.
Step 1 — draw it
idle, guarded on “doors shut” and “there is a target above/below”. It fires the instant both become true, which may be when a request arrives or when the doors finish closing. You do not have to enumerate those two occasions.Step 2 — build it
exercises/p3_elevator/machine.py —
the skeleton. Its docstring is the contract: exact state ids, event names, and context attributes.exercises/p3_elevator/test_machine.py —
11 acceptance tests. Do not edit them.exercises/p3_elevator/_solution.py —
a reference solution with commentary. Open it after yours is green, not before.cd statecharts/exercises/p3_elevator pytest -q
The trap
You will arrive at a floor, raise an internal “open the doors” event, and watch the car set off for the next floor anyway. Work out why before opening this.
closed. The guard is reading a true fact about a configuration that is about to be wrong.closed guarded on it; entering opening clears it. Both regions now see the same fact at the same instant, and neither names the other's states in a transition.When it is green
Count the guards that mention the doors. There should be one. In the twelve-state product version that same rule has to appear on every arrow into every moving state, and again on every arrow you add next year — which is the difference between a rule and a convention.
Sources: SCXML Appendix D · processing model · RESOURCES.md