// 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
);
    localparam STOPPED=2'd0, ALIGNING=2'd1, GENERATING=2'd2, STOPPING=2'd3;
    reg [1:0] state, reset_pipe;
    reg [2:0] sensors_meta, sensors;
    reg [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 @(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 @(posedge CLOCK_50) begin
        sensors_meta <= {V_GPIO[30:29], V_GPIO[24]};
        sensors <= sensors_meta;
    end
    always @(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) state <= aligned ? GENERATING : ALIGNING;
                default: if (!steady) state <= STOPPING;
                         else state <= aligned ? GENERATING : ALIGNING;
            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
