TrafficLight
Overview of stateforward.example.traffic_light.py Module
The stateforward.example.traffic_light.py module is part of the stateforward package, which provides a framework for building state machines using the asyncio capabilities of Python. This specific module includes an example implementation of a traffic light state machine.
Features:
- Asynchronous state machine implementation for traffic lights.
- Custom events such as
PedestrianWalkButtonandCarSensor. - Use of timers to automatically transition between states (
afterfunction). - Guard functions that allow conditional transitions.
Traffic Light Example Usage
Below is a possible sequence of operations for the TrafficLight state machine:
- The traffic light starts in the
Onstate with thegreensubmachine state active. - When a
PedestrianWalkButtonevent occurs, the light transitions to theyellowsubmachine state. - After 3 seconds (simulated by the
afterguard condition), the light transitions to theredsubmachine state.
State Machine Diagram
Here is a mermaid.js diagram that visualizes the state machine for the traffic light example:
Traffic Light
stateDiagram-v2
direction LR
Off: Off
Off: entry / display(self)
Off: exit / display(self)
On: On
On: entry / display(self)
On: exit / display(self)
[*] --> On
On --> [*]
On --> Off : after(1s) / guard self.flashing
Off --> On : after(1s)
stateDiagram-v2
direction LR
state On {
[*] --> green
}
stateDiagram-v2
direction LR
state On {
initial --> green
green --> yellow: PedestrianWalkButton
yellow --> red: after(3s)
}
[*] --> On
On --> Off: power_off
Development Notes
Event Classes
PedestrianWalkButton- Represents the event of a pedestrian pressing the walk button.CarSensor- Represents the detection of a car waiting at the traffic light.OffEvent- Indicates that the traffic light has been turned off.FlashingEvent- Indicates the traffic light has entered a flashing state.
Behavior Implementation
Signal- A state machine used to represent a traffic signal mechanism that can switch betweenOnandOffstates.TrafficLight- A more complex state machine representing a traffic light system that can handle pedestrian interaction and power-off events.
Guard Functions
walk_guard- A guard function to allow thePedestrianregion to transition fromDontWalktoWalk.
Helper Functions
display- A debugging function to visually display the traffic light's current state.
Usage
To run the traffic light simulation, execute traffic_light_main() within an asyncio event loop, asynchronously starting the traffic light state machine and allowing for interaction through event dispatching.
Concurrency
This example takes advantage of the ConcurrencyKind.asynchronous to ensure that the traffic light state machine runs in an asynchronous environment suitable for IO-bound and high-level structured network code.