Smart Trains 1

ST 6 Stop the Train – A Case Study of the Power of Visual Language

In the previous post, we introduced statechart as a method for designing asynchronous systems such as this G-scale model train named Hierarki. To see why statecharts are useful, let’s look at two safety-critical stories:
1. The train shall decelerate slowly when it detects arrival at a station (via a hall-effect sensor).
2. The train shall decelerate rapidly when the emergency button (Button A) on either side of the powered unit is pressed.

These stories appear simple, but as we implement them, we may find ambiguities. What should it do if Button A is pressed when it is already decelerating? What if it detects arrival at a station after Button A has been pressed?

Though natural language is the star these days, it is imprecise when used to specify behaviors. A visual language like statechart does a much better job at that. Coupled with a suitable library such as QP for C++ or xstate for Javascript, it can be mapped directly to code allowing full traceability.

Here is the simplified statechart of the Train state machine showing the Auto (shuttling) substate with error checking hidden for brevity. ARRIVING is the event generated by the hall-effect sensor. BTN_A_PRESS is generated when the emergency button is pressed.

LIGHT_CTRL_OP_REQ (Operation Request) is the event sent to the LightCtrl state machine to control the headlights. MOTOR_RUN_REQ is the event sent to the Motor state machine to set the running speed. MOTOR_DONE and LIGHT_DONE are generated when the corresponding requests have been successfully completed.

The highlights show the power of hierarchical states. They tell us a lot:
1. At any time when the train is active in auto mode, upon ARRIVING, it decelerates slowly (at default rate) until it comes to rest after which it waits for some time and runs again in the reverse direction. This excludes the case when the train is already decelerating for any reason (overridden and ignored).
2. At any time when the train is active in auto mode, upon BTN_A_PRESS, it decelerates rapidly (at fast rate) until it comes to idle after which it must be reactivated manually. This excludes the case when it is already braking rapidly or at rest but includes the case when it is approaching a station.

Without statecharts, making sense of hundreds of natural language descriptions like these would be extremely difficult. As Prof. David Harel stated in his recollection, “Specifying its behavior is the real issue”.