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
PedestrianWalkButton
andCarSensor
. - Use of timers to automatically transition between states (
after
function). - 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
On
state with thegreen
submachine state active. - When a
PedestrianWalkButton
event occurs, the light transitions to theyellow
submachine state. - After 3 seconds (simulated by the
after
guard condition), the light transitions to thered
submachine 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 betweenOn
andOff
states.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 thePedestrian
region to transition fromDontWalk
toWalk
.
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.