// SPDX-License-Identifier: MIT
// Select the Airport Wind Station interface. SW0 holds the controller in reset.
module wind_interlock #(parameter CLOCKS_PER_TICK = 50000000)(
    input CLOCK_50, input [9:0] V_SW, inout [35:23] V_GPIO,
    output [9:0] LEDR
);
    typedef enum logic [1:0] {STOPPED, ALIGNING, GENERATING, STOPPING} motion_t;
    motion_t state;
    logic [1:0] reset_pipe;
    logic [2:0] sensors_meta, sensors;
    logic [25:0] divider;
    wire reset = reset_pipe[1];
    wire steady = sensors[2:1] == 2'b10;
    wire gust = sensors[2:1] == 2'b11;
    wire aligned = sensors[0];

    always_ff @(posedge CLOCK_50 or posedge V_SW[0]) begin
        if (V_SW[0]) reset_pipe <= 2'b11;
        else reset_pipe <= {reset_pipe[0], 1'b0};
    end
    // Keep measuring the simulated weather even when the operator holds SW0.
    always_ff @(posedge CLOCK_50) begin
        sensors_meta <= {V_GPIO[30:29], V_GPIO[24]};
        sensors <= sensors_meta;
    end
    always_ff @(posedge CLOCK_50) begin
        if (reset) begin
            state <= STOPPED;
            divider <= 0;
        end else if (divider == CLOCKS_PER_TICK-1) begin
            divider <= 0;
            case (state)
                STOPPING: state <= STOPPED;
                STOPPED: if (steady) begin
                    if (aligned) state <= GENERATING;
                    else state <= ALIGNING;
                end
                default: begin
                    if (!steady) state <= STOPPING;
                    else if (aligned) state <= GENERATING;
                    else state <= ALIGNING;
                end
            endcase
        end else divider <= divider + 1'b1;
    end

    wire active = !reset && state != STOPPED;
    wire yaw = active && state == ALIGNING && steady && !aligned;
    wire generator = active && state == GENERATING && steady && aligned;
    wire runway_alert = gust && !reset;
    assign V_GPIO[26] = yaw;
    assign V_GPIO[27] = 1'b0;
    assign V_GPIO[32] = generator;
    assign V_GPIO[34] = active;
    assign V_GPIO[31] = runway_alert;
    assign LEDR = {1'b0, reset, aligned, steady, runway_alert, active,
                   generator, yaw, reset ? STOPPED : state};
endmodule
