traffic_light/
traffic_light.rs

1use rustate::{Action, ActionType, Machine, MachineBuilder, State, Transition};
2use std::thread::sleep;
3use std::time::Duration;
4
5fn main() -> rustate::Result<()> {
6    // Create a traffic light state machine
7    let machine = create_traffic_light()?;
8
9    println!("Traffic light state machine created");
10    println!("Current state: {:?}", machine.current_states);
11
12    // Run the traffic light simulation
13    run_simulation(machine)?;
14
15    Ok(())
16}
17
18fn create_traffic_light() -> rustate::Result<Machine> {
19    // Create the states
20    let green = State::new("green");
21    let yellow = State::new("yellow");
22    let red = State::new("red");
23
24    // Create the transitions
25    let green_to_yellow = Transition::new("green", "TIMER", "yellow");
26    let yellow_to_red = Transition::new("yellow", "TIMER", "red");
27    let red_to_green = Transition::new("red", "TIMER", "green");
28
29    // Define some actions
30    let log_green = Action::new("logGreen", ActionType::Entry, |_ctx, _evt| {
31        println!("Entering GREEN state - Go!")
32    });
33
34    let log_yellow = Action::new("logYellow", ActionType::Entry, |_ctx, _evt| {
35        println!("Entering YELLOW state - Slow down!")
36    });
37
38    let log_red = Action::new("logRed", ActionType::Entry, |_ctx, _evt| {
39        println!("Entering RED state - Stop!")
40    });
41
42    // Build the machine
43    let machine = MachineBuilder::new("trafficLight")
44        .state(green)
45        .state(yellow)
46        .state(red)
47        .initial("green")
48        .transition(green_to_yellow)
49        .transition(yellow_to_red)
50        .transition(red_to_green)
51        .on_entry("green", log_green)
52        .on_entry("yellow", log_yellow)
53        .on_entry("red", log_red)
54        .build()?;
55
56    Ok(machine)
57}
58
59fn run_simulation(mut machine: Machine) -> rustate::Result<()> {
60    println!("\nStarting traffic light simulation...");
61    println!("Press Ctrl+C to exit\n");
62
63    loop {
64        // Wait some time in the current state
65        let wait_time = match machine.current_states.iter().next() {
66            Some(state) if state == "green" => 3,
67            Some(state) if state == "yellow" => 1,
68            Some(state) if state == "red" => 2,
69            _ => 1,
70        };
71
72        sleep(Duration::from_secs(wait_time));
73
74        // Send a timer event to transition to the next state
75        machine.send("TIMER")?;
76    }
77}